upload rwkv-5-model-1b5
Browse files- README.md +57 -0
- config.json +25 -0
- configuration_rwkv5.py +125 -0
- modeling_rwkv5.py +675 -0
- pytorch_model.bin +3 -0
- rwkv_vocab_v20230424.json +0 -0
- special_tokens_map.json +1 -0
- tokenization_rwkv_world.py +505 -0
- tokenizer_config.json +12 -0
README.md
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Run Huggingface RWKV5 World Model
|
2 |
+
|
3 |
+
|
4 |
+
#### CPU
|
5 |
+
|
6 |
+
```python
|
7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
8 |
+
|
9 |
+
model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-5-world-1b5", trust_remote_code=True)
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-5-world-1b5", trust_remote_code=True)
|
11 |
+
|
12 |
+
text = "\nIn a shocking finding, scientist discovered a herd of dragons living in a remote, previously unexplored valley, in Tibet. Even more surprising to the researchers was the fact that the dragons spoke perfect Chinese."
|
13 |
+
prompt = f'Question: {text.strip()}\n\nAnswer:'
|
14 |
+
|
15 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
16 |
+
output = model.generate(inputs["input_ids"], max_new_tokens=256)
|
17 |
+
print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
|
18 |
+
```
|
19 |
+
|
20 |
+
output:
|
21 |
+
|
22 |
+
```shell
|
23 |
+
Question: In a shocking finding, scientist discovered a herd of dragons living in a remote, previously unexplored valley, in Tibet. Even more surprising to the researchers was the fact that the dragons spoke perfect Chinese.
|
24 |
+
|
25 |
+
Answer: The researchers were shocked to discover that the dragons in the valley were not only intelligent but also spoke perfect Chinese. This discovery has opened up new possibilities for cultural exchange and understanding between China and Tibet.
|
26 |
+
```
|
27 |
+
|
28 |
+
#### GPU
|
29 |
+
|
30 |
+
```python
|
31 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
32 |
+
|
33 |
+
model = AutoModelForCausalLM.from_pretrained("/data/user/cangshui/bbuf/RWKV-World-HF-Tokenizer/rwkv5-v2-world-1b5-model/", trust_remote_code=True).to(0)
|
34 |
+
tokenizer = AutoTokenizer.from_pretrained("/data/user/cangshui/bbuf/RWKV-World-HF-Tokenizer/rwkv5-v2-world-1b5-model/", trust_remote_code=True)
|
35 |
+
|
36 |
+
text = "请介绍北京的旅游景点"
|
37 |
+
prompt = f'Question: {text.strip()}\n\nAnswer:'
|
38 |
+
|
39 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(0)
|
40 |
+
output = model.generate(inputs["input_ids"], max_new_tokens=256, do_sample=True, temperature=1.0, top_p=0.1, top_k=0, )
|
41 |
+
print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
|
42 |
+
```
|
43 |
+
|
44 |
+
output:
|
45 |
+
|
46 |
+
```shell
|
47 |
+
Question: 请介绍北京的旅游景点
|
48 |
+
|
49 |
+
Answer: 北京是中国的首都,拥有许多著名的旅游景点。以下是其中一些:
|
50 |
+
1. 故宫:位于北京市中心,是明清两代的皇宫,是中国最大的古代宫殿建筑群之一。
|
51 |
+
2. 天安门广场:位于北京市中心,是中国最著名的广场之一,是中国人民政治协商会议的旧址。
|
52 |
+
3. 颐和园:位于北京市西郊,是中国最著名的皇家园林之一,有许多美丽的湖泊和花园。
|
53 |
+
4. 长城:位于北京市西北部,是中国最著名的古代防御工程之一,有许多壮观的景点。
|
54 |
+
5. 北京大学:位于北京市东城区,是中国著名的高等教育机构之一,有许多知名的学者和教授。
|
55 |
+
6. 北京奥林匹克公园:位于北京市
|
56 |
+
```
|
57 |
+
|
config.json
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"RwkvForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_rwkv5.Rwkv5Config",
|
7 |
+
"AutoModelForCausalLM": "modeling_rwkv5.RwkvForCausalLM"
|
8 |
+
},
|
9 |
+
"attention_hidden_size": 2048,
|
10 |
+
"bos_token_id": 0,
|
11 |
+
"context_length": 4096,
|
12 |
+
"eos_token_id": 0,
|
13 |
+
"head_size": 64,
|
14 |
+
"hidden_size": 2048,
|
15 |
+
"intermediate_size": null,
|
16 |
+
"layer_norm_epsilon": 1e-05,
|
17 |
+
"model_type": "rwkv5",
|
18 |
+
"model_version": "5_2",
|
19 |
+
"num_hidden_layers": 24,
|
20 |
+
"rescale_every": 6,
|
21 |
+
"tie_word_embeddings": false,
|
22 |
+
"transformers_version": "4.33.1",
|
23 |
+
"use_cache": true,
|
24 |
+
"vocab_size": 65536
|
25 |
+
}
|
configuration_rwkv5.py
ADDED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
RWKV_PRETRAINED_CONFIG_ARCHIVE_MAP = {
|
25 |
+
|
26 |
+
}
|
27 |
+
|
28 |
+
|
29 |
+
class Rwkv5Config(PretrainedConfig):
|
30 |
+
"""
|
31 |
+
This is the configuration class to store the configuration of a [`RwkvModel`]. It is used to instantiate a RWKV
|
32 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
33 |
+
defaults will yield a similar configuration to that of the RWVK-4
|
34 |
+
[RWKV/rwkv-4-169m-pile](https://huggingface.co/RWKV/rwkv-4-169m-pile) architecture.
|
35 |
+
|
36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
37 |
+
documentation from [`PretrainedConfig`] for more information.
|
38 |
+
|
39 |
+
|
40 |
+
Args:
|
41 |
+
vocab_size (`int`, *optional*, defaults to 50277):
|
42 |
+
Vocabulary size of the RWKV model. Defines the number of different tokens that can be represented by the
|
43 |
+
`inputs_ids` passed when calling [`RwkvModel`].
|
44 |
+
context_length (`int`, *optional*, defaults to 1024):
|
45 |
+
The maximum sequence length that this model can be be used with in a single forward (using it in RNN mode
|
46 |
+
lets use any sequence length).
|
47 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
48 |
+
Dimensionality of the embeddings and hidden states.
|
49 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
50 |
+
Number of hidden layers in the model.
|
51 |
+
attention_hidden_size (`int`, *optional*):
|
52 |
+
Dimensionality of the attention hidden states. Will default to `hidden_size` if unset.
|
53 |
+
intermediate_size (`int`, *optional*):
|
54 |
+
Dimensionality of the inner feed-forward layers. Will default to 4 times `hidden_size` if unset.
|
55 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
56 |
+
The epsilon to use in the layer normalization layers.
|
57 |
+
bos_token_id (`int`, *optional*, defaults to 0):
|
58 |
+
The id of the beginning of sentence token in the vocabulary. Defaults to 0 as RWKV uses the same tokenizer
|
59 |
+
as GPTNeoX.
|
60 |
+
eos_token_id (`int`, *optional*, defaults to 0):
|
61 |
+
The id of the end of sentence token in the vocabulary. Defaults to 0 as RWKV uses the same tokenizer as
|
62 |
+
GPTNeoX.
|
63 |
+
rescale_every (`int`, *optional*, default to 6):
|
64 |
+
At inference, the hidden states (and weights of the correponding output layers) are divided by 2 every
|
65 |
+
`rescale_every` layer. If set to 0 or a negative number, no rescale is done.
|
66 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
67 |
+
Whether or not to tie the word embeddings with the input token embeddings.
|
68 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
69 |
+
Whether or not the model should return the last state.
|
70 |
+
|
71 |
+
|
72 |
+
Example:
|
73 |
+
|
74 |
+
```python
|
75 |
+
>>> from transformers import RwkvConfig, RwkvModel
|
76 |
+
|
77 |
+
>>> # Initializing a Rwkv configuration
|
78 |
+
>>> configuration = RwkvConfig()
|
79 |
+
|
80 |
+
>>> # Initializing a model (with random weights) from the configuration
|
81 |
+
>>> model = RwkvModel(configuration)
|
82 |
+
|
83 |
+
>>> # Accessing the model configuration
|
84 |
+
>>> configuration = model.config
|
85 |
+
```"""
|
86 |
+
|
87 |
+
model_type = "rwkv5"
|
88 |
+
attribute_map = {"max_position_embeddings": "context_length"}
|
89 |
+
|
90 |
+
def __init__( #1.5B World
|
91 |
+
self,
|
92 |
+
vocab_size=65536,
|
93 |
+
context_length=4096,
|
94 |
+
hidden_size=768,
|
95 |
+
num_hidden_layers=24,
|
96 |
+
attention_hidden_size=None,
|
97 |
+
head_size=64,
|
98 |
+
intermediate_size=None,
|
99 |
+
layer_norm_epsilon=1e-5,
|
100 |
+
bos_token_id=0,
|
101 |
+
eos_token_id=0,
|
102 |
+
rescale_every=6,
|
103 |
+
tie_word_embeddings=False,
|
104 |
+
use_cache=True,
|
105 |
+
model_version="5_2",
|
106 |
+
**kwargs,
|
107 |
+
):
|
108 |
+
self.vocab_size = vocab_size
|
109 |
+
self.context_length = context_length
|
110 |
+
self.hidden_size = hidden_size
|
111 |
+
self.num_hidden_layers = num_hidden_layers
|
112 |
+
self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
|
113 |
+
self.head_size = head_size
|
114 |
+
self.intermediate_size = None
|
115 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
116 |
+
self.rescale_every = rescale_every
|
117 |
+
self.use_cache = use_cache
|
118 |
+
|
119 |
+
self.bos_token_id = bos_token_id
|
120 |
+
self.eos_token_id = eos_token_id
|
121 |
+
self.model_version = model_version
|
122 |
+
|
123 |
+
super().__init__(
|
124 |
+
tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
|
125 |
+
)
|
modeling_rwkv5.py
ADDED
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Bo Peng and HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""PyTorch RWKV5 World model."""
|
17 |
+
|
18 |
+
import math
|
19 |
+
from dataclasses import dataclass
|
20 |
+
from pathlib import Path
|
21 |
+
from typing import List, Optional, Tuple, Union
|
22 |
+
|
23 |
+
import torch
|
24 |
+
import torch.utils.checkpoint
|
25 |
+
from torch import nn
|
26 |
+
import torch.nn.functional as F
|
27 |
+
from torch.nn import CrossEntropyLoss
|
28 |
+
|
29 |
+
from transformers.modeling_utils import PreTrainedModel
|
30 |
+
from transformers.utils import (
|
31 |
+
ModelOutput,
|
32 |
+
add_code_sample_docstrings,
|
33 |
+
add_start_docstrings,
|
34 |
+
add_start_docstrings_to_model_forward,
|
35 |
+
is_ninja_available,
|
36 |
+
is_torch_cuda_available,
|
37 |
+
logging,
|
38 |
+
)
|
39 |
+
from .configuration_rwkv5 import Rwkv5Config
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
_CHECKPOINT_FOR_DOC = "RWKV/rwkv-5-world"
|
45 |
+
_CONFIG_FOR_DOC = "Rwkv5Config"
|
46 |
+
|
47 |
+
RWKV_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
48 |
+
|
49 |
+
]
|
50 |
+
|
51 |
+
def rwkv_linear_attention_v5_0(H, S, T, hidden, time_decay, time_first, receptance, key, value, lxw, lxb, ow, state, return_state=False, seq_mode=True):
|
52 |
+
time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1,1,1)
|
53 |
+
time_first = torch.exp(time_first.float()).reshape(-1,1,1)
|
54 |
+
lxw = lxw.float()
|
55 |
+
lxb = lxb.float()
|
56 |
+
|
57 |
+
if seq_mode:
|
58 |
+
w = time_decay.reshape(-1, 1)
|
59 |
+
u = time_first.reshape(-1, 1)
|
60 |
+
ws = w.pow(T).reshape(H, 1, 1)
|
61 |
+
ind = torch.arange(T-1, -1, -1, device=w.device).unsqueeze(0).repeat(H, 1)
|
62 |
+
w = w.repeat(1, T).pow(ind)
|
63 |
+
wk = w.reshape(H, 1, T)
|
64 |
+
wb = wk.transpose(-2, -1).flip(1)
|
65 |
+
w = torch.cat([w[:, 1:], u], dim=1)
|
66 |
+
w = F.pad(w, (0, T))
|
67 |
+
w = torch.tile(w, [T])
|
68 |
+
w = w[:, :-T].reshape(-1, T, 2 * T - 1)
|
69 |
+
w = w[:, :, T-1:].reshape(H, T, T)
|
70 |
+
out = ((receptance @ key) * w) @ value + (receptance @ state) * wb
|
71 |
+
state = ws * state + (key * wk) @ value
|
72 |
+
|
73 |
+
out = out.transpose(1, 2).contiguous().reshape(T, H*S)
|
74 |
+
out = F.group_norm(out, num_groups=H, weight=lxw, bias=lxb)
|
75 |
+
out = out.to(dtype=hidden.dtype)
|
76 |
+
out = out @ ow
|
77 |
+
else:
|
78 |
+
a = key @ value
|
79 |
+
out = receptance @ (time_first * a + state)
|
80 |
+
state = a + time_decay * state
|
81 |
+
out = out.flatten()
|
82 |
+
out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lxw, bias=lxb)
|
83 |
+
out = out.to(dtype=hidden.dtype)
|
84 |
+
out = out @ ow
|
85 |
+
|
86 |
+
return out, state
|
87 |
+
|
88 |
+
def rwkv_linear_attention_v5_2(H, S, T, n_head, hidden, time_decay, time_first, receptance, key, value, gate, lxw, lxb, ow, state, return_state=False, seq_mode=True):
|
89 |
+
time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1,1,1).reshape(n_head, -1, 1)
|
90 |
+
time_first = time_first.float().reshape(-1,1,1).reshape(n_head, -1, 1)
|
91 |
+
lxw = lxw.float()
|
92 |
+
lxb = lxb.float()
|
93 |
+
if seq_mode:
|
94 |
+
out = torch.empty((T, H, S), dtype=receptance.dtype, device=receptance.device)
|
95 |
+
for t in range(T):
|
96 |
+
rt = receptance[:,t:t+1,:]
|
97 |
+
kt = key[:,:,t:t+1]
|
98 |
+
vt = value[:,t:t+1,:]
|
99 |
+
at = kt @ vt
|
100 |
+
out[t] = (rt @ (time_first * at + state.squeeze(0))).squeeze(1)
|
101 |
+
state = at + time_decay * state
|
102 |
+
|
103 |
+
out = out.reshape(T, H*S)
|
104 |
+
out = F.group_norm(out, num_groups=H, weight=lxw, bias=lxb)
|
105 |
+
out = out.to(dtype=hidden.dtype) * gate
|
106 |
+
out = out @ ow
|
107 |
+
else:
|
108 |
+
a = key @ value
|
109 |
+
out = receptance @ (time_first * a + state.squeeze(0))
|
110 |
+
state = a + time_decay * state
|
111 |
+
out = out.flatten()
|
112 |
+
out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lxw, bias=lxb).squeeze(0)
|
113 |
+
out = out.to(dtype=hidden.dtype) * gate
|
114 |
+
out = out @ ow
|
115 |
+
|
116 |
+
return out, state
|
117 |
+
|
118 |
+
|
119 |
+
class RwkvSelfAttention(nn.Module):
|
120 |
+
def __init__(self, config, layer_id=0):
|
121 |
+
super().__init__()
|
122 |
+
self.config = config
|
123 |
+
self.layer_id = layer_id
|
124 |
+
hidden_size = config.hidden_size
|
125 |
+
# https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v4neo/src/model.py#L146
|
126 |
+
num_attention_heads = hidden_size // config.head_size
|
127 |
+
self.num_attention_heads = num_attention_heads
|
128 |
+
attention_hidden_size = (
|
129 |
+
config.attention_hidden_size if config.attention_hidden_size is not None else hidden_size
|
130 |
+
)
|
131 |
+
self.attention_hidden_size = attention_hidden_size
|
132 |
+
|
133 |
+
if self.config.model_version == "5_2":
|
134 |
+
self.time_decay = nn.Parameter(torch.empty(num_attention_heads, config.head_size))
|
135 |
+
self.time_faaaa = nn.Parameter(torch.empty(num_attention_heads, config.head_size))
|
136 |
+
self.time_mix_gate = nn.Parameter(torch.empty(1, 1, hidden_size))
|
137 |
+
else:
|
138 |
+
self.time_decay = nn.Parameter(torch.empty(num_attention_heads))
|
139 |
+
self.time_first = nn.Parameter(torch.empty(num_attention_heads))
|
140 |
+
|
141 |
+
self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
|
142 |
+
self.time_mix_value = nn.Parameter(torch.empty(1, 1, hidden_size))
|
143 |
+
self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
|
144 |
+
|
145 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
146 |
+
self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
147 |
+
self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
148 |
+
self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
149 |
+
if self.config.model_version == "5_2":
|
150 |
+
self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
151 |
+
self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
|
152 |
+
# https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/src/model.py#L190C1-L190C1
|
153 |
+
self.ln_x = nn.GroupNorm(hidden_size // config.head_size, hidden_size)
|
154 |
+
|
155 |
+
# TODO: maybe jit, otherwise move inside forward
|
156 |
+
def extract_key_value(self, H, S, T, hidden, state=None):
|
157 |
+
# Mix hidden with the previous timestep to produce key, value, receptance
|
158 |
+
if hidden.size(1) == 1 and state is not None:
|
159 |
+
shifted = state[0][:, :, self.layer_id]
|
160 |
+
else:
|
161 |
+
shifted = self.time_shift(hidden)
|
162 |
+
if state is not None:
|
163 |
+
shifted[:, 0] = state[0][:, :, self.layer_id]
|
164 |
+
key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
|
165 |
+
value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
|
166 |
+
receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
|
167 |
+
if self.config.model_version == "5_2":
|
168 |
+
gate = hidden* self.time_mix_gate + shifted * (1 - self.time_mix_gate)
|
169 |
+
|
170 |
+
if hidden.size(1) == 1 and state is not None:
|
171 |
+
receptance = self.receptance(receptance).to(torch.float32).view(H, 1, S)
|
172 |
+
key = self.key(key).to(torch.float32).view(H, S, 1)
|
173 |
+
value = self.value(value).to(torch.float32).view(H, 1, S)
|
174 |
+
else:
|
175 |
+
# https://github.com/BlinkDL/ChatRWKV/blob/main/rwkv_pip_package/src/rwkv/model.py#L693
|
176 |
+
key = self.key(key).to(torch.float32).view(T, H, S).transpose(0, 1).transpose(-2, -1)
|
177 |
+
value = self.value(value).to(torch.float32).view(T, H, S).transpose(0, 1)
|
178 |
+
receptance = self.receptance(receptance).to(torch.float32).view(T, H, S).transpose(0, 1)
|
179 |
+
|
180 |
+
if self.config.model_version == "5_2":
|
181 |
+
gate = F.silu(self.gate(gate))
|
182 |
+
|
183 |
+
if state is not None:
|
184 |
+
state[0][:, :, self.layer_id] = hidden[:, -1]
|
185 |
+
|
186 |
+
if self.config.model_version == "5_2":
|
187 |
+
return receptance, key, value, gate, state
|
188 |
+
return receptance, key, value, state
|
189 |
+
|
190 |
+
def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
|
191 |
+
H = self.time_decay.shape[0]
|
192 |
+
S = hidden.shape[-1] // H
|
193 |
+
T = hidden.shape[1]
|
194 |
+
|
195 |
+
if self.config.model_version == "5_2":
|
196 |
+
receptance, key, value, gate, state = self.extract_key_value(H, S, T, hidden, state=state)
|
197 |
+
else:
|
198 |
+
receptance, key, value, state = self.extract_key_value(H, S, T, hidden, state=state)
|
199 |
+
layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
|
200 |
+
if self.config.model_version == "5_2":
|
201 |
+
rwkv, layer_state = rwkv_linear_attention_v5_2(
|
202 |
+
H,
|
203 |
+
S,
|
204 |
+
T,
|
205 |
+
self.num_attention_heads,
|
206 |
+
hidden,
|
207 |
+
self.time_decay,
|
208 |
+
self.time_faaaa,
|
209 |
+
receptance,
|
210 |
+
key,
|
211 |
+
value,
|
212 |
+
gate,
|
213 |
+
self.ln_x.weight,
|
214 |
+
self.ln_x.bias,
|
215 |
+
self.output.weight.t(),
|
216 |
+
state=layer_state,
|
217 |
+
return_state=use_cache,
|
218 |
+
seq_mode=seq_mode,
|
219 |
+
)
|
220 |
+
else:
|
221 |
+
rwkv, layer_state = rwkv_linear_attention_v5_0(
|
222 |
+
H,
|
223 |
+
S,
|
224 |
+
T,
|
225 |
+
hidden,
|
226 |
+
self.time_decay,
|
227 |
+
self.time_first,
|
228 |
+
receptance,
|
229 |
+
key,
|
230 |
+
value,
|
231 |
+
self.ln_x.weight,
|
232 |
+
self.ln_x.bias,
|
233 |
+
self.output.weight.t(),
|
234 |
+
state=layer_state,
|
235 |
+
return_state=use_cache,
|
236 |
+
seq_mode=seq_mode,
|
237 |
+
)
|
238 |
+
|
239 |
+
if layer_state is not None:
|
240 |
+
state[1][:, :, :, :, self.layer_id] = layer_state
|
241 |
+
|
242 |
+
return rwkv, state
|
243 |
+
|
244 |
+
|
245 |
+
class RwkvFeedForward(nn.Module):
|
246 |
+
def __init__(self, config, layer_id=0):
|
247 |
+
super().__init__()
|
248 |
+
self.config = config
|
249 |
+
self.layer_id = layer_id
|
250 |
+
hidden_size = config.hidden_size
|
251 |
+
# https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
|
252 |
+
if self.config.model_version == "5_2":
|
253 |
+
intermediate_size = (
|
254 |
+
config.intermediate_size if config.intermediate_size is not None else int((config.hidden_size * 3.5) // 32 * 32)
|
255 |
+
)
|
256 |
+
else:
|
257 |
+
intermediate_size = (
|
258 |
+
config.intermediate_size if config.intermediate_size is not None else 4 * config.hidden_size
|
259 |
+
)
|
260 |
+
|
261 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
262 |
+
self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
|
263 |
+
self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
|
264 |
+
|
265 |
+
self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
|
266 |
+
self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
|
267 |
+
self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
|
268 |
+
|
269 |
+
def forward(self, hidden, state=None):
|
270 |
+
if hidden.size(1) == 1 and state is not None:
|
271 |
+
shifted = state[2][:, :, self.layer_id]
|
272 |
+
else:
|
273 |
+
shifted = self.time_shift(hidden)
|
274 |
+
if state is not None:
|
275 |
+
shifted[:, 0] = state[2][:, :, self.layer_id]
|
276 |
+
key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
|
277 |
+
receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
|
278 |
+
|
279 |
+
key = torch.square(torch.relu(self.key(key)))
|
280 |
+
value = self.value(key)
|
281 |
+
receptance = torch.sigmoid(self.receptance(receptance))
|
282 |
+
|
283 |
+
if state is not None:
|
284 |
+
state[2][:, :, self.layer_id] = hidden[:, -1]
|
285 |
+
|
286 |
+
return receptance * value, state
|
287 |
+
|
288 |
+
|
289 |
+
class RwkvBlock(nn.Module):
|
290 |
+
def __init__(self, config, layer_id):
|
291 |
+
super().__init__()
|
292 |
+
self.config = config
|
293 |
+
self.layer_id = layer_id
|
294 |
+
|
295 |
+
if layer_id == 0:
|
296 |
+
self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
297 |
+
|
298 |
+
self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
299 |
+
self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
300 |
+
|
301 |
+
self.attention = RwkvSelfAttention(config, layer_id)
|
302 |
+
self.feed_forward = RwkvFeedForward(config, layer_id)
|
303 |
+
|
304 |
+
def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
|
305 |
+
|
306 |
+
attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
|
307 |
+
hidden = hidden + attention
|
308 |
+
|
309 |
+
feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
|
310 |
+
hidden = hidden + feed_forward
|
311 |
+
|
312 |
+
outputs = (hidden, state)
|
313 |
+
if output_attentions:
|
314 |
+
outputs += (attention,)
|
315 |
+
else:
|
316 |
+
outputs += (None,)
|
317 |
+
|
318 |
+
return outputs
|
319 |
+
|
320 |
+
|
321 |
+
class RwkvPreTrainedModel(PreTrainedModel):
|
322 |
+
"""
|
323 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
324 |
+
models.
|
325 |
+
"""
|
326 |
+
|
327 |
+
config_class = Rwkv5Config
|
328 |
+
base_model_prefix = "transformer"
|
329 |
+
_no_split_modules = ["RwkvBlock"]
|
330 |
+
_keep_in_fp32_modules = ["time_decay", "time_first"]
|
331 |
+
|
332 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
333 |
+
if isinstance(module, RwkvModel):
|
334 |
+
module.gradient_checkpointing = value
|
335 |
+
|
336 |
+
|
337 |
+
@dataclass
|
338 |
+
class RwkvOutput(ModelOutput):
|
339 |
+
"""
|
340 |
+
Class for the RWKV model outputs.
|
341 |
+
|
342 |
+
Args:
|
343 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
344 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
345 |
+
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
|
346 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
347 |
+
avoid providing the old `input_ids`.
|
348 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
349 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
350 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
351 |
+
|
352 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
353 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
354 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
355 |
+
sequence_length)`.
|
356 |
+
|
357 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
358 |
+
heads.
|
359 |
+
"""
|
360 |
+
|
361 |
+
last_hidden_state: torch.FloatTensor = None
|
362 |
+
state: Optional[List[torch.FloatTensor]] = None
|
363 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
364 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
365 |
+
|
366 |
+
|
367 |
+
@dataclass
|
368 |
+
class RwkvCausalLMOutput(ModelOutput):
|
369 |
+
"""
|
370 |
+
Base class for causal language model (or autoregressive) outputs.
|
371 |
+
|
372 |
+
Args:
|
373 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
374 |
+
Language modeling loss (for next-token prediction).
|
375 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
376 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
377 |
+
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
|
378 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
379 |
+
avoid providing the old `input_ids`.
|
380 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
381 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
382 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
383 |
+
|
384 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
385 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
386 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
387 |
+
sequence_length)`.
|
388 |
+
|
389 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
390 |
+
heads.
|
391 |
+
"""
|
392 |
+
|
393 |
+
loss: Optional[torch.FloatTensor] = None
|
394 |
+
logits: torch.FloatTensor = None
|
395 |
+
state: Optional[List[torch.FloatTensor]] = None
|
396 |
+
last_hidden_state: Optional[Tuple[torch.FloatTensor]] = None
|
397 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
398 |
+
|
399 |
+
|
400 |
+
RWKV_START_DOCSTRING = r"""
|
401 |
+
|
402 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
403 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
404 |
+
etc.)
|
405 |
+
|
406 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
407 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
408 |
+
and behavior.
|
409 |
+
|
410 |
+
Parameters:
|
411 |
+
config ([`Rwkv5Config`]): Model configuration class with all the parameters of the model.
|
412 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
413 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
414 |
+
"""
|
415 |
+
|
416 |
+
RWKV_INPUTS_DOCSTRING = r"""
|
417 |
+
Args:
|
418 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
419 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
420 |
+
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
421 |
+
sequence tokens in the vocabulary.
|
422 |
+
|
423 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
424 |
+
`input_ids`.
|
425 |
+
|
426 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
427 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
428 |
+
|
429 |
+
[What are input IDs?](../glossary#input-ids)
|
430 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
431 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
432 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
433 |
+
model's internal embedding lookup matrix.
|
434 |
+
state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
|
435 |
+
If passed along, the model uses the previous state in all the blocks (which will give the output for the
|
436 |
+
`input_ids` provided as if the model add `state_input_ids + input_ids` as context).
|
437 |
+
use_cache (`bool`, *optional*):
|
438 |
+
If set to `True`, the last state is returned and can be used to quickly generate the next logits.
|
439 |
+
output_attentions (`bool`, *optional*):
|
440 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
441 |
+
tensors for more detail.
|
442 |
+
output_hidden_states (`bool`, *optional*):
|
443 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
444 |
+
more detail.
|
445 |
+
return_dict (`bool`, *optional*):
|
446 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
447 |
+
"""
|
448 |
+
|
449 |
+
|
450 |
+
@add_start_docstrings(
|
451 |
+
"The bare RWKV Model transformer outputting raw hidden-states without any specific head on top.",
|
452 |
+
RWKV_START_DOCSTRING,
|
453 |
+
)
|
454 |
+
class RwkvModel(RwkvPreTrainedModel):
|
455 |
+
def __init__(self, config):
|
456 |
+
super().__init__(config)
|
457 |
+
|
458 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
459 |
+
self.blocks = nn.ModuleList([RwkvBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
|
460 |
+
self.ln_out = nn.LayerNorm(config.hidden_size)
|
461 |
+
|
462 |
+
self.layers_are_rescaled = False
|
463 |
+
self.pre_ln_flag = False
|
464 |
+
|
465 |
+
# Initialize weights and apply final processing
|
466 |
+
self.post_init()
|
467 |
+
|
468 |
+
def get_input_embeddings(self):
|
469 |
+
return self.embeddings
|
470 |
+
|
471 |
+
def set_input_embeddings(self, new_embeddings):
|
472 |
+
self.embeddings = new_embeddings
|
473 |
+
|
474 |
+
@add_start_docstrings_to_model_forward(RWKV_INPUTS_DOCSTRING)
|
475 |
+
@add_code_sample_docstrings(
|
476 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
477 |
+
output_type=RwkvOutput,
|
478 |
+
config_class=_CONFIG_FOR_DOC,
|
479 |
+
)
|
480 |
+
def forward(
|
481 |
+
self,
|
482 |
+
input_ids: Optional[torch.LongTensor] = None,
|
483 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
484 |
+
state: Optional[List[torch.FloatTensor]] = None,
|
485 |
+
use_cache: Optional[bool] = None,
|
486 |
+
output_attentions: Optional[bool] = None,
|
487 |
+
output_hidden_states: Optional[bool] = None,
|
488 |
+
return_dict: Optional[bool] = None,
|
489 |
+
) -> Union[Tuple, RwkvOutput]:
|
490 |
+
seq_mode = input_ids.shape[1] > 1
|
491 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
492 |
+
output_hidden_states = (
|
493 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
494 |
+
)
|
495 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
496 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
497 |
+
|
498 |
+
if self.training == self.layers_are_rescaled and (self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16):
|
499 |
+
self._rescale_layers()
|
500 |
+
|
501 |
+
if input_ids is not None and inputs_embeds is not None:
|
502 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
503 |
+
elif input_ids is None and inputs_embeds is None:
|
504 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
505 |
+
|
506 |
+
if inputs_embeds is None:
|
507 |
+
if not self.pre_ln_flag:
|
508 |
+
normalized_weight = F.layer_norm(self.embeddings.weight, (self.config.hidden_size, ), weight=self.blocks[0].pre_ln.weight, bias=self.blocks[0].pre_ln.bias)
|
509 |
+
self.embeddings.weight = nn.Parameter(normalized_weight)
|
510 |
+
self.pre_ln_flag = True
|
511 |
+
inputs_embeds = self.embeddings(input_ids)
|
512 |
+
|
513 |
+
if use_cache and state is None:
|
514 |
+
# https://github.com/BlinkDL/ChatRWKV/blob/main/rwkv_pip_package/src/rwkv/model.py#L904-L906
|
515 |
+
state = []
|
516 |
+
num_attention_heads = self.config.hidden_size // self.config.head_size
|
517 |
+
state.append(torch.zeros((inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers), dtype=inputs_embeds.dtype, requires_grad=False, device=inputs_embeds.device).contiguous())
|
518 |
+
state.append(torch.zeros((inputs_embeds.size(0), num_attention_heads, self.config.hidden_size // num_attention_heads, self.config.hidden_size // num_attention_heads, self.config.num_hidden_layers), dtype=torch.float32, requires_grad=False, device=inputs_embeds.device).contiguous())
|
519 |
+
state.append(torch.zeros((inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers), dtype=inputs_embeds.dtype, requires_grad=False, device=inputs_embeds.device).contiguous())
|
520 |
+
|
521 |
+
|
522 |
+
hidden_states = inputs_embeds
|
523 |
+
|
524 |
+
all_self_attentions = () if output_attentions else None
|
525 |
+
all_hidden_states = () if output_hidden_states else None
|
526 |
+
for idx, block in enumerate(self.blocks):
|
527 |
+
hidden_states, state, attentions = block(
|
528 |
+
hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
|
529 |
+
)
|
530 |
+
if (
|
531 |
+
self.layers_are_rescaled
|
532 |
+
and self.config.rescale_every > 0
|
533 |
+
and (idx + 1) % self.config.rescale_every == 0
|
534 |
+
):
|
535 |
+
hidden_states = hidden_states / 2
|
536 |
+
|
537 |
+
if output_hidden_states:
|
538 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
539 |
+
|
540 |
+
if output_attentions:
|
541 |
+
all_self_attentions = all_self_attentions + (attentions,)
|
542 |
+
|
543 |
+
if self.config.model_version == "5_2" and seq_mode:
|
544 |
+
hidden_states = hidden_states[:, -1, :].unsqueeze(1)
|
545 |
+
|
546 |
+
hidden_states = self.ln_out(hidden_states)
|
547 |
+
|
548 |
+
if output_hidden_states:
|
549 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
550 |
+
|
551 |
+
if not return_dict:
|
552 |
+
return (hidden_states, state, all_hidden_states, all_self_attentions)
|
553 |
+
|
554 |
+
return RwkvOutput(
|
555 |
+
last_hidden_state=hidden_states,
|
556 |
+
state=state,
|
557 |
+
hidden_states=all_hidden_states, #None
|
558 |
+
attentions=all_self_attentions, #None
|
559 |
+
)
|
560 |
+
|
561 |
+
def _rescale_layers(self):
|
562 |
+
# Layers should be rescaled for inference only.
|
563 |
+
if self.layers_are_rescaled == (not self.training):
|
564 |
+
return
|
565 |
+
if self.config.rescale_every > 0:
|
566 |
+
with torch.no_grad():
|
567 |
+
for block_id, block in enumerate(self.blocks):
|
568 |
+
if self.training:
|
569 |
+
block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
|
570 |
+
block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
|
571 |
+
else:
|
572 |
+
block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
|
573 |
+
block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
|
574 |
+
|
575 |
+
self.layers_are_rescaled = not self.training
|
576 |
+
|
577 |
+
|
578 |
+
@add_start_docstrings(
|
579 |
+
"""
|
580 |
+
The RWKV Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
581 |
+
embeddings).
|
582 |
+
""",
|
583 |
+
RWKV_START_DOCSTRING,
|
584 |
+
)
|
585 |
+
class RwkvForCausalLM(RwkvPreTrainedModel):
|
586 |
+
def __init__(self, config):
|
587 |
+
super().__init__(config)
|
588 |
+
self.rwkv = RwkvModel(config)
|
589 |
+
self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
590 |
+
|
591 |
+
# Initialize weights and apply final processing
|
592 |
+
self.post_init()
|
593 |
+
|
594 |
+
def get_output_embeddings(self):
|
595 |
+
return self.head
|
596 |
+
|
597 |
+
def set_output_embeddings(self, new_embeddings):
|
598 |
+
self.head = new_embeddings
|
599 |
+
|
600 |
+
def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
|
601 |
+
# only last token for inputs_ids if the state is passed along.
|
602 |
+
if state is not None:
|
603 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
604 |
+
|
605 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
606 |
+
if inputs_embeds is not None and state is None:
|
607 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
608 |
+
else:
|
609 |
+
model_inputs = {"input_ids": input_ids}
|
610 |
+
|
611 |
+
model_inputs["state"] = state
|
612 |
+
return model_inputs
|
613 |
+
|
614 |
+
@add_start_docstrings_to_model_forward(RWKV_INPUTS_DOCSTRING)
|
615 |
+
@add_code_sample_docstrings(
|
616 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
617 |
+
output_type=RwkvCausalLMOutput,
|
618 |
+
config_class=_CONFIG_FOR_DOC,
|
619 |
+
)
|
620 |
+
def forward(
|
621 |
+
self,
|
622 |
+
input_ids: Optional[torch.LongTensor] = None,
|
623 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
624 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
625 |
+
state: Optional[List[torch.FloatTensor]] = None,
|
626 |
+
labels: Optional[torch.LongTensor] = None,
|
627 |
+
use_cache: Optional[bool] = None,
|
628 |
+
output_attentions: Optional[bool] = None,
|
629 |
+
output_hidden_states: Optional[bool] = None,
|
630 |
+
return_dict: Optional[bool] = None,
|
631 |
+
) -> Union[Tuple, RwkvCausalLMOutput]:
|
632 |
+
r"""
|
633 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
634 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
635 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
636 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
637 |
+
"""
|
638 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
639 |
+
|
640 |
+
rwkv_outputs = self.rwkv(
|
641 |
+
input_ids,
|
642 |
+
inputs_embeds=inputs_embeds,
|
643 |
+
state=state,
|
644 |
+
use_cache=use_cache,
|
645 |
+
output_attentions=output_attentions,
|
646 |
+
output_hidden_states=output_hidden_states,
|
647 |
+
return_dict=return_dict,
|
648 |
+
)
|
649 |
+
last_hidden_state = rwkv_outputs.last_hidden_state
|
650 |
+
state = rwkv_outputs.state
|
651 |
+
|
652 |
+
logits = self.head(last_hidden_state)
|
653 |
+
|
654 |
+
loss = None
|
655 |
+
if labels is not None:
|
656 |
+
# move labels to correct device to enable model parallelism
|
657 |
+
labels = labels.to(logits.device)
|
658 |
+
# Shift so that tokens < n predict n
|
659 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
660 |
+
shift_labels = labels[..., 1:].contiguous()
|
661 |
+
# Flatten the tokens
|
662 |
+
loss_fct = CrossEntropyLoss()
|
663 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
664 |
+
|
665 |
+
if not return_dict:
|
666 |
+
output = (logits,) + rwkv_outputs[1:]
|
667 |
+
return ((loss,) + output) if loss is not None else output
|
668 |
+
|
669 |
+
return RwkvCausalLMOutput(
|
670 |
+
loss=loss,
|
671 |
+
logits=logits,
|
672 |
+
state=rwkv_outputs.state,
|
673 |
+
last_hidden_state=rwkv_outputs.last_hidden_state,
|
674 |
+
attentions=rwkv_outputs.attentions,
|
675 |
+
)
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:277fcb7726967bb35d0c2790be7edde1fbebc0ed3336fde4e10303270dbf1947
|
3 |
+
size 3155572993
|
rwkv_vocab_v20230424.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
special_tokens_map.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{}
|
tokenization_rwkv_world.py
ADDED
@@ -0,0 +1,505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 OpenAI GPT."""
|
16 |
+
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
|
20 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
21 |
+
from transformers.utils import logging, to_py_obj
|
22 |
+
from transformers.tokenization_utils_base import BatchEncoding
|
23 |
+
|
24 |
+
import bisect
|
25 |
+
import itertools
|
26 |
+
import re
|
27 |
+
import unicodedata
|
28 |
+
from collections import OrderedDict
|
29 |
+
from typing import Any, Dict, List, Optional, Tuple, Union, overload
|
30 |
+
|
31 |
+
from transformers.tokenization_utils_base import (
|
32 |
+
ENCODE_KWARGS_DOCSTRING,
|
33 |
+
ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING,
|
34 |
+
INIT_TOKENIZER_DOCSTRING,
|
35 |
+
AddedToken,
|
36 |
+
BatchEncoding,
|
37 |
+
EncodedInput,
|
38 |
+
EncodedInputPair,
|
39 |
+
PreTokenizedInput,
|
40 |
+
PreTokenizedInputPair,
|
41 |
+
PreTrainedTokenizerBase,
|
42 |
+
TextInput,
|
43 |
+
TextInputPair,
|
44 |
+
TruncationStrategy,
|
45 |
+
)
|
46 |
+
from transformers.utils import PaddingStrategy, TensorType, add_end_docstrings, logging
|
47 |
+
|
48 |
+
|
49 |
+
if TYPE_CHECKING:
|
50 |
+
from transformers.pipelines.conversational import Conversation
|
51 |
+
|
52 |
+
logger = logging.get_logger(__name__)
|
53 |
+
|
54 |
+
VOCAB_FILES_NAMES = {
|
55 |
+
"vocab_file": "rwkv_vocab_v20230424.json",
|
56 |
+
}
|
57 |
+
|
58 |
+
|
59 |
+
class DATrie:
|
60 |
+
class Node:
|
61 |
+
def __init__(self, is_leaf=False, leaf_data=None, tail=""):
|
62 |
+
self._is_leaf = is_leaf
|
63 |
+
self._leaf_data = leaf_data
|
64 |
+
self._tail = tail
|
65 |
+
self._next_map = {}
|
66 |
+
|
67 |
+
def is_leaf(self):
|
68 |
+
return self._is_leaf
|
69 |
+
|
70 |
+
def set_leaf(self):
|
71 |
+
self._is_leaf = True
|
72 |
+
|
73 |
+
def has_next(self, w):
|
74 |
+
if w in self._next_map:
|
75 |
+
return True
|
76 |
+
return False
|
77 |
+
|
78 |
+
def add_node(self, w, node):
|
79 |
+
self._next_map[w] = node
|
80 |
+
|
81 |
+
def get_node(self, w):
|
82 |
+
if w in self._next_map:
|
83 |
+
return self._next_map[w]
|
84 |
+
return None
|
85 |
+
|
86 |
+
def get_tail(self):
|
87 |
+
return self._tail
|
88 |
+
|
89 |
+
def get_data(self):
|
90 |
+
return self._leaf_data
|
91 |
+
|
92 |
+
def set_data(self, data):
|
93 |
+
self._leaf_data = data
|
94 |
+
|
95 |
+
def __init__(self, special_ids):
|
96 |
+
self.root = self.Node()
|
97 |
+
self.data = {}
|
98 |
+
self.r_data = {}
|
99 |
+
self.special_ids = special_ids
|
100 |
+
|
101 |
+
def insert(self, word, data):
|
102 |
+
self.data[word] = data
|
103 |
+
self.r_data[data] = word
|
104 |
+
idx = 0
|
105 |
+
node = self.root
|
106 |
+
while idx < len(word):
|
107 |
+
w = word[idx]
|
108 |
+
is_leaf = (idx == (len(word) - 1))
|
109 |
+
leaf_data = (data if is_leaf else None)
|
110 |
+
# 不存在则插入
|
111 |
+
if not node.has_next(w):
|
112 |
+
node.add_node(w, self.Node(is_leaf=is_leaf, leaf_data=leaf_data))
|
113 |
+
# last word
|
114 |
+
node = node.get_node(w)
|
115 |
+
idx += 1
|
116 |
+
if not node.is_leaf():
|
117 |
+
node.set_leaf()
|
118 |
+
node.set_data(data)
|
119 |
+
|
120 |
+
def findStrict(self, word):
|
121 |
+
idx = 0
|
122 |
+
node = self.root
|
123 |
+
while node is not None and idx < len(word):
|
124 |
+
w = word[idx]
|
125 |
+
if not node.has_next(w):
|
126 |
+
return None
|
127 |
+
# last word
|
128 |
+
node = node.get_node(w)
|
129 |
+
idx += 1
|
130 |
+
if node.is_leaf():
|
131 |
+
return node.get_data()
|
132 |
+
return None
|
133 |
+
|
134 |
+
def prefix(self, word):
|
135 |
+
idx = 0
|
136 |
+
node = self.root
|
137 |
+
result = []
|
138 |
+
while node is not None and idx < len(word):
|
139 |
+
w = word[idx]
|
140 |
+
if not node.has_next(w):
|
141 |
+
return result
|
142 |
+
# last word
|
143 |
+
node = node.get_node(w)
|
144 |
+
if node.is_leaf():
|
145 |
+
result.append([word[:idx + 1], node.get_data()])
|
146 |
+
idx += 1
|
147 |
+
return result
|
148 |
+
|
149 |
+
def max_prefix(self, content, start_idx):
|
150 |
+
idx = start_idx
|
151 |
+
node = self.root
|
152 |
+
l = len(content)
|
153 |
+
result = [["", ], ]
|
154 |
+
while node is not None and idx < l:
|
155 |
+
w = content[idx]
|
156 |
+
if not node.has_next(w):
|
157 |
+
return result[-1]
|
158 |
+
# last word
|
159 |
+
node = node.get_node(w)
|
160 |
+
if node.is_leaf():
|
161 |
+
result.append([content[start_idx:idx + 1], node.get_data()])
|
162 |
+
idx += 1
|
163 |
+
return result[-1]
|
164 |
+
|
165 |
+
def max_score(self, content, start_idx):
|
166 |
+
idx = start_idx
|
167 |
+
node = self.root
|
168 |
+
l = len(content)
|
169 |
+
result = [["", (3, 0)], ]
|
170 |
+
while node is not None and idx < l:
|
171 |
+
w = content[idx]
|
172 |
+
if not node.has_next(w):
|
173 |
+
break
|
174 |
+
# last word
|
175 |
+
node = node.get_node(w)
|
176 |
+
if node.is_leaf():
|
177 |
+
result.append([content[start_idx:idx + 1], node.get_data()])
|
178 |
+
idx += 1
|
179 |
+
if len(result) > 1:
|
180 |
+
result = sorted(result, key=lambda x: x[1][1])
|
181 |
+
return result[-1]
|
182 |
+
|
183 |
+
def match(self, content, add_unk=True, unk_id=-1, **kwargs):
|
184 |
+
# length
|
185 |
+
l = len(content)
|
186 |
+
i = 0
|
187 |
+
result_list = []
|
188 |
+
while i < l:
|
189 |
+
match_word = self.max_prefix(content=content, start_idx=i)
|
190 |
+
# print(match_word)
|
191 |
+
w = match_word[0]
|
192 |
+
if len(w) > 0:
|
193 |
+
result_list.append(match_word[1])
|
194 |
+
i += len(w)
|
195 |
+
else:
|
196 |
+
if add_unk:
|
197 |
+
result_list.append(unk_id)
|
198 |
+
i += 1
|
199 |
+
return result_list
|
200 |
+
|
201 |
+
def id2str(self, ids, escape_special_ids=True, end_ids=[], **kwargs):
|
202 |
+
res_str = ""
|
203 |
+
for rid in ids:
|
204 |
+
if rid in self.r_data:
|
205 |
+
if rid in end_ids:
|
206 |
+
break
|
207 |
+
if escape_special_ids and rid in self.special_ids:
|
208 |
+
continue
|
209 |
+
rstr = self.r_data[rid]
|
210 |
+
res_str += rstr
|
211 |
+
elif rid == 0:
|
212 |
+
break
|
213 |
+
else:
|
214 |
+
print("ERROR unknown id %d" % rid)
|
215 |
+
res_str += "UNK"
|
216 |
+
return res_str
|
217 |
+
|
218 |
+
def id2str_v2(self, ids, escape_special_ids=True, end_ids=[], **kwargs):
|
219 |
+
res_str = ""
|
220 |
+
for rid in ids:
|
221 |
+
if rid in self.r_data:
|
222 |
+
if rid in end_ids:
|
223 |
+
break
|
224 |
+
rstr = self.r_data[rid]
|
225 |
+
if escape_special_ids and rid in self.special_ids:
|
226 |
+
continue
|
227 |
+
res_str += rstr
|
228 |
+
elif rid == 0:
|
229 |
+
break
|
230 |
+
else:
|
231 |
+
print("ERROR unknown id %d" % rid)
|
232 |
+
res_str += "UNK"
|
233 |
+
return res_str
|
234 |
+
|
235 |
+
|
236 |
+
class RWKVWorldTokenizer(PreTrainedTokenizer):
|
237 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
238 |
+
model_input_names = ["input_ids", "attention_mask"]
|
239 |
+
|
240 |
+
def __init__(
|
241 |
+
self,
|
242 |
+
vocab_file,
|
243 |
+
errors="replace",
|
244 |
+
**kwargs
|
245 |
+
):
|
246 |
+
self.add_bos_token = False
|
247 |
+
|
248 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
249 |
+
self.encoder = json.load(vocab_handle)
|
250 |
+
super().__init__(
|
251 |
+
errors=errors,
|
252 |
+
**kwargs,
|
253 |
+
)
|
254 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
255 |
+
self.trie = DATrie(self.all_special_ids)
|
256 |
+
for k, v in self.encoder.items():
|
257 |
+
self.trie.insert(k, v)
|
258 |
+
self.errors = errors # how to handle errors in decoding
|
259 |
+
self.cache = {}
|
260 |
+
|
261 |
+
@property
|
262 |
+
def vocab_size(self):
|
263 |
+
return len(self.encoder)
|
264 |
+
|
265 |
+
def get_vocab(self):
|
266 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
267 |
+
|
268 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
269 |
+
if self.add_bos_token:
|
270 |
+
bos_token_ids = [self.bos_token_id]
|
271 |
+
else:
|
272 |
+
bos_token_ids = []
|
273 |
+
|
274 |
+
output = bos_token_ids + token_ids_0
|
275 |
+
|
276 |
+
if token_ids_1 is None:
|
277 |
+
return output
|
278 |
+
|
279 |
+
return output + bos_token_ids + token_ids_1
|
280 |
+
|
281 |
+
def get_special_tokens_mask(
|
282 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None,
|
283 |
+
already_has_special_tokens: bool = False
|
284 |
+
) -> List[int]:
|
285 |
+
"""
|
286 |
+
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
|
287 |
+
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
|
288 |
+
|
289 |
+
Args:
|
290 |
+
token_ids_0 (`List[int]`):
|
291 |
+
List of IDs.
|
292 |
+
token_ids_1 (`List[int]`, *optional*):
|
293 |
+
Optional second list of IDs for sequence pairs.
|
294 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
295 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
296 |
+
|
297 |
+
Returns:
|
298 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
299 |
+
"""
|
300 |
+
if already_has_special_tokens:
|
301 |
+
return super().get_special_tokens_mask(
|
302 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
303 |
+
)
|
304 |
+
|
305 |
+
if not self.add_bos_token:
|
306 |
+
return super().get_special_tokens_mask(
|
307 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
|
308 |
+
)
|
309 |
+
|
310 |
+
if token_ids_1 is None:
|
311 |
+
return [1] + ([0] * len(token_ids_0))
|
312 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
|
313 |
+
|
314 |
+
def _tokenize(self, text, **kwargs):
|
315 |
+
"""Tokenize a string."""
|
316 |
+
return self.trie.match(text, unk_id=self.unk_token_id, **kwargs)
|
317 |
+
|
318 |
+
def _decode(self,
|
319 |
+
token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
|
320 |
+
skip_special_tokens: bool = False,
|
321 |
+
**kwargs
|
322 |
+
) -> str:
|
323 |
+
|
324 |
+
# Convert inputs to python lists
|
325 |
+
token_ids = to_py_obj(token_ids)
|
326 |
+
if isinstance(token_ids, int):
|
327 |
+
if token_ids in self.all_special_ids and skip_special_tokens:
|
328 |
+
return ""
|
329 |
+
return self.decoder.get(token_ids, self.unk_token)
|
330 |
+
elif isinstance(token_ids, list):
|
331 |
+
return self.trie.id2str(
|
332 |
+
token_ids,
|
333 |
+
escape_special_ids=skip_special_tokens,
|
334 |
+
**kwargs
|
335 |
+
)
|
336 |
+
else:
|
337 |
+
return token_ids
|
338 |
+
|
339 |
+
def _convert_token_to_id(self, token):
|
340 |
+
"""Converts a token (str) in an id using the vocab."""
|
341 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
342 |
+
|
343 |
+
def _convert_id_to_token(self, index):
|
344 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
345 |
+
return self.decoder.get(index)
|
346 |
+
|
347 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
348 |
+
if not os.path.exists(save_directory):
|
349 |
+
os.mkdir(save_directory)
|
350 |
+
if not os.path.isdir(save_directory):
|
351 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
352 |
+
return
|
353 |
+
vocab_file = os.path.join(
|
354 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
355 |
+
)
|
356 |
+
|
357 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
358 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
359 |
+
|
360 |
+
return (vocab_file,)
|
361 |
+
|
362 |
+
def prepare_for_tokenization(self, text, **kwargs):
|
363 |
+
return (text, kwargs)
|
364 |
+
|
365 |
+
def _encode_plus(
|
366 |
+
self,
|
367 |
+
text: Union[TextInput, EncodedInput],
|
368 |
+
add_special_tokens: bool = True,
|
369 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
370 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
371 |
+
max_length: Optional[int] = None,
|
372 |
+
stride: int = 0,
|
373 |
+
pad_to_multiple_of: Optional[int] = None,
|
374 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
375 |
+
return_token_type_ids: Optional[bool] = None,
|
376 |
+
return_attention_mask: Optional[bool] = None,
|
377 |
+
return_overflowing_tokens: bool = False,
|
378 |
+
return_special_tokens_mask: bool = False,
|
379 |
+
return_offsets_mapping: bool = False,
|
380 |
+
return_length: bool = False,
|
381 |
+
verbose: bool = True,
|
382 |
+
**kwargs
|
383 |
+
) -> BatchEncoding:
|
384 |
+
def get_input_ids(text):
|
385 |
+
if isinstance(text, str):
|
386 |
+
text_id = self.trie.match(text, unk_id=self.unk_token_id)
|
387 |
+
return text_id
|
388 |
+
elif isinstance(text, list) and len(text) > 0 and isinstance(text[0], str):
|
389 |
+
return [self.trie.match(t, unk_id=self.unk_token_id) for t in text]
|
390 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
|
391 |
+
return text
|
392 |
+
else:
|
393 |
+
raise ValueError(
|
394 |
+
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
|
395 |
+
)
|
396 |
+
|
397 |
+
if return_offsets_mapping:
|
398 |
+
raise NotImplementedError(
|
399 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
400 |
+
"To use this feature, change your tokenizer to one deriving from "
|
401 |
+
"transformers.PreTrainedTokenizerFast. "
|
402 |
+
"More information on available tokenizers at "
|
403 |
+
"https://github.com/huggingface/transformers/pull/2674"
|
404 |
+
)
|
405 |
+
|
406 |
+
first_ids = get_input_ids(text)
|
407 |
+
|
408 |
+
return self.prepare_for_model(
|
409 |
+
first_ids,
|
410 |
+
pair_ids=None,
|
411 |
+
add_special_tokens=add_special_tokens,
|
412 |
+
padding=padding_strategy.value,
|
413 |
+
truncation=truncation_strategy.value,
|
414 |
+
max_length=max_length,
|
415 |
+
stride=stride,
|
416 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
417 |
+
return_tensors=return_tensors,
|
418 |
+
prepend_batch_axis=True,
|
419 |
+
return_attention_mask=return_attention_mask,
|
420 |
+
return_token_type_ids=return_token_type_ids,
|
421 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
422 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
423 |
+
return_length=return_length,
|
424 |
+
verbose=verbose,
|
425 |
+
)
|
426 |
+
|
427 |
+
def _batch_encode_plus(
|
428 |
+
self,
|
429 |
+
batch_text_or_text_pairs: Union[
|
430 |
+
List[TextInput],
|
431 |
+
List[EncodedInput],
|
432 |
+
],
|
433 |
+
add_special_tokens: bool = True,
|
434 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
435 |
+
truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
|
436 |
+
max_length: Optional[int] = None,
|
437 |
+
stride: int = 0,
|
438 |
+
pad_to_multiple_of: Optional[int] = None,
|
439 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
440 |
+
return_token_type_ids: Optional[bool] = None,
|
441 |
+
return_attention_mask: Optional[bool] = None,
|
442 |
+
return_overflowing_tokens: bool = False,
|
443 |
+
return_special_tokens_mask: bool = False,
|
444 |
+
return_offsets_mapping: bool = False,
|
445 |
+
return_length: bool = False,
|
446 |
+
verbose: bool = True,
|
447 |
+
**kwargs
|
448 |
+
) -> BatchEncoding:
|
449 |
+
def get_input_ids(text):
|
450 |
+
if isinstance(text, str):
|
451 |
+
text_id = self.trie.match(text, unk_id=self.unk_token_id)
|
452 |
+
return text_id
|
453 |
+
elif isinstance(text, list) and len(text) > 0 and isinstance(text[0], str):
|
454 |
+
return [self.trie.match(t, unk_id=self.unk_token_id) for t in text]
|
455 |
+
elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
|
456 |
+
return text
|
457 |
+
else:
|
458 |
+
raise ValueError(
|
459 |
+
"Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
|
460 |
+
)
|
461 |
+
|
462 |
+
if return_offsets_mapping:
|
463 |
+
raise NotImplementedError(
|
464 |
+
"return_offset_mapping is not available when using Python tokenizers. "
|
465 |
+
"To use this feature, change your tokenizer to one deriving from "
|
466 |
+
"transformers.PreTrainedTokenizerFast."
|
467 |
+
)
|
468 |
+
|
469 |
+
input_ids = []
|
470 |
+
for ids_or_pair_ids in batch_text_or_text_pairs:
|
471 |
+
if not isinstance(ids_or_pair_ids, (list, tuple)):
|
472 |
+
ids, pair_ids = ids_or_pair_ids, None
|
473 |
+
else:
|
474 |
+
ids, pair_ids = ids_or_pair_ids
|
475 |
+
|
476 |
+
first_ids = get_input_ids(ids)
|
477 |
+
second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
|
478 |
+
input_ids.append((first_ids, second_ids))
|
479 |
+
|
480 |
+
batch_outputs = self._batch_prepare_for_model(
|
481 |
+
input_ids,
|
482 |
+
add_special_tokens=add_special_tokens,
|
483 |
+
padding_strategy=padding_strategy,
|
484 |
+
truncation_strategy=truncation_strategy,
|
485 |
+
max_length=max_length,
|
486 |
+
stride=stride,
|
487 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
488 |
+
return_attention_mask=return_attention_mask,
|
489 |
+
return_token_type_ids=return_token_type_ids,
|
490 |
+
return_overflowing_tokens=return_overflowing_tokens,
|
491 |
+
return_special_tokens_mask=return_special_tokens_mask,
|
492 |
+
return_length=return_length,
|
493 |
+
return_tensors=return_tensors,
|
494 |
+
verbose=verbose,
|
495 |
+
)
|
496 |
+
|
497 |
+
return BatchEncoding(batch_outputs)
|
498 |
+
|
499 |
+
def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
|
500 |
+
input_ids = []
|
501 |
+
for is_user, text in conversation.iter_texts():
|
502 |
+
input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])
|
503 |
+
if len(input_ids) > self.model_max_length:
|
504 |
+
input_ids = input_ids[-self.model_max_length:]
|
505 |
+
return input_ids
|
tokenizer_config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name_or_path": "rwkv-world",
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"tokenizer_class": "RWKVWorldTokenizer",
|
5 |
+
"use_fast": false,
|
6 |
+
"auto_map": {
|
7 |
+
"AutoTokenizer": [
|
8 |
+
"tokenization_rwkv_world.RWKVWorldTokenizer",
|
9 |
+
null
|
10 |
+
]
|
11 |
+
}
|
12 |
+
}
|