something-else
commited on
Commit
•
0555b88
1
Parent(s):
7a7bf9e
Upload folder using huggingface_hub
Browse files- config.json +24 -0
- configuration_rwkv5.py +118 -0
- generation_config.json +12 -0
- modeling_rwkv5.py +845 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +5 -0
- tokenization_rwkv5.py +229 -0
- tokenizer_config.json +12 -0
- vocab.txt +0 -0
config.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Rwkv5ForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_rwkv5.Rwkv5Config",
|
7 |
+
"AutoModelForCausalLM": "modeling_rwkv5.Rwkv5ForCausalLM"
|
8 |
+
},
|
9 |
+
"attention_hidden_size": 4096,
|
10 |
+
"bos_token_id": 0,
|
11 |
+
"eos_token_id": 0,
|
12 |
+
"head_size": 64,
|
13 |
+
"hidden_size": 4096,
|
14 |
+
"intermediate_size": null,
|
15 |
+
"layer_norm_epsilon": 1e-05,
|
16 |
+
"model_type": "rwkv5",
|
17 |
+
"num_attention_heads": 64,
|
18 |
+
"num_hidden_layers": 40,
|
19 |
+
"rescale_every": 6,
|
20 |
+
"tie_word_embeddings": false,
|
21 |
+
"transformers_version": "4.41.2",
|
22 |
+
"use_cache": true,
|
23 |
+
"vocab_size": 65536
|
24 |
+
}
|
configuration_rwkv5.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
""" RWKV configuration"""
|
17 |
+
|
18 |
+
from transformers.configuration_utils import PretrainedConfig
|
19 |
+
from transformers.utils import logging
|
20 |
+
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
RWKV5_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
25 |
+
|
26 |
+
|
27 |
+
class Rwkv5Config(PretrainedConfig):
|
28 |
+
"""
|
29 |
+
This is the configuration class to store the configuration of a [`Rwkv5Model`]. It is used to instantiate a RWKV5
|
30 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
31 |
+
defaults will yield a similar configuration to that of the RWVK-4
|
32 |
+
[RWKV/rwkv-5-world-1b5](https://huggingface.co/RWKV/rwkv-5-world-1b5) architecture.
|
33 |
+
|
34 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
35 |
+
documentation from [`PretrainedConfig`] for more information.
|
36 |
+
|
37 |
+
|
38 |
+
Args:
|
39 |
+
vocab_size (`int`, *optional*, defaults to 65536):
|
40 |
+
Vocabulary size of the RWKV5 model. Defines the number of different tokens that can be represented by the
|
41 |
+
`inputs_ids` passed when calling [`Rwkv5Model`].
|
42 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
43 |
+
Dimensionality of the embeddings and hidden states.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
45 |
+
Number of hidden layers in the model.
|
46 |
+
attention_hidden_size (`int`, *optional*):
|
47 |
+
Dimensionality of the attention hidden states. Will default to `hidden_size` if unset.
|
48 |
+
num_attention_heads (`int`, *optional*, defaults to 64):
|
49 |
+
The attention heads to use in rwkv5 self_attention module.
|
50 |
+
head_size (`int`, *optional*, defaults to 64): head_size of rwkv5 self_attention module.
|
51 |
+
intermediate_size (`int`, *optional*):
|
52 |
+
Dimensionality of the inner feed-forward layers. Will default to 4 times `hidden_size` if unset.
|
53 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
|
54 |
+
The epsilon to use in the layer normalization layers.
|
55 |
+
bos_token_id (`int`, *optional*, defaults to 0):
|
56 |
+
The id of the beginning of sentence token in the vocabulary. Defaults to 0.
|
57 |
+
eos_token_id (`int`, *optional*, defaults to 0):
|
58 |
+
The id of the end of sentence token in the vocabulary. Defaults to 0.
|
59 |
+
rescale_every (`int`, *optional*, defaults to 6):
|
60 |
+
At inference, the hidden states (and weights of the correponding output layers) are divided by 2 every
|
61 |
+
`rescale_every` layer. If set to 0 or a negative number, no rescale is done.
|
62 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
63 |
+
Whether or not to tie the word embeddings with the input token embeddings.
|
64 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
65 |
+
Whether or not the model should return the last state.
|
66 |
+
|
67 |
+
|
68 |
+
Example:
|
69 |
+
|
70 |
+
```python
|
71 |
+
>>> from transformers import Rwkv5Config, Rwkv5Model
|
72 |
+
|
73 |
+
>>> # Initializing a Rwkv5 configuration
|
74 |
+
>>> configuration = Rwkv5Config()
|
75 |
+
|
76 |
+
>>> # Initializing a model (with random weights) from the configuration
|
77 |
+
>>> model = Rwkv5Model(configuration)
|
78 |
+
|
79 |
+
>>> # Accessing the model configuration
|
80 |
+
>>> configuration = model.config
|
81 |
+
```"""
|
82 |
+
|
83 |
+
model_type = "rwkv5"
|
84 |
+
|
85 |
+
def __init__(
|
86 |
+
self,
|
87 |
+
vocab_size=65536,
|
88 |
+
hidden_size=768,
|
89 |
+
num_hidden_layers=24,
|
90 |
+
attention_hidden_size=None,
|
91 |
+
head_size=64,
|
92 |
+
head_size_divisor=8,
|
93 |
+
intermediate_size=None,
|
94 |
+
layer_norm_epsilon=1e-5,
|
95 |
+
bos_token_id=0,
|
96 |
+
eos_token_id=0,
|
97 |
+
rescale_every=6,
|
98 |
+
tie_word_embeddings=False,
|
99 |
+
use_cache=True,
|
100 |
+
**kwargs,
|
101 |
+
):
|
102 |
+
self.vocab_size = vocab_size
|
103 |
+
self.hidden_size = hidden_size
|
104 |
+
self.num_hidden_layers = num_hidden_layers
|
105 |
+
self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
|
106 |
+
self.head_size = head_size
|
107 |
+
self.head_size_divisor = head_size_divisor
|
108 |
+
self.intermediate_size = None
|
109 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
110 |
+
self.rescale_every = rescale_every
|
111 |
+
self.use_cache = use_cache
|
112 |
+
|
113 |
+
self.bos_token_id = bos_token_id
|
114 |
+
self.eos_token_id = eos_token_id
|
115 |
+
|
116 |
+
super().__init__(
|
117 |
+
tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
|
118 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"chat_format": "chatml",
|
3 |
+
"eos_token_id": 0,
|
4 |
+
"pad_token_id": 0,
|
5 |
+
"max_window_size": 4096,
|
6 |
+
"max_new_tokens": 4096,
|
7 |
+
"do_sample": true,
|
8 |
+
"top_k": 0,
|
9 |
+
"top_p": 0.1,
|
10 |
+
"repetition_penalty": 1.0,
|
11 |
+
"transformers_version": "4.31.1"
|
12 |
+
}
|
modeling_rwkv5.py
ADDED
@@ -0,0 +1,845 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The RWKV team and HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""PyTorch RWKV5 World model."""
|
16 |
+
|
17 |
+
from dataclasses import dataclass
|
18 |
+
from pathlib import Path
|
19 |
+
from typing import List, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.nn.functional as F
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from torch.nn import CrossEntropyLoss
|
26 |
+
|
27 |
+
from transformers.modeling_utils import PreTrainedModel
|
28 |
+
from transformers.utils import (
|
29 |
+
ModelOutput,
|
30 |
+
add_code_sample_docstrings,
|
31 |
+
add_start_docstrings,
|
32 |
+
add_start_docstrings_to_model_forward,
|
33 |
+
is_bitsandbytes_available,
|
34 |
+
is_ninja_available,
|
35 |
+
is_torch_cuda_available,
|
36 |
+
logging,
|
37 |
+
)
|
38 |
+
|
39 |
+
from .configuration_rwkv5 import Rwkv5Config
|
40 |
+
|
41 |
+
|
42 |
+
logger = logging.get_logger(__name__)
|
43 |
+
|
44 |
+
_CHECKPOINT_FOR_DOC = "RWKV/rwkv-5-world-1b5"
|
45 |
+
_CONFIG_FOR_DOC = "Rwkv5Config"
|
46 |
+
|
47 |
+
rwkv5_cuda_kernel = None
|
48 |
+
|
49 |
+
|
50 |
+
# Copied from https://github.com/huggingface/transformers/blob/18cbaf13dcaca7145f5652aefb9b19734c56c3cd/src/transformers/models/rwkv/modeling_rwkv.py#L65
|
51 |
+
def load_wkv5_cuda_kernel(head_size):
|
52 |
+
from torch.utils.cpp_extension import load as load_kernel
|
53 |
+
|
54 |
+
global rwkv5_cuda_kernel
|
55 |
+
|
56 |
+
kernel_folder = Path(__file__).parent.resolve()
|
57 |
+
cuda_kernel_files = [kernel_folder / f for f in ["wkv5_op.cpp", "wkv5_cuda.cu"]]
|
58 |
+
|
59 |
+
# Only load the kernel if it's not been loaded yet or if we changed the context length
|
60 |
+
if rwkv5_cuda_kernel is not None and rwkv5_cuda_kernel.head_size == head_size:
|
61 |
+
return
|
62 |
+
|
63 |
+
logger.info(f"Loading CUDA kernel for RWKV5 at head size of {head_size}.")
|
64 |
+
|
65 |
+
flags = [
|
66 |
+
"-res-usage",
|
67 |
+
"--maxrregcount 60",
|
68 |
+
"--use_fast_math",
|
69 |
+
"-O3",
|
70 |
+
"-Xptxas -O3",
|
71 |
+
"--extra-device-vectorization",
|
72 |
+
f"-D_N_={head_size}",
|
73 |
+
]
|
74 |
+
rwkv5_cuda_kernel = load_kernel(
|
75 |
+
name=f"wkv_{head_size}",
|
76 |
+
sources=cuda_kernel_files,
|
77 |
+
verbose=(logging.get_verbosity() == logging.DEBUG),
|
78 |
+
extra_cuda_cflags=flags,
|
79 |
+
)
|
80 |
+
rwkv5_cuda_kernel.head_size = head_size
|
81 |
+
|
82 |
+
|
83 |
+
class Rwkv5LinearAttention(torch.autograd.Function):
|
84 |
+
@staticmethod
|
85 |
+
def forward(ctx, receptance, key, value, time_decay, time_first, state):
|
86 |
+
with torch.no_grad():
|
87 |
+
assert receptance.dtype == torch.bfloat16
|
88 |
+
assert key.dtype == torch.bfloat16
|
89 |
+
assert value.dtype == torch.bfloat16
|
90 |
+
assert time_decay.dtype == torch.bfloat16
|
91 |
+
assert time_first.dtype == torch.bfloat16
|
92 |
+
assert state.dtype == torch.float32
|
93 |
+
batch, seq_length, hidden_size = key.shape
|
94 |
+
num_heads = time_decay.shape[0]
|
95 |
+
ctx.batch = batch
|
96 |
+
ctx.seq_length = seq_length
|
97 |
+
ctx.hidden_size = hidden_size
|
98 |
+
ctx.num_heads = num_heads
|
99 |
+
e_time_decay = (-torch.exp(time_decay.float())).contiguous()
|
100 |
+
ee_time_decay = (torch.exp(e_time_decay)).contiguous()
|
101 |
+
assert ee_time_decay.dtype == torch.float32
|
102 |
+
ctx.save_for_backward(receptance, key, value, ee_time_decay, e_time_decay, time_first)
|
103 |
+
out = torch.empty(
|
104 |
+
(batch, seq_length, hidden_size),
|
105 |
+
device=receptance.device,
|
106 |
+
dtype=torch.bfloat16,
|
107 |
+
memory_format=torch.contiguous_format,
|
108 |
+
)
|
109 |
+
state = state.clone()
|
110 |
+
rwkv5_cuda_kernel.forward_bf16(
|
111 |
+
batch,
|
112 |
+
seq_length,
|
113 |
+
hidden_size,
|
114 |
+
num_heads,
|
115 |
+
state,
|
116 |
+
receptance,
|
117 |
+
key,
|
118 |
+
value,
|
119 |
+
ee_time_decay,
|
120 |
+
time_first,
|
121 |
+
out,
|
122 |
+
)
|
123 |
+
return out, state
|
124 |
+
|
125 |
+
@staticmethod
|
126 |
+
def backward(ctx, gout):
|
127 |
+
with torch.no_grad():
|
128 |
+
assert gout.dtype == torch.bfloat16
|
129 |
+
batch = ctx.batch
|
130 |
+
seq_length = ctx.seq_length
|
131 |
+
hidden_size = ctx.hidden_size
|
132 |
+
num_heads = ctx.num_heads
|
133 |
+
receptance, key, value, ee_time_decay, e_time_decay, time_first = ctx.saved_tensors
|
134 |
+
|
135 |
+
global_shape = (batch, seq_length, hidden_size)
|
136 |
+
|
137 |
+
# TODO dtype should not be forced here IMO
|
138 |
+
greceptance = torch.empty(
|
139 |
+
global_shape,
|
140 |
+
device=gout.device,
|
141 |
+
requires_grad=False,
|
142 |
+
dtype=torch.bfloat16,
|
143 |
+
memory_format=torch.contiguous_format,
|
144 |
+
)
|
145 |
+
g_key = torch.empty(
|
146 |
+
global_shape,
|
147 |
+
device=gout.device,
|
148 |
+
requires_grad=False,
|
149 |
+
dtype=torch.bfloat16,
|
150 |
+
memory_format=torch.contiguous_format,
|
151 |
+
)
|
152 |
+
g_value = torch.empty(
|
153 |
+
global_shape,
|
154 |
+
device=gout.device,
|
155 |
+
requires_grad=False,
|
156 |
+
dtype=torch.bfloat16,
|
157 |
+
memory_format=torch.contiguous_format,
|
158 |
+
)
|
159 |
+
g_time_decay = torch.empty(
|
160 |
+
(batch, hidden_size),
|
161 |
+
device=gout.device,
|
162 |
+
requires_grad=False,
|
163 |
+
dtype=torch.bfloat16,
|
164 |
+
memory_format=torch.contiguous_format,
|
165 |
+
)
|
166 |
+
g_time_first = torch.empty(
|
167 |
+
(batch, hidden_size),
|
168 |
+
device=gout.device,
|
169 |
+
requires_grad=False,
|
170 |
+
dtype=torch.bfloat16,
|
171 |
+
memory_format=torch.contiguous_format,
|
172 |
+
)
|
173 |
+
rwkv5_cuda_kernel.backward_bf16(
|
174 |
+
batch,
|
175 |
+
seq_length,
|
176 |
+
hidden_size,
|
177 |
+
num_heads,
|
178 |
+
receptance,
|
179 |
+
key,
|
180 |
+
value,
|
181 |
+
ee_time_decay,
|
182 |
+
e_time_decay,
|
183 |
+
time_first,
|
184 |
+
gout,
|
185 |
+
greceptance,
|
186 |
+
g_key,
|
187 |
+
g_value,
|
188 |
+
g_time_decay,
|
189 |
+
g_time_first,
|
190 |
+
)
|
191 |
+
head_size = hidden_size // num_heads
|
192 |
+
g_time_decay = torch.sum(g_time_decay, 0).view(num_heads, head_size)
|
193 |
+
g_time_first = torch.sum(g_time_first, 0).view(num_heads, head_size)
|
194 |
+
return (None, None, None, None, greceptance, g_key, g_value, g_time_decay, g_time_first)
|
195 |
+
|
196 |
+
|
197 |
+
def rwkv5_linear_attention_cpu(receptance, key, value, time_decay, time_first, state):
|
198 |
+
input_dtype = receptance.dtype
|
199 |
+
# For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel if not executed
|
200 |
+
# within a torch.no_grad.
|
201 |
+
batch, seq_length, hidden_size = receptance.shape
|
202 |
+
num_heads, head_size = time_first.shape
|
203 |
+
key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2).transpose(-2, -1)
|
204 |
+
value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
|
205 |
+
receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
|
206 |
+
time_decay = torch.exp(-torch.exp(time_decay.float())).reshape(-1, 1, 1).reshape(num_heads, -1, 1)
|
207 |
+
time_first = time_first.float().reshape(-1, 1, 1).reshape(num_heads, -1, 1)
|
208 |
+
out = torch.zeros_like(key).reshape(batch, seq_length, num_heads, head_size)
|
209 |
+
|
210 |
+
for current_index in range(seq_length):
|
211 |
+
current_receptance = receptance[:, :, current_index:current_index+1, :]
|
212 |
+
current_key = key[:, :, :, current_index:current_index+1]
|
213 |
+
current_value = value[:, :, current_index:current_index+1, :]
|
214 |
+
attention_output = current_key @ current_value
|
215 |
+
out[:, current_index] = (current_receptance @ (time_first * attention_output + state)).squeeze(2)
|
216 |
+
with torch.no_grad():
|
217 |
+
state = attention_output + time_decay * state
|
218 |
+
|
219 |
+
return out, state
|
220 |
+
|
221 |
+
# copied from RWKV but with receptance
|
222 |
+
def RWKV5_linear_attention(training, receptance, key, value, time_decay, time_first, state):
|
223 |
+
no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, key, value])
|
224 |
+
# Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
|
225 |
+
# in this case).
|
226 |
+
one_token = key.size(1) == 1
|
227 |
+
if not training or rwkv5_cuda_kernel is None or no_cuda or one_token:
|
228 |
+
return rwkv5_linear_attention_cpu(
|
229 |
+
receptance, key, value, time_decay, time_first, state
|
230 |
+
)
|
231 |
+
else:
|
232 |
+
return Rwkv5LinearAttention.apply(receptance, key, value, time_decay, time_first, state)
|
233 |
+
|
234 |
+
|
235 |
+
class Rwkv5SelfAttention(nn.Module):
|
236 |
+
def __init__(self, config, layer_id=0):
|
237 |
+
super().__init__()
|
238 |
+
self.config = config
|
239 |
+
kernel_loaded = rwkv5_cuda_kernel is not None and rwkv5_cuda_kernel.head_size == config.head_size
|
240 |
+
if is_ninja_available() and is_torch_cuda_available() and not kernel_loaded:
|
241 |
+
try:
|
242 |
+
load_wkv5_cuda_kernel(config.head_size)
|
243 |
+
except Exception:
|
244 |
+
logger.info("Could not load the custom CUDA kernel for RWKV5 attention.")
|
245 |
+
self.layer_id = layer_id
|
246 |
+
hidden_size = config.hidden_size
|
247 |
+
attention_hidden_size = config.attention_hidden_size
|
248 |
+
self.attention_hidden_size = attention_hidden_size
|
249 |
+
head_size = config.head_size
|
250 |
+
num_heads = attention_hidden_size // head_size
|
251 |
+
|
252 |
+
self.time_decay = nn.Parameter(torch.empty(num_heads, head_size))
|
253 |
+
self.time_faaaa = nn.Parameter(torch.empty(num_heads, head_size))
|
254 |
+
self.time_mix_gate = nn.Parameter(torch.empty(1, 1, hidden_size))
|
255 |
+
|
256 |
+
self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
|
257 |
+
self.time_mix_value = nn.Parameter(torch.empty(1, 1, hidden_size))
|
258 |
+
self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
|
259 |
+
|
260 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
261 |
+
self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
262 |
+
self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
263 |
+
self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
264 |
+
self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
|
265 |
+
self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
|
266 |
+
self.ln_x = nn.GroupNorm(num_heads, hidden_size)
|
267 |
+
|
268 |
+
def extract_key_value(self, hidden, state=None):
|
269 |
+
# Mix hidden with the previous timestep to produce key, value, receptance
|
270 |
+
if hidden.size(1) == 1 and state is not None:
|
271 |
+
shifted = state[0][:, :, self.layer_id]
|
272 |
+
else:
|
273 |
+
shifted = self.time_shift(hidden)
|
274 |
+
if state is not None:
|
275 |
+
shifted[:, 0] = state[0][:, :, self.layer_id]
|
276 |
+
if len(shifted.size()) == 2:
|
277 |
+
shifted = shifted.unsqueeze(1)
|
278 |
+
|
279 |
+
key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
|
280 |
+
value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
|
281 |
+
receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
|
282 |
+
gate = hidden * self.time_mix_gate + shifted * (1 - self.time_mix_gate)
|
283 |
+
|
284 |
+
key = self.key(key)
|
285 |
+
value = self.value(value)
|
286 |
+
receptance = self.receptance(receptance)
|
287 |
+
gate = F.silu(self.gate(gate))
|
288 |
+
|
289 |
+
if state is not None:
|
290 |
+
state[0][:, :, self.layer_id] = hidden[:, -1]
|
291 |
+
|
292 |
+
return receptance, key, value, gate, state
|
293 |
+
|
294 |
+
def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
|
295 |
+
receptance, key, value, gate, state = self.extract_key_value(hidden, state=state)
|
296 |
+
|
297 |
+
B,T,C = receptance.shape
|
298 |
+
H, S = self.time_faaaa.shape
|
299 |
+
|
300 |
+
layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
|
301 |
+
out, layer_state = RWKV5_linear_attention(
|
302 |
+
self.training, receptance, key, value, self.time_decay, self.time_faaaa, layer_state
|
303 |
+
)
|
304 |
+
|
305 |
+
if layer_state is not None:
|
306 |
+
state[1][:, :, :, :, self.layer_id] = layer_state
|
307 |
+
|
308 |
+
out = out.reshape(B * T, H * S)
|
309 |
+
out = F.group_norm(out / self.config.head_size_divisor, num_groups=H, weight=self.ln_x.weight.to(out.dtype), bias=self.ln_x.bias.to(out.dtype), eps=self.ln_x.eps).reshape(B, T, H * S)
|
310 |
+
out = out.to(dtype=hidden.dtype) * gate
|
311 |
+
out = self.output(out)
|
312 |
+
return out, state
|
313 |
+
|
314 |
+
# Copied from rwkv exceot for the intermediate size
|
315 |
+
class Rwkv5FeedForward(nn.Module):
|
316 |
+
def __init__(self, config, layer_id=0):
|
317 |
+
super().__init__()
|
318 |
+
self.config = config
|
319 |
+
self.layer_id = layer_id
|
320 |
+
hidden_size = config.hidden_size
|
321 |
+
intermediate_size = (
|
322 |
+
config.intermediate_size
|
323 |
+
if config.intermediate_size is not None
|
324 |
+
else int((config.hidden_size * 3.5) // 32 * 32)
|
325 |
+
)
|
326 |
+
|
327 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
328 |
+
self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
|
329 |
+
self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
|
330 |
+
|
331 |
+
self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
|
332 |
+
self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
|
333 |
+
self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
|
334 |
+
|
335 |
+
def forward(self, hidden, state=None):
|
336 |
+
if hidden.size(1) == 1 and state is not None:
|
337 |
+
shifted = state[2][:, :, self.layer_id]
|
338 |
+
else:
|
339 |
+
shifted = self.time_shift(hidden)
|
340 |
+
if state is not None:
|
341 |
+
shifted[:, 0] = state[2][:, :, self.layer_id]
|
342 |
+
if len(shifted.size()) == 2:
|
343 |
+
shifted = shifted.unsqueeze(1)
|
344 |
+
key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
|
345 |
+
receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
|
346 |
+
|
347 |
+
key = torch.square(torch.relu(self.key(key)))
|
348 |
+
value = self.value(key)
|
349 |
+
receptance = torch.sigmoid(self.receptance(receptance))
|
350 |
+
|
351 |
+
if state is not None:
|
352 |
+
state[2][:, :, self.layer_id] = hidden[:, -1]
|
353 |
+
|
354 |
+
return receptance * value, state
|
355 |
+
|
356 |
+
|
357 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvBlock with Rwkv->Rwkv5
|
358 |
+
class Rwkv5Block(nn.Module):
|
359 |
+
def __init__(self, config, layer_id):
|
360 |
+
super().__init__()
|
361 |
+
self.config = config
|
362 |
+
self.layer_id = layer_id
|
363 |
+
|
364 |
+
if layer_id == 0:
|
365 |
+
self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
366 |
+
|
367 |
+
self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
368 |
+
self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
369 |
+
|
370 |
+
self.attention = Rwkv5SelfAttention(config, layer_id)
|
371 |
+
self.feed_forward = Rwkv5FeedForward(config, layer_id)
|
372 |
+
|
373 |
+
def forward(self, hidden, state=None, use_cache=False, output_attentions=False, seq_mode=True):
|
374 |
+
if self.layer_id == 0:
|
375 |
+
hidden = self.pre_ln(hidden)
|
376 |
+
attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
|
377 |
+
hidden = hidden + attention
|
378 |
+
|
379 |
+
feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
|
380 |
+
hidden = hidden + feed_forward
|
381 |
+
|
382 |
+
outputs = (hidden, state)
|
383 |
+
if output_attentions:
|
384 |
+
outputs += (attention,)
|
385 |
+
else:
|
386 |
+
outputs += (None,)
|
387 |
+
|
388 |
+
return outputs
|
389 |
+
|
390 |
+
|
391 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvPreTrainedModel with Rwkv->Rwkv5
|
392 |
+
class Rwkv5PreTrainedModel(PreTrainedModel):
|
393 |
+
"""
|
394 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
395 |
+
models.
|
396 |
+
"""
|
397 |
+
|
398 |
+
config_class = Rwkv5Config
|
399 |
+
base_model_prefix = "rwkv5"
|
400 |
+
_no_split_modules = ["Rwkv5Block"]
|
401 |
+
_keep_in_fp32_modules = ["time_decay", "time_first"]
|
402 |
+
supports_gradient_checkpointing = True
|
403 |
+
|
404 |
+
def _init_weights(self, module):
|
405 |
+
"""Initialize the weights."""
|
406 |
+
if isinstance(module, Rwkv5SelfAttention):
|
407 |
+
layer_id = module.layer_id
|
408 |
+
num_hidden_layers = module.config.num_hidden_layers
|
409 |
+
hidden_size = module.config.hidden_size
|
410 |
+
attention_hidden_size = module.attention_hidden_size
|
411 |
+
head_size = module.config.head_size
|
412 |
+
num_heads = attention_hidden_size // head_size
|
413 |
+
|
414 |
+
ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
|
415 |
+
ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
|
416 |
+
|
417 |
+
time_weight = torch.tensor(
|
418 |
+
[i / hidden_size for i in range(hidden_size)],
|
419 |
+
dtype=module.time_mix_key.dtype,
|
420 |
+
device=module.time_mix_key.device,
|
421 |
+
)
|
422 |
+
time_weight = time_weight[None, None, :]
|
423 |
+
|
424 |
+
decay_speed = [
|
425 |
+
-6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
|
426 |
+
for h in range(attention_hidden_size)
|
427 |
+
]
|
428 |
+
decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
|
429 |
+
tmp = torch.tensor(
|
430 |
+
[
|
431 |
+
(1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
|
432 |
+
for i in range(attention_hidden_size)
|
433 |
+
],
|
434 |
+
dtype=module.time_faaaa.dtype,
|
435 |
+
device=module.time_faaaa.device,
|
436 |
+
)
|
437 |
+
|
438 |
+
with torch.no_grad():
|
439 |
+
module.time_decay.data = decay_speed.reshape(num_heads, head_size)
|
440 |
+
module.time_faaaa.data = tmp.reshape(num_heads, head_size)
|
441 |
+
module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
|
442 |
+
|
443 |
+
module.time_mix_value.data = torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1
|
444 |
+
module.time_mix_receptance.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
|
445 |
+
module.time_mix_gate.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
|
446 |
+
|
447 |
+
elif isinstance(module, Rwkv5FeedForward):
|
448 |
+
layer_id = module.layer_id
|
449 |
+
num_hidden_layers = module.config.num_hidden_layers
|
450 |
+
hidden_size = module.config.hidden_size
|
451 |
+
|
452 |
+
ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
|
453 |
+
|
454 |
+
time_weight = torch.tensor(
|
455 |
+
[i / hidden_size for i in range(hidden_size)],
|
456 |
+
dtype=module.time_mix_key.dtype,
|
457 |
+
device=module.time_mix_key.device,
|
458 |
+
)
|
459 |
+
time_weight = time_weight[None, None, :]
|
460 |
+
|
461 |
+
with torch.no_grad():
|
462 |
+
module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
|
463 |
+
module.time_mix_receptance.data = torch.pow(time_weight, ratio_1_to_almost0)
|
464 |
+
|
465 |
+
|
466 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvOutput with Rwkv->Rwkv5
|
467 |
+
@dataclass
|
468 |
+
class Rwkv5Output(ModelOutput):
|
469 |
+
"""
|
470 |
+
Class for the RWKV5 model outputs.
|
471 |
+
|
472 |
+
Args:
|
473 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
474 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
475 |
+
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
|
476 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
477 |
+
avoid providing the old `input_ids`.
|
478 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
479 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
480 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
|
481 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
482 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
483 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
484 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
485 |
+
the self-attention heads.
|
486 |
+
"""
|
487 |
+
|
488 |
+
last_hidden_state: torch.FloatTensor = None
|
489 |
+
state: Optional[List[torch.FloatTensor]] = None
|
490 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
491 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
492 |
+
|
493 |
+
|
494 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvCausalLMOutput with Rwkv->Rwkv5
|
495 |
+
@dataclass
|
496 |
+
class Rwkv5CausalLMOutput(ModelOutput):
|
497 |
+
"""
|
498 |
+
Base class for causal language model (or autoregressive) outputs.
|
499 |
+
|
500 |
+
Args:
|
501 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
502 |
+
Language modeling loss (for next-token prediction).
|
503 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
504 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
505 |
+
state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
|
506 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
507 |
+
avoid providing the old `input_ids`.
|
508 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
509 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
510 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
|
511 |
+
the model at the output of each layer plus the optional initial embedding outputs.
|
512 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
513 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
514 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
515 |
+
the self-attention heads.
|
516 |
+
"""
|
517 |
+
|
518 |
+
loss: Optional[torch.FloatTensor] = None
|
519 |
+
logits: torch.FloatTensor = None
|
520 |
+
state: Optional[List[torch.FloatTensor]] = None
|
521 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
522 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
523 |
+
|
524 |
+
|
525 |
+
RWKV5_START_DOCSTRING = r"""
|
526 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
527 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
528 |
+
etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
|
529 |
+
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
|
530 |
+
general usage and behavior.
|
531 |
+
|
532 |
+
Parameters:
|
533 |
+
config ([`Rwkv5Config`]): Model configuration class with all the parameters of the model.
|
534 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
535 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
536 |
+
"""
|
537 |
+
|
538 |
+
RWKV5_INPUTS_DOCSTRING = r"""
|
539 |
+
Args:
|
540 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
541 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
542 |
+
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
543 |
+
sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
|
544 |
+
past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
|
545 |
+
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
|
546 |
+
IDs?](../glossary#input-ids)
|
547 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
548 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
549 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
550 |
+
model's internal embedding lookup matrix.
|
551 |
+
state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
|
552 |
+
If passed along, the model uses the previous state in all the blocks (which will give the output for the
|
553 |
+
`input_ids` provided as if the model add `state_input_ids + input_ids` as context).
|
554 |
+
use_cache (`bool`, *optional*):
|
555 |
+
If set to `True`, the last state is returned and can be used to quickly generate the next logits.
|
556 |
+
output_attentions (`bool`, *optional*):
|
557 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
558 |
+
tensors for more detail.
|
559 |
+
output_hidden_states (`bool`, *optional*):
|
560 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
561 |
+
more detail.
|
562 |
+
return_dict (`bool`, *optional*):
|
563 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
564 |
+
"""
|
565 |
+
|
566 |
+
|
567 |
+
@add_start_docstrings(
|
568 |
+
"The bare RWKV5 Model transformer outputting raw hidden-states without any specific head on top.",
|
569 |
+
RWKV5_START_DOCSTRING,
|
570 |
+
)
|
571 |
+
class Rwkv5Model(Rwkv5PreTrainedModel):
|
572 |
+
def __init__(self, config):
|
573 |
+
super().__init__(config)
|
574 |
+
|
575 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
576 |
+
self.blocks = nn.ModuleList([Rwkv5Block(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
|
577 |
+
self.ln_out = nn.LayerNorm(config.hidden_size)
|
578 |
+
|
579 |
+
self.layers_are_rescaled = False
|
580 |
+
self.gradient_checkpointing = False
|
581 |
+
|
582 |
+
# Initialize weights and apply final processing
|
583 |
+
self.post_init()
|
584 |
+
|
585 |
+
def get_input_embeddings(self):
|
586 |
+
return self.embeddings
|
587 |
+
|
588 |
+
def set_input_embeddings(self, new_embeddings):
|
589 |
+
self.embeddings = new_embeddings
|
590 |
+
|
591 |
+
@add_start_docstrings_to_model_forward(RWKV5_INPUTS_DOCSTRING)
|
592 |
+
@add_code_sample_docstrings(
|
593 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
594 |
+
output_type=Rwkv5Output,
|
595 |
+
config_class=_CONFIG_FOR_DOC,
|
596 |
+
)
|
597 |
+
def forward(
|
598 |
+
self,
|
599 |
+
input_ids: Optional[torch.LongTensor] = None,
|
600 |
+
attention_mask: Optional[torch.LongTensor] = None, # noqa
|
601 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
602 |
+
state: Optional[List[torch.FloatTensor]] = None,
|
603 |
+
use_cache: Optional[bool] = None,
|
604 |
+
output_attentions: Optional[bool] = None,
|
605 |
+
output_hidden_states: Optional[bool] = None,
|
606 |
+
return_dict: Optional[bool] = None,
|
607 |
+
) -> Union[Tuple, Rwkv5Output]:
|
608 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
609 |
+
output_hidden_states = (
|
610 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
611 |
+
)
|
612 |
+
# FIXME - training is supportable with the CUDA code
|
613 |
+
# rwkv5 only support inference in huggingface.
|
614 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
615 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
616 |
+
|
617 |
+
if self.training == self.layers_are_rescaled and (
|
618 |
+
self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
|
619 |
+
):
|
620 |
+
self._rescale_layers()
|
621 |
+
|
622 |
+
if input_ids is not None and inputs_embeds is not None:
|
623 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
624 |
+
elif input_ids is None and inputs_embeds is None:
|
625 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
626 |
+
|
627 |
+
if inputs_embeds is None:
|
628 |
+
inputs_embeds = self.embeddings(input_ids)
|
629 |
+
|
630 |
+
if state is None:
|
631 |
+
state = []
|
632 |
+
head_size = self.config.head_size
|
633 |
+
num_heads = self.config.attention_hidden_size // head_size
|
634 |
+
state_attn_x = torch.zeros(
|
635 |
+
(inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
|
636 |
+
dtype=inputs_embeds.dtype,
|
637 |
+
requires_grad=False,
|
638 |
+
device=inputs_embeds.device,
|
639 |
+
).contiguous()
|
640 |
+
state_attn_kv = torch.zeros(
|
641 |
+
(
|
642 |
+
inputs_embeds.size(0),
|
643 |
+
num_heads,
|
644 |
+
head_size,
|
645 |
+
head_size,
|
646 |
+
self.config.num_hidden_layers,
|
647 |
+
),
|
648 |
+
dtype=torch.float32,
|
649 |
+
requires_grad=False,
|
650 |
+
device=inputs_embeds.device,
|
651 |
+
).contiguous()
|
652 |
+
state_ffn_x = torch.zeros(
|
653 |
+
(inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
|
654 |
+
dtype=inputs_embeds.dtype,
|
655 |
+
requires_grad=False,
|
656 |
+
device=inputs_embeds.device,
|
657 |
+
).contiguous()
|
658 |
+
state.append(state_attn_x)
|
659 |
+
state.append(state_attn_kv)
|
660 |
+
state.append(state_ffn_x)
|
661 |
+
|
662 |
+
seq_mode = inputs_embeds.shape[1] > 1
|
663 |
+
hidden_states = inputs_embeds
|
664 |
+
|
665 |
+
all_self_attentions = () if output_attentions else None
|
666 |
+
all_hidden_states = () if output_hidden_states else None
|
667 |
+
for idx, block in enumerate(self.blocks):
|
668 |
+
hidden_states, state, attentions = block(
|
669 |
+
hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
|
670 |
+
)
|
671 |
+
if (
|
672 |
+
self.layers_are_rescaled
|
673 |
+
and self.config.rescale_every > 0
|
674 |
+
and (idx + 1) % self.config.rescale_every == 0
|
675 |
+
):
|
676 |
+
hidden_states = hidden_states / 2
|
677 |
+
|
678 |
+
if output_hidden_states:
|
679 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
680 |
+
|
681 |
+
if output_attentions:
|
682 |
+
all_self_attentions = all_self_attentions + (attentions,)
|
683 |
+
|
684 |
+
hidden_states = self.ln_out(hidden_states)
|
685 |
+
|
686 |
+
if output_hidden_states:
|
687 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
688 |
+
|
689 |
+
if not return_dict:
|
690 |
+
return (hidden_states, state, all_hidden_states, all_self_attentions)
|
691 |
+
|
692 |
+
return Rwkv5Output(
|
693 |
+
last_hidden_state=hidden_states,
|
694 |
+
state=state,
|
695 |
+
hidden_states=all_hidden_states, # None
|
696 |
+
attentions=all_self_attentions, # None
|
697 |
+
)
|
698 |
+
|
699 |
+
def _rescale_layers(self):
|
700 |
+
# Layers should be rescaled for inference only.
|
701 |
+
if self.layers_are_rescaled == (not self.training):
|
702 |
+
return
|
703 |
+
if self.config.rescale_every > 0:
|
704 |
+
with torch.no_grad():
|
705 |
+
for block_id, block in enumerate(self.blocks):
|
706 |
+
if self.training:
|
707 |
+
block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
|
708 |
+
block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
|
709 |
+
else:
|
710 |
+
# Deal with quantization statistics
|
711 |
+
if hasattr(block.attention.output.weight, "SCB"):
|
712 |
+
block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
|
713 |
+
block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
|
714 |
+
elif hasattr(block.attention.output.weight, "quant_state"):
|
715 |
+
self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
|
716 |
+
self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
|
717 |
+
else:
|
718 |
+
block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
|
719 |
+
block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
|
720 |
+
|
721 |
+
self.layers_are_rescaled = not self.training
|
722 |
+
|
723 |
+
def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
|
724 |
+
r"""
|
725 |
+
Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
|
726 |
+
be quantized again.
|
727 |
+
"""
|
728 |
+
if not is_bitsandbytes_available():
|
729 |
+
raise ImportError("Please install bitsandbytes to use this method.")
|
730 |
+
import bitsandbytes as bnb
|
731 |
+
|
732 |
+
dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
|
733 |
+
|
734 |
+
dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
|
735 |
+
|
736 |
+
# re-quantize the model:
|
737 |
+
# we need to put it first on CPU then back to the device
|
738 |
+
# this will create an overhead :/
|
739 |
+
# We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
|
740 |
+
# bugs with bnb
|
741 |
+
quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
|
742 |
+
setattr(target_layer, "weight", quant_weight)
|
743 |
+
|
744 |
+
|
745 |
+
# copied from HuggingFace https://github.com/huggingface/transformers/blob/main/src/transformers/models/rwkv/modeling_rwkv.py
|
746 |
+
@add_start_docstrings(
|
747 |
+
"""
|
748 |
+
The RWKV5 Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
749 |
+
embeddings).
|
750 |
+
""",
|
751 |
+
RWKV5_START_DOCSTRING,
|
752 |
+
)
|
753 |
+
# Copied from transformers.models.rwkv.modeling_rwkv.RwkvForCausalLM with Rwkv->Rwkv5
|
754 |
+
class Rwkv5ForCausalLM(Rwkv5PreTrainedModel):
|
755 |
+
_tied_weights_keys = ["head.weight"]
|
756 |
+
|
757 |
+
def __init__(self, config):
|
758 |
+
super().__init__(config)
|
759 |
+
self.rwkv = Rwkv5Model(config)
|
760 |
+
self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
761 |
+
|
762 |
+
# Initialize weights and apply final processing
|
763 |
+
self.post_init()
|
764 |
+
|
765 |
+
def get_output_embeddings(self):
|
766 |
+
return self.head
|
767 |
+
|
768 |
+
def set_output_embeddings(self, new_embeddings):
|
769 |
+
self.head = new_embeddings
|
770 |
+
|
771 |
+
def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
|
772 |
+
# only last token for inputs_ids if the state is passed along.
|
773 |
+
if state is not None:
|
774 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
775 |
+
|
776 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
777 |
+
if inputs_embeds is not None and state is None:
|
778 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
779 |
+
else:
|
780 |
+
model_inputs = {"input_ids": input_ids}
|
781 |
+
|
782 |
+
model_inputs["state"] = state
|
783 |
+
return model_inputs
|
784 |
+
|
785 |
+
@add_start_docstrings_to_model_forward(RWKV5_INPUTS_DOCSTRING)
|
786 |
+
@add_code_sample_docstrings(
|
787 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
788 |
+
output_type=Rwkv5CausalLMOutput,
|
789 |
+
config_class=_CONFIG_FOR_DOC,
|
790 |
+
)
|
791 |
+
def forward(
|
792 |
+
self,
|
793 |
+
input_ids: Optional[torch.LongTensor] = None,
|
794 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
795 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
796 |
+
state: Optional[List[torch.FloatTensor]] = None,
|
797 |
+
labels: Optional[torch.LongTensor] = None,
|
798 |
+
use_cache: Optional[bool] = None,
|
799 |
+
output_attentions: Optional[bool] = None,
|
800 |
+
output_hidden_states: Optional[bool] = None,
|
801 |
+
return_dict: Optional[bool] = None,
|
802 |
+
) -> Union[Tuple, Rwkv5CausalLMOutput]:
|
803 |
+
r"""
|
804 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
805 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
806 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
807 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
808 |
+
"""
|
809 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
810 |
+
|
811 |
+
outputs = self.rwkv(
|
812 |
+
input_ids,
|
813 |
+
inputs_embeds=inputs_embeds,
|
814 |
+
state=state,
|
815 |
+
use_cache=use_cache,
|
816 |
+
output_attentions=output_attentions,
|
817 |
+
output_hidden_states=output_hidden_states,
|
818 |
+
return_dict=return_dict,
|
819 |
+
)
|
820 |
+
hidden_states = outputs[0]
|
821 |
+
|
822 |
+
logits = self.head(hidden_states)
|
823 |
+
|
824 |
+
loss = None
|
825 |
+
if labels is not None:
|
826 |
+
# move labels to correct device to enable model parallelism
|
827 |
+
labels = labels.to(logits.device)
|
828 |
+
# Shift so that tokens < n predict n
|
829 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
830 |
+
shift_labels = labels[..., 1:].contiguous()
|
831 |
+
# Flatten the tokens
|
832 |
+
loss_fct = CrossEntropyLoss()
|
833 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
834 |
+
|
835 |
+
if not return_dict:
|
836 |
+
output = (logits,) + outputs[1:]
|
837 |
+
return ((loss,) + output) if loss is not None else output
|
838 |
+
|
839 |
+
return Rwkv5CausalLMOutput(
|
840 |
+
loss=loss,
|
841 |
+
logits=logits,
|
842 |
+
state=outputs.state,
|
843 |
+
hidden_states=outputs.hidden_states,
|
844 |
+
attentions=outputs.attentions,
|
845 |
+
)
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d6309884bb502468a627066dc0b34e38a3d9988905bcb8137b9e59265ac11e98
|
3 |
+
size 18526784330
|
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
|
|