BBuf commited on
Commit
235518c
·
1 Parent(s): fa0f7db

Upload 11 files

Browse files
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("RWKV/rwkv-5-world-1b5", trust_remote_code=True).to(0)
34
+ tokenizer = AutoTokenizer.from_pretrained("RWKV/rwkv-5-world-1b5", 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,795 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import math
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ import torch.nn.functional as F
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
+ from .configuration_rwkv5 import Rwkv5Config
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CHECKPOINT_FOR_DOC = "RWKV/rwkv-5-world"
42
+ _CONFIG_FOR_DOC = "Rwkv5Config"
43
+
44
+ RWKV_PRETRAINED_MODEL_ARCHIVE_LIST = [
45
+
46
+ ]
47
+
48
+ rwkv5_cuda_kernel = None
49
+
50
+ def load_wkv5_cuda_kernel(config):
51
+ global rwkv5_cuda_kernel
52
+ if config.model_version == "5_2" and torch.cuda.is_available():
53
+ HEAD_SIZE = args.attention_hidden_size // args.head_size
54
+ module_root = pathlib.Path(__file__).parent
55
+ rwkv5_cuda_kernel = load(name="rwkv5", sources=[f"{module_root}/rwkv5_op.cpp", f"{module_root}/rwkv5.cu"],
56
+ verbose=True, extra_cuda_cflags=["-res-usage", "--use_fast_math", "-O3", "-Xptxas -O3" if os.name != "nt" else "", "--extra-device-vectorization", f"-D_N_={HEAD_SIZE}"])
57
+
58
+ class RWKV_5(torch.autograd.Function):
59
+ @staticmethod
60
+ def forward(ctx, B, T, C, H, state, r, k, v, w, u):
61
+ with torch.no_grad():
62
+ assert HEAD_SIZE == C // H
63
+ ctx.B = B
64
+ ctx.T = T
65
+ ctx.C = C
66
+ ctx.H = H
67
+ assert state.dtype == torch.float32
68
+ assert w.dtype == torch.float32
69
+ assert r.is_contiguous()
70
+ assert k.is_contiguous()
71
+ assert v.is_contiguous()
72
+ assert w.is_contiguous()
73
+ assert u.is_contiguous()
74
+ assert state.is_contiguous()
75
+
76
+ y = torch.empty((B, T, C), device=w.device, dtype=r.dtype, memory_format=torch.contiguous_format)
77
+ if r.dtype == torch.bfloat16:
78
+ rwkv5_cuda_kernel.forward_bf16(B, T, C, H, state, r, k, v, w, u, y)
79
+ elif r.dtype == torch.float16:
80
+ rwkv5_cuda_kernel.forward_fp16(B, T, C, H, state, r, k, v, w, u, y)
81
+ elif r.dtype == torch.float32:
82
+ rwkv5_cuda_kernel.forward_fp32(B, T, C, H, state, r, k, v, w, u, y)
83
+ return y, state
84
+
85
+ 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):
86
+ time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1,1,1)
87
+ time_first = torch.exp(time_first.float()).reshape(-1,1,1)
88
+ lxw = lxw.float()
89
+ lxb = lxb.float()
90
+
91
+ if seq_mode:
92
+ w = time_decay.reshape(-1, 1)
93
+ u = time_first.reshape(-1, 1)
94
+ ws = w.pow(T).reshape(H, 1, 1)
95
+ ind = torch.arange(T-1, -1, -1, device=w.device).unsqueeze(0).repeat(H, 1)
96
+ w = w.repeat(1, T).pow(ind)
97
+ wk = w.reshape(H, 1, T)
98
+ wb = wk.transpose(-2, -1).flip(1)
99
+ w = torch.cat([w[:, 1:], u], dim=1)
100
+ w = F.pad(w, (0, T))
101
+ w = torch.tile(w, [T])
102
+ w = w[:, :-T].reshape(-1, T, 2 * T - 1)
103
+ w = w[:, :, T-1:].reshape(H, T, T)
104
+ out = ((receptance @ key) * w) @ value + (receptance @ state) * wb
105
+ state = ws * state + (key * wk) @ value
106
+
107
+ out = out.transpose(1, 2).contiguous().reshape(T, H*S)
108
+ out = F.group_norm(out, num_groups=H, weight=lxw, bias=lxb)
109
+ out = out.to(dtype=hidden.dtype)
110
+ out = out @ ow
111
+ else:
112
+ a = key @ value
113
+ out = receptance @ (time_first * a + state)
114
+ state = a + time_decay * state
115
+ out = out.flatten()
116
+ out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lxw, bias=lxb)
117
+ out = out.to(dtype=hidden.dtype)
118
+ out = out @ ow
119
+
120
+ return out, state
121
+
122
+ def rwkv_linear_attention_v5_2_cpu(H, S, T, n_head, hidden, time_decay, time_first, receptance, key, value, gate, lxw, lxb, ow, state, return_state=False, seq_mode=True):
123
+ time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1,1,1).reshape(n_head, -1, 1)
124
+ time_first = time_first.float().reshape(-1,1,1).reshape(n_head, -1, 1)
125
+ lxw = lxw.float()
126
+ lxb = lxb.float()
127
+ if seq_mode:
128
+ out = torch.empty((T, H, S), dtype=receptance.dtype, device=receptance.device)
129
+ for t in range(T):
130
+ rt = receptance[:,t:t+1,:]
131
+ kt = key[:,:,t:t+1]
132
+ vt = value[:,t:t+1,:]
133
+ at = kt @ vt
134
+ out[t] = (rt @ (time_first * at + state.squeeze(0))).squeeze(1)
135
+ state = at + time_decay * state
136
+
137
+ out = out.reshape(T, H*S)
138
+ out = F.group_norm(out, num_groups=H, weight=lxw, bias=lxb)
139
+ out = out.to(dtype=hidden.dtype) * gate
140
+ out = out @ ow
141
+ else:
142
+ a = key @ value
143
+ out = receptance @ (time_first * a + state.squeeze(0))
144
+ state = a + time_decay * state
145
+ out = out.flatten()
146
+ out = F.group_norm(out.unsqueeze(0), num_groups=H, weight=lxw, bias=lxb).squeeze(0)
147
+ out = out.to(dtype=hidden.dtype) * gate
148
+ out = out @ ow
149
+
150
+ return out, state
151
+ class RwkvSelfAttention(nn.Module):
152
+ def __init__(self, config, layer_id=0):
153
+ super().__init__()
154
+ self.config = config
155
+ self.layer_id = layer_id
156
+ kernel_loaded = rwkv5_cuda_kernel is not None
157
+ if torch.cuda.is_available() and not kernel_loaded:
158
+ try:
159
+ load_wkv5_cuda_kernel(config)
160
+ except Exception:
161
+ logger.info("Could not load the custom CUDA kernel for RWKV5 attention.")
162
+ self.hidden_size = config.hidden_size
163
+ # https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v4neo/src/model.py#L146
164
+ num_attention_heads = self.hidden_size // config.head_size
165
+ self.num_attention_heads = num_attention_heads
166
+ attention_hidden_size = (
167
+ config.attention_hidden_size if config.attention_hidden_size is not None else self.hidden_size
168
+ )
169
+ self.attention_hidden_size = attention_hidden_size
170
+
171
+ if self.config.model_version == "5_2":
172
+ self.time_decay = nn.Parameter(torch.empty(num_attention_heads, config.head_size))
173
+ self.time_faaaa = nn.Parameter(torch.empty(num_attention_heads, config.head_size))
174
+ self.time_mix_gate = nn.Parameter(torch.empty(1, 1, self.hidden_size))
175
+ else:
176
+ self.time_decay = nn.Parameter(torch.empty(num_attention_heads))
177
+ self.time_first = nn.Parameter(torch.empty(num_attention_heads))
178
+
179
+ self.time_mix_key = nn.Parameter(torch.empty(1, 1, self.hidden_size))
180
+ self.time_mix_value = nn.Parameter(torch.empty(1, 1, self.hidden_size))
181
+ self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, self.hidden_size))
182
+
183
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
184
+ self.key = nn.Linear(self.hidden_size, attention_hidden_size, bias=False)
185
+ self.value = nn.Linear(self.hidden_size, attention_hidden_size, bias=False)
186
+ self.receptance = nn.Linear(self.hidden_size, attention_hidden_size, bias=False)
187
+ if self.config.model_version == "5_2":
188
+ self.gate = nn.Linear(self.hidden_size, attention_hidden_size, bias=False)
189
+ self.output = nn.Linear(attention_hidden_size, self.hidden_size, bias=False)
190
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/src/model.py#L190C1-L190C1
191
+ self.ln_x = nn.GroupNorm(self.hidden_size // config.head_size, self.hidden_size)
192
+
193
+ # TODO: maybe jit, otherwise move inside forward
194
+ def extract_key_value(self, H, S, T, hidden, state=None):
195
+ # Mix hidden with the previous timestep to produce key, value, receptance
196
+ if hidden.size(1) == 1 and state is not None:
197
+ shifted = state[0][:, :, self.layer_id]
198
+ else:
199
+ shifted = self.time_shift(hidden)
200
+ if state is not None:
201
+ shifted[:, 0] = state[0][:, :, self.layer_id]
202
+ key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
203
+ value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
204
+ receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
205
+ if self.config.model_version == "5_2":
206
+ gate = hidden* self.time_mix_gate + shifted * (1 - self.time_mix_gate)
207
+ gate = F.silu(self.gate(gate))
208
+
209
+ if rwkv5_cuda_kernel is None:
210
+ if hidden.size(1) == 1 and state is not None:
211
+ receptance = self.receptance(receptance).to(torch.float32).view(H, 1, S)
212
+ key = self.key(key).to(torch.float32).view(H, S, 1)
213
+ value = self.value(value).to(torch.float32).view(H, 1, S)
214
+ else:
215
+ # https://github.com/BlinkDL/ChatRWKV/blob/main/rwkv_pip_package/src/rwkv/model.py#L693
216
+ key = self.key(key).to(torch.float32).view(T, H, S).transpose(0, 1).transpose(-2, -1)
217
+ value = self.value(value).to(torch.float32).view(T, H, S).transpose(0, 1)
218
+ receptance = self.receptance(receptance).to(torch.float32).view(T, H, S).transpose(0, 1)
219
+
220
+ if state is not None:
221
+ state[0][:, :, self.layer_id] = hidden[:, -1]
222
+
223
+ if self.config.model_version == "5_2":
224
+ return receptance, key, value, gate, state
225
+ return receptance, key, value, state
226
+
227
+ def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
228
+ H = self.time_decay.shape[0]
229
+ S = hidden.shape[-1] // H
230
+ T = hidden.shape[1]
231
+
232
+ if self.config.model_version == "5_2":
233
+ receptance, key, value, gate, state = self.extract_key_value(H, S, T, hidden, state=state)
234
+ else:
235
+ receptance, key, value, state = self.extract_key_value(H, S, T, hidden, state=state)
236
+ layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
237
+ if self.config.model_version == "5_2":
238
+ if rwkv5_cuda_kernel is not None and seq_mode:
239
+ rwkv, layer_state = RWKV_5.apply(1, T, self.hidden_size, H, layer_state.transpose(-1, -2).contiguous(),
240
+ receptance, key, value, self.time_decay, self.time_faaaa,)
241
+ layer_state = layer_state.transpose(-1,-2)
242
+ rwkv = rwkv.reshape(T, H*N)
243
+ rwkv = F.group_norm(rwkv, num_groups=H, weight=self.ln_x.weight, bias=self.ln_x.bias)
244
+ rwkv = rwkv.to(dtype=hidden.dtype) * gate
245
+ rwkv = rwkv @ self.output.weight.t()
246
+ else:
247
+ rwkv, layer_state = rwkv_linear_attention_v5_2_cpu(
248
+ H,
249
+ S,
250
+ T,
251
+ self.num_attention_heads,
252
+ hidden,
253
+ self.time_decay,
254
+ self.time_faaaa,
255
+ receptance,
256
+ key,
257
+ value,
258
+ gate,
259
+ self.ln_x.weight,
260
+ self.ln_x.bias,
261
+ self.output.weight.t(),
262
+ state=layer_state,
263
+ return_state=use_cache,
264
+ seq_mode=seq_mode,
265
+ )
266
+ else:
267
+ rwkv, layer_state = rwkv_linear_attention_v5_0(
268
+ H,
269
+ S,
270
+ T,
271
+ hidden,
272
+ self.time_decay,
273
+ self.time_first,
274
+ receptance,
275
+ key,
276
+ value,
277
+ self.ln_x.weight,
278
+ self.ln_x.bias,
279
+ self.output.weight.t(),
280
+ state=layer_state,
281
+ return_state=use_cache,
282
+ seq_mode=seq_mode,
283
+ )
284
+
285
+ if layer_state is not None:
286
+ state[1][:, :, :, :, self.layer_id] = layer_state
287
+
288
+ return rwkv, state
289
+
290
+
291
+ class RwkvFeedForward(nn.Module):
292
+ def __init__(self, config, layer_id=0):
293
+ super().__init__()
294
+ self.config = config
295
+ self.layer_id = layer_id
296
+ hidden_size = config.hidden_size
297
+ # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
298
+ if self.config.model_version == "5_2":
299
+ intermediate_size = (
300
+ config.intermediate_size if config.intermediate_size is not None else int((config.hidden_size * 3.5) // 32 * 32)
301
+ )
302
+ else:
303
+ intermediate_size = (
304
+ config.intermediate_size if config.intermediate_size is not None else 4 * config.hidden_size
305
+ )
306
+
307
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
308
+ self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
309
+ self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
310
+
311
+ self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
312
+ self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
313
+ self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
314
+
315
+ def forward(self, hidden, state=None):
316
+ if hidden.size(1) == 1 and state is not None:
317
+ shifted = state[2][:, :, self.layer_id]
318
+ else:
319
+ shifted = self.time_shift(hidden)
320
+ if state is not None:
321
+ shifted[:, 0] = state[2][:, :, self.layer_id]
322
+ key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
323
+ receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
324
+
325
+ key = torch.square(torch.relu(self.key(key)))
326
+ value = self.value(key)
327
+ receptance = torch.sigmoid(self.receptance(receptance))
328
+
329
+ if state is not None:
330
+ state[2][:, :, self.layer_id] = hidden[:, -1]
331
+
332
+ return receptance * value, state
333
+
334
+
335
+ class RwkvBlock(nn.Module):
336
+ def __init__(self, config, layer_id):
337
+ super().__init__()
338
+ self.config = config
339
+ self.layer_id = layer_id
340
+
341
+ if layer_id == 0:
342
+ self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
343
+
344
+ self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
345
+ self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
346
+
347
+ self.attention = RwkvSelfAttention(config, layer_id)
348
+ self.feed_forward = RwkvFeedForward(config, layer_id)
349
+
350
+ def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
351
+
352
+ attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
353
+ hidden = hidden + attention
354
+
355
+ feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
356
+ hidden = hidden + feed_forward
357
+
358
+ outputs = (hidden, state)
359
+ if output_attentions:
360
+ outputs += (attention,)
361
+ else:
362
+ outputs += (None,)
363
+
364
+ return outputs
365
+
366
+
367
+ class RwkvPreTrainedModel(PreTrainedModel):
368
+ """
369
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
370
+ models.
371
+ """
372
+
373
+ config_class = Rwkv5Config
374
+ base_model_prefix = "transformer"
375
+ _no_split_modules = ["RwkvBlock"]
376
+ _keep_in_fp32_modules = ["time_decay", "time_first"]
377
+
378
+ def _init_weights(self, module):
379
+ """Initialize the weights."""
380
+ if isinstance(module, RwkvSelfAttention):
381
+ layer_id = module.layer_id
382
+ num_hidden_layers = module.config.num_hidden_layers
383
+ hidden_size = module.config.hidden_size
384
+ attention_hidden_size = module.attention_hidden_size
385
+ num_attention_heads = hidden_size // module.config.head_size
386
+
387
+ ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
388
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
389
+
390
+ time_weight = torch.tensor(
391
+ [i / hidden_size for i in range(hidden_size)],
392
+ dtype=module.time_mix_key.dtype,
393
+ device=module.time_mix_key.device,
394
+ )
395
+ time_weight = time_weight[None, None, :]
396
+
397
+ if module.config.model_version == "5_2":
398
+ # https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v4neo/src/model.py#L398
399
+ decay_speed = [
400
+ -6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
401
+ for h in range(attention_hidden_size)
402
+ ]
403
+ else:
404
+ # https://github.com/BlinkDL/RWKV-LM/blob/main/RWKV-v4neo/src/model.py#L172
405
+ decay_speed = [
406
+ -6.0 + 5.0 * (h / (num_attention_heads - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
407
+ for h in range(num_attention_heads)
408
+ ]
409
+ decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
410
+ if module.config.model_version == "5_2":
411
+ tmp = (
412
+ torch.tensor(
413
+ [(1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1) for i in range(attention_hidden_size)],
414
+ dtype=module.time_faaaa.dtype,
415
+ device=module.time_faaaa.device,
416
+ )
417
+ )
418
+ else:
419
+ tmp = torch.ones(num_attention_heads) * (-3.0)
420
+
421
+ with torch.no_grad():
422
+ if module.config.model_version == "5_2":
423
+ module.time_decay.data = decay_speed.reshape(num_attention_heads, module.config.head_size)
424
+ module.time_faaaa.data = tmp.reshape(num_attention_heads, module.config.head_size)
425
+ else:
426
+ module.time_decay.data = decay_speed
427
+ module.time_first.data = tmp
428
+
429
+ module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
430
+ module.time_mix_value.data = torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1
431
+ module.time_mix_receptance.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
432
+ if module.config.model_version == "5_2":
433
+ module.time_mix_gate.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
434
+ elif isinstance(module, RwkvFeedForward):
435
+ layer_id = module.layer_id
436
+ num_hidden_layers = module.config.num_hidden_layers
437
+ hidden_size = module.config.hidden_size
438
+
439
+ ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
440
+
441
+ time_weight = torch.tensor(
442
+ [i / hidden_size for i in range(hidden_size)],
443
+ dtype=module.time_mix_key.dtype,
444
+ device=module.time_mix_key.device,
445
+ )
446
+ time_weight = time_weight[None, None, :]
447
+
448
+ with torch.no_grad():
449
+ module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
450
+ module.time_mix_receptance.data = torch.pow(time_weight, ratio_1_to_almost0)
451
+
452
+ def _set_gradient_checkpointing(self, module, value=False):
453
+ if isinstance(module, RwkvModel):
454
+ module.gradient_checkpointing = value
455
+
456
+
457
+ @dataclass
458
+ class RwkvOutput(ModelOutput):
459
+ """
460
+ Class for the RWKV model outputs.
461
+
462
+ Args:
463
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
464
+ Sequence of hidden-states at the output of the last layer of the model.
465
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
466
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
467
+ avoid providing the old `input_ids`.
468
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
469
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
470
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
471
+
472
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
473
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
474
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
475
+ sequence_length)`.
476
+
477
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
478
+ heads.
479
+ """
480
+
481
+ last_hidden_state: torch.FloatTensor = None
482
+ state: Optional[List[torch.FloatTensor]] = None
483
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
484
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
485
+
486
+
487
+ @dataclass
488
+ class RwkvCausalLMOutput(ModelOutput):
489
+ """
490
+ Base class for causal language model (or autoregressive) outputs.
491
+
492
+ Args:
493
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
494
+ Language modeling loss (for next-token prediction).
495
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
496
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
497
+ state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
498
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
499
+ avoid providing the old `input_ids`.
500
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
501
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
502
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
503
+
504
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
505
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
506
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
507
+ sequence_length)`.
508
+
509
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
510
+ heads.
511
+ """
512
+
513
+ loss: Optional[torch.FloatTensor] = None
514
+ logits: torch.FloatTensor = None
515
+ state: Optional[List[torch.FloatTensor]] = None
516
+ last_hidden_state: Optional[Tuple[torch.FloatTensor]] = None
517
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
518
+
519
+
520
+ RWKV_START_DOCSTRING = r"""
521
+
522
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
523
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
524
+ etc.)
525
+
526
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
527
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
528
+ and behavior.
529
+
530
+ Parameters:
531
+ config ([`Rwkv5Config`]): Model configuration class with all the parameters of the model.
532
+ Initializing with a config file does not load the weights associated with the model, only the
533
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
534
+ """
535
+
536
+ RWKV_INPUTS_DOCSTRING = r"""
537
+ Args:
538
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
539
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
540
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
541
+ sequence tokens in the vocabulary.
542
+
543
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
544
+ `input_ids`.
545
+
546
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
547
+ [`PreTrainedTokenizer.__call__`] for details.
548
+
549
+ [What are input IDs?](../glossary#input-ids)
550
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
551
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
552
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
553
+ model's internal embedding lookup matrix.
554
+ state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
555
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
556
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
557
+ use_cache (`bool`, *optional*):
558
+ If set to `True`, the last state is returned and can be used to quickly generate the next logits.
559
+ output_attentions (`bool`, *optional*):
560
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
561
+ tensors for more detail.
562
+ output_hidden_states (`bool`, *optional*):
563
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
564
+ more detail.
565
+ return_dict (`bool`, *optional*):
566
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
567
+ """
568
+
569
+
570
+ @add_start_docstrings(
571
+ "The bare RWKV Model transformer outputting raw hidden-states without any specific head on top.",
572
+ RWKV_START_DOCSTRING,
573
+ )
574
+ class RwkvModel(RwkvPreTrainedModel):
575
+ def __init__(self, config):
576
+ super().__init__(config)
577
+
578
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
579
+ self.blocks = nn.ModuleList([RwkvBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
580
+ self.ln_out = nn.LayerNorm(config.hidden_size)
581
+
582
+ self.layers_are_rescaled = False
583
+ self.pre_ln_flag = False
584
+
585
+ # Initialize weights and apply final processing
586
+ self.post_init()
587
+
588
+ def get_input_embeddings(self):
589
+ return self.embeddings
590
+
591
+ def set_input_embeddings(self, new_embeddings):
592
+ self.embeddings = new_embeddings
593
+
594
+ @add_start_docstrings_to_model_forward(RWKV_INPUTS_DOCSTRING)
595
+ @add_code_sample_docstrings(
596
+ checkpoint=_CHECKPOINT_FOR_DOC,
597
+ output_type=RwkvOutput,
598
+ config_class=_CONFIG_FOR_DOC,
599
+ )
600
+ def forward(
601
+ self,
602
+ input_ids: Optional[torch.LongTensor] = None,
603
+ inputs_embeds: Optional[torch.FloatTensor] = None,
604
+ state: Optional[List[torch.FloatTensor]] = None,
605
+ use_cache: Optional[bool] = None,
606
+ output_attentions: Optional[bool] = None,
607
+ output_hidden_states: Optional[bool] = None,
608
+ return_dict: Optional[bool] = None,
609
+ ) -> Union[Tuple, RwkvOutput]:
610
+ seq_mode = input_ids.shape[1] > 1
611
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
612
+ output_hidden_states = (
613
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
614
+ )
615
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
616
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
617
+
618
+ if self.training == self.layers_are_rescaled and (self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16):
619
+ self._rescale_layers()
620
+
621
+ if input_ids is not None and inputs_embeds is not None:
622
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
623
+ elif input_ids is None and inputs_embeds is None:
624
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
625
+
626
+ if inputs_embeds is None:
627
+ if not self.pre_ln_flag:
628
+ 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)
629
+ self.embeddings.weight = nn.Parameter(normalized_weight)
630
+ self.pre_ln_flag = True
631
+ inputs_embeds = self.embeddings(input_ids)
632
+
633
+ if use_cache and state is None:
634
+ # https://github.com/BlinkDL/ChatRWKV/blob/main/rwkv_pip_package/src/rwkv/model.py#L904-L906
635
+ state = []
636
+ num_attention_heads = self.config.hidden_size // self.config.head_size
637
+ 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())
638
+ 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())
639
+ 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())
640
+
641
+
642
+ hidden_states = inputs_embeds
643
+
644
+ all_self_attentions = () if output_attentions else None
645
+ all_hidden_states = () if output_hidden_states else None
646
+ for idx, block in enumerate(self.blocks):
647
+ hidden_states, state, attentions = block(
648
+ hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
649
+ )
650
+ if (
651
+ self.layers_are_rescaled
652
+ and self.config.rescale_every > 0
653
+ and (idx + 1) % self.config.rescale_every == 0
654
+ ):
655
+ hidden_states = hidden_states / 2
656
+
657
+ if output_hidden_states:
658
+ all_hidden_states = all_hidden_states + (hidden_states,)
659
+
660
+ if output_attentions:
661
+ all_self_attentions = all_self_attentions + (attentions,)
662
+
663
+ if self.config.model_version == "5_2" and seq_mode:
664
+ hidden_states = hidden_states[:, -1, :].unsqueeze(1)
665
+
666
+ hidden_states = self.ln_out(hidden_states)
667
+
668
+ if output_hidden_states:
669
+ all_hidden_states = all_hidden_states + (hidden_states,)
670
+
671
+ if not return_dict:
672
+ return (hidden_states, state, all_hidden_states, all_self_attentions)
673
+
674
+ return RwkvOutput(
675
+ last_hidden_state=hidden_states,
676
+ state=state,
677
+ hidden_states=all_hidden_states, #None
678
+ attentions=all_self_attentions, #None
679
+ )
680
+
681
+ def _rescale_layers(self):
682
+ # Layers should be rescaled for inference only.
683
+ if self.layers_are_rescaled == (not self.training):
684
+ return
685
+ if self.config.rescale_every > 0:
686
+ with torch.no_grad():
687
+ for block_id, block in enumerate(self.blocks):
688
+ if self.training:
689
+ block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
690
+ block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
691
+ else:
692
+ block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
693
+ block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
694
+
695
+ self.layers_are_rescaled = not self.training
696
+
697
+
698
+ @add_start_docstrings(
699
+ """
700
+ The RWKV Model transformer with a language modeling head on top (linear layer with weights tied to the input
701
+ embeddings).
702
+ """,
703
+ RWKV_START_DOCSTRING,
704
+ )
705
+ class RwkvForCausalLM(RwkvPreTrainedModel):
706
+ def __init__(self, config):
707
+ super().__init__(config)
708
+ self.rwkv = RwkvModel(config)
709
+ self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
710
+
711
+ # Initialize weights and apply final processing
712
+ self.post_init()
713
+
714
+ def get_output_embeddings(self):
715
+ return self.head
716
+
717
+ def set_output_embeddings(self, new_embeddings):
718
+ self.head = new_embeddings
719
+
720
+ def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
721
+ # only last token for inputs_ids if the state is passed along.
722
+ if state is not None:
723
+ input_ids = input_ids[:, -1].unsqueeze(-1)
724
+
725
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
726
+ if inputs_embeds is not None and state is None:
727
+ model_inputs = {"inputs_embeds": inputs_embeds}
728
+ else:
729
+ model_inputs = {"input_ids": input_ids}
730
+
731
+ model_inputs["state"] = state
732
+ return model_inputs
733
+
734
+ @add_start_docstrings_to_model_forward(RWKV_INPUTS_DOCSTRING)
735
+ @add_code_sample_docstrings(
736
+ checkpoint=_CHECKPOINT_FOR_DOC,
737
+ output_type=RwkvCausalLMOutput,
738
+ config_class=_CONFIG_FOR_DOC,
739
+ )
740
+ def forward(
741
+ self,
742
+ input_ids: Optional[torch.LongTensor] = None,
743
+ attention_mask: Optional[torch.LongTensor] = None,
744
+ inputs_embeds: Optional[torch.FloatTensor] = None,
745
+ state: Optional[List[torch.FloatTensor]] = None,
746
+ labels: Optional[torch.LongTensor] = None,
747
+ use_cache: Optional[bool] = None,
748
+ output_attentions: Optional[bool] = None,
749
+ output_hidden_states: Optional[bool] = None,
750
+ return_dict: Optional[bool] = None,
751
+ ) -> Union[Tuple, RwkvCausalLMOutput]:
752
+ r"""
753
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
754
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
755
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
756
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
757
+ """
758
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
759
+
760
+ rwkv_outputs = self.rwkv(
761
+ input_ids,
762
+ inputs_embeds=inputs_embeds,
763
+ state=state,
764
+ use_cache=use_cache,
765
+ output_attentions=output_attentions,
766
+ output_hidden_states=output_hidden_states,
767
+ return_dict=return_dict,
768
+ )
769
+ last_hidden_state = rwkv_outputs.last_hidden_state
770
+ state = rwkv_outputs.state
771
+
772
+ logits = self.head(last_hidden_state)
773
+
774
+ loss = None
775
+ if labels is not None:
776
+ # move labels to correct device to enable model parallelism
777
+ labels = labels.to(logits.device)
778
+ # Shift so that tokens < n predict n
779
+ shift_logits = logits[..., :-1, :].contiguous()
780
+ shift_labels = labels[..., 1:].contiguous()
781
+ # Flatten the tokens
782
+ loss_fct = CrossEntropyLoss()
783
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
784
+
785
+ if not return_dict:
786
+ output = (logits,) + rwkv_outputs[1:]
787
+ return ((loss,) + output) if loss is not None else output
788
+
789
+ return RwkvCausalLMOutput(
790
+ loss=loss,
791
+ logits=logits,
792
+ state=rwkv_outputs.state,
793
+ last_hidden_state=rwkv_outputs.last_hidden_state,
794
+ attentions=rwkv_outputs.attentions,
795
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:277fcb7726967bb35d0c2790be7edde1fbebc0ed3336fde4e10303270dbf1947
3
+ size 3155572993
rwkv5.cu ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stdio.h>
2
+ #include <assert.h>
3
+ #include "ATen/ATen.h"
4
+ typedef at::BFloat16 bf16;
5
+ typedef at::Half fp16;
6
+ typedef float fp32;
7
+
8
+ template <typename F>
9
+ __global__ void kernel_forward(const int B, const int T, const int C, const int H, float *__restrict__ _state,
10
+ const F *__restrict__ const _r, const F *__restrict__ const _k, const F *__restrict__ const _v, const float *__restrict__ _w, const F *__restrict__ _u,
11
+ F *__restrict__ const _y)
12
+ {
13
+ const int b = blockIdx.x / H;
14
+ const int h = blockIdx.x % H;
15
+ const int i = threadIdx.x;
16
+ _w += h*_N_;
17
+ _u += h*_N_;
18
+ _state += h*_N_*_N_ + i*_N_; // wrong if B > 1 !!!
19
+
20
+ __shared__ float r[_N_], k[_N_], u[_N_], w[_N_];
21
+
22
+ float state[_N_];
23
+ #pragma unroll
24
+ for (int j = 0; j < _N_; j++)
25
+ state[j] = _state[j];
26
+
27
+ __syncthreads();
28
+ u[i] = float(_u[i]);
29
+ w[i] = _w[i];
30
+ __syncthreads();
31
+
32
+ for (int t = b*T*C + h*_N_ + i; t < (b+1)*T*C + h*_N_ + i; t += C)
33
+ {
34
+ __syncthreads();
35
+ r[i] = float(_r[t]);
36
+ k[i] = float(_k[t]);
37
+ __syncthreads();
38
+
39
+ const float v = float(_v[t]);
40
+ float y = 0;
41
+
42
+ #pragma unroll
43
+ for (int j = 0; j < _N_; j+=4)
44
+ {
45
+ const float4& r_ = (float4&)(r[j]);
46
+ const float4& k_ = (float4&)(k[j]);
47
+ const float4& w_ = (float4&)(w[j]);
48
+ const float4& u_ = (float4&)(u[j]);
49
+ float4& s = (float4&)(state[j]);
50
+ float4 x;
51
+
52
+ x.x = k_.x * v;
53
+ x.y = k_.y * v;
54
+ x.z = k_.z * v;
55
+ x.w = k_.w * v;
56
+
57
+ y += r_.x * (u_.x * x.x + s.x);
58
+ y += r_.y * (u_.y * x.y + s.y);
59
+ y += r_.z * (u_.z * x.z + s.z);
60
+ y += r_.w * (u_.w * x.w + s.w);
61
+
62
+ s.x = s.x * w_.x + x.x;
63
+ s.y = s.y * w_.y + x.y;
64
+ s.z = s.z * w_.z + x.z;
65
+ s.w = s.w * w_.w + x.w;
66
+ }
67
+ _y[t] = F(y);
68
+ }
69
+ #pragma unroll
70
+ for (int j = 0; j < _N_; j++)
71
+ _state[j] = state[j];
72
+ }
73
+
74
+ void cuda_forward_bf16(int B, int T, int C, int H, float *state, bf16 *r, bf16 *k, bf16 *v, float *w, bf16 *u, bf16 *y)
75
+ {
76
+ assert(H*_N_ == C);
77
+ kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
78
+ }
79
+ void cuda_forward_fp16(int B, int T, int C, int H, float *state, fp16 *r, fp16 *k, fp16 *v, float *w, fp16 *u, fp16 *y)
80
+ {
81
+ assert(H*_N_ == C);
82
+ kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
83
+ }
84
+ void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y)
85
+ {
86
+ assert(H*_N_ == C);
87
+ kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
88
+ }
rwkv5_op.cpp ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <torch/extension.h>
2
+ #include "ATen/ATen.h"
3
+ #include <c10/cuda/CUDAGuard.h>
4
+ typedef at::BFloat16 bf16;
5
+ typedef at::Half fp16;
6
+ typedef float fp32;
7
+
8
+ void cuda_forward_bf16(int B, int T, int C, int H, float *state, bf16 *r, bf16 *k, bf16 *v, float *w, bf16 *u, bf16 *y);
9
+ void cuda_forward_fp16(int B, int T, int C, int H, float *state, fp16 *r, fp16 *k, fp16 *v, float *w, fp16 *u, fp16 *y);
10
+ void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y);
11
+
12
+ void forward_bf16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
13
+ const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
14
+ cuda_forward_bf16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), w.data_ptr<float>(), u.data_ptr<bf16>(), y.data_ptr<bf16>());
15
+ }
16
+ void forward_fp16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
17
+ const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
18
+ cuda_forward_fp16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp16>(), k.data_ptr<fp16>(), v.data_ptr<fp16>(), w.data_ptr<float>(), u.data_ptr<fp16>(), y.data_ptr<fp16>());
19
+ }
20
+ void forward_fp32(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
21
+ const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
22
+ cuda_forward_fp32(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp32>(), k.data_ptr<fp32>(), v.data_ptr<fp32>(), w.data_ptr<float>(), u.data_ptr<fp32>(), y.data_ptr<fp32>());
23
+ }
24
+
25
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
26
+ m.def("forward_bf16", &forward_bf16, "rwkv5 forward_bf16");
27
+ m.def("forward_fp16", &forward_fp16, "rwkv5 forward_fp16");
28
+ m.def("forward_fp32", &forward_fp32, "rwkv5 forward_fp32");
29
+ }
30
+ TORCH_LIBRARY(rwkv5, m) {
31
+ m.def("forward_bf16", forward_bf16);
32
+ m.def("forward_fp16", forward_fp16);
33
+ m.def("forward_fp32", forward_fp32);
34
+ }
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
+ }