yueyulin commited on
Commit
e6cb871
·
verified ·
1 Parent(s): da559ef

Upload 4 files

Browse files
Files changed (4) hide show
  1. hybrid_cache.py +154 -0
  2. modeling_rwkv_hybrid.py +632 -0
  3. test_gradio.py +80 -0
  4. wkv.py +522 -0
hybrid_cache.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from typing import Any, Dict, Optional, Union
3
+ from transformers.cache_utils import DynamicCache
4
+
5
+
6
+ class TimeMixState:
7
+ def __init__(self, shift_state: torch.Tensor, wkv_state: torch.Tensor):
8
+ self.shift_state = shift_state
9
+ self.wkv_state = wkv_state
10
+
11
+
12
+ class ChannelMixState:
13
+ def __init__(self, shift_state: torch.Tensor):
14
+ self.shift_state = shift_state
15
+
16
+
17
+ class BlockState:
18
+ def __init__(self, time_mix_state: TimeMixState,
19
+ channel_mix_state: ChannelMixState):
20
+ self.time_mix_state = time_mix_state
21
+ self.channel_mix_state = channel_mix_state
22
+
23
+
24
+ class BlockStateList:
25
+ def __init__(self, shift_states, wkv_states):
26
+ self.wkv_states = wkv_states
27
+ self.shift_states = shift_states
28
+
29
+ @staticmethod
30
+ def create(N, B, C, H, device, dtype):
31
+ result = BlockStateList.empty(N, B, C, H, device, dtype)
32
+ result.wkv_states[:] = 0
33
+ result.wkv_states[:] = 0
34
+ result.shift_states[:] = 0
35
+ return result
36
+
37
+ @staticmethod
38
+ def empty(N, B, C, H, device, dtype):
39
+ wkv_states = torch.empty((N, B, H, C//H, C//H),
40
+ device=device,
41
+ dtype=torch.bfloat16)
42
+ shift_states = torch.empty((N, 2, B, C), device=device, dtype=dtype)
43
+ return BlockStateList(shift_states, wkv_states)
44
+
45
+ def __getitem__(self, layer: int):
46
+ return BlockState(
47
+ TimeMixState(self.shift_states[layer, 0], self.wkv_states[layer]),
48
+ ChannelMixState(self.shift_states[layer, 1]))
49
+
50
+ def __setitem__(self, layer: int, state: BlockState):
51
+ self.shift_states[layer, 0] = state.time_mix_state.shift_state
52
+ self.wkv_states[layer] = state.time_mix_state.wkv_state
53
+ self.shift_states[layer, 1] = state.channel_mix_state.shift_state
54
+
55
+
56
+ class HybridCache(DynamicCache):
57
+ def __init__(self) -> None:
58
+ super().__init__()
59
+ self.rwkv_layers = set()
60
+
61
+ def __repr__(self) -> str:
62
+ rwkv_layers = f"HybridCache(rwkv_layers={self.rwkv_layers})"
63
+ # count the number of key_cache and value_cache
64
+ key_cache_count = sum(len(cache) for cache in self.key_cache)
65
+ value_cache_count = sum(len(cache) for cache in self.value_cache)
66
+ count_info = rwkv_layers + \
67
+ f", key_cache_count={key_cache_count}, value_cache_count={value_cache_count}"
68
+ memories = 0
69
+ seq_length = self.get_seq_length()
70
+ for cache in self.value_cache:
71
+ for data in cache:
72
+ if not isinstance(data, torch.Tensor):
73
+ memories += data.time_mix_state.wkv_state.numel()
74
+ else:
75
+ memories += data.numel()
76
+ count_info += f", memories={memories / 1024/1024}MB, seq_length={seq_length}"
77
+ return count_info
78
+
79
+ def update(self,
80
+ key_states: Union[int, torch.Tensor],
81
+ value_states: Union[torch.Tensor, BlockState],
82
+ layer_idx: int,
83
+ cache_kwargs: Optional[Dict[str, Any]] = None):
84
+ if isinstance(key_states, int) and not isinstance(value_states, torch.Tensor):
85
+ self.rwkv_layers.add(layer_idx)
86
+ if layer_idx >= len(self.key_cache):
87
+ self.key_cache.append([])
88
+ self.value_cache.append([])
89
+
90
+ if len(self.key_cache[layer_idx]) == 0:
91
+ self.key_cache[layer_idx].append(key_states)
92
+ self.value_cache[layer_idx].append(value_states)
93
+ else:
94
+ self.key_cache[layer_idx][0] = self.key_cache[layer_idx][0]+key_states
95
+ self.value_cache[layer_idx][0] = value_states
96
+
97
+ return key_states, value_states
98
+
99
+ return super().update(key_states, value_states, layer_idx, cache_kwargs)
100
+
101
+ def get_seq_length(self, layer_idx: Optional[int] = 0):
102
+ if layer_idx in self.rwkv_layers:
103
+ return self.key_cache[layer_idx][0]
104
+ return super().get_seq_length(layer_idx)
105
+
106
+ def get_max_length(self):
107
+ return super().get_max_length()
108
+
109
+ def reorder_cache(self, beam_idx):
110
+ return super().reorder_cache(beam_idx)
111
+
112
+ def __getitem__(self, item):
113
+ if item in self.rwkv_layers:
114
+ return self.value_cache[item]
115
+ return super().__getitem__(item)
116
+
117
+ def offload_to_cpu(self):
118
+ for cache in self.value_cache:
119
+ for data in cache:
120
+ if isinstance(data, torch.Tensor):
121
+ data.cpu()
122
+ else:
123
+ data.time_mix_state.wkv_state.cpu()
124
+ data.time_mix_state.shift_state.cpu()
125
+
126
+ def offload_to_cuda(self, device: str):
127
+ for cache in self.value_cache:
128
+ for data in cache:
129
+ if isinstance(data, torch.Tensor):
130
+ data.cuda(device)
131
+ else:
132
+ data.time_mix_state.wkv_state.cuda(device)
133
+ data.time_mix_state.shift_state.cuda(device)
134
+
135
+ def offload_to_device(self, device_type: str, device_id: int = 0):
136
+ for cache in self.value_cache:
137
+ for data in cache:
138
+ if isinstance(data, torch.Tensor):
139
+ method = getattr(data, device_type)
140
+ if device_type == 'cpu':
141
+ method()
142
+ else:
143
+ method(device_id)
144
+ else:
145
+ wkv_state_method = getattr(
146
+ data.time_mix_state.wkv_state, device_type)
147
+ shift_state_method = getattr(
148
+ data.time_mix_state.shift_state, device_type)
149
+ if device_type == 'cpu':
150
+ wkv_state_method()
151
+ shift_state_method()
152
+ else:
153
+ wkv_state_method(device_id)
154
+ shift_state_method(device_id)
modeling_rwkv_hybrid.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers.cache_utils import Cache
6
+
7
+ from transformers.activations import ACT2FN
8
+ from transformers.cache_utils import Cache, StaticCache
9
+ from .hybrid_cache import HybridCache
10
+ from transformers.generation import GenerationMixin
11
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
12
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
13
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
14
+
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPast,
17
+ CausalLMOutputWithPast,
18
+ )
19
+ from transformers.processing_utils import Unpack
20
+ from transformers.utils import (
21
+ LossKwargs,
22
+ add_start_docstrings,
23
+ add_start_docstrings_to_model_forward,
24
+ logging,
25
+ )
26
+
27
+ import threading
28
+ from .wkv import Rwkv7Attention, Rwkv6Attention
29
+ from .configuration_rwkv_hybrid import RwkvHybridConfig
30
+
31
+ from transformers.models.qwen2.modeling_qwen2 import (Qwen2MLP,
32
+ Qwen2RMSNorm,
33
+ Qwen2RotaryEmbedding,
34
+ Qwen2Attention)
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CONFIG_FOR_DOC = "RwkvHybridConfig"
39
+
40
+ class RwkvHybridDecoderLayer(nn.Module):
41
+ def __init__(self, config: RwkvHybridConfig, layer_idx: int, update_v_first, get_v_first):
42
+ super().__init__()
43
+ self.hidden_size = config.hidden_size
44
+
45
+ self.is_rwkv = True if layer_idx in config.wkv_layers else False
46
+ if self.is_rwkv:
47
+ if config.wkv_version == 7:
48
+ self.self_attn = Rwkv7Attention(args=config, layer_id=layer_idx,
49
+ update_v_first=update_v_first,
50
+ get_v_first=get_v_first)
51
+ elif config.wkv_version == 6:
52
+ self.self_attn = Rwkv6Attention(args=config, layer_id=layer_idx,
53
+ update_v_first=update_v_first,
54
+ get_v_first=get_v_first)
55
+ else:
56
+ raise NotImplementedError
57
+ elif not self.is_rwkv:
58
+ self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
59
+ else:
60
+ self.self_attn = None
61
+ raise NotImplementedError
62
+
63
+ self.mlp = Qwen2MLP(config)
64
+ self.input_layernorm = Qwen2RMSNorm(
65
+ config.hidden_size, eps=config.rms_norm_eps)
66
+ self.post_attention_layernorm = Qwen2RMSNorm(
67
+ config.hidden_size, eps=config.rms_norm_eps)
68
+
69
+
70
+ def forward(
71
+ self,
72
+ hidden_states: torch.Tensor,
73
+ attention_mask: Optional[torch.Tensor] = None,
74
+ position_ids: Optional[torch.LongTensor] = None,
75
+ past_key_value: Optional[Cache] = None,
76
+ output_attentions: Optional[bool] = False,
77
+ use_cache: Optional[bool] = False,
78
+ cache_position: Optional[torch.LongTensor] = None,
79
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
80
+ **kwargs,
81
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
82
+ residual = hidden_states
83
+
84
+ hidden_states = self.input_layernorm(hidden_states)
85
+
86
+ # RWKV attention
87
+ hidden_states, self_attn_weights = self.self_attn(
88
+ hidden_states=hidden_states,
89
+ attention_mask=attention_mask,
90
+ position_ids=position_ids,
91
+ past_key_value=past_key_value,
92
+ output_attentions=output_attentions,
93
+ use_cache=use_cache,
94
+ cache_position=cache_position,
95
+ position_embeddings=position_embeddings,
96
+ )
97
+ hidden_states = residual + hidden_states
98
+
99
+ # Fully Connected
100
+ residual = hidden_states
101
+ hidden_states = self.post_attention_layernorm(hidden_states)
102
+ hidden_states = self.mlp(hidden_states)
103
+ hidden_states = residual + hidden_states
104
+
105
+ outputs = (hidden_states,)
106
+ if output_attentions:
107
+ outputs += (self_attn_weights,)
108
+
109
+ return outputs
110
+
111
+ RWKV_HYBRID_START_DOCSTRING = r"""
112
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
113
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
114
+ etc.)
115
+
116
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
117
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
118
+ and behavior.
119
+
120
+ Parameters:
121
+ config ([`RwkvHybridConfig`]):
122
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
123
+ load the weights associated with the model, only the configuration. Check out the
124
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
125
+ """
126
+
127
+ @add_start_docstrings(
128
+ "The bare RWKV Hybrid Model outputting raw hidden-states without any specific head on top.",
129
+ RWKV_HYBRID_START_DOCSTRING,
130
+ )
131
+ class RwkvHybridPreTrainedModel(PreTrainedModel):
132
+ config_class = RwkvHybridConfig
133
+ base_model_prefix = "rwkv_hybrid"
134
+ supports_gradient_checkpointing = True
135
+ _no_split_modules = ["RwkvHybridDecoderLayer"]
136
+ _skip_keys_device_placement = ["past_key_values"]
137
+
138
+ def _init_weights(self, module):
139
+ std = self.config.initializer_range
140
+ if isinstance(module, nn.Linear):
141
+ module.weight.data.normal_(mean=0.0, std=std)
142
+ if module.bias is not None:
143
+ module.bias.data.zero_()
144
+ elif isinstance(module, nn.Embedding):
145
+ module.weight.data.normal_(mean=0.0, std=std)
146
+ if module.padding_idx is not None:
147
+ module.weight.data[module.padding_idx].zero_()
148
+
149
+ RWKV_HYBRID_INPUTS_DOCSTRING = r"""
150
+ Args:
151
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
152
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
153
+ it.
154
+
155
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
156
+ [`PreTrainedTokenizer.__call__`] for details.
157
+
158
+ [What are input IDs?](../glossary#input-ids)
159
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
160
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
161
+
162
+ - 1 for tokens that are **not masked**,
163
+ - 0 for tokens that are **masked**.
164
+
165
+ [What are attention masks?](../glossary#attention-mask)
166
+
167
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
168
+ [`PreTrainedTokenizer.__call__`] for details.
169
+
170
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
171
+ `past_key_values`).
172
+
173
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
174
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
175
+ information on the default strategy.
176
+
177
+ - 1 indicates the head is **not masked**,
178
+ - 0 indicates the head is **masked**.
179
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
180
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
181
+ config.n_positions - 1]`.
182
+
183
+ [What are position IDs?](../glossary#position-ids)
184
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
185
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
186
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
187
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
188
+
189
+ Two formats are allowed:
190
+ - a [`~cache_utils.Cache`] instance, see our
191
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
192
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
193
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
194
+ cache format.
195
+
196
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
197
+ legacy cache format will be returned.
198
+
199
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
200
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
201
+ of shape `(batch_size, sequence_length)`.
202
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
203
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
204
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
205
+ model's internal embedding lookup matrix.
206
+ use_cache (`bool`, *optional*):
207
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
208
+ `past_key_values`).
209
+ output_attentions (`bool`, *optional*):
210
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
211
+ tensors for more detail.
212
+ output_hidden_states (`bool`, *optional*):
213
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
214
+ more detail.
215
+ return_dict (`bool`, *optional*):
216
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
217
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
218
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
219
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
220
+ the complete sequence length.
221
+ """
222
+
223
+
224
+ @add_start_docstrings(
225
+ "The bare RWKV Hybrid Model outputting raw hidden-states without any specific head on top.",
226
+ RWKV_HYBRID_START_DOCSTRING,
227
+ )
228
+ class RwkvHybridModel(RwkvHybridPreTrainedModel):
229
+ """
230
+ RWKV and Transformer hybrid decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`RwkvHybridDecoderLayer`]
231
+
232
+ Args:
233
+ config: RwkvHybridConfig
234
+ """
235
+
236
+ def __init__(self, config: RwkvHybridConfig):
237
+ super().__init__(config)
238
+ self.padding_idx = config.pad_token_id
239
+ self.vocab_size = config.vocab_size
240
+
241
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
242
+ self.thread_local = threading.local()
243
+ self.thread_local.v_first = None
244
+ self.layers = nn.ModuleList(
245
+ [RwkvHybridDecoderLayer(config, layer_idx, self.update_v_first, self.get_v_first) for layer_idx in range(config.num_hidden_layers)]
246
+ )
247
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
248
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
249
+ self.gradient_checkpointing = False
250
+
251
+ # Initialize weights and apply final processing
252
+ self.post_init()
253
+
254
+ def post_init(self):
255
+ """
256
+ A method executed at the end of each Transformer model initialization, to execute code that needs the model's
257
+ modules properly initialized (such as weight initialization).
258
+ """
259
+ self.init_weights()
260
+ self._backward_compatibility_gradient_checkpointing()
261
+ # If current model is a base model, attach `base_model_tp_plan` from config
262
+ if self.base_model is self:
263
+ self._tp_plan = self.config.base_model_tp_plan
264
+ from transformers.modeling_utils import _init_weights
265
+ if _init_weights:
266
+ for layer in self.layers:
267
+ layer.self_attn.time_mixer.post_init()
268
+
269
+ def update_v_first(self, new_v_first):
270
+ """Callback function to update v_first in HybridModel."""
271
+ self.thread_local.v_first = new_v_first
272
+
273
+ def get_v_first(self):
274
+ return self.thread_local.v_first
275
+
276
+ def get_input_embeddings(self):
277
+ return self.embed_tokens
278
+
279
+ def set_input_embeddings(self, value):
280
+ self.embed_tokens = value
281
+
282
+ @add_start_docstrings_to_model_forward(RWKV_HYBRID_INPUTS_DOCSTRING)
283
+ def forward(
284
+ self,
285
+ input_ids: torch.LongTensor = None,
286
+ attention_mask: Optional[torch.Tensor] = None,
287
+ position_ids: Optional[torch.LongTensor] = None,
288
+ past_key_values: Optional[Cache] = None,
289
+ inputs_embeds: Optional[torch.FloatTensor] = None,
290
+ use_cache: Optional[bool] = None,
291
+ output_attentions: Optional[bool] = None,
292
+ output_hidden_states: Optional[bool] = None,
293
+ return_dict: Optional[bool] = None,
294
+ cache_position: Optional[torch.LongTensor] = None,
295
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
296
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
297
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
298
+ output_hidden_states = (
299
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
300
+ )
301
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
302
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
303
+
304
+ if (input_ids is None) ^ (inputs_embeds is not None):
305
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
306
+
307
+ if self.gradient_checkpointing and self.training and use_cache:
308
+ logger.warning_once(
309
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
310
+ )
311
+ use_cache = False
312
+
313
+ if inputs_embeds is None:
314
+ inputs_embeds = self.embed_tokens(input_ids)
315
+
316
+ if use_cache and past_key_values is None:
317
+ past_key_values = HybridCache()
318
+
319
+ if cache_position is None:
320
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
321
+ cache_position = torch.arange(
322
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
323
+ )
324
+
325
+ if position_ids is None:
326
+ position_ids = cache_position.unsqueeze(0)
327
+
328
+ causal_mask = self._update_causal_mask(
329
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
330
+ )
331
+
332
+ hidden_states = inputs_embeds
333
+
334
+ # create position embeddings to be shared across the decoder layers
335
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
336
+
337
+ # decoder layers
338
+ all_hidden_states = () if output_hidden_states else None
339
+ all_self_attns = () if output_attentions else None
340
+
341
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
342
+ if output_hidden_states:
343
+ all_hidden_states += (hidden_states,)
344
+
345
+ if self.gradient_checkpointing and self.training:
346
+ layer_outputs = self._gradient_checkpointing_func(
347
+ decoder_layer.__call__,
348
+ hidden_states,
349
+ causal_mask,
350
+ position_ids,
351
+ past_key_values,
352
+ output_attentions,
353
+ use_cache,
354
+ cache_position,
355
+ position_embeddings,
356
+ )
357
+ else:
358
+ layer_outputs = decoder_layer(
359
+ hidden_states,
360
+ attention_mask=causal_mask,
361
+ position_ids=position_ids,
362
+ past_key_value=past_key_values,
363
+ output_attentions=output_attentions,
364
+ use_cache=use_cache,
365
+ cache_position=cache_position,
366
+ position_embeddings=position_embeddings,
367
+ **flash_attn_kwargs,
368
+ )
369
+
370
+ hidden_states = layer_outputs[0]
371
+
372
+ if output_attentions:
373
+ all_self_attns += (layer_outputs[1],)
374
+
375
+ hidden_states = self.norm(hidden_states)
376
+
377
+ # add hidden states from the last decoder layer
378
+ if output_hidden_states:
379
+ all_hidden_states += (hidden_states,)
380
+
381
+ output = BaseModelOutputWithPast(
382
+ last_hidden_state=hidden_states,
383
+ past_key_values=past_key_values if use_cache else None,
384
+ hidden_states=all_hidden_states,
385
+ attentions=all_self_attns,
386
+ )
387
+ return output if return_dict else output.to_tuple()
388
+
389
+ def _update_causal_mask(
390
+ self,
391
+ attention_mask: torch.Tensor,
392
+ input_tensor: torch.Tensor,
393
+ cache_position: torch.Tensor,
394
+ past_key_values: Cache,
395
+ output_attentions: bool,
396
+ ):
397
+ if self.config._attn_implementation == "flash_attention_2":
398
+ if attention_mask is not None and (attention_mask == 0.0).any():
399
+ return attention_mask
400
+ return None
401
+
402
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
403
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
404
+ # to infer the attention mask.
405
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
406
+ using_static_cache = isinstance(past_key_values, StaticCache)
407
+
408
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
409
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
410
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
411
+ attention_mask,
412
+ inputs_embeds=input_tensor,
413
+ past_key_values_length=past_seen_tokens,
414
+ is_training=self.training,
415
+ ):
416
+ return None
417
+
418
+ dtype, device = input_tensor.dtype, input_tensor.device
419
+ sequence_length = input_tensor.shape[1]
420
+ if using_static_cache:
421
+ target_length = past_key_values.get_max_cache_shape()
422
+ else:
423
+ target_length = (
424
+ attention_mask.shape[-1]
425
+ if isinstance(attention_mask, torch.Tensor)
426
+ else past_seen_tokens + sequence_length + 1
427
+ )
428
+
429
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
430
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
431
+ attention_mask,
432
+ sequence_length=sequence_length,
433
+ target_length=target_length,
434
+ dtype=dtype,
435
+ device=device,
436
+ cache_position=cache_position,
437
+ batch_size=input_tensor.shape[0],
438
+ )
439
+
440
+ if (
441
+ self.config._attn_implementation == "sdpa"
442
+ and attention_mask is not None
443
+ and attention_mask.device.type == "cuda"
444
+ and not output_attentions
445
+ ):
446
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
447
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
448
+ # Details: https://github.com/pytorch/pytorch/issues/110213
449
+ min_dtype = torch.finfo(dtype).min
450
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
451
+
452
+ return causal_mask
453
+
454
+ @staticmethod
455
+ def _prepare_4d_causal_attention_mask_with_cache_position(
456
+ attention_mask: torch.Tensor,
457
+ sequence_length: int,
458
+ target_length: int,
459
+ dtype: torch.dtype,
460
+ device: torch.device,
461
+ cache_position: torch.Tensor,
462
+ batch_size: int,
463
+ **kwargs,
464
+ ):
465
+ """
466
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
467
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
468
+
469
+ Args:
470
+ attention_mask (`torch.Tensor`):
471
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
472
+ `(batch_size, 1, query_length, key_value_length)`.
473
+ sequence_length (`int`):
474
+ The sequence length being processed.
475
+ target_length (`int`):
476
+ The target length: when generating with static cache, the mask should be as long as the static cache,
477
+ to account for the 0 padding, the part of the cache that is not filled yet.
478
+ dtype (`torch.dtype`):
479
+ The dtype to use for the 4D attention mask.
480
+ device (`torch.device`):
481
+ The device to plcae the 4D attention mask on.
482
+ cache_position (`torch.Tensor`):
483
+ Indices depicting the position of the input sequence tokens in the sequence.
484
+ batch_size (`torch.Tensor`):
485
+ Batch size.
486
+ """
487
+ if attention_mask is not None and attention_mask.dim() == 4:
488
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
489
+ causal_mask = attention_mask
490
+ else:
491
+ min_dtype = torch.finfo(dtype).min
492
+ causal_mask = torch.full(
493
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
494
+ )
495
+ if sequence_length != 1:
496
+ causal_mask = torch.triu(causal_mask, diagonal=1)
497
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
498
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
499
+ if attention_mask is not None:
500
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
501
+ mask_length = attention_mask.shape[-1]
502
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
503
+ padding_mask = padding_mask == 0
504
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
505
+ padding_mask, min_dtype
506
+ )
507
+
508
+ return causal_mask
509
+
510
+
511
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
512
+
513
+ class RwkvHybridForCausalLM(RwkvHybridPreTrainedModel, GenerationMixin):
514
+ _tied_weights_keys = ["lm_head.weight"]
515
+ _tp_plan = {"lm_head": "colwise_rep"}
516
+
517
+ def __init__(self, config):
518
+ super().__init__(config)
519
+ self.model = RwkvHybridModel(config)
520
+ self.vocab_size = config.vocab_size
521
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
522
+
523
+ # Initialize weights and apply final processing
524
+ self.post_init()
525
+
526
+ def get_input_embeddings(self):
527
+ return self.model.embed_tokens
528
+
529
+ def set_input_embeddings(self, value):
530
+ self.model.embed_tokens = value
531
+
532
+ def get_output_embeddings(self):
533
+ return self.lm_head
534
+
535
+ def set_output_embeddings(self, new_embeddings):
536
+ self.lm_head = new_embeddings
537
+
538
+ def set_decoder(self, decoder):
539
+ self.model = decoder
540
+
541
+ def get_decoder(self):
542
+ return self.model
543
+
544
+ # @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
545
+ # @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
546
+ def forward(
547
+ self,
548
+ input_ids: torch.LongTensor = None,
549
+ attention_mask: Optional[torch.Tensor] = None,
550
+ position_ids: Optional[torch.LongTensor] = None,
551
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
552
+ inputs_embeds: Optional[torch.FloatTensor] = None,
553
+ labels: Optional[torch.LongTensor] = None,
554
+ use_cache: Optional[bool] = None,
555
+ output_attentions: Optional[bool] = None,
556
+ output_hidden_states: Optional[bool] = None,
557
+ return_dict: Optional[bool] = None,
558
+ cache_position: Optional[torch.LongTensor] = None,
559
+ num_logits_to_keep: int = 0,
560
+ **kwargs: Unpack[KwargsForCausalLM],
561
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
562
+ r"""
563
+ Args:
564
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
565
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
566
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
567
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
568
+
569
+ num_logits_to_keep (`int`, *optional*):
570
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
571
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
572
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
573
+
574
+ Returns:
575
+
576
+ Example:
577
+
578
+ ```python
579
+ >>> from transformers import AutoTokenizer, RwkvHybridForCausalLM
580
+
581
+ >>> model = Qwen2ForCausalLM.from_pretrained("RWKV-Red-Team/ARWKV-7B-Preview-0.1")
582
+ >>> tokenizer = AutoTokenizer.from_pretrained("RWKV-Red-Team/ARWKV-7B-Preview-0.1")
583
+
584
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
585
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
586
+
587
+ >>> # Generate
588
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
589
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
590
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
591
+ ```"""
592
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
593
+ output_hidden_states = (
594
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
595
+ )
596
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
597
+
598
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
599
+ outputs = self.model(
600
+ input_ids=input_ids,
601
+ attention_mask=attention_mask,
602
+ position_ids=position_ids,
603
+ past_key_values=past_key_values,
604
+ inputs_embeds=inputs_embeds,
605
+ use_cache=use_cache,
606
+ output_attentions=output_attentions,
607
+ output_hidden_states=output_hidden_states,
608
+ return_dict=return_dict,
609
+ cache_position=cache_position,
610
+ **kwargs,
611
+ )
612
+
613
+ hidden_states = outputs[0]
614
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
615
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
616
+
617
+ loss = None
618
+ if labels is not None:
619
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
620
+
621
+ if not return_dict:
622
+ output = (logits,) + outputs[1:]
623
+ return (loss,) + output if loss is not None else output
624
+
625
+ return CausalLMOutputWithPast(
626
+ loss=loss,
627
+ logits=logits,
628
+ past_key_values=outputs.past_key_values,
629
+ hidden_states=outputs.hidden_states,
630
+ attentions=outputs.attentions,
631
+ )
632
+
test_gradio.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from transformers import TextIteratorStreamer
5
+ import threading
6
+
7
+
8
+ model = AutoModelForCausalLM.from_pretrained(
9
+ "RWKV-Red-Team/ARWKV-7B-Preview-0.1",
10
+ device_map="auto",
11
+ torch_dtype=torch.float16,
12
+ trust_remote_code=True,
13
+ )
14
+ tokenizer = AutoTokenizer.from_pretrained(
15
+ "RWKV-Red-Team/ARWKV-7B-Preview-0.1"
16
+ )
17
+ device = "cuda"
18
+
19
+
20
+ def convert_history_to_messages(history):
21
+ messages = []
22
+ for user_msg, bot_msg in history:
23
+ messages.append({"role": "user", "content": user_msg})
24
+ if bot_msg is not None:
25
+ messages.append({"role": "assistant", "content": bot_msg})
26
+ return messages
27
+
28
+
29
+ def stream_chat(prompt, history):
30
+
31
+ messages = convert_history_to_messages(history)
32
+ messages.append({"role": "user", "content": prompt})
33
+
34
+ text = tokenizer.apply_chat_template(
35
+ messages, tokenize=False, add_generation_prompt=True
36
+ )
37
+ model_inputs = tokenizer([text], return_tensors="pt").to(device)
38
+
39
+ streamer = TextIteratorStreamer(
40
+ tokenizer, skip_prompt=True, skip_special_tokens=True
41
+ )
42
+
43
+ generation_kwargs = dict(
44
+ model_inputs,
45
+ streamer=streamer,
46
+ max_new_tokens=4096,
47
+ do_sample=True,
48
+ temperature=1.5,
49
+ top_p=0.2,
50
+ top_k=0,
51
+ )
52
+ thread = threading.Thread(target=model.generate, kwargs=generation_kwargs)
53
+ thread.start()
54
+
55
+ response = ""
56
+ for new_text in streamer:
57
+ response += new_text
58
+ yield history + [(prompt, response)]
59
+
60
+
61
+ with gr.Blocks() as demo:
62
+ chatbot = gr.Chatbot(label="Chat with LLM", height=750)
63
+ msg = gr.Textbox(label="Your Message")
64
+ clear = gr.Button("Clear Chat")
65
+
66
+ def user(user_message, history):
67
+ return "", history + [[user_message, None]]
68
+
69
+ def bot(history):
70
+ prompt = history[-1][0]
71
+ history[-1][1] = ""
72
+ for updated_history in stream_chat(prompt, history[:-1]):
73
+ yield updated_history
74
+
75
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
76
+ bot, chatbot, chatbot
77
+ )
78
+ clear.click(lambda: None, None, chatbot, queue=False)
79
+
80
+ demo.queue().launch(server_name="0.0.0.0")
wkv.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from einops import rearrange
3
+
4
+ from .hybrid_cache import TimeMixState, BlockState
5
+ import math
6
+ import torch.nn as nn
7
+ from torch.nn import functional as F
8
+ from .configuration_rwkv_hybrid import RwkvHybridConfig
9
+
10
+ try:
11
+ import triton
12
+ from rwkvfla.ops.rwkv7 import (
13
+ fused_recurrent_rwkv7,
14
+ chunk_rwkv7,
15
+ native_recurrent_rwkv7,
16
+ ) # pylint: disable=C0411
17
+ from rwkvfla.ops.rwkv6 import (
18
+ fused_recurrent_rwkv6,
19
+ chunk_rwkv6,
20
+ native_recurrent_rwkv6,
21
+ )
22
+ except ImportError:
23
+ from rwkvfla.ops.rwkv7 import native_recurrent_rwkv7 # pylint: disable=C0411
24
+ from rwkvfla.ops.rwkv6 import native_recurrent_rwkv6
25
+
26
+ fused_recurrent_rwkv7 = native_recurrent_rwkv7
27
+ chunk_rwkv7 = native_recurrent_rwkv7
28
+ chunk_rwkv6 = native_recurrent_rwkv6
29
+ fused_recurrent_rwkv6 = native_recurrent_rwkv6
30
+
31
+
32
+ class Rwkv_Tmix_x070(nn.Module):
33
+ def __init__(self, args: RwkvHybridConfig, layer_id, update_v_first, get_v_first):
34
+ super().__init__()
35
+ self.args = args
36
+ self.layer_id = layer_id
37
+ self.hidden_size = args.hidden_size
38
+
39
+ self.update_v_first = update_v_first
40
+ self.get_v_first = get_v_first
41
+
42
+ self.head_size = args.head_size
43
+ self.n_head = args.num_wkv_heads
44
+ assert args.hidden_size % self.n_head == 0
45
+ H = self.n_head
46
+ N = self.head_size
47
+
48
+ self.x_r = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
49
+ self.x_w = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
50
+ self.x_k = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
51
+ self.x_v = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
52
+ self.x_a = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
53
+ self.x_g = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
54
+
55
+ D_DECAY_LORA = 64
56
+ D_AAA_LORA = 64
57
+ D_MV_LORA = 32
58
+ D_GATE_LORA = 128
59
+
60
+ self.w1 = nn.Parameter(torch.Tensor(args.hidden_size, D_DECAY_LORA))
61
+ self.w2 = nn.Parameter(torch.Tensor(D_DECAY_LORA, args.hidden_size))
62
+ self.w0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
63
+
64
+ self.a1 = nn.Parameter(torch.Tensor(args.hidden_size, D_AAA_LORA))
65
+ self.a2 = nn.Parameter(torch.Tensor(D_AAA_LORA, args.hidden_size))
66
+ self.a0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
67
+
68
+ self.v1 = nn.Parameter(torch.Tensor(args.hidden_size, D_MV_LORA))
69
+ self.v2 = nn.Parameter(torch.Tensor(D_MV_LORA, args.hidden_size))
70
+ self.v0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
71
+
72
+ if self.args.wkv_has_gate:
73
+ self.g1 = nn.Parameter(torch.Tensor(args.hidden_size, D_GATE_LORA))
74
+ self.g2 = nn.Parameter(torch.Tensor(D_GATE_LORA, args.hidden_size))
75
+
76
+ self.k_k = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
77
+ self.k_a = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
78
+ self.r_k = nn.Parameter(torch.Tensor(H, N))
79
+
80
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
81
+ self.receptance = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
82
+ self.key = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
83
+ self.value = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
84
+ self.output = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
85
+
86
+ if self.args.wkv_has_group_norm:
87
+ self.ln_x = nn.GroupNorm(
88
+ H, args.hidden_size, eps=(1e-5) * (args.head_size_divisor**2)
89
+ )
90
+
91
+ def post_init(self):
92
+ with torch.no_grad():
93
+ ratio_0_to_1 = self.layer_id / (self.args.num_hidden_layers - 1) # 0 to 1
94
+ ratio_1_to_almost0 = 1.0 - (
95
+ self.layer_id / self.args.num_hidden_layers
96
+ ) # 1 to ~0
97
+
98
+ ddd = torch.ones(1, 1, self.args.hidden_size)
99
+ for i in range(self.args.hidden_size):
100
+ ddd[0, 0, i] = i / self.args.hidden_size
101
+
102
+ nn.init.constant_(self.x_r, 1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0))
103
+ nn.init.constant_(self.x_w, 1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0))
104
+ nn.init.constant_(
105
+ self.x_k,
106
+ 1.0 - (torch.pow(ddd, 0.9 * ratio_1_to_almost0) + 0.4 * ratio_0_to_1),
107
+ )
108
+ nn.init.constant_(
109
+ self.x_v,
110
+ 1.0 - (torch.pow(ddd, 0.4 * ratio_1_to_almost0) + 0.6 * ratio_0_to_1),
111
+ )
112
+ nn.init.constant_(self.x_a, 1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0))
113
+ nn.init.constant_(self.x_g, 1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0))
114
+
115
+ def ortho_init(x, scale):
116
+ shape = x.shape
117
+ original_dtype = x.dtype
118
+ x_fp32 = x.float()
119
+ if len(shape) == 2:
120
+ gain = math.sqrt(shape[0] / shape[1]) if shape[0] > shape[1] else 1
121
+ nn.init.orthogonal_(x_fp32, gain=gain * scale)
122
+ elif len(shape) == 3:
123
+ gain = math.sqrt(shape[1] / shape[2]) if shape[1] > shape[2] else 1
124
+ for i in range(shape[0]):
125
+ nn.init.orthogonal_(x_fp32[i], gain=gain * scale)
126
+ else:
127
+ raise ValueError("ortho_init only supports 2D or 3D tensors")
128
+ x.data.copy_(x_fp32.to(original_dtype))
129
+ return x
130
+
131
+ D_DECAY_LORA = 64
132
+ nn.init.zeros_(self.w1)
133
+ self.w2 = nn.Parameter(
134
+ ortho_init(torch.zeros(D_DECAY_LORA, self.args.hidden_size), 0.1)
135
+ )
136
+
137
+ decay_speed = torch.ones(self.args.hidden_size)
138
+ for n in range(self.args.hidden_size):
139
+ decay_speed[n] = -7 + 5 * (n / (self.args.hidden_size - 1)) ** (
140
+ 0.85 + 1.0 * ratio_0_to_1**0.5
141
+ )
142
+ nn.init.constant_(
143
+ self.w0, decay_speed.reshape(1, 1, self.args.hidden_size) + 0.5
144
+ )
145
+
146
+ D_AAA_LORA = 64
147
+ nn.init.zeros_(self.a1)
148
+ self.a2 = nn.Parameter(
149
+ ortho_init(torch.zeros(D_AAA_LORA, self.args.hidden_size), 0.1)
150
+ )
151
+ nn.init.zeros_(self.a0)
152
+
153
+ D_MV_LORA = 32
154
+ nn.init.zeros_(self.v1)
155
+ self.v2 = nn.Parameter(
156
+ ortho_init(torch.zeros(D_MV_LORA, self.args.hidden_size), 0.1)
157
+ )
158
+ nn.init.constant_(self.v0, 1.0)
159
+
160
+ D_GATE_LORA = 128
161
+ if self.args.wkv_has_gate:
162
+ nn.init.zeros_(self.g1)
163
+ self.g2 = nn.Parameter(
164
+ ortho_init(torch.zeros(D_GATE_LORA, self.args.hidden_size), 0.1)
165
+ )
166
+
167
+ nn.init.constant_(self.k_k, 0.85)
168
+ nn.init.constant_(self.k_a, 1.0)
169
+ nn.init.zeros_(self.r_k)
170
+
171
+ nn.init.zeros_(self.receptance.weight)
172
+ nn.init.zeros_(self.key.weight)
173
+ nn.init.zeros_(self.value.weight)
174
+ nn.init.zeros_(self.output.weight)
175
+
176
+ if self.args.wkv_has_group_norm:
177
+ nn.init.ones_(self.ln_x.weight)
178
+ nn.init.zeros_(self.ln_x.bias)
179
+
180
+ def apply_wkv7_state(self, r, k, v, w, a, b, s):
181
+ r = rearrange(r, "b l (h d) -> b h l d", h=self.n_head)
182
+ k = rearrange(k, "b l (h d) -> b h l d", h=self.n_head)
183
+ v = rearrange(v, "b l (h d) -> b h l d", h=self.n_head)
184
+ w = rearrange(w, "b l (h d) -> b h l d", h=self.n_head)
185
+ a = rearrange(a, "b l (h d) -> b h l d", h=self.n_head)
186
+ b = rearrange(b, "b l (h d) -> b h l d", h=self.n_head)
187
+
188
+ if r.device.type == "cpu":
189
+ o, state = native_recurrent_rwkv7(
190
+ r,
191
+ k,
192
+ v,
193
+ w,
194
+ a,
195
+ b,
196
+ scale=1.0,
197
+ initial_state=s.transpose(-1, -2),
198
+ output_final_state=True,
199
+ use_log_w=False,
200
+ head_first=True,
201
+ )
202
+ state = state.transpose(-1, -2)
203
+ elif self.training:
204
+ o, state = chunk_rwkv7(
205
+ r,
206
+ k,
207
+ v,
208
+ w,
209
+ a,
210
+ b,
211
+ scale=1.0,
212
+ initial_state=s,
213
+ output_final_state=True,
214
+ use_log_w=False,
215
+ head_first=True,
216
+ )
217
+ else:
218
+ o, state = fused_recurrent_rwkv7(
219
+ r,
220
+ k,
221
+ v,
222
+ w,
223
+ a,
224
+ b,
225
+ scale=1.0,
226
+ initial_state=s,
227
+ output_final_state=True,
228
+ use_log_w=False,
229
+ head_first=True,
230
+ )
231
+
232
+ x = rearrange(o, "b h l d -> b l (h d)")
233
+ return x, state
234
+
235
+ def forward(self, x, last_state: TimeMixState):
236
+ shift_state = last_state.shift_state
237
+ B, T, C = x.size()
238
+ H = self.n_head
239
+ if shift_state is not None:
240
+ xx = torch.concat((shift_state.unsqueeze(1), x[:, :-1]), dim=1) - x
241
+ else:
242
+ xx = self.time_shift(x) - x
243
+ lx = x[:, -1]
244
+
245
+ xr = x + xx * self.x_r
246
+ xw = x + xx * self.x_w
247
+ xk = x + xx * self.x_k
248
+ xv = x + xx * self.x_v
249
+ xa = x + xx * self.x_a
250
+ xg = x + xx * self.x_g
251
+
252
+ r = self.receptance(xr)
253
+ w = (
254
+ -F.softplus(-(self.w0 + torch.tanh(xw @ self.w1) @ self.w2)) - 0.5
255
+ ) # soft-clamp to (-inf, -0.5)
256
+ k = self.key(xk)
257
+ v = self.value(xv)
258
+ if self.layer_id == 0:
259
+ self.update_v_first(v)
260
+ else:
261
+ # Original implementation
262
+ v = v + (self.get_v_first().to(v.device) - v) * torch.sigmoid(
263
+ self.v0 + (xv @ self.v1) @ self.v2
264
+ ) # add value residual
265
+
266
+ a = torch.sigmoid(
267
+ self.a0 + (xa @ self.a1) @ self.a2
268
+ ) # a is "in-context learning rate"
269
+ if self.args.wkv_has_gate:
270
+ g = torch.sigmoid(xg @ self.g1) @ self.g2
271
+ kk = k * self.k_k
272
+ kk = F.normalize(kk.view(B, T, H, -1), dim=-1, p=2.0).view(B, T, C)
273
+ k = k * (1 + (a - 1) * self.k_a)
274
+
275
+ wkv_state = last_state.wkv_state
276
+ x, wkv_state = self.apply_wkv7_state(
277
+ r,
278
+ k,
279
+ v,
280
+ w,
281
+ -kk,
282
+ (kk * a),
283
+ s=wkv_state,
284
+ )
285
+ if self.args.wkv_has_group_norm:
286
+ x = self.ln_x(x.view(B * T, C)).view(B, T, C)
287
+ x = x + (
288
+ (r.view(B, T, H, -1) * k.view(B, T, H, -1) * self.r_k).sum(
289
+ dim=-1, keepdim=True
290
+ )
291
+ * v.view(B, T, H, -1)
292
+ ).view(B, T, C)
293
+ x = self.output(x * g) if self.args.wkv_has_gate else self.output(x)
294
+ return x, TimeMixState(lx, wkv_state)
295
+
296
+
297
+ class Rwkv7Attention(nn.Module):
298
+ def __init__(self, args: RwkvHybridConfig, layer_id, update_v_first, get_v_first):
299
+ super().__init__()
300
+ self.args = args
301
+ self.layer_idx = layer_id
302
+ self.time_mixer = Rwkv_Tmix_x070(args, layer_id, update_v_first, get_v_first)
303
+
304
+ def forward(self, hidden_states, past_key_value, **kwargs):
305
+ attn_output = hidden_states
306
+ batch_size, token_length, _ = attn_output.size()
307
+
308
+ if past_key_value is not None and len(past_key_value) > self.layer_idx:
309
+ last_state = past_key_value[self.layer_idx][0]
310
+ else:
311
+ last_state = self.init_state(
312
+ batch_size, attn_output.device, attn_output.dtype
313
+ )
314
+
315
+ attn_output, states = self.time_mixer(attn_output, last_state.time_mix_state)
316
+ last_state.time_mix_state = states
317
+
318
+ if past_key_value is not None:
319
+ past_key_value.update(token_length, last_state, self.layer_idx)
320
+ return attn_output, None
321
+
322
+ def init_state(self, batch_size, device, dtype) -> BlockState:
323
+ wkv_states = torch.zeros(
324
+ (
325
+ batch_size,
326
+ self.args.num_wkv_heads,
327
+ self.args.head_size,
328
+ self.args.head_size,
329
+ ),
330
+ device=device,
331
+ dtype=torch.float32,
332
+ )
333
+ token_shift = torch.zeros(
334
+ (batch_size, self.args.hidden_size), device=device, dtype=dtype
335
+ )
336
+ return BlockState(TimeMixState(token_shift, wkv_states), None)
337
+
338
+
339
+ class Rwkv_Tmix_x060(nn.Module):
340
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
341
+ super().__init__()
342
+ self.args = args
343
+ self.layer_id = layer_id
344
+ self.hidden_size = args.hidden_size
345
+
346
+ self.head_size = args.head_size
347
+ self.n_head = args.num_wkv_heads
348
+ assert args.hidden_size % self.n_head == 0
349
+ H = self.n_head
350
+ N = self.head_size
351
+
352
+ with torch.no_grad():
353
+ ratio_0_to_1 = layer_id / (args.n_layer - 1) # 0 to 1
354
+ ratio_1_to_almost0 = 1.0 - (layer_id / args.n_layer) # 1 to ~0
355
+ ddd = torch.ones(1, 1, args.hidden_size)
356
+ for i in range(args.hidden_size):
357
+ ddd[0, 0, i] = i / args.hidden_size
358
+
359
+ # fancy time_mix
360
+ self.time_maa_x = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
361
+ self.time_maa_w = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
362
+ self.time_maa_k = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
363
+ self.time_maa_v = nn.Parameter(
364
+ 1.0 - (torch.pow(ddd, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
365
+ )
366
+ self.time_maa_r = nn.Parameter(
367
+ 1.0 - torch.pow(ddd, 0.5 * ratio_1_to_almost0)
368
+ )
369
+ self.time_maa_g = nn.Parameter(
370
+ 1.0 - torch.pow(ddd, 0.5 * ratio_1_to_almost0)
371
+ )
372
+
373
+ D_MIX_LORA = 32 # generate TIME_MIX for w,k,v,r,g
374
+ if args.hidden_size == 4096:
375
+ D_MIX_LORA = D_MIX_LORA * 2
376
+ self.time_maa_w1 = nn.Parameter(
377
+ torch.zeros(args.hidden_size, D_MIX_LORA * 5)
378
+ )
379
+ self.time_maa_w2 = nn.Parameter(
380
+ torch.zeros(5, D_MIX_LORA, args.hidden_size).uniform_(-0.01, 0.01)
381
+ )
382
+
383
+ # fancy time_decay
384
+ decay_speed = torch.ones(args.head_size)
385
+ for n in range(args.head_size):
386
+ decay_speed[n] = -6 + 5 * (n / (args.head_size - 1)) ** (
387
+ 0.7 + 1.3 * ratio_0_to_1
388
+ )
389
+ self.time_decay = nn.Parameter(decay_speed.reshape(1, 1, args.head_size))
390
+
391
+ D_DECAY_LORA = 64
392
+ if args.hidden_size == 4096:
393
+ D_DECAY_LORA = D_DECAY_LORA * 2
394
+ self.time_decay_w1 = nn.Parameter(
395
+ torch.zeros(args.hidden_size, D_DECAY_LORA)
396
+ )
397
+ self.time_decay_w2 = nn.Parameter(
398
+ torch.zeros(D_DECAY_LORA, args.head_size).uniform_(-0.01, 0.01)
399
+ )
400
+
401
+ tmp = torch.zeros(args.head_size)
402
+ for n in range(args.head_size):
403
+ zigzag = ((n + 1) % 3 - 1) * 0.1
404
+ tmp[n] = ratio_0_to_1 * (1 - (n / (args.head_size - 1))) + zigzag
405
+
406
+ self.time_faaaa = nn.Parameter(tmp.reshape(self.n_head, self.head_size))
407
+ # self.time_state = nn.Parameter(torch.zeros(self.n_head, self.head_size, self.head_size))
408
+
409
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
410
+ self.receptance = nn.Linear(args.hidden_size, args.head_size, bias=False)
411
+ self.key = nn.Linear(args.hidden_size, args.head_size, bias=False)
412
+
413
+ self.value = nn.Linear(args.hidden_size, args.head_size, bias=False)
414
+ self.output = nn.Linear(args.head_size, args.hidden_size, bias=False)
415
+ self.gate = nn.Linear(args.hidden_size, args.head_size, bias=False)
416
+
417
+ if self.args.wkv_has_group_norm:
418
+ self.ln_x = nn.GroupNorm(
419
+ self.n_head, args.head_size, eps=(1e-5) * (args.head_size_divisor**2)
420
+ )
421
+
422
+ def post_init(self):
423
+ pass
424
+
425
+ def forward(self, x, last_state: TimeMixState):
426
+ shift_state = last_state.shift_state
427
+ B, T, C = x.size()
428
+ H = self.n_head
429
+ if shift_state is not None:
430
+ xx = torch.concat((shift_state.unsqueeze(1), x[:, :-1]), dim=1) - x
431
+ else:
432
+ xx = self.time_shift(x) - x
433
+ lx = x[:, -1]
434
+
435
+ xxx = x + xx * self.time_maa_x
436
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B * T, 5, -1).transpose(0, 1)
437
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
438
+ mw, mk, mv, mr, mg = xxx.unbind(dim=0)
439
+
440
+ xw = x + xx * (self.time_maa_w + mw)
441
+ xk = x + xx * (self.time_maa_k + mk)
442
+ xv = x + xx * (self.time_maa_v + mv)
443
+ xr = x + xx * (self.time_maa_r + mr)
444
+ xg = x + xx * (self.time_maa_g + mg)
445
+
446
+ r = self.receptance(xr)
447
+ k = self.key(xk)
448
+ v = self.value(xv)
449
+ g = F.silu(self.gate(xg))
450
+
451
+ ww = torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2
452
+ w = self.time_decay + ww
453
+
454
+ wkv_state = last_state.wkv_state
455
+ x, wkv_state = self.apply_wkv6_state(
456
+ B, T, C, H, r, k, v, w, u=self.time_faaaa, s=wkv_state
457
+ )
458
+ if self.args.wkv_has_group_norm:
459
+ x = self.ln_x(x.view(B * T, C)).view(B, T, C)
460
+ x = self.output(x * g)
461
+ return x, TimeMixState(lx, wkv_state)
462
+
463
+ def apply_wkv6_state(self, B, T, C, H, r, k, v, w, u, s):
464
+ r = rearrange(r, "b l (h d) -> b h l d", h=H)
465
+ k = rearrange(k, "b l (h d) -> b h l d", h=H)
466
+ v = rearrange(v, "b l (h d) -> b h l d", h=H)
467
+ w = rearrange(w, "b l (h d) -> b h l d", h=H)
468
+
469
+ if r.device.type == "cpu":
470
+ wkv6_func = native_recurrent_rwkv6
471
+ elif self.training:
472
+ wkv6_func = chunk_rwkv6
473
+ else:
474
+ wkv6_func = fused_recurrent_rwkv6
475
+
476
+ o, state = wkv6_func(
477
+ r,
478
+ k,
479
+ v,
480
+ -torch.exp(w),
481
+ u=u,
482
+ scale=1.0,
483
+ initial_state=s,
484
+ output_final_state=True,
485
+ )
486
+ x = rearrange(o, "b h l d -> b l (h d)")
487
+ return x, state
488
+
489
+
490
+ class Rwkv6Attention(nn.Module):
491
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
492
+ super().__init__()
493
+ self.args = args
494
+ self.layer_idx = layer_id
495
+ self.time_mixer = Rwkv_Tmix_x060(args, layer_id, **kwargs)
496
+
497
+ def forward(self, hidden_states, past_key_value, **kwargs):
498
+ attn_output = hidden_states
499
+ B, T, C = attn_output.size()
500
+ if past_key_value is not None:
501
+ if len(past_key_value) <= self.layer_idx:
502
+ last_state = None
503
+ else:
504
+ last_state = past_key_value[self.layer_idx][0]
505
+ if last_state is None:
506
+ wkv_states = torch.zeros(
507
+ (B, self.args.num_wkv_heads, self.args.head_size, self.args.head_size),
508
+ device=attn_output.device,
509
+ dtype=torch.float32,
510
+ )
511
+ token_shift = torch.zeros(
512
+ (B, C), device=attn_output.device, dtype=attn_output.dtype
513
+ )
514
+ time_state = TimeMixState(token_shift, wkv_states)
515
+ channel_state = None
516
+ last_state = BlockState(time_state, channel_state)
517
+ attn_output, states = self.time_mixer(attn_output, last_state.time_mix_state)
518
+ last_state.time_mix_state = states
519
+
520
+ if past_key_value is not None:
521
+ past_key_value.update(T, last_state, self.layer_idx)
522
+ return attn_output, None