zhiyuan8 commited on
Commit
ba4f8ad
·
verified ·
1 Parent(s): 353a1a6

Upload modeling_rwkv_hybrid.py

Browse files
Files changed (1) hide show
  1. modeling_rwkv_hybrid.py +632 -0
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
+