zhiyuan8 commited on
Commit
8ebdde3
·
verified ·
1 Parent(s): c60dcb4

Upload 3 files

Browse files
Files changed (3) hide show
  1. hybrid_cache.py +154 -0
  2. modeling_rwkv_hybrid.py +632 -0
  3. wkv.py +565 -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
+
wkv.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING, Optional
10
+ from transformers.cache_utils import Cache
11
+
12
+ try:
13
+ import triton
14
+ from rwkvfla.ops.rwkv7 import (
15
+ fused_recurrent_rwkv7,
16
+ chunk_rwkv7,
17
+ native_recurrent_rwkv7,
18
+ fused_addcmul_rwkv7,
19
+ ) # pylint: disable=C0411
20
+ from rwkvfla.ops.rwkv6 import (
21
+ fused_recurrent_rwkv6,
22
+ chunk_rwkv6,
23
+ native_recurrent_rwkv6,
24
+ )
25
+ except ImportError:
26
+ from rwkvfla.ops.rwkv7 import native_recurrent_rwkv7 # pylint: disable=C0411
27
+ from rwkvfla.ops.rwkv6 import native_recurrent_rwkv6
28
+ from rwkvfla.ops.rwkv7 import torch_addcmul_rwkv7
29
+
30
+ fused_recurrent_rwkv7 = native_recurrent_rwkv7
31
+ chunk_rwkv7 = native_recurrent_rwkv7
32
+ chunk_rwkv6 = native_recurrent_rwkv6
33
+ fused_recurrent_rwkv6 = native_recurrent_rwkv6
34
+ fused_addcmul_rwkv7 = torch_addcmul_rwkv7
35
+
36
+
37
+ class Rwkv_Tmix_x070(nn.Module):
38
+ def __init__(self, args: RwkvHybridConfig, layer_id, update_v_first, get_v_first):
39
+ super().__init__()
40
+ self.args = args
41
+ self.layer_id = layer_id
42
+ self.hidden_size = args.hidden_size
43
+
44
+ self.update_v_first = update_v_first
45
+ self.get_v_first = get_v_first
46
+
47
+ self.head_size = args.head_size
48
+ self.n_head = args.num_wkv_heads
49
+ assert args.hidden_size % self.n_head == 0
50
+ H = self.n_head
51
+ N = self.head_size
52
+
53
+ self.x_r = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
54
+ self.x_w = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
55
+ self.x_k = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
56
+ self.x_v = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
57
+ self.x_a = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
58
+
59
+ D_DECAY_LORA = 64
60
+ D_AAA_LORA = 64
61
+ D_MV_LORA = 32
62
+ D_GATE_LORA = 128
63
+
64
+ self.w1 = nn.Parameter(torch.Tensor(args.hidden_size, D_DECAY_LORA))
65
+ self.w2 = nn.Parameter(torch.Tensor(D_DECAY_LORA, args.hidden_size))
66
+ self.w0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
67
+
68
+ self.a1 = nn.Parameter(torch.Tensor(args.hidden_size, D_AAA_LORA))
69
+ self.a2 = nn.Parameter(torch.Tensor(D_AAA_LORA, args.hidden_size))
70
+ self.a0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
71
+
72
+ self.v1 = nn.Parameter(torch.Tensor(args.hidden_size, D_MV_LORA))
73
+ self.v2 = nn.Parameter(torch.Tensor(D_MV_LORA, args.hidden_size))
74
+ self.v0 = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
75
+
76
+ if self.args.wkv_has_gate:
77
+ self.x_g = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
78
+ self.g1 = nn.Parameter(torch.Tensor(args.hidden_size, D_GATE_LORA))
79
+ self.g2 = nn.Parameter(torch.Tensor(D_GATE_LORA, args.hidden_size))
80
+
81
+ self.k_k = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
82
+ self.k_a = nn.Parameter(torch.Tensor(1, 1, args.hidden_size))
83
+ self.r_k = nn.Parameter(torch.Tensor(H, N))
84
+
85
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
86
+ self.receptance = nn.Linear(
87
+ args.hidden_size, args.hidden_size, bias=False)
88
+ self.key = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
89
+ self.value = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
90
+ self.output = nn.Linear(args.hidden_size, args.hidden_size, bias=False)
91
+
92
+ if self.args.wkv_has_group_norm:
93
+ self.ln_x = nn.GroupNorm(
94
+ H, args.hidden_size, eps=(1e-5) * (args.head_size_divisor**2)
95
+ )
96
+
97
+ def post_init(self):
98
+ with torch.no_grad():
99
+ ratio_0_to_1 = self.layer_id / \
100
+ (self.args.num_hidden_layers - 1) # 0 to 1
101
+ ratio_1_to_almost0 = 1.0 - (
102
+ self.layer_id / self.args.num_hidden_layers
103
+ ) # 1 to ~0
104
+
105
+ ddd = torch.ones(1, 1, self.args.hidden_size)
106
+ for i in range(self.args.hidden_size):
107
+ ddd[0, 0, i] = i / self.args.hidden_size
108
+
109
+ nn.init.constant_(
110
+ self.x_r, 1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0))
111
+ nn.init.constant_(
112
+ self.x_w, 1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0))
113
+ nn.init.constant_(
114
+ self.x_k,
115
+ 1.0 - (torch.pow(ddd, 0.9 * ratio_1_to_almost0) +
116
+ 0.4 * ratio_0_to_1),
117
+ )
118
+ nn.init.constant_(
119
+ self.x_v,
120
+ 1.0 - (torch.pow(ddd, 0.4 * ratio_1_to_almost0) +
121
+ 0.6 * ratio_0_to_1),
122
+ )
123
+ nn.init.constant_(
124
+ self.x_a, 1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0))
125
+
126
+
127
+ def ortho_init(x, scale):
128
+ shape = x.shape
129
+ original_dtype = x.dtype
130
+ x_fp32 = x.float()
131
+ if len(shape) == 2:
132
+ gain = math.sqrt(shape[0] / shape[1]
133
+ ) if shape[0] > shape[1] else 1
134
+ nn.init.orthogonal_(x_fp32, gain=gain * scale)
135
+ elif len(shape) == 3:
136
+ gain = math.sqrt(shape[1] / shape[2]
137
+ ) if shape[1] > shape[2] else 1
138
+ for i in range(shape[0]):
139
+ nn.init.orthogonal_(x_fp32[i], gain=gain * scale)
140
+ else:
141
+ raise ValueError(
142
+ "ortho_init only supports 2D or 3D tensors")
143
+ x.data.copy_(x_fp32.to(original_dtype))
144
+ return x
145
+
146
+ D_DECAY_LORA = 64
147
+ nn.init.zeros_(self.w1)
148
+ self.w2 = nn.Parameter(
149
+ ortho_init(torch.zeros(
150
+ D_DECAY_LORA, self.args.hidden_size), 0.1)
151
+ )
152
+
153
+ decay_speed = torch.ones(self.args.hidden_size)
154
+ for n in range(self.args.hidden_size):
155
+ decay_speed[n] = -7 + 5 * (n / (self.args.hidden_size - 1)) ** (
156
+ 0.85 + 1.0 * ratio_0_to_1**0.5
157
+ )
158
+ nn.init.constant_(
159
+ self.w0, decay_speed.reshape(1, 1, self.args.hidden_size) + 0.5
160
+ )
161
+
162
+ D_AAA_LORA = 64
163
+ nn.init.zeros_(self.a1)
164
+ self.a2 = nn.Parameter(
165
+ ortho_init(torch.zeros(D_AAA_LORA, self.args.hidden_size), 0.1)
166
+ )
167
+ nn.init.zeros_(self.a0)
168
+
169
+ D_MV_LORA = 32
170
+ nn.init.zeros_(self.v1)
171
+ self.v2 = nn.Parameter(
172
+ ortho_init(torch.zeros(D_MV_LORA, self.args.hidden_size), 0.1)
173
+ )
174
+ nn.init.constant_(self.v0, 1.0)
175
+
176
+ D_GATE_LORA = 128
177
+ if self.args.wkv_has_gate:
178
+ nn.init.zeros_(self.g1)
179
+ self.g2 = nn.Parameter(
180
+ ortho_init(torch.zeros(
181
+ D_GATE_LORA, self.args.hidden_size), 0.1)
182
+ )
183
+ nn.init.constant_(
184
+ self.x_g, 1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0))
185
+
186
+ nn.init.constant_(self.k_k, 0.85)
187
+ nn.init.constant_(self.k_a, 1.0)
188
+ nn.init.zeros_(self.r_k)
189
+
190
+ nn.init.zeros_(self.receptance.weight)
191
+ nn.init.zeros_(self.key.weight)
192
+ nn.init.zeros_(self.value.weight)
193
+ nn.init.zeros_(self.output.weight)
194
+
195
+ if self.args.wkv_has_group_norm:
196
+ nn.init.ones_(self.ln_x.weight)
197
+ nn.init.zeros_(self.ln_x.bias)
198
+
199
+ def apply_wkv7_state(self, r, k, v, w, a, b, s,
200
+ output_final_state,
201
+ cu_seqlens,
202
+ head_first
203
+ ):
204
+
205
+ if r.device.type == "cpu":
206
+ r, w, k, v, a, b = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.n_head), (r, w, k, v, a, b))
207
+ o, state = native_recurrent_rwkv7(
208
+ r=r, k=k, v=v, w=w,
209
+ a=a, b=b,
210
+ scale=1.0,
211
+ initial_state=s.transpose(-1, -2),
212
+ output_final_state=True,
213
+ head_first=True,
214
+ )
215
+ state = state.transpose(-1, -2)
216
+ x = rearrange(o, "b h l d -> b l (h d)")
217
+ else:
218
+ r, w, k, v, a, b = map(lambda x: rearrange(x, 'b l (h d) -> b l h d', h=self.n_head), (r, w, k, v, a, b))
219
+ wkv7_func = chunk_rwkv7 if self.training else fused_recurrent_rwkv7
220
+ o, state = wkv7_func(
221
+ r=r, k=k, v=v, w=w,
222
+ a=a, b=b,
223
+ scale=1.0,
224
+ initial_state=s,
225
+ output_final_state=output_final_state,
226
+ cu_seqlens=cu_seqlens,
227
+ head_first=head_first,
228
+ )
229
+ x = rearrange(o, "b l h d -> b l (h d)")
230
+ return x, state
231
+
232
+ def forward(
233
+ self,
234
+ hidden_states,
235
+ last_state: TimeMixState,
236
+ sequence_mask: Optional[torch.Tensor] = None,
237
+ use_cache: Optional[bool] = False,
238
+ cu_seqlens: Optional[torch.Tensor] = None,
239
+ **kwargs
240
+ ):
241
+ if sequence_mask is not None:
242
+ hidden_states = hidden_states.mul(
243
+ sequence_mask[:, -hidden_states.shape[-2]:, None])
244
+
245
+ shift_state = last_state.shift_state
246
+ B, T, C = hidden_states.size()
247
+
248
+ if shift_state is not None:
249
+ xx = torch.concat((shift_state.unsqueeze(
250
+ 1), hidden_states[:, :-1]), dim=1) - hidden_states
251
+ else:
252
+ xx = self.time_shift(hidden_states) - hidden_states
253
+
254
+ lx = hidden_states[:, -1]
255
+
256
+ if self.args.wkv_has_gate:
257
+ xr, xw, xk, xv, xa, xg = fused_addcmul_rwkv7(
258
+ hidden_states, xx, self.x_r, self.x_w, self.x_k, self.x_v, self.x_a, self.x_g)
259
+ else:
260
+ xr, xw, xk, xv, xa, _ = fused_addcmul_rwkv7(hidden_states, xx, self.x_r, self.x_w, self.x_k, self.x_v, self.x_a)
261
+
262
+ r = self.receptance(xr)
263
+ w = (
264
+ -F.softplus(-(self.w0 + torch.tanh(xw @ self.w1) @ self.w2)) - 0.5
265
+ ) # soft-clamp to (-inf, -0.5)
266
+ k = self.key(xk)
267
+ v = self.value(xv)
268
+ if self.layer_id == 0:
269
+ self.update_v_first(v)
270
+ else:
271
+ # Original implementation
272
+ v = v + (self.get_v_first().to(v.device) - v) * torch.sigmoid(
273
+ self.v0 + (xv @ self.v1) @ self.v2
274
+ ) # add value residual
275
+
276
+ a = torch.sigmoid(
277
+ self.a0 + (xa @ self.a1) @ self.a2
278
+ ) # a is "in-context learning rate"
279
+ if self.args.wkv_has_gate:
280
+ g = torch.sigmoid(xg @ self.g1) @ self.g2
281
+ kk = k * self.k_k
282
+ kk = F.normalize(kk.view(B, T, self.n_head, -1), dim=-1, p=2.0).view(B, T, C)
283
+ k = k * (1 + (a - 1) * self.k_a)
284
+
285
+ wkv_state = last_state.wkv_state
286
+ hidden_states, wkv_state = self.apply_wkv7_state(
287
+ r,
288
+ k,
289
+ v,
290
+ w,
291
+ -kk,
292
+ (kk * a),
293
+ s=wkv_state,
294
+ output_final_state=use_cache,
295
+ cu_seqlens=cu_seqlens,
296
+ head_first=False
297
+ )
298
+ if self.args.wkv_has_group_norm:
299
+ hidden_states = self.ln_x(
300
+ hidden_states.view(B * T, C)).view(B, T, C)
301
+ hidden_states = hidden_states + (
302
+ (r.view(B, T, self.n_head, -1) * k.view(B, T, self.n_head, -1) * self.r_k).sum(
303
+ dim=-1, keepdim=True
304
+ )
305
+ * v.view(B, T, self.n_head, -1)
306
+ ).view(B, T, C)
307
+ hidden_states = self.output(
308
+ hidden_states * g) if self.args.wkv_has_gate else self.output(hidden_states)
309
+ return hidden_states, TimeMixState(lx, wkv_state)
310
+
311
+
312
+ class Rwkv7Attention(nn.Module):
313
+ def __init__(self, args: RwkvHybridConfig, layer_id, update_v_first, get_v_first):
314
+ super().__init__()
315
+ self.args = args
316
+ self.layer_idx = layer_id
317
+ self.time_mixer = Rwkv_Tmix_x070(
318
+ args, layer_id, update_v_first, get_v_first)
319
+
320
+ def forward(
321
+ self,
322
+ hidden_states: torch.Tensor,
323
+ sequence_mask: Optional[torch.Tensor] = None,
324
+ past_key_value: Optional[Cache] = None,
325
+ use_cache: Optional[bool] = False,
326
+ output_attentions: Optional[bool] = False,
327
+ **kwargs
328
+ ):
329
+ if sequence_mask is not None:
330
+ assert len(sequence_mask.shape) == 2, (
331
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
332
+ "for padding purposes (0 indicating padding). "
333
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
334
+ )
335
+ batch_size, token_length, _ = hidden_states.shape
336
+
337
+ if past_key_value is not None and len(past_key_value) > self.layer_idx:
338
+ last_state = past_key_value[self.layer_idx][0]
339
+ else:
340
+ last_state = self.init_state(
341
+ batch_size, hidden_states.device, hidden_states.dtype
342
+ )
343
+
344
+ attn_output, states = self.time_mixer(hidden_states=hidden_states,
345
+ last_state=last_state.time_mix_state,
346
+ sequence_mask=sequence_mask,
347
+ use_cache=use_cache,
348
+ **kwargs)
349
+ last_state.time_mix_state = states
350
+
351
+ if past_key_value is not None:
352
+ past_key_value.update(token_length, last_state, self.layer_idx)
353
+
354
+ return attn_output, None
355
+
356
+ def init_state(self, batch_size, device, dtype) -> BlockState:
357
+ wkv_states = torch.zeros(
358
+ (
359
+ batch_size,
360
+ self.args.num_wkv_heads,
361
+ self.args.head_size,
362
+ self.args.head_size,
363
+ ),
364
+ device=device,
365
+ dtype=torch.float32,
366
+ )
367
+ token_shift = torch.zeros(
368
+ (batch_size, self.args.hidden_size), device=device, dtype=dtype
369
+ )
370
+ return BlockState(TimeMixState(token_shift, wkv_states), None)
371
+
372
+
373
+ class Rwkv_Tmix_x060(nn.Module):
374
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
375
+ super().__init__()
376
+ self.args = args
377
+ self.layer_id = layer_id
378
+ self.hidden_size = args.hidden_size
379
+
380
+ self.head_size = args.head_size
381
+ self.n_head = args.num_wkv_heads
382
+ assert args.hidden_size % self.n_head == 0
383
+ H = self.n_head
384
+ N = self.head_size
385
+
386
+ with torch.no_grad():
387
+ ratio_0_to_1 = layer_id / (args.n_layer - 1) # 0 to 1
388
+ ratio_1_to_almost0 = 1.0 - (layer_id / args.n_layer) # 1 to ~0
389
+ ddd = torch.ones(1, 1, args.hidden_size)
390
+ for i in range(args.hidden_size):
391
+ ddd[0, 0, i] = i / args.hidden_size
392
+
393
+ # fancy time_mix
394
+ self.time_maa_x = nn.Parameter(
395
+ 1.0 - torch.pow(ddd, ratio_1_to_almost0))
396
+ self.time_maa_w = nn.Parameter(
397
+ 1.0 - torch.pow(ddd, ratio_1_to_almost0))
398
+ self.time_maa_k = nn.Parameter(
399
+ 1.0 - torch.pow(ddd, ratio_1_to_almost0))
400
+ self.time_maa_v = nn.Parameter(
401
+ 1.0 - (torch.pow(ddd, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
402
+ )
403
+ self.time_maa_r = nn.Parameter(
404
+ 1.0 - torch.pow(ddd, 0.5 * ratio_1_to_almost0)
405
+ )
406
+ self.time_maa_g = nn.Parameter(
407
+ 1.0 - torch.pow(ddd, 0.5 * ratio_1_to_almost0)
408
+ )
409
+
410
+ D_MIX_LORA = 32 # generate TIME_MIX for w,k,v,r,g
411
+ if args.hidden_size == 4096:
412
+ D_MIX_LORA = D_MIX_LORA * 2
413
+ self.time_maa_w1 = nn.Parameter(
414
+ torch.zeros(args.hidden_size, D_MIX_LORA * 5)
415
+ )
416
+ self.time_maa_w2 = nn.Parameter(
417
+ torch.zeros(5, D_MIX_LORA,
418
+ args.hidden_size).uniform_(-0.01, 0.01)
419
+ )
420
+
421
+ # fancy time_decay
422
+ decay_speed = torch.ones(args.head_size)
423
+ for n in range(args.head_size):
424
+ decay_speed[n] = -6 + 5 * (n / (args.head_size - 1)) ** (
425
+ 0.7 + 1.3 * ratio_0_to_1
426
+ )
427
+ self.time_decay = nn.Parameter(
428
+ decay_speed.reshape(1, 1, args.head_size))
429
+
430
+ D_DECAY_LORA = 64
431
+ if args.hidden_size == 4096:
432
+ D_DECAY_LORA = D_DECAY_LORA * 2
433
+ self.time_decay_w1 = nn.Parameter(
434
+ torch.zeros(args.hidden_size, D_DECAY_LORA)
435
+ )
436
+ self.time_decay_w2 = nn.Parameter(
437
+ torch.zeros(D_DECAY_LORA, args.head_size).uniform_(-0.01, 0.01)
438
+ )
439
+
440
+ tmp = torch.zeros(args.head_size)
441
+ for n in range(args.head_size):
442
+ zigzag = ((n + 1) % 3 - 1) * 0.1
443
+ tmp[n] = ratio_0_to_1 * \
444
+ (1 - (n / (args.head_size - 1))) + zigzag
445
+
446
+ self.time_faaaa = nn.Parameter(
447
+ tmp.reshape(self.n_head, self.head_size))
448
+ # self.time_state = nn.Parameter(torch.zeros(self.n_head, self.head_size, self.head_size))
449
+
450
+ self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
451
+ self.receptance = nn.Linear(
452
+ args.hidden_size, args.head_size, bias=False)
453
+ self.key = nn.Linear(args.hidden_size, args.head_size, bias=False)
454
+
455
+ self.value = nn.Linear(args.hidden_size, args.head_size, bias=False)
456
+ self.output = nn.Linear(args.head_size, args.hidden_size, bias=False)
457
+ self.gate = nn.Linear(args.hidden_size, args.head_size, bias=False)
458
+
459
+ if self.args.wkv_has_group_norm:
460
+ self.ln_x = nn.GroupNorm(
461
+ self.n_head, args.head_size, eps=(
462
+ 1e-5) * (args.head_size_divisor**2)
463
+ )
464
+
465
+ def post_init(self):
466
+ pass
467
+
468
+ def forward(self, x, last_state: TimeMixState):
469
+ shift_state = last_state.shift_state
470
+ B, T, C = x.size()
471
+ H = self.n_head
472
+ if shift_state is not None:
473
+ xx = torch.concat((shift_state.unsqueeze(1), x[:, :-1]), dim=1) - x
474
+ else:
475
+ xx = self.time_shift(x) - x
476
+ lx = x[:, -1]
477
+
478
+ xxx = x + xx * self.time_maa_x
479
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B *
480
+ T, 5, -1).transpose(0, 1)
481
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
482
+ mw, mk, mv, mr, mg = xxx.unbind(dim=0)
483
+
484
+ xw = x + xx * (self.time_maa_w + mw)
485
+ xk = x + xx * (self.time_maa_k + mk)
486
+ xv = x + xx * (self.time_maa_v + mv)
487
+ xr = x + xx * (self.time_maa_r + mr)
488
+ xg = x + xx * (self.time_maa_g + mg)
489
+
490
+ r = self.receptance(xr)
491
+ k = self.key(xk)
492
+ v = self.value(xv)
493
+ g = F.silu(self.gate(xg))
494
+
495
+ ww = torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2
496
+ w = self.time_decay + ww
497
+
498
+ wkv_state = last_state.wkv_state
499
+ x, wkv_state = self.apply_wkv6_state(
500
+ B, T, C, H, r, k, v, w, u=self.time_faaaa, s=wkv_state
501
+ )
502
+ if self.args.wkv_has_group_norm:
503
+ x = self.ln_x(x.view(B * T, C)).view(B, T, C)
504
+ x = self.output(x * g)
505
+ return x, TimeMixState(lx, wkv_state)
506
+
507
+ def apply_wkv6_state(self, B, T, C, H, r, k, v, w, u, s):
508
+ r, w, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.n_head), (r, w, k, v))
509
+
510
+ if r.device.type == "cpu":
511
+ wkv6_func = native_recurrent_rwkv6
512
+ elif self.training:
513
+ wkv6_func = chunk_rwkv6
514
+ else:
515
+ wkv6_func = fused_recurrent_rwkv6
516
+
517
+ o, state = wkv6_func(
518
+ r,
519
+ k,
520
+ v,
521
+ -torch.exp(w),
522
+ u=u,
523
+ scale=1.0,
524
+ initial_state=s,
525
+ output_final_state=True,
526
+ )
527
+ x = rearrange(o, "b h l d -> b l (h d)")
528
+ return x, state
529
+
530
+
531
+ class Rwkv6Attention(nn.Module):
532
+ def __init__(self, args: RwkvHybridConfig, layer_id, **kwargs):
533
+ super().__init__()
534
+ self.args = args
535
+ self.layer_idx = layer_id
536
+ self.time_mixer = Rwkv_Tmix_x060(args, layer_id, **kwargs)
537
+
538
+ def forward(self, hidden_states, past_key_value, **kwargs):
539
+ attn_output = hidden_states
540
+ B, T, C = attn_output.size()
541
+ if past_key_value is not None:
542
+ if len(past_key_value) <= self.layer_idx:
543
+ last_state = None
544
+ else:
545
+ last_state = past_key_value[self.layer_idx][0]
546
+ if last_state is None:
547
+ wkv_states = torch.zeros(
548
+ (B, self.args.num_wkv_heads,
549
+ self.args.head_size, self.args.head_size),
550
+ device=attn_output.device,
551
+ dtype=torch.float32,
552
+ )
553
+ token_shift = torch.zeros(
554
+ (B, C), device=attn_output.device, dtype=attn_output.dtype
555
+ )
556
+ time_state = TimeMixState(token_shift, wkv_states)
557
+ channel_state = None
558
+ last_state = BlockState(time_state, channel_state)
559
+ attn_output, states = self.time_mixer(
560
+ attn_output, last_state.time_mix_state)
561
+ last_state.time_mix_state = states
562
+
563
+ if past_key_value is not None:
564
+ past_key_value.update(T, last_state, self.layer_idx)
565
+ return attn_output, None