KaleiNeely commited on
Commit
d718e08
1 Parent(s): c4f34c1

Upload 10 files

Browse files
README.md ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Run Huggingface RWKV6 World Model
2
+
3
+ > origin pth weight from https://huggingface.co/BlinkDL/rwkv-6-world/blob/main/RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth .
4
+
5
+ #### CPU
6
+
7
+ ```python
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+
11
+ def generate_prompt(instruction, input=""):
12
+ instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
13
+ input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
14
+ if input:
15
+ return f"""Instruction: {instruction}
16
+
17
+ Input: {input}
18
+
19
+ Response:"""
20
+ else:
21
+ return f"""User: hi
22
+
23
+ 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.
24
+
25
+ User: {instruction}
26
+
27
+ Assistant:"""
28
+
29
+
30
+ model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-6-world-3b-v2.1", trust_remote_code=True).to(torch.float32)
31
+ tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-6-world-3b-v2.1", trust_remote_code=True, padding_side='left', pad_token="<s>")
32
+
33
+ text = "请介绍北京的旅游景点"
34
+ prompt = generate_prompt(text)
35
+
36
+ inputs = tokenizer(prompt, return_tensors="pt")
37
+ output = model.generate(inputs["input_ids"], max_new_tokens=333, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
38
+ print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
39
+ ```
40
+
41
+ output:
42
+
43
+ ```shell
44
+ User: hi
45
+
46
+ 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.
47
+
48
+ User: 请介绍北京的旅游景点
49
+
50
+ Assistant: 北京是中国的首都,拥有众多的旅游景点,以下是其中一些著名的景点:
51
+ 1. 故宫:位于北京市中心,是明清两代的皇宫,内有大量的文物和艺术品。
52
+ 2. 天安门广场:是中国最著名的广场之一,是中国人民政治协商会议的旧址,也是中国人民政治协商会议的中心。
53
+ 3. 颐和园:是中国古代皇家园林之一,有着悠久的历史和丰富的文化内涵。
54
+ 4. 长城:是中国古代的一道长城,全长约万里,是中国最著名的旅游景点之一。
55
+ 5. 北京大学:是中国著名的高等教育机构之一,有着悠久的历史和丰富的文化内涵。
56
+ 6. 北京动物园:是中国最大的动物园之一,有着丰富的动物资源和丰富的文化内涵。
57
+ 7. 故宫博物院:是中国最著名的博物馆之一,收藏了大量的文物和艺术品,是中国最重要的文化遗产之一。
58
+ 8. 天坛:是中国古代皇家
59
+ ```
60
+
61
+ #### GPU
62
+
63
+ ```python
64
+ import torch
65
+ from transformers import AutoModelForCausalLM, AutoTokenizer
66
+
67
+ def generate_prompt(instruction, input=""):
68
+ instruction = instruction.strip().replace('\r\n','\n').replace('\n\n','\n')
69
+ input = input.strip().replace('\r\n','\n').replace('\n\n','\n')
70
+ if input:
71
+ return f"""Instruction: {instruction}
72
+
73
+ Input: {input}
74
+
75
+ Response:"""
76
+ else:
77
+ return f"""User: hi
78
+
79
+ 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.
80
+
81
+ User: {instruction}
82
+
83
+ Assistant:"""
84
+
85
+
86
+ model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-6-world-3b-v2.1", trust_remote_code=True, torch_dtype=torch.float16).to(0)
87
+ tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-6-world-3b-v2.1", trust_remote_code=True, padding_side='left', pad_token="<s>")
88
+
89
+ text = "介绍一下大熊猫"
90
+ prompt = generate_prompt(text)
91
+
92
+ inputs = tokenizer(prompt, return_tensors="pt").to(0)
93
+ output = model.generate(inputs["input_ids"], max_new_tokens=128, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
94
+ print(tokenizer.decode(output[0].tolist(), skip_special_tokens=True))
95
+ ```
96
+
97
+ output:
98
+
99
+ ```shell
100
+ User: hi
101
+
102
+ 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.
103
+
104
+ User: 介绍一下大熊猫
105
+
106
+ Assistant: 大熊猫是一种中国特有的哺乳动物,也是中国的国宝之一。它们的外貌特征是圆形的黑白相间的身体,有着黑色的毛发和白色的耳朵。大熊猫的食物主要是竹子,它们会在竹林中寻找竹子,并且会将竹子放在竹笼中进行储存。大熊猫的寿命约为20至30年,但由于栖息地的丧失和人类活动的
107
+ ```
108
+
109
+ #### Batch Inference
110
+
111
+ ```python
112
+ import torch
113
+ from transformers import AutoModelForCausalLM, AutoTokenizer
114
+
115
+ def generate_prompt(instruction, input=""):
116
+ instruction = instruction.strip().replace('\r\n', '\n').replace('\n\n', '\n')
117
+ input = input.strip().replace('\r\n', '\n').replace('\n\n', '\n')
118
+ if input:
119
+ return f"""Instruction: {instruction}
120
+
121
+ Input: {input}
122
+
123
+ Response:"""
124
+ else:
125
+ return f"""User: hi
126
+
127
+ 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.
128
+
129
+ User: {instruction}
130
+
131
+ Assistant:"""
132
+
133
+ model = AutoModelForCausalLM.from_pretrained("RWKV/rwkv-6-world-3b-v2.1", trust_remote_code=True).to(torch.float32)
134
+ tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-6-world-3b-v2.1", trust_remote_code=True, padding_side='left', pad_token="<s>")
135
+
136
+ texts = ["请介绍北京的旅游景点", "介绍一下大熊猫", "乌兰察布"]
137
+ prompts = [generate_prompt(text) for text in texts]
138
+
139
+ inputs = tokenizer(prompts, return_tensors="pt", padding=True)
140
+ outputs = model.generate(inputs["input_ids"], max_new_tokens=128, do_sample=True, temperature=1.0, top_p=0.3, top_k=0, )
141
+
142
+ for output in outputs:
143
+ print(tokenizer.decode(output.tolist(), skip_special_tokens=True))
144
+
145
+ ```
146
+
147
+ output:
148
+
149
+ ```shell
150
+ User: hi
151
+
152
+ 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.
153
+
154
+ User: 请介绍北京的旅游景点
155
+
156
+ Assistant: 北京是中国的首都,拥有丰富的旅游资源和历史文化遗产。以下是一些北京的旅游景点:
157
+ 1. 故宫:位于北京市中心,是明清两代的皇宫,是中国最大的古代宫殿建筑群之一。
158
+ 2. 天安门广场:位于北京市中心,是中国最著名的城市广场之一,也是中国最大的城市广场。
159
+ 3. 颐和
160
+ User: hi
161
+
162
+ 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.
163
+
164
+ User: 介绍一下大熊猫
165
+
166
+ Assistant: 大熊猫是一种生活在中国中部地区的哺乳动物,也是中国的国宝之一。它们的外貌特征是圆形的黑白相间的身体,有着黑色的毛发和圆圆的眼睛。大熊猫是一种濒危物种,目前只有在野外的几个保护区才能看到它们的身影。大熊猫的食物主要是竹子,它们会在竹子上寻找食物,并且可以通
167
+ User: hi
168
+
169
+ 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.
170
+
171
+ User: 乌兰察布
172
+
173
+ Assistant: 乌兰察布是中国新疆维吾尔自治区的一个县级市,位于新疆维吾尔自治区中部,是新疆的第二大城市。乌兰察布市是新疆的第一大城市,也是新疆的重要城市之一。乌兰察布市是新疆的经济中心,也是新疆的重要交通枢纽之一。乌兰察布市的人口约为2.5万人,其中汉族占绝大多数。乌
174
+ ```
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<s>": 0
3
+ }
config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "attention_hidden_size": 2560,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "head_size": 64,
6
+ "head_size_divisor": 8,
7
+ "hidden_size": 2560,
8
+ "intermediate_size": null,
9
+ "layer_norm_epsilon": 1e-05,
10
+ "model_type": "rwkv6",
11
+ "num_attention_heads": 64,
12
+ "num_hidden_layers": 32,
13
+ "rescale_every": 6,
14
+ "tie_word_embeddings": false,
15
+ "transformers_version": "4.34.0",
16
+ "use_cache": true,
17
+ "vocab_size": 65536
18
+ }
configuration_rwkv6.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ RWKV configuration"""
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ RWKV6_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
+
26
+
27
+ class Rwkv6Config(PretrainedConfig):
28
+ """
29
+ This is the configuration class to store the configuration of a [`Rwkv6Model`]. It is used to instantiate a RWKV6
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of the RWVK-4
32
+ [RWKV/rwkv-5-world-1b5](https://huggingface.co/RWKV/rwkv-5-world-1b5) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 65536):
40
+ Vocabulary size of the RWKV6 model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`Rwkv6Model`].
42
+ hidden_size (`int`, *optional*, defaults to 768):
43
+ Dimensionality of the embeddings and hidden states.
44
+ num_hidden_layers (`int`, *optional*, defaults to 24):
45
+ Number of hidden layers in the model.
46
+ attention_hidden_size (`int`, *optional*):
47
+ Dimensionality of the attention hidden states. Will default to `hidden_size` if unset.
48
+ num_attention_heads (`int`, *optional*, defaults to 64):
49
+ The attention heads to use in rwkv6 self_attention module.
50
+ head_size (`int`, *optional*, defaults to 64): head_size of rwkv6 self_attention module.
51
+ intermediate_size (`int`, *optional*):
52
+ Dimensionality of the inner feed-forward layers. Will default to 4 times `hidden_size` if unset.
53
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
54
+ The epsilon to use in the layer normalization layers.
55
+ bos_token_id (`int`, *optional*, defaults to 0):
56
+ The id of the beginning of sentence token in the vocabulary. Defaults to 0.
57
+ eos_token_id (`int`, *optional*, defaults to 0):
58
+ The id of the end of sentence token in the vocabulary. Defaults to 0.
59
+ rescale_every (`int`, *optional*, defaults to 6):
60
+ At inference, the hidden states (and weights of the correponding output layers) are divided by 2 every
61
+ `rescale_every` layer. If set to 0 or a negative number, no rescale is done.
62
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to tie the word embeddings with the input token embeddings.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last state.
66
+
67
+
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import Rwkv6Config, Rwkv6Model
72
+
73
+ >>> # Initializing a Rwkv6 configuration
74
+ >>> configuration = Rwkv6Config()
75
+
76
+ >>> # Initializing a model (with random weights) from the configuration
77
+ >>> model = Rwkv6Model(configuration)
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config
81
+ ```"""
82
+
83
+ model_type = "rwkv6"
84
+
85
+ def __init__(
86
+ self,
87
+ vocab_size=65536,
88
+ hidden_size=768,
89
+ num_hidden_layers=24,
90
+ attention_hidden_size=None,
91
+ head_size=64,
92
+ head_size_divisor=8,
93
+ intermediate_size=None,
94
+ layer_norm_epsilon=1e-5,
95
+ bos_token_id=0,
96
+ eos_token_id=0,
97
+ rescale_every=6,
98
+ tie_word_embeddings=False,
99
+ use_cache=True,
100
+ **kwargs,
101
+ ):
102
+ self.vocab_size = vocab_size
103
+ self.hidden_size = hidden_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
106
+ self.head_size = head_size
107
+ self.head_size_divisor = head_size_divisor
108
+ self.intermediate_size = None
109
+ self.layer_norm_epsilon = layer_norm_epsilon
110
+ self.rescale_every = rescale_every
111
+ self.use_cache = use_cache
112
+
113
+ self.bos_token_id = bos_token_id
114
+ self.eos_token_id = eos_token_id
115
+
116
+ super().__init__(
117
+ tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
118
+ )
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "chat_format": "chatml",
3
+ "eos_token_id": 0,
4
+ "pad_token_id": 0,
5
+ "max_window_size": 4096,
6
+ "max_new_tokens": 4096,
7
+ "do_sample": true,
8
+ "top_k": 0,
9
+ "top_p": 0.1,
10
+ "repetition_penalty": 1.0,
11
+ "transformers_version": "4.31.1"
12
+ }
modeling_rwkv6.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The RWKV team and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch RWKV6 World model."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ from pathlib import Path
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ is_ninja_available,
35
+ is_torch_cuda_available,
36
+ logging,
37
+ )
38
+
39
+ from .configuration_rwkv6 import Rwkv6Config
40
+ try:
41
+ from fla.ops.rwkv6.recurrent_fuse import fused_recurrent_rwkv6
42
+ except ImportError:
43
+ print("Required module is not installed. Please install it using the following commands:")
44
+ print("pip install -U git+https://github.com/sustcsonglin/flash-linear-attention")
45
+ print("Additionally, ensure you have the correct version of Triton installed:")
46
+ print("pip install triton==2.2.0")
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "RWKV/rwkv-6-world-1b6"
52
+ _CONFIG_FOR_DOC = "Rwkv6Config"
53
+
54
+ def rwkv6_linear_attention_cpu(receptance, key, value, time_decay, time_first, state):
55
+ # For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel if not executed
56
+ # within a torch.no_grad.
57
+ batch, seq_length, _ = receptance.shape
58
+ num_heads, head_size = time_first.shape
59
+ key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2).transpose(-2, -1)
60
+ value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
61
+ receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
62
+ time_decay = torch.exp(-torch.exp(time_decay.float())).view(batch, seq_length, num_heads, head_size).permute(0, 2, 3, 1)
63
+ time_first = time_first.float().reshape(-1, 1, 1).reshape(num_heads, -1, 1)
64
+ out = torch.zeros_like(key).reshape(batch, seq_length, num_heads, head_size)
65
+
66
+ for current_index in range(seq_length):
67
+ current_receptance = receptance[:, :, current_index:current_index+1, :]
68
+ current_key = key[:, :, :, current_index:current_index+1]
69
+ current_value = value[:, :, current_index:current_index+1, :]
70
+ current_time_decay = time_decay[:, :, :, current_index:current_index+1]
71
+ attention_output = current_key @ current_value
72
+ out[:, current_index] = (current_receptance @ (time_first * attention_output + state)).squeeze(2)
73
+ with torch.no_grad():
74
+ state = attention_output + current_time_decay * state
75
+
76
+ return out, state
77
+
78
+ def rwkv6_linear_attention(
79
+ training,
80
+ receptance,
81
+ key,
82
+ value,
83
+ time_decay,
84
+ time_first,
85
+ state,
86
+ ):
87
+ no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, receptance, key, value])
88
+ # Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
89
+ # in this case).
90
+ one_token = key.size(1) == 1
91
+ if not training or no_cuda or one_token:
92
+ return rwkv6_linear_attention_cpu(
93
+ receptance, key, value, time_decay, time_first, state
94
+ )
95
+ else:
96
+ batch, seq_length, _ = receptance.shape
97
+ num_heads, head_size = time_first.shape
98
+ key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, T, H, K -> B, H, T, K
99
+ value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, T, H, K - > B, H, T, V
100
+ receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, H, T, K
101
+ time_decay = -torch.exp(time_decay.float()).view(batch, seq_length, num_heads, head_size).permute(0, 2, 1, 3) # B, T, H, K -> B, H, T, K
102
+ time_first = time_first.float().reshape(num_heads, head_size) # H, K
103
+ out, state = fused_recurrent_rwkv6(receptance, key, value, time_decay, time_first, scale=1.0, initial_state=state, output_final_state=True)
104
+ return out.transpose(1, 2), state
105
+
106
+
107
+ class Rwkv6SelfAttention(nn.Module):
108
+ def __init__(self, config, layer_id=0):
109
+ super().__init__()
110
+ self.config = config
111
+ self.layer_id = layer_id
112
+ hidden_size = config.hidden_size
113
+ attention_hidden_size = config.attention_hidden_size
114
+ self.attention_hidden_size = attention_hidden_size
115
+ head_size = config.head_size
116
+ num_heads = attention_hidden_size // head_size
117
+
118
+ self.time_maa_x = nn.Parameter(torch.empty(1, 1, hidden_size))
119
+ self.time_maa_w = nn.Parameter(torch.empty(1, 1, hidden_size))
120
+ self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
121
+ self.time_maa_v = nn.Parameter(torch.empty(1, 1, hidden_size))
122
+ self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
123
+ self.time_maa_g = nn.Parameter(torch.empty(1, 1, hidden_size))
124
+
125
+ TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
126
+ if hidden_size == 4096: #7b
127
+ TIME_MIX_EXTRA_DIM = 64
128
+ self.time_maa_w1 = nn.Parameter(torch.empty(hidden_size, TIME_MIX_EXTRA_DIM*5))
129
+ self.time_maa_w2 = nn.Parameter(torch.empty(5, TIME_MIX_EXTRA_DIM, hidden_size))
130
+
131
+ self.time_decay = nn.Parameter(torch.empty(1, 1, attention_hidden_size))
132
+
133
+ TIME_DECAY_EXTRA_DIM = 64
134
+ if hidden_size == 4096: #7b
135
+ TIME_DECAY_EXTRA_DIM = 128
136
+ self.time_decay_w1 = nn.Parameter(torch.empty(hidden_size, TIME_DECAY_EXTRA_DIM))
137
+ self.time_decay_w2 = nn.Parameter(torch.empty(TIME_DECAY_EXTRA_DIM, attention_hidden_size))
138
+
139
+ self.time_faaaa = nn.Parameter(torch.empty(num_heads, config.head_size))
140
+
141
+
142
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
143
+ self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
144
+ self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
145
+ self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
146
+ self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
147
+ self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
148
+ self.ln_x = nn.GroupNorm(num_heads, hidden_size, eps=(1e-5)*(config.head_size_divisor**2))
149
+
150
+ def extract_key_value(self, hidden, state=None):
151
+ # Mix hidden with the previous timestep to produce key, value, receptance
152
+ if hidden.size(1) == 1 and state is not None:
153
+ shifted = state[0][:, :, self.layer_id]
154
+ else:
155
+ shifted = self.time_shift(hidden)
156
+ if state is not None:
157
+ shifted[:, 0] = state[0][:, :, self.layer_id]
158
+ if len(shifted.size()) == 2:
159
+ shifted = shifted.unsqueeze(1)
160
+
161
+ x = hidden
162
+
163
+ B, T, C = hidden.shape
164
+
165
+ xx = shifted - x
166
+
167
+ xxx = x + xx * self.time_maa_x
168
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B*T, 5, -1).transpose(0, 1)
169
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
170
+ mw, mk, mv, mr, mg = xxx.unbind(dim=0)
171
+
172
+ time_decay = x + xx * (self.time_maa_w + mw)
173
+ key = x + xx * (self.time_maa_k + mk)
174
+ value = x + xx * (self.time_maa_v + mv)
175
+ receptance = x + xx * (self.time_maa_r + mr)
176
+ gate = x + xx * (self.time_maa_g + mg)
177
+
178
+ receptance = self.receptance(receptance)
179
+ key = self.key(key)
180
+ value = self.value(value)
181
+ gate = F.silu(self.gate(gate))
182
+
183
+ time_decay = torch.tanh(time_decay @ self.time_decay_w1) @ self.time_decay_w2
184
+ time_decay = self.time_decay + time_decay
185
+
186
+ if state is not None:
187
+ state[0][:, :, self.layer_id] = hidden[:, -1]
188
+
189
+ return receptance, key, value, gate, time_decay, state
190
+
191
+ def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
192
+ receptance, key, value, gate, time_decay, state = self.extract_key_value(hidden, state=state)
193
+
194
+ B,T,C = receptance.shape
195
+ H, S = self.time_faaaa.shape
196
+
197
+ layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
198
+ out, layer_state = rwkv6_linear_attention(
199
+ self.training, receptance, key, value, time_decay, self.time_faaaa, layer_state,
200
+ )
201
+
202
+ if layer_state is not None:
203
+ state[1][:, :, :, :, self.layer_id] = layer_state
204
+
205
+ out = out.reshape(B * T, H * S)
206
+ out = F.group_norm(out, num_groups=H, weight=self.ln_x.weight.to(out.dtype), bias=self.ln_x.bias.to(out.dtype), eps=self.ln_x.eps).reshape(B, T, H * S)
207
+ out = out.to(dtype=hidden.dtype) * gate
208
+ out = self.output(out)
209
+ return out, state
210
+
211
+
212
+ class Rwkv6FeedForward(nn.Module):
213
+ def __init__(self, config, layer_id=0):
214
+ super().__init__()
215
+ self.config = config
216
+ self.layer_id = layer_id
217
+ hidden_size = config.hidden_size
218
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
219
+ intermediate_size = (
220
+ config.intermediate_size
221
+ if config.intermediate_size is not None
222
+ else int((config.hidden_size * 3.5) // 32 * 32)
223
+ )
224
+
225
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
226
+ self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
227
+ self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
228
+
229
+ self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
230
+ self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
231
+ self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
232
+
233
+ def forward(self, hidden, state=None):
234
+ if hidden.size(1) == 1 and state is not None:
235
+ shifted = state[2][:, :, self.layer_id]
236
+ else:
237
+ shifted = self.time_shift(hidden)
238
+ if state is not None:
239
+ shifted[:, 0] = state[2][:, :, self.layer_id]
240
+ if len(shifted.size()) == 2:
241
+ shifted = shifted.unsqueeze(1)
242
+
243
+ delta_hidden_to_shifted = shifted - hidden
244
+ key = hidden + delta_hidden_to_shifted * self.time_maa_k
245
+ receptance = hidden + delta_hidden_to_shifted * self.time_maa_r
246
+
247
+ key = torch.square(torch.relu(self.key(key)))
248
+ value = self.value(key)
249
+ receptance = torch.sigmoid(self.receptance(receptance))
250
+
251
+ if state is not None:
252
+ state[2][:, :, self.layer_id] = hidden[:, -1]
253
+
254
+ return receptance * value, state
255
+
256
+
257
+ class Rwkv6Block(nn.Module):
258
+ def __init__(self, config, layer_id):
259
+ super().__init__()
260
+ self.config = config
261
+ self.layer_id = layer_id
262
+
263
+ if layer_id == 0:
264
+ self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
265
+
266
+ self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
267
+ self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
268
+
269
+ self.attention = Rwkv6SelfAttention(config, layer_id)
270
+ self.feed_forward = Rwkv6FeedForward(config, layer_id)
271
+
272
+ def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
273
+ if self.layer_id == 0:
274
+ hidden = self.pre_ln(hidden)
275
+ attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
276
+ hidden = hidden + attention
277
+
278
+ feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
279
+ hidden = hidden + feed_forward
280
+
281
+ outputs = (hidden, state)
282
+ if output_attentions:
283
+ outputs += (attention,)
284
+ else:
285
+ outputs += (None,)
286
+
287
+ return outputs
288
+
289
+
290
+ class Rwkv6PreTrainedModel(PreTrainedModel):
291
+ """
292
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
293
+ models.
294
+ """
295
+
296
+ config_class = Rwkv6Config
297
+ base_model_prefix = "rwkv6"
298
+ _no_split_modules = ["Rwkv6Block"]
299
+ _keep_in_fp32_modules = ["time_decay", "time_first"]
300
+ supports_gradient_checkpointing = True
301
+
302
+ def _init_weights(self, module):
303
+ """Initialize the weights."""
304
+ if isinstance(module, Rwkv6SelfAttention):
305
+ layer_id = module.layer_id
306
+ num_hidden_layers = module.config.num_hidden_layers
307
+ hidden_size = module.config.hidden_size
308
+ attention_hidden_size = module.attention_hidden_size
309
+ head_size = module.config.head_size
310
+ num_heads = attention_hidden_size // head_size
311
+
312
+ ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
313
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
314
+
315
+ time_weight = torch.tensor(
316
+ [i / hidden_size for i in range(hidden_size)],
317
+ dtype=module.time_maa_k.dtype,
318
+ device=module.time_maa_k.device,
319
+ )
320
+ time_weight = time_weight[None, None, :]
321
+
322
+ decay_speed = [
323
+ -6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
324
+ for h in range(attention_hidden_size)
325
+ ]
326
+ decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
327
+ tmp = torch.tensor(
328
+ [
329
+ (1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
330
+ for i in range(attention_hidden_size)
331
+ ],
332
+ dtype=module.time_faaaa.dtype,
333
+ device=module.time_faaaa.device,
334
+ )
335
+
336
+ with torch.no_grad():
337
+ module.time_maa_x.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
338
+ module.time_maa_w.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
339
+ module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
340
+ module.time_maa_v.data = 1.0 - (torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
341
+ module.time_maa_r.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
342
+ module.time_maa_g.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
343
+
344
+ TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
345
+ module.time_maa_w1.data = torch.zeros(hidden_size, TIME_MIX_EXTRA_DIM*5, dtype=module.time_maa_w1.dtype, device=module.time_maa_w1.device).uniform_(-1e-4, 1e-4)
346
+ module.time_maa_w2.data = torch.zeros(5, TIME_MIX_EXTRA_DIM, hidden_size, dtype=module.time_maa_w2.dtype, device=module.time_maa_w2.device).uniform_(-1e-4, 1e-4)
347
+
348
+ TIME_DECAY_EXTRA_DIM = 64
349
+ module.time_decay_w1.data = torch.zeros(hidden_size, TIME_DECAY_EXTRA_DIM, dtype=module.time_decay_w1.dtype, device=module.time_decay_w1.device).uniform_(-1e-4, 1e-4)
350
+ module.time_decay_w2.data = torch.zeros(TIME_DECAY_EXTRA_DIM, attention_hidden_size, dtype=module.time_decay_w2.dtype, device=module.time_decay_w2.device).uniform_(-1e-4, 1e-4)
351
+
352
+ module.time_decay.data = decay_speed.reshape(num_heads, head_size)
353
+ module.time_faaaa.data = tmp.reshape(num_heads, head_size)
354
+
355
+ elif isinstance(module, Rwkv6FeedForward):
356
+ layer_id = module.layer_id
357
+ num_hidden_layers = module.config.num_hidden_layers
358
+ hidden_size = module.config.hidden_size
359
+
360
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
361
+
362
+ time_weight = torch.tensor(
363
+ [i / hidden_size for i in range(hidden_size)],
364
+ dtype=module.time_maa_k.dtype,
365
+ device=module.time_maa_k.device,
366
+ )
367
+ time_weight = time_weight[None, None, :]
368
+
369
+ with torch.no_grad():
370
+ module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
371
+ module.time_maa_r.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
372
+
373
+
374
+ @dataclass
375
+ class Rwkv6Output(ModelOutput):
376
+ """
377
+ Class for the RWKV model outputs.
378
+
379
+ Args:
380
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
381
+ Sequence of hidden-states at the output of the last layer of the model.
382
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
383
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
384
+ avoid providing the old `input_ids`.
385
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
386
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
387
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
388
+ the model at the output of each layer plus the optional initial embedding outputs.
389
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
390
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
391
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
392
+ the self-attention heads.
393
+ """
394
+
395
+ last_hidden_state: torch.FloatTensor = None
396
+ state: Optional[List[torch.FloatTensor]] = None
397
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
398
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
399
+
400
+
401
+ @dataclass
402
+ class Rwkv6CausalLMOutput(ModelOutput):
403
+ """
404
+ Base class for causal language model (or autoregressive) outputs.
405
+
406
+ Args:
407
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
408
+ Language modeling loss (for next-token prediction).
409
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
410
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
411
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
412
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
413
+ avoid providing the old `input_ids`.
414
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
415
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
416
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
417
+ the model at the output of each layer plus the optional initial embedding outputs.
418
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
419
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
420
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
421
+ the self-attention heads.
422
+ """
423
+
424
+ loss: Optional[torch.FloatTensor] = None
425
+ logits: torch.FloatTensor = None
426
+ state: Optional[List[torch.FloatTensor]] = None
427
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
428
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
429
+
430
+
431
+ RWKV6_START_DOCSTRING = r"""
432
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
433
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
434
+ etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
435
+ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
436
+ general usage and behavior.
437
+
438
+ Parameters:
439
+ config ([`Rwkv6Config`]): Model configuration class with all the parameters of the model.
440
+ Initializing with a config file does not load the weights associated with the model, only the
441
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
442
+ """
443
+
444
+ RWKV6_INPUTS_DOCSTRING = r"""
445
+ Args:
446
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
447
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
448
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
449
+ sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
450
+ past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
451
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
452
+ IDs?](../glossary#input-ids)
453
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
454
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
455
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
456
+ model's internal embedding lookup matrix.
457
+ state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
458
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
459
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
460
+ use_cache (`bool`, *optional*):
461
+ If set to `True`, the last state is returned and can be used to quickly generate the next logits.
462
+ output_attentions (`bool`, *optional*):
463
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
464
+ tensors for more detail.
465
+ output_hidden_states (`bool`, *optional*):
466
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
467
+ more detail.
468
+ return_dict (`bool`, *optional*):
469
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
470
+ """
471
+
472
+
473
+ @add_start_docstrings(
474
+ "The bare RWKV6 Model transformer outputting raw hidden-states without any specific head on top.",
475
+ RWKV6_START_DOCSTRING,
476
+ )
477
+ class Rwkv6Model(Rwkv6PreTrainedModel):
478
+ def __init__(self, config):
479
+ super().__init__(config)
480
+
481
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
482
+ self.blocks = nn.ModuleList([Rwkv6Block(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
483
+ self.ln_out = nn.LayerNorm(config.hidden_size)
484
+
485
+ self.layers_are_rescaled = False
486
+ self.gradient_checkpointing = False
487
+
488
+ # Initialize weights and apply final processing
489
+ self.post_init()
490
+
491
+ def get_input_embeddings(self):
492
+ return self.embeddings
493
+
494
+ def set_input_embeddings(self, new_embeddings):
495
+ self.embeddings = new_embeddings
496
+
497
+ @add_start_docstrings_to_model_forward(RWKV6_INPUTS_DOCSTRING)
498
+ @add_code_sample_docstrings(
499
+ checkpoint=_CHECKPOINT_FOR_DOC,
500
+ output_type=Rwkv6Output,
501
+ config_class=_CONFIG_FOR_DOC,
502
+ )
503
+ def forward(
504
+ self,
505
+ input_ids: Optional[torch.LongTensor] = None,
506
+ attention_mask: Optional[torch.LongTensor] = None, # noqa
507
+ inputs_embeds: Optional[torch.FloatTensor] = None,
508
+ state: Optional[List[torch.FloatTensor]] = None,
509
+ use_cache: Optional[bool] = None,
510
+ output_attentions: Optional[bool] = None,
511
+ output_hidden_states: Optional[bool] = None,
512
+ return_dict: Optional[bool] = None,
513
+ ) -> Union[Tuple, Rwkv6Output]:
514
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
515
+ output_hidden_states = (
516
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
517
+ )
518
+ # FIXME - training is supportable with the CUDA code
519
+ # rwkv6 only support inference in huggingface.
520
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
521
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
522
+
523
+ if self.training == self.layers_are_rescaled and (
524
+ self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
525
+ ):
526
+ self._rescale_layers()
527
+
528
+ if input_ids is not None and inputs_embeds is not None:
529
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
530
+ elif input_ids is None and inputs_embeds is None:
531
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
532
+
533
+ if inputs_embeds is None:
534
+ inputs_embeds = self.embeddings(input_ids)
535
+
536
+ if state is None:
537
+ state = []
538
+ head_size = self.config.head_size
539
+ num_heads = self.config.attention_hidden_size // head_size
540
+ state_attn_x = torch.zeros(
541
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
542
+ dtype=inputs_embeds.dtype,
543
+ requires_grad=False,
544
+ device=inputs_embeds.device,
545
+ ).contiguous()
546
+ state_attn_kv = torch.zeros(
547
+ (
548
+ inputs_embeds.size(0),
549
+ num_heads,
550
+ head_size,
551
+ head_size,
552
+ self.config.num_hidden_layers,
553
+ ),
554
+ dtype=torch.float32,
555
+ requires_grad=False,
556
+ device=inputs_embeds.device,
557
+ ).contiguous()
558
+ state_ffn_x = torch.zeros(
559
+ (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
560
+ dtype=inputs_embeds.dtype,
561
+ requires_grad=False,
562
+ device=inputs_embeds.device,
563
+ ).contiguous()
564
+ state.append(state_attn_x)
565
+ state.append(state_attn_kv)
566
+ state.append(state_ffn_x)
567
+
568
+ seq_mode = inputs_embeds.shape[1] > 1
569
+ hidden_states = inputs_embeds
570
+
571
+ all_self_attentions = () if output_attentions else None
572
+ all_hidden_states = () if output_hidden_states else None
573
+ for idx, block in enumerate(self.blocks):
574
+ hidden_states, state, attentions = block(
575
+ hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
576
+ )
577
+ if (
578
+ self.layers_are_rescaled
579
+ and self.config.rescale_every > 0
580
+ and (idx + 1) % self.config.rescale_every == 0
581
+ ):
582
+ hidden_states = hidden_states / 2
583
+
584
+ if output_hidden_states:
585
+ all_hidden_states = all_hidden_states + (hidden_states,)
586
+
587
+ if output_attentions:
588
+ all_self_attentions = all_self_attentions + (attentions,)
589
+
590
+ hidden_states = self.ln_out(hidden_states)
591
+
592
+ if output_hidden_states:
593
+ all_hidden_states = all_hidden_states + (hidden_states,)
594
+
595
+ if not return_dict:
596
+ return (hidden_states, state, all_hidden_states, all_self_attentions)
597
+
598
+ return Rwkv6Output(
599
+ last_hidden_state=hidden_states,
600
+ state=state,
601
+ hidden_states=all_hidden_states, # None
602
+ attentions=all_self_attentions, # None
603
+ )
604
+
605
+ def _rescale_layers(self):
606
+ # Layers should be rescaled for inference only.
607
+ if self.layers_are_rescaled == (not self.training):
608
+ return
609
+ if self.config.rescale_every > 0:
610
+ with torch.no_grad():
611
+ for block_id, block in enumerate(self.blocks):
612
+ if self.training:
613
+ block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
614
+ block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
615
+ else:
616
+ # Deal with quantization statistics
617
+ if hasattr(block.attention.output.weight, "SCB"):
618
+ block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
619
+ block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
620
+ elif hasattr(block.attention.output.weight, "quant_state"):
621
+ self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
622
+ self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
623
+ else:
624
+ block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
625
+ block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
626
+
627
+ self.layers_are_rescaled = not self.training
628
+
629
+ def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
630
+ r"""
631
+ Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
632
+ be quantized again.
633
+ """
634
+ if not is_bitsandbytes_available():
635
+ raise ImportError("Please install bitsandbytes to use this method.")
636
+ import bitsandbytes as bnb
637
+
638
+ dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
639
+
640
+ dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
641
+
642
+ # re-quantize the model:
643
+ # we need to put it first on CPU then back to the device
644
+ # this will create an overhead :/
645
+ # We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
646
+ # bugs with bnb
647
+ quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
648
+ setattr(target_layer, "weight", quant_weight)
649
+
650
+
651
+ # copied from HuggingFace https://github.com/huggingface/transformers/blob/main/src/transformers/models/rwkv/modeling_rwkv.py
652
+ @add_start_docstrings(
653
+ """
654
+ The RWKV6 Model transformer with a language modeling head on top (linear layer with weights tied to the input
655
+ embeddings).
656
+ """,
657
+ RWKV6_START_DOCSTRING,
658
+ )
659
+ class Rwkv6ForCausalLM(Rwkv6PreTrainedModel):
660
+ _tied_weights_keys = ["head.weight"]
661
+
662
+ def __init__(self, config):
663
+ super().__init__(config)
664
+ self.rwkv = Rwkv6Model(config)
665
+ self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
666
+
667
+ # Initialize weights and apply final processing
668
+ self.post_init()
669
+
670
+ def get_output_embeddings(self):
671
+ return self.head
672
+
673
+ def set_output_embeddings(self, new_embeddings):
674
+ self.head = new_embeddings
675
+
676
+ def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
677
+ # only last token for inputs_ids if the state is passed along.
678
+ if state is not None:
679
+ input_ids = input_ids[:, -1].unsqueeze(-1)
680
+
681
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
682
+ if inputs_embeds is not None and state is None:
683
+ model_inputs = {"inputs_embeds": inputs_embeds}
684
+ else:
685
+ model_inputs = {"input_ids": input_ids}
686
+
687
+ model_inputs["state"] = state
688
+ return model_inputs
689
+
690
+ @add_start_docstrings_to_model_forward(RWKV6_INPUTS_DOCSTRING)
691
+ @add_code_sample_docstrings(
692
+ checkpoint=_CHECKPOINT_FOR_DOC,
693
+ output_type=Rwkv6CausalLMOutput,
694
+ config_class=_CONFIG_FOR_DOC,
695
+ )
696
+ def forward(
697
+ self,
698
+ input_ids: Optional[torch.LongTensor] = None,
699
+ attention_mask: Optional[torch.LongTensor] = None,
700
+ inputs_embeds: Optional[torch.FloatTensor] = None,
701
+ state: Optional[List[torch.FloatTensor]] = None,
702
+ labels: Optional[torch.LongTensor] = None,
703
+ use_cache: Optional[bool] = None,
704
+ output_attentions: Optional[bool] = None,
705
+ output_hidden_states: Optional[bool] = None,
706
+ return_dict: Optional[bool] = None,
707
+ ) -> Union[Tuple, Rwkv6CausalLMOutput]:
708
+ r"""
709
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
710
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
711
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
712
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
713
+ """
714
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
715
+
716
+ outputs = self.rwkv(
717
+ input_ids,
718
+ inputs_embeds=inputs_embeds,
719
+ state=state,
720
+ use_cache=use_cache,
721
+ output_attentions=output_attentions,
722
+ output_hidden_states=output_hidden_states,
723
+ return_dict=return_dict,
724
+ )
725
+ hidden_states = outputs[0]
726
+
727
+ logits = self.head(hidden_states)
728
+
729
+ loss = None
730
+ if labels is not None:
731
+ # move labels to correct device to enable model parallelism
732
+ labels = labels.to(logits.device)
733
+ # Shift so that tokens < n predict n
734
+ shift_logits = logits[..., :-1, :].contiguous()
735
+ shift_labels = labels[..., 1:].contiguous()
736
+ # Flatten the tokens
737
+ loss_fct = CrossEntropyLoss()
738
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
739
+
740
+ if not return_dict:
741
+ output = (logits,) + outputs[1:]
742
+ return ((loss,) + output) if loss is not None else output
743
+
744
+ return Rwkv6CausalLMOutput(
745
+ loss=loss,
746
+ logits=logits,
747
+ state=outputs.state,
748
+ hidden_states=outputs.hidden_states,
749
+ attentions=outputs.attentions,
750
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "eos_token": "<s>",
4
+ "unk_token": "<s>"
5
+ }
tokenization_rwkv5.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import re
19
+ from typing import TYPE_CHECKING, List, Optional, Tuple
20
+
21
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
22
+ from transformers.utils import logging
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ pass
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ 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
+ def whitespace_tokenize(text):
41
+ """Runs basic whitespace cleaning and splitting on a piece of text.
42
+ The separators are kept
43
+ """
44
+ text = text.strip()
45
+ if not text:
46
+ return []
47
+ tokens = re.split(b"(?= )", text)
48
+ return tokens
49
+
50
+
51
+ class WordpieceTokenizer(object):
52
+ """Runs WordPiece tokenization."""
53
+
54
+ def __init__(self, vocab, unk_token):
55
+ self.vocab = vocab
56
+ self.unk_token = unk_token
57
+
58
+ def tokenize(self, text):
59
+ """
60
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
61
+ tokenization using the given vocabulary.
62
+
63
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
64
+
65
+ Args:
66
+ text: A single token or whitespace separated tokens. This should have
67
+ already been passed through *BasicTokenizer*.
68
+
69
+ Returns:
70
+ A list of wordpiece tokens.
71
+ """
72
+
73
+ output_tokens = []
74
+ for token in whitespace_tokenize(text):
75
+ chars = list(token)
76
+ is_bad = False
77
+ start = 0
78
+ sub_tokens = []
79
+ while start < len(chars):
80
+ end = len(chars)
81
+ cur_substr = None
82
+ while start < end:
83
+ substr = bytes(chars[start:end])
84
+ if substr in self.vocab:
85
+ cur_substr = substr
86
+ break
87
+ end -= 1
88
+ if cur_substr is None:
89
+ is_bad = True
90
+ break
91
+ try:
92
+ cur_substr = cur_substr.decode()
93
+ except UnicodeDecodeError:
94
+ cur_substr = str(cur_substr)
95
+ sub_tokens.append(cur_substr)
96
+ start = end
97
+ if is_bad:
98
+ output_tokens.append(self.unk_token)
99
+ else:
100
+ output_tokens.extend(sub_tokens)
101
+ return output_tokens
102
+
103
+
104
+ class Rwkv5Tokenizer(PreTrainedTokenizer):
105
+ vocab_files_names = VOCAB_FILES_NAMES
106
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
107
+ max_model_input_sizes = {"ArthurZ/rwkv-5-utf": 2048}
108
+
109
+ model_input_names = ["input_ids", "attention_mask"]
110
+
111
+ def __init__(self, vocab_file, bos_token="<s>", eos_token="<s>", unk_token="<s>", **kwargs):
112
+ if not os.path.isfile(vocab_file):
113
+ raise ValueError(
114
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
115
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
116
+ )
117
+
118
+ with open(vocab_file, "r") as reader:
119
+ tokens = reader.readlines()
120
+ vocab = {}
121
+ for index, token in enumerate(tokens):
122
+ token = eval(token.rstrip("\n"))
123
+ vocab[token] = index
124
+
125
+ self.add_bos_token = True
126
+ self.encoder = vocab
127
+ self.decoder = {v: k for k, v in vocab.items()}
128
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.encoder, unk_token=str(unk_token))
129
+ self._added_tokens_decoder = {0: AddedToken(str(bos_token))}
130
+ super().__init__(bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, **kwargs)
131
+
132
+ @property
133
+ def vocab_size(self):
134
+ return len(self.encoder)
135
+
136
+ def get_vocab(self):
137
+ vocab = {str(self.convert_ids_to_tokens(i)): i for i in range(self.vocab_size)}
138
+ vocab.update(self.added_tokens_encoder)
139
+ return vocab
140
+
141
+ def _tokenize(self, text, split_special_tokens=False):
142
+ return self.wordpiece_tokenizer.tokenize(text.encode("utf-8"))
143
+
144
+ def _convert_token_to_id(self, token):
145
+ """Converts a token (byte) to an id using the vocab."""
146
+ if token.startswith("b'\\"):
147
+ token = eval(token)
148
+ elif not isinstance(token, bytes):
149
+ token = token.encode("utf-8", errors="replace")
150
+ return self.encoder.get(token, self.unk_token_id)
151
+
152
+ def _convert_id_to_token(self, index):
153
+ """Converts an index (integer) in a token (byte) using the vocab."""
154
+ token = self.decoder.get(index, self.unk_token)
155
+ if isinstance(token, (bytes)):
156
+ token = token.decode("utf-8", errors="replace")
157
+ return token
158
+
159
+ def convert_tokens_to_string(self, tokens):
160
+ """Converts a sequence of tokens (bytes) in a single string. Additional tokens are encoded to bytes"""
161
+ out_string = b"".join([k.encode(errors="replace") if isinstance(k, str) else k for k in tokens]).decode(
162
+ "utf-8"
163
+ )
164
+ return out_string
165
+
166
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
167
+ index = 0
168
+ if os.path.isdir(save_directory):
169
+ vocab_file = os.path.join(
170
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
171
+ )
172
+ else:
173
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
174
+ with open(vocab_file, "w") as writer:
175
+ for token, token_index in sorted(self.encoder.items(), key=lambda kv: kv[1]):
176
+ if index != token_index:
177
+ logger.warning(
178
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
179
+ " Please check that the vocabulary is not corrupted!"
180
+ )
181
+ index = token_index
182
+ writer.write(str(token) + "\n")
183
+ index += 1
184
+ return (vocab_file,)
185
+
186
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
187
+ if self.add_bos_token:
188
+ bos_token_ids = [self.bos_token_id]
189
+ else:
190
+ bos_token_ids = []
191
+
192
+ output = bos_token_ids + token_ids_0
193
+
194
+ if token_ids_1 is None:
195
+ return output
196
+
197
+ return output + bos_token_ids + token_ids_1
198
+
199
+ def get_special_tokens_mask(
200
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
201
+ ) -> List[int]:
202
+ """
203
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
204
+ special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
205
+
206
+ Args:
207
+ token_ids_0 (`List[int]`):
208
+ List of IDs.
209
+ token_ids_1 (`List[int]`, *optional*):
210
+ Optional second list of IDs for sequence pairs.
211
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
212
+ Whether or not the token list is already formatted with special tokens for the model.
213
+
214
+ Returns:
215
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
216
+ """
217
+ if already_has_special_tokens:
218
+ return super().get_special_tokens_mask(
219
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
220
+ )
221
+
222
+ if not self.add_bos_token:
223
+ return super().get_special_tokens_mask(
224
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
225
+ )
226
+
227
+ if token_ids_1 is None:
228
+ return [1] + ([0] * len(token_ids_0))
229
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
tokenizer_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name_or_path": "rwkv-5-tokenizer",
3
+ "add_prefix_space": false,
4
+ "tokenizer_class": "Rwkv5Tokenizer",
5
+ "use_fast": false,
6
+ "auto_map": {
7
+ "AutoTokenizer": [
8
+ "tokenization_rwkv5.Rwkv5Tokenizer",
9
+ null
10
+ ]
11
+ }
12
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff