SmerkyG commited on
Commit
85ef652
·
verified ·
1 Parent(s): 85678d7

Update configuration_rwkv6qwen2.py

Browse files
Files changed (1) hide show
  1. configuration_rwkv6qwen2.py +1162 -178
configuration_rwkv6qwen2.py CHANGED
@@ -1,6 +1,11 @@
1
  # coding=utf-8
2
  # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
  #
 
 
 
 
 
4
  # Licensed under the Apache License, Version 2.0 (the "License");
5
  # you may not use this file except in compliance with the License.
6
  # You may obtain a copy of the License at
@@ -12,195 +17,1174 @@
12
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
- """RWKV6Qwen2 model configuration"""
 
 
 
 
 
 
 
 
 
 
16
 
17
- from transformers.configuration_utils import PretrainedConfig
18
- from transformers.modeling_rope_utils import rope_config_validation
19
- from transformers.utils import logging
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
 
 
21
 
22
  logger = logging.get_logger(__name__)
23
 
24
 
25
- class RWKV6Qwen2Config(PretrainedConfig):
26
- r"""
27
- This is the configuration class to store the configuration of a [`RWKV6Qwen2Model`]. It is used to instantiate a
28
- RWKV6Qwen2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
- with the defaults will yield a similar configuration to that of
30
- Qwen2-7B-beta [Qwen/Qwen2-7B-beta](https://huggingface.co/Qwen/Qwen2-7B-beta).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
- documentation from [`PretrainedConfig`] for more information.
 
 
 
 
 
 
 
 
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  Args:
37
- vocab_size (`int`, *optional*, defaults to 151936):
38
- Vocabulary size of the RWKV6Qwen2 model. Defines the number of different tokens that can be represented by the
39
- `inputs_ids` passed when calling [`RWKV6Qwen2Model`]
40
- hidden_size (`int`, *optional*, defaults to 4096):
41
- Dimension of the hidden representations.
42
- intermediate_size (`int`, *optional*, defaults to 22016):
43
- Dimension of the MLP representations.
44
- num_hidden_layers (`int`, *optional*, defaults to 32):
45
- Number of hidden layers in the Transformer encoder.
46
- num_attention_heads (`int`, *optional*, defaults to 32):
47
- Number of attention heads for each attention layer in the Transformer encoder.
48
- num_key_value_heads (`int`, *optional*, defaults to 32):
49
- This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
- `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
- `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
- converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
- by meanpooling all the original heads within that group. For more details checkout [this
54
- paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
55
- hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
- The non-linear activation function (function or string) in the decoder.
57
- max_position_embeddings (`int`, *optional*, defaults to 32768):
58
- The maximum sequence length that this model might ever be used with.
59
- initializer_range (`float`, *optional*, defaults to 0.02):
60
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
- rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
- The epsilon used by the rms normalization layers.
63
- use_cache (`bool`, *optional*, defaults to `True`):
64
- Whether or not the model should return the last key/values attentions (not used by all models). Only
65
- relevant if `config.is_decoder=True`.
66
- tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
- Whether the model's input and output word embeddings should be tied.
68
- rope_theta (`float`, *optional*, defaults to 10000.0):
69
- The base period of the RoPE embeddings.
70
- rope_scaling (`Dict`, *optional*):
71
- Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
- and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
- accordingly.
74
- Expected contents:
75
- `rope_type` (`str`):
76
- The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
- 'llama3'], with 'default' being the original RoPE implementation.
78
- `factor` (`float`, *optional*):
79
- Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
- most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
- original maximum pre-trained length.
82
- `original_max_position_embeddings` (`int`, *optional*):
83
- Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
84
- pretraining.
85
- `attention_factor` (`float`, *optional*):
86
- Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
- computation. If unspecified, it defaults to value recommended by the implementation, using the
88
- `factor` field to infer the suggested value.
89
- `beta_fast` (`float`, *optional*):
90
- Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
- ramp function. If unspecified, it defaults to 32.
92
- `beta_slow` (`float`, *optional*):
93
- Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
- ramp function. If unspecified, it defaults to 1.
95
- `short_factor` (`List[float]`, *optional*):
96
- Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
- size divided by the number of attention heads divided by 2
99
- `long_factor` (`List[float]`, *optional*):
100
- Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
- `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
- size divided by the number of attention heads divided by 2
103
- `low_freq_factor` (`float`, *optional*):
104
- Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
105
- `high_freq_factor` (`float`, *optional*):
106
- Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
107
- use_sliding_window (`bool`, *optional*, defaults to `False`):
108
- Whether to use sliding window attention.
109
- sliding_window (`int`, *optional*, defaults to 4096):
110
- Sliding window attention (SWA) window size. If not specified, will default to `4096`.
111
- max_window_layers (`int`, *optional*, defaults to 28):
112
- The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
113
- attention_dropout (`float`, *optional*, defaults to 0.0):
114
- The dropout ratio for the attention probabilities.
115
-
116
- ```python
117
- >>> from transformers import RWKV6Qwen2Model, RWKV6Qwen2Config
118
-
119
- >>> # Initializing a RWKV6Qwen2 style configuration
120
- >>> configuration = RWKV6Qwen2Config()
121
-
122
- >>> # Initializing a model from the RWKV6Qwen2-7B style configuration
123
- >>> model = RWKV6Qwen2Model(configuration)
124
-
125
- >>> # Accessing the model configuration
126
- >>> configuration = model.config
127
- ```"""
128
-
129
- model_type = "rwkv6qwen2"
130
- keys_to_ignore_at_inference = ["past_key_values"]
131
-
132
- def __init__(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  self,
134
- vocab_size=151936,
135
- hidden_size=4096,
136
- intermediate_size=22016,
137
- num_hidden_layers=32,
138
- num_attention_heads=32,
139
- num_key_value_heads=32,
140
- lora_rank_tokenshift=None,
141
- lora_rank_decay=None,
142
- hidden_act="silu",
143
- max_position_embeddings=32768,
144
- initializer_range=0.02,
145
- rms_norm_eps=1e-6,
146
- use_cache=True,
147
- tie_word_embeddings=False,
148
- use_rope=False,
149
- rope_theta=10000.0,
150
- rope_scaling=None,
151
- use_sliding_window=False,
152
- sliding_window=4096,
153
- max_window_layers=28,
154
- attention_dropout=0.0,
155
- attention_bias=True,
156
- attention_output_bias=False,
157
- gate_rank_type=1,
158
- lora_rank_gate=None,
159
- balance_state=True,
160
- groupnorm_att=False,
161
- use_tokenshift=True,
162
- **kwargs,
163
  ):
164
- self.vocab_size = vocab_size
165
- self.max_position_embeddings = max_position_embeddings
166
- self.hidden_size = hidden_size
167
- self.intermediate_size = intermediate_size
168
- self.num_hidden_layers = num_hidden_layers
169
- self.num_attention_heads = num_attention_heads
170
- self.use_sliding_window = use_sliding_window
171
- self.sliding_window = sliding_window if use_sliding_window else None
172
- self.max_window_layers = max_window_layers
173
-
174
- # for backward compatibility
175
- if num_key_value_heads is None:
176
- num_key_value_heads = num_attention_heads
177
-
178
- self.num_key_value_heads = num_key_value_heads
179
- self.lora_rank_tokenshift = lora_rank_tokenshift
180
- self.lora_rank_decay = lora_rank_decay
181
- self.hidden_act = hidden_act
182
- self.initializer_range = initializer_range
183
- self.rms_norm_eps = rms_norm_eps
184
- self.use_cache = use_cache
185
- self.use_rope = use_rope
186
- self.rope_theta = rope_theta
187
- self.rope_scaling = rope_scaling
188
- self.attention_dropout = attention_dropout
189
- # Validate the correctness of rotary position embeddings parameters
190
- # BC: if there is a 'type' field, move it to 'rope_type'.
191
- if self.rope_scaling is not None and "type" in self.rope_scaling:
192
- self.rope_scaling["rope_type"] = self.rope_scaling["type"]
193
- rope_config_validation(self)
194
-
195
- self.attention_bias = attention_bias
196
- self.attention_output_bias = attention_output_bias
197
- self.gate_rank_type = gate_rank_type
198
- self.lora_rank_gate = lora_rank_gate
199
- self.balance_state = balance_state
200
- self.groupnorm_att = groupnorm_att
201
- self.use_tokenshift = use_tokenshift
202
-
203
- super().__init__(
204
- tie_word_embeddings=tie_word_embeddings,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  **kwargs,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  )
 
1
  # coding=utf-8
2
  # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
3
  #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
  # Licensed under the Apache License, Version 2.0 (the "License");
10
  # you may not use this file except in compliance with the License.
11
  # You may obtain a copy of the License at
 
17
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
  # See the License for the specific language governing permissions and
19
  # limitations under the License.
20
+ """PyTorch RWKV6Qwen2 model."""
21
+
22
+ import math
23
+ import inspect
24
+ from typing import List, Optional, Tuple, Union, Dict, Any
25
+
26
+ import torch
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ import torch.nn.functional as F
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
 
32
+ from transformers.cache_utils import Cache, StaticCache, DynamicCache
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ add_code_sample_docstrings,
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from .configuration_rwkv6qwen2 import RWKV6Qwen2Config
52
 
53
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer, Qwen2MLP, Qwen2RMSNorm, repeat_kv
54
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
55
 
56
  logger = logging.get_logger(__name__)
57
 
58
 
59
+ _CHECKPOINT_FOR_DOC = "RWKV/RWKV6Qwen2-7B"
60
+ _CONFIG_FOR_DOC = "RWKV6Qwen2Config"
61
+
62
+ class RWKV6State():
63
+ def __init__(self) -> None:
64
+ super().__init__()
65
+ self._seen_tokens = 0 # Used in `generate` to keep tally of how many tokens the cache has seen
66
+ self.layer_kv_states: List[torch.Tensor] = []
67
+ self.layer_shift_states: List[torch.Tensor] = []
68
+
69
+ def __getitem__(self, layer_idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
70
+ """
71
+ Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
72
+ sequence length.
73
+ """
74
+ if layer_idx < len(self):
75
+ return (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
76
+ else:
77
+ raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
78
+
79
+ def __iter__(self):
80
+ """
81
+ Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
82
+ keys and values
83
+ """
84
+ for layer_idx in range(len(self)):
85
+ yield (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
86
+
87
+ def __len__(self):
88
+ """
89
+ Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
90
+ to the number of layers in the model.
91
+ """
92
+ return len(self.layer_kv_states)
93
+
94
+ def get_usable_length(self, new_seq_length: int, layer_idx: Optional[int] = 0) -> int:
95
+ """Given the sequence length of the new inputs, returns the usable length of the cache."""
96
+ # Linear Attention variants do not have a maximum length
97
+ return new_seq_length
98
+
99
+ def reorder_cache(self, beam_idx: torch.LongTensor):
100
+ """Reorders the cache for beam search, given the selected beam indices."""
101
+ raise NotImplementedError('Cannot reorder Linear Attention state')
102
+
103
+ def get_seq_length(self, layer_idx: int = 0) -> int:
104
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
105
+ return self._seen_tokens
106
+
107
+ def get_max_cache_shape(self) -> Optional[int]:
108
+ """Returns the maximum sequence length of the cache object. DynamicCache does not have a maximum length."""
109
+ return None
110
+
111
+ def get_max_length(self) -> Optional[int]:
112
+ """
113
+ Returns the maximum sequence length of the cached states. DynamicCache does not have a maximum length.
114
+ """
115
+ return None
116
+
117
+ def crop(self, max_length: int):
118
+ # can't implement this for linear attention variants
119
+ return
120
+
121
+ @torch.no_grad
122
+ def update(
123
+ self,
124
+ kv_state: torch.Tensor,
125
+ shift_state: torch.Tensor,
126
+ layer_idx: int,
127
+ token_count: int = 0,
128
+ cache_kwargs: Optional[Dict[str, Any]] = None,
129
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
130
+ # Update the number of seen tokens
131
+ if layer_idx == 0:
132
+ self._seen_tokens += token_count
133
+
134
+ # Update the cache
135
+ # There may be skipped layers, fill them with empty lists
136
+ for _ in range(len(self.layer_kv_states), layer_idx + 1):
137
+ self.layer_kv_states.append(torch.zeros_like(kv_state).requires_grad_(False))
138
+ self.layer_shift_states.append(torch.zeros_like(shift_state).requires_grad_(False))
139
+ self.layer_kv_states[layer_idx].copy_(kv_state)
140
+ self.layer_shift_states[layer_idx].copy_(shift_state)
141
+
142
+ return self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx]
143
+
144
+ try:
145
+ #from fla.ops.gla.chunk import chunk_gla
146
+ from fla.ops.gla.fused_recurrent import fused_recurrent_gla
147
+ except ImportError:
148
+ print("Required module is not installed. Please install it using the following commands:")
149
+ print("pip install --no-use-pep517 flash-linear-attention")
150
+ print("Additionally, ensure you have at least version 2.2.0 of Triton installed:")
151
+ print("pip install triton>=2.2.0")
152
+
153
+ class Qwen2RotaryEmbedding(nn.Module):
154
+ def __init__(self, config: RWKV6Qwen2Config, device=None):
155
+ super().__init__()
156
+ # BC: "rope_type" was originally "type"
157
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
158
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
159
+ else:
160
+ self.rope_type = "default"
161
+ self.max_seq_len_cached = config.max_position_embeddings
162
+ self.original_max_seq_len = config.max_position_embeddings
163
+
164
+ self.config = config
165
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
166
+
167
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
168
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
169
+ self.original_inv_freq = self.inv_freq
170
+
171
+ def _dynamic_frequency_update(self, position_ids, device):
172
+ """
173
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
174
+ 1 - growing beyond the cached sequence length (allow scaling)
175
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
176
+ """
177
+ seq_len = torch.max(position_ids) + 1
178
+ if seq_len > self.max_seq_len_cached: # growth
179
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
180
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
181
+ self.max_seq_len_cached = seq_len
182
+
183
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
184
+ # This .to() is needed if the model has been moved to a device after being initialized (because
185
+ # the buffer is automatically moved, but not the original copy)
186
+ self.original_inv_freq = self.original_inv_freq.to(device)
187
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
188
+ self.max_seq_len_cached = self.original_max_seq_len
189
+
190
+ @torch.no_grad()
191
+ def forward(self, x, position_ids):
192
+ if "dynamic" in self.rope_type:
193
+ self._dynamic_frequency_update(position_ids, device=x.device)
194
 
195
+ # Core RoPE block
196
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
197
+ position_ids_expanded = position_ids[:, None, :].float()
198
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
199
+ device_type = x.device.type
200
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
201
+ with torch.autocast(device_type=device_type, enabled=False):
202
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
203
+ emb = torch.cat((freqs, freqs), dim=-1)
204
+ cos = emb.cos()
205
+ sin = emb.sin()
206
 
207
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
208
+ cos = cos * self.attention_scaling
209
+ sin = sin * self.attention_scaling
210
+
211
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
212
+
213
+ def generate_rotary_embedding(max_seqlen:int, dim:int, theta:float = 10000.0, scale:float = 1):
214
+ #inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float).to(device) / dim))
215
+
216
+ angular_velocity = theta ** -(torch.arange(0, dim, 2, dtype=torch.float) / dim) / scale # frequencies from 1.0 ... 1/theta
217
+ angles = torch.outer(torch.arange(max_seqlen), angular_velocity)
218
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
219
+ emb = torch.cat((angles, angles), dim=-1)
220
+ return torch.stack([emb.cos(), emb.sin()], dim=0)
221
+ #return torch.polar(torch.ones_like(angles), angles)
222
+
223
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
224
+ def rotate_half(x):
225
+ """Rotates half the hidden dims of the input."""
226
+ x1 = x[..., : x.shape[-1] // 2]
227
+ x2 = x[..., x.shape[-1] // 2 :]
228
+ return torch.cat((-x2, x1), dim=-1)
229
+
230
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
231
+ """Applies Rotary Position Embedding to the query and key tensors.
232
 
233
  Args:
234
+ q (`torch.Tensor`): The query tensor.
235
+ k (`torch.Tensor`): The key tensor.
236
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
237
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
238
+ position_ids (`torch.Tensor`, *optional*):
239
+ Deprecated and unused.
240
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
241
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
242
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
243
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
244
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
245
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
246
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
247
+ Returns:
248
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
249
+ """
250
+ cos = cos.unsqueeze(unsqueeze_dim)
251
+ sin = sin.unsqueeze(unsqueeze_dim)
252
+ q_embed = (q * cos) + (rotate_half(q) * sin)
253
+ k_embed = (k * cos) + (rotate_half(k) * sin)
254
+ return q_embed, k_embed
255
+
256
+ def ortho_init(x, scale):
257
+ with torch.no_grad():
258
+ shape = x.shape
259
+ if len(shape) == 2:
260
+ gain = math.sqrt(shape[0] / shape[1]) if shape[0] > shape[1] else 1
261
+ #nn.init.orthogonal_(x, gain=gain * scale)
262
+ x.copy_(nn.init.orthogonal_(torch.empty_like(x, dtype=torch.float32), gain=gain * scale))
263
+ elif len(shape) == 3:
264
+ gain = math.sqrt(shape[1] / shape[2]) if shape[1] > shape[2] else 1
265
+ for i in range(shape[0]):
266
+ #nn.init.orthogonal_(x[i], gain=gain * scale)
267
+ x[i].copy_(nn.init.orthogonal_(torch.empty_like(x[i], dtype=torch.float32), gain=gain * scale))
268
+ else:
269
+ assert False
270
+ return x
271
+
272
+ class RWKV6Attention(nn.Module):
273
+ def __init__(self, config, layer_idx: Optional[int] = None):
274
+ super().__init__()
275
+ self.config = config
276
+ self.layer_idx = layer_idx
277
+
278
+ if layer_idx is None:
279
+ logger.warning_once(
280
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
281
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
282
+ "when creating this class."
283
+ )
284
+
285
+ self.hidden_size = config.hidden_size
286
+ self.num_heads = config.num_attention_heads
287
+ self.head_dim = getattr(config, 'head_dim', self.hidden_size // self.num_heads)
288
+ self.num_key_value_heads = config.num_key_value_heads
289
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
290
+ self.attention_dropout = config.attention_dropout
291
+
292
+ n_layer = self.config.num_hidden_layers
293
+ n_embd = self.hidden_size
294
+ dim_att = self.num_heads * self.head_dim
295
+ layer_id = self.layer_idx
296
+
297
+ if self.hidden_size % self.num_heads != 0:
298
+ raise ValueError(
299
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
300
+ f" and `num_heads`: {self.num_heads})."
301
+ )
302
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
303
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
304
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
305
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=getattr(config, 'attention_output_bias', config.attention_bias))
306
+
307
+ calc_lora_rank = lambda exponent, multiplier: max(1, round(self.hidden_size ** exponent * multiplier / 32)) * 32
308
+
309
+ if config.gate_rank_type == 1:
310
+ self.gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
311
+ elif config.gate_rank_type == 2:
312
+ lora_rank_gate = config.lora_rank_gate or calc_lora_rank(0.8, 0.6)
313
+ self.g1 = nn.Parameter(torch.empty(n_embd, lora_rank_gate))
314
+ self.g2 = nn.Parameter(torch.empty(lora_rank_gate, n_embd))
315
+
316
+ if config.groupnorm_att:
317
+ self.ln_x = nn.GroupNorm(self.num_heads, dim_att, eps=self.head_dim * 1e-5)
318
+
319
+ with torch.no_grad():
320
+ if config.gate_rank_type == 1:
321
+ self.gate.weight.zero_()
322
+ elif config.gate_rank_type == 2:
323
+ self.g1.zero_()
324
+ ortho_init(self.g2, 0.1)
325
+
326
+ ratio_0_to_1 = layer_id / (n_layer - 1) # 0 to 1
327
+ ratio_1_to_almost0 = 1.0 - (layer_id / n_layer) # 1 to ~0
328
+
329
+ if self.config.use_tokenshift:
330
+ ddd = torch.ones(1, 1, n_embd)
331
+ for i in range(n_embd):
332
+ ddd[0, 0, i] = i / n_embd
333
+
334
+ ddd = torch.zeros(1, 1, n_embd)
335
+ self.time_maa_x = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
336
+ self.time_maa_r = nn.Parameter(torch.zeros_like(ddd))
337
+ self.time_maa_k = nn.Parameter(torch.zeros_like(ddd))
338
+ self.time_maa_v = nn.Parameter(torch.zeros_like(ddd))
339
+ self.time_maa_w = nn.Parameter(torch.zeros_like(ddd))
340
+ self.time_maa_g = nn.Parameter(torch.zeros_like(ddd))
341
+
342
+ lora_rank_tokenshift = config.lora_rank_tokenshift or (32 if n_embd < 4096 else 64)
343
+
344
+ self.time_maa_w2 = nn.Parameter(torch.zeros(5, lora_rank_tokenshift, n_embd).uniform_(-0.01, 0.01))
345
+ self.time_maa_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_tokenshift*self.time_maa_w2.size(0)))
346
+
347
+ lora_rank_decay = config.lora_rank_decay or (64 if n_embd < 4096 else 128)
348
+
349
+ # RWKV-6
350
+ decay_speed = torch.ones(dim_att)
351
+ for n in range(dim_att):
352
+ decay_speed[n] = -6 + 5 * (n / (dim_att - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
353
+ self.time_decay = nn.Parameter(decay_speed.reshape(1,1,dim_att))
354
+ self.time_decay_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_decay))
355
+ self.time_decay_w2 = nn.Parameter(torch.zeros(lora_rank_decay, dim_att).uniform_(-0.01, 0.01))
356
+
357
+ def forward(
358
  self,
359
+ hidden_states: torch.Tensor,
360
+ attention_mask: Optional[torch.Tensor] = None,
361
+ position_ids: Optional[torch.LongTensor] = None,
362
+ past_key_values: Optional[RWKV6State] = None,
363
+ output_attentions: bool = False,
364
+ use_cache: bool = False,
365
+ cache_position: Optional[torch.LongTensor] = None,
366
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  ):
368
+ output_shift_state = hidden_states[:, -1:].detach().clone()
369
+
370
+ x = hidden_states
371
+
372
+ B, T, C = hidden_states.shape
373
+ H = self.num_heads
374
+ N = self.head_dim
375
+
376
+ if use_cache and past_key_values is not None and len(past_key_values) > self.layer_idx:
377
+ input_kv_state, input_shift_state = past_key_values[self.layer_idx]
378
+ xprev = torch.cat([input_shift_state, x[:, :-1]], dim=1)
379
+ else:
380
+ input_kv_state = None
381
+ xprev = F.pad(x, (0, 0, 1, -1))
382
+
383
+ if self.config.use_tokenshift:
384
+ dxprev = xprev - x
385
+
386
+ xxx = x + dxprev * self.time_maa_x
387
+ xxx = torch.tanh(xxx @ self.time_maa_w1).view(B*T, self.time_maa_w2.size(0), -1).transpose(0, 1)
388
+ xxx = torch.bmm(xxx, self.time_maa_w2).view(self.time_maa_w2.size(0), B, T, C)
389
+
390
+ mr, mk, mv, mw, mg = xxx.unbind(dim=0)
391
+ xr = x + dxprev * (self.time_maa_r + mr)
392
+ xk = x + dxprev * (self.time_maa_k + mk)
393
+ xv = x + dxprev * (self.time_maa_v + mv)
394
+ xw = x + dxprev * (self.time_maa_w + mw)
395
+ xg = x + dxprev * (self.time_maa_g + mg)
396
+ else:
397
+ xr = xk = xv = xw = xg = x
398
+
399
+ r = self.q_proj(xr)
400
+ k = self.k_proj(xk)
401
+ v = self.v_proj(xv)
402
+ w_lora_result = (self.time_decay + torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2).to(r.dtype)
403
+ if self.config.gate_rank_type == 1:
404
+ g = torch.sigmoid(self.gate(xg))
405
+ elif self.config.gate_rank_type == 2:
406
+ g = torch.sigmoid(xg @ self.g1) @ self.g2
407
+
408
+ if position_embeddings is not None:
409
+ r = r.view(B,T,-1,N)
410
+ k = k.view(B,T,-1,N)
411
+ cos, sin = position_embeddings
412
+ r, k = apply_rotary_pos_emb(r, k, cos, sin, unsqueeze_dim=2)
413
+
414
+ # repeat k/v heads if n_kv_heads < n_heads
415
+ k = k.view(B, T, -1, 1, self.head_dim).expand(-1, -1, -1, self.num_key_value_groups, -1).reshape(B, T, -1)
416
+ v = v.view(B, T, -1, 1, self.head_dim).expand(-1, -1, -1, self.num_key_value_groups, -1).reshape(B, T, -1)
417
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
418
+
419
+ log_w = -w_lora_result.float().exp()
420
+ log_w = log_w.clamp(-5)
421
+ if self.config.balance_state:
422
+ k = (k * (1 - log_w.exp())).to(k.dtype)
423
+
424
+ # dealing with left-padding
425
+ if attention_mask is not None:
426
+ v = v * attention_mask[:, -v.shape[-2]:, None]
427
+
428
+ r = r.view(B,T,-1,N).to(v.dtype)
429
+ k = k.view(B,T,-1,N).to(v.dtype)
430
+ v = v.view(B,T,-1,N)
431
+ log_w = log_w.view(B,T,-1,N)
432
+
433
+ attn_weights = torch.empty(0, device=x.device)
434
+
435
+ scale = r.shape[-1] ** -0.5
436
+ output_final_state = not self.training and use_cache and past_key_values is not None
437
+ attn_output, output_kv_state = fused_recurrent_gla(r, k, v, log_w, None, scale, input_kv_state, output_final_state)
438
+
439
+ attn_output = attn_output.view(B, T, -1)
440
+ if self.config.groupnorm_att:
441
+ attn_output = self.ln_x(attn_output.view(B * T, -1)).view(B, T, -1)
442
+ if self.config.gate_rank_type != 0:
443
+ attn_output = attn_output * g
444
+ attn_output = self.o_proj(attn_output)
445
+
446
+ if output_final_state:
447
+ past_key_values.update(output_kv_state, output_shift_state, self.layer_idx, T)
448
+
449
+ return attn_output, attn_weights
450
+
451
+ class RWKV6Qwen2DecoderLayer(Qwen2DecoderLayer):
452
+ def __init__(self, config: RWKV6Qwen2Config, layer_idx: int):
453
+ nn.Module.__init__(self)
454
+ self.hidden_size = config.hidden_size
455
+
456
+ self.self_attn = RWKV6Attention(config, layer_idx) #QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
457
+
458
+ self.mlp = Qwen2MLP(config)
459
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
460
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
461
+
462
+ def forward(
463
+ self,
464
+ hidden_states: torch.Tensor,
465
+ attention_mask: Optional[torch.Tensor] = None,
466
+ position_ids: Optional[torch.LongTensor] = None,
467
+ past_key_values: Optional[Cache] = None,
468
+ output_attentions: Optional[bool] = False,
469
+ use_cache: Optional[bool] = False,
470
+ cache_position: Optional[torch.LongTensor] = None,
471
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
472
+ **kwargs,
473
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
474
+ residual = hidden_states
475
+
476
+ hidden_states = self.input_layernorm(hidden_states)
477
+
478
+ # Self Attention
479
+ hidden_states, self_attn_weights = self.self_attn(
480
+ hidden_states=hidden_states,
481
+ attention_mask=attention_mask,
482
+ position_ids=position_ids,
483
+ past_key_values=past_key_values,
484
+ output_attentions=output_attentions,
485
+ use_cache=use_cache,
486
+ cache_position=cache_position,
487
+ position_embeddings=position_embeddings,
488
  **kwargs,
489
+ )
490
+ hidden_states = residual + hidden_states
491
+
492
+ # Fully Connected
493
+ residual = hidden_states
494
+ hidden_states = self.post_attention_layernorm(hidden_states)
495
+ hidden_states = self.mlp(hidden_states)
496
+ hidden_states = residual + hidden_states
497
+
498
+ outputs = (hidden_states,)
499
+ if output_attentions:
500
+ outputs += (self_attn_weights,)
501
+
502
+ return outputs
503
+
504
+ RWKV6QWEN2_START_DOCSTRING = r"""
505
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
506
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
507
+ etc.)
508
+
509
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
510
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
511
+ and behavior.
512
+
513
+ Parameters:
514
+ config ([`RWKV6Qwen2Config`]):
515
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
516
+ load the weights associated with the model, only the configuration. Check out the
517
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
518
+ """
519
+
520
+
521
+ @add_start_docstrings(
522
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
523
+ RWKV6QWEN2_START_DOCSTRING,
524
+ )
525
+ class RWKV6Qwen2PreTrainedModel(PreTrainedModel):
526
+ config_class = RWKV6Qwen2Config
527
+ base_model_prefix = "model"
528
+ supports_gradient_checkpointing = True
529
+ _no_split_modules = ["RWKV6Qwen2DecoderLayer"]
530
+ _skip_keys_device_placement = "past_key_values"
531
+ _supports_flash_attn_2 = True
532
+ _supports_sdpa = True
533
+ _supports_cache_class = True
534
+ _supports_quantized_cache = True
535
+ _supports_static_cache = True
536
+
537
+ def _init_weights(self, module):
538
+ std = self.config.initializer_range
539
+ if isinstance(module, nn.Linear):
540
+ module.weight.data.normal_(mean=0.0, std=std)
541
+ if module.bias is not None:
542
+ module.bias.data.zero_()
543
+ elif isinstance(module, nn.Embedding):
544
+ module.weight.data.normal_(mean=0.0, std=std)
545
+ if module.padding_idx is not None:
546
+ module.weight.data[module.padding_idx].zero_()
547
+
548
+
549
+ RWKV6QWEN2_INPUTS_DOCSTRING = r"""
550
+ Args:
551
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
552
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
553
+ it.
554
+
555
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
556
+ [`PreTrainedTokenizer.__call__`] for details.
557
+
558
+ [What are input IDs?](../glossary#input-ids)
559
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
560
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
561
+
562
+ - 1 for tokens that are **not masked**,
563
+ - 0 for tokens that are **masked**.
564
+
565
+ [What are attention masks?](../glossary#attention-mask)
566
+
567
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
568
+ [`PreTrainedTokenizer.__call__`] for details.
569
+
570
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
571
+ `past_key_values`).
572
+
573
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
574
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
575
+ information on the default strategy.
576
+
577
+ - 1 indicates the head is **not masked**,
578
+ - 0 indicates the head is **masked**.
579
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
580
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
581
+ config.n_positions - 1]`.
582
+
583
+ [What are position IDs?](../glossary#position-ids)
584
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
585
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
586
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
587
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
588
+
589
+ Two formats are allowed:
590
+ - a [`~cache_utils.Cache`] instance, see our
591
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
592
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
593
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
594
+ cache format.
595
+
596
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
597
+ legacy cache format will be returned.
598
+
599
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
600
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
601
+ of shape `(batch_size, sequence_length)`.
602
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
603
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
604
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
605
+ model's internal embedding lookup matrix.
606
+ use_cache (`bool`, *optional*):
607
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
608
+ `past_key_values`).
609
+ output_attentions (`bool`, *optional*):
610
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
611
+ tensors for more detail.
612
+ output_hidden_states (`bool`, *optional*):
613
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
614
+ more detail.
615
+ return_dict (`bool`, *optional*):
616
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
617
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
618
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
619
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
620
+ the complete sequence length.
621
+ """
622
+
623
+ @add_start_docstrings(
624
+ "The bare RWKV6Qwen2 Model outputting raw hidden-states without any specific head on top.",
625
+ RWKV6QWEN2_START_DOCSTRING,
626
+ )
627
+ class RWKV6Qwen2Model(RWKV6Qwen2PreTrainedModel):
628
+ """
629
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
630
+
631
+ Args:
632
+ config: RWKV6Qwen2Config
633
+ """
634
+
635
+ def __init__(self, config: RWKV6Qwen2Config):
636
+ super().__init__(config)
637
+ self.padding_idx = config.pad_token_id
638
+ self.vocab_size = config.vocab_size
639
+
640
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
641
+ self.layers = nn.ModuleList(
642
+ [RWKV6Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
643
+ )
644
+ self._attn_implementation = config._attn_implementation
645
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
646
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
647
+
648
+ self.gradient_checkpointing = False
649
+ # Initialize weights and apply final processing
650
+ self.post_init()
651
+
652
+ def get_input_embeddings(self):
653
+ return self.embed_tokens
654
+
655
+ def set_input_embeddings(self, value):
656
+ self.embed_tokens = value
657
+
658
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
659
+ def forward(
660
+ self,
661
+ input_ids: torch.LongTensor = None,
662
+ attention_mask: Optional[torch.Tensor] = None,
663
+ position_ids: Optional[torch.LongTensor] = None,
664
+ past_key_values: Optional[Cache] = None,
665
+ inputs_embeds: Optional[torch.FloatTensor] = None,
666
+ use_cache: Optional[bool] = None,
667
+ output_attentions: Optional[bool] = None,
668
+ output_hidden_states: Optional[bool] = None,
669
+ return_dict: Optional[bool] = None,
670
+ cache_position: Optional[torch.LongTensor] = None,
671
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
672
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
673
+ output_hidden_states = (
674
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
675
+ )
676
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
677
+
678
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
679
+
680
+ if (input_ids is None) ^ (inputs_embeds is not None):
681
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
682
+
683
+ if self.gradient_checkpointing and self.training and use_cache:
684
+ logger.warning_once(
685
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
686
+ )
687
+ use_cache = False
688
+
689
+ if inputs_embeds is None:
690
+ inputs_embeds = self.embed_tokens(input_ids)
691
+
692
+ if use_cache and not isinstance(past_key_values, RWKV6State):
693
+ past_key_values = RWKV6State()
694
+
695
+ #if cache_position is None:
696
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
697
+ cache_position = torch.arange(
698
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
699
+ )
700
+
701
+ if position_ids is None:
702
+ position_ids = cache_position.unsqueeze(0)
703
+
704
+ # causal_mask = self._update_causal_mask(
705
+ # attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
706
+ # )
707
+
708
+ causal_mask = None
709
+
710
+ hidden_states = inputs_embeds
711
+
712
+ # create position embeddings to be shared across the decoder layers
713
+ if self.config.use_rope:
714
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
715
+ else:
716
+ position_embeddings = None
717
+
718
+ # decoder layers
719
+ all_hidden_states = () if output_hidden_states else None
720
+ all_self_attns = () if output_attentions else None
721
+ next_decoder_cache = None
722
+
723
+ for decoder_layer in self.layers:
724
+ if output_hidden_states:
725
+ all_hidden_states += (hidden_states,)
726
+
727
+ if self.gradient_checkpointing and self.training:
728
+ layer_outputs = self._gradient_checkpointing_func(
729
+ decoder_layer.__call__,
730
+ hidden_states,
731
+ causal_mask,
732
+ position_ids,
733
+ past_key_values,
734
+ output_attentions,
735
+ use_cache,
736
+ cache_position,
737
+ position_embeddings,
738
+ )
739
+ else:
740
+ layer_outputs = decoder_layer(
741
+ hidden_states,
742
+ attention_mask=attention_mask,
743
+ position_ids=position_ids,
744
+ past_key_values=past_key_values,
745
+ output_attentions=output_attentions,
746
+ use_cache=use_cache,
747
+ cache_position=cache_position,
748
+ position_embeddings=position_embeddings,
749
+ )
750
+
751
+ hidden_states = layer_outputs[0]
752
+
753
+ if output_attentions:
754
+ all_self_attns += (layer_outputs[1],)
755
+
756
+ hidden_states = self.norm(hidden_states)
757
+
758
+ # add hidden states from the last decoder layer
759
+ if output_hidden_states:
760
+ all_hidden_states += (hidden_states,)
761
+
762
+ #if return_legacy_cache:
763
+ # next_cache = next_cache.to_legacy_cache()
764
+
765
+ if not return_dict:
766
+ return tuple(v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None)
767
+ return BaseModelOutputWithPast(
768
+ last_hidden_state=hidden_states,
769
+ past_key_values=past_key_values,
770
+ hidden_states=all_hidden_states,
771
+ attentions=all_self_attns,
772
+ )
773
+
774
+ class RWKV6Qwen2ForCausalLM(RWKV6Qwen2PreTrainedModel, GenerationMixin):
775
+ _tied_weights_keys = ["lm_head.weight"]
776
+
777
+ def __init__(self, config):
778
+ super().__init__(config)
779
+ self.model = RWKV6Qwen2Model(config)
780
+ self.vocab_size = config.vocab_size
781
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
782
+
783
+ # Initialize weights and apply final processing
784
+ self.post_init()
785
+
786
+ def get_input_embeddings(self):
787
+ return self.model.embed_tokens
788
+
789
+ def set_input_embeddings(self, value):
790
+ self.model.embed_tokens = value
791
+
792
+ def get_output_embeddings(self):
793
+ return self.lm_head
794
+
795
+ def set_output_embeddings(self, new_embeddings):
796
+ self.lm_head = new_embeddings
797
+
798
+ def set_decoder(self, decoder):
799
+ self.model = decoder
800
+
801
+ def get_decoder(self):
802
+ return self.model
803
+
804
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
805
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
806
+ def forward(
807
+ self,
808
+ input_ids: torch.LongTensor = None,
809
+ attention_mask: Optional[torch.Tensor] = None,
810
+ position_ids: Optional[torch.LongTensor] = None,
811
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
812
+ inputs_embeds: Optional[torch.FloatTensor] = None,
813
+ labels: Optional[torch.LongTensor] = None,
814
+ use_cache: Optional[bool] = None,
815
+ output_attentions: Optional[bool] = None,
816
+ output_hidden_states: Optional[bool] = None,
817
+ return_dict: Optional[bool] = None,
818
+ cache_position: Optional[torch.LongTensor] = None,
819
+ num_logits_to_keep: int = 0,
820
+ **loss_kwargs,
821
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
822
+ r"""
823
+ Args:
824
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
825
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
826
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
827
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
828
+
829
+ num_logits_to_keep (`int`, *optional*):
830
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
831
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
832
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
833
+
834
+ Returns:
835
+
836
+ Example:
837
+
838
+ ```python
839
+ >>> from transformers import AutoTokenizer, RWKV6Qwen2ForCausalLM
840
+
841
+ >>> model = RWKV6Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
842
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
843
+
844
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
845
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
846
+
847
+ >>> # Generate
848
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
849
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
850
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
851
+ ```"""
852
+
853
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
854
+ output_hidden_states = (
855
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
856
+ )
857
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
858
+
859
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
860
+ outputs = self.model(
861
+ input_ids=input_ids,
862
+ attention_mask=attention_mask,
863
+ position_ids=position_ids,
864
+ past_key_values=past_key_values,
865
+ inputs_embeds=inputs_embeds,
866
+ use_cache=use_cache,
867
+ output_attentions=output_attentions,
868
+ output_hidden_states=output_hidden_states,
869
+ return_dict=return_dict,
870
+ cache_position=cache_position,
871
+ )
872
+
873
+ hidden_states = outputs[0]
874
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
875
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
876
+
877
+ loss = None
878
+ if labels is not None:
879
+ loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
880
+
881
+ if not return_dict:
882
+ output = (logits,) + outputs[1:]
883
+ return (loss,) + output if loss is not None else output
884
+
885
+ return CausalLMOutputWithPast(
886
+ loss=loss,
887
+ logits=logits,
888
+ past_key_values=outputs.past_key_values,
889
+ hidden_states=outputs.hidden_states,
890
+ attentions=outputs.attentions,
891
+ )
892
+
893
+ @add_start_docstrings(
894
+ """
895
+ The RWKV6Qwen2 Model transformer with a sequence classification head on top (linear layer).
896
+
897
+ [`RWKV6Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
898
+ (e.g. GPT-2) do.
899
+
900
+ Since it does classification on the last token, it requires to know the position of the last token. If a
901
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
902
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
903
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
904
+ each row of the batch).
905
+ """,
906
+ RWKV6QWEN2_START_DOCSTRING,
907
+ )
908
+ class RWKV6Qwen2ForSequenceClassification(RWKV6Qwen2PreTrainedModel):
909
+ def __init__(self, config):
910
+ super().__init__(config)
911
+ self.num_labels = config.num_labels
912
+ self.model = RWKV6Qwen2Model(config)
913
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
914
+
915
+ # Initialize weights and apply final processing
916
+ self.post_init()
917
+
918
+ def get_input_embeddings(self):
919
+ return self.model.embed_tokens
920
+
921
+ def set_input_embeddings(self, value):
922
+ self.model.embed_tokens = value
923
+
924
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
925
+ def forward(
926
+ self,
927
+ input_ids: torch.LongTensor = None,
928
+ attention_mask: Optional[torch.Tensor] = None,
929
+ position_ids: Optional[torch.LongTensor] = None,
930
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
931
+ inputs_embeds: Optional[torch.FloatTensor] = None,
932
+ labels: Optional[torch.LongTensor] = None,
933
+ use_cache: Optional[bool] = None,
934
+ output_attentions: Optional[bool] = None,
935
+ output_hidden_states: Optional[bool] = None,
936
+ return_dict: Optional[bool] = None,
937
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
938
+ r"""
939
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
940
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
941
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
942
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
943
+ """
944
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
945
+
946
+ transformer_outputs = self.model(
947
+ input_ids,
948
+ attention_mask=attention_mask,
949
+ position_ids=position_ids,
950
+ past_key_values=past_key_values,
951
+ inputs_embeds=inputs_embeds,
952
+ use_cache=use_cache,
953
+ output_attentions=output_attentions,
954
+ output_hidden_states=output_hidden_states,
955
+ return_dict=return_dict,
956
+ )
957
+ hidden_states = transformer_outputs[0]
958
+ logits = self.score(hidden_states)
959
+
960
+ if input_ids is not None:
961
+ batch_size = input_ids.shape[0]
962
+ else:
963
+ batch_size = inputs_embeds.shape[0]
964
+
965
+ if self.config.pad_token_id is None and batch_size != 1:
966
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
967
+ if self.config.pad_token_id is None:
968
+ sequence_lengths = -1
969
+ else:
970
+ if input_ids is not None:
971
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
972
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
973
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
974
+ sequence_lengths = sequence_lengths.to(logits.device)
975
+ else:
976
+ sequence_lengths = -1
977
+
978
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
979
+
980
+ loss = None
981
+ if labels is not None:
982
+ labels = labels.to(logits.device)
983
+ if self.config.problem_type is None:
984
+ if self.num_labels == 1:
985
+ self.config.problem_type = "regression"
986
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
987
+ self.config.problem_type = "single_label_classification"
988
+ else:
989
+ self.config.problem_type = "multi_label_classification"
990
+
991
+ if self.config.problem_type == "regression":
992
+ loss_fct = MSELoss()
993
+ if self.num_labels == 1:
994
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
995
+ else:
996
+ loss = loss_fct(pooled_logits, labels)
997
+ elif self.config.problem_type == "single_label_classification":
998
+ loss_fct = CrossEntropyLoss()
999
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1000
+ elif self.config.problem_type == "multi_label_classification":
1001
+ loss_fct = BCEWithLogitsLoss()
1002
+ loss = loss_fct(pooled_logits, labels)
1003
+ if not return_dict:
1004
+ output = (pooled_logits,) + transformer_outputs[1:]
1005
+ return ((loss,) + output) if loss is not None else output
1006
+
1007
+ return SequenceClassifierOutputWithPast(
1008
+ loss=loss,
1009
+ logits=pooled_logits,
1010
+ past_key_values=transformer_outputs.past_key_values,
1011
+ hidden_states=transformer_outputs.hidden_states,
1012
+ attentions=transformer_outputs.attentions,
1013
+ )
1014
+
1015
+
1016
+ @add_start_docstrings(
1017
+ """
1018
+ The RWKV6Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1019
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1020
+ """,
1021
+ RWKV6QWEN2_START_DOCSTRING,
1022
+ )
1023
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->RWKV6Qwen2, LLAMA->RWKV6QWEN2
1024
+ class RWKV6Qwen2ForTokenClassification(RWKV6Qwen2PreTrainedModel):
1025
+ def __init__(self, config):
1026
+ super().__init__(config)
1027
+ self.num_labels = config.num_labels
1028
+ self.model = RWKV6Qwen2Model(config)
1029
+ if getattr(config, "classifier_dropout", None) is not None:
1030
+ classifier_dropout = config.classifier_dropout
1031
+ elif getattr(config, "hidden_dropout", None) is not None:
1032
+ classifier_dropout = config.hidden_dropout
1033
+ else:
1034
+ classifier_dropout = 0.1
1035
+ self.dropout = nn.Dropout(classifier_dropout)
1036
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1037
+
1038
+ # Initialize weights and apply final processing
1039
+ self.post_init()
1040
+
1041
+ def get_input_embeddings(self):
1042
+ return self.model.embed_tokens
1043
+
1044
+ def set_input_embeddings(self, value):
1045
+ self.model.embed_tokens = value
1046
+
1047
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
1048
+ @add_code_sample_docstrings(
1049
+ checkpoint=_CHECKPOINT_FOR_DOC,
1050
+ output_type=TokenClassifierOutput,
1051
+ config_class=_CONFIG_FOR_DOC,
1052
+ )
1053
+ def forward(
1054
+ self,
1055
+ input_ids: Optional[torch.LongTensor] = None,
1056
+ attention_mask: Optional[torch.Tensor] = None,
1057
+ position_ids: Optional[torch.LongTensor] = None,
1058
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1059
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1060
+ labels: Optional[torch.LongTensor] = None,
1061
+ use_cache: Optional[bool] = None,
1062
+ output_attentions: Optional[bool] = None,
1063
+ output_hidden_states: Optional[bool] = None,
1064
+ return_dict: Optional[bool] = None,
1065
+ ) -> Union[Tuple, TokenClassifierOutput]:
1066
+ r"""
1067
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1068
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1069
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1070
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1071
+ """
1072
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1073
+
1074
+ outputs = self.model(
1075
+ input_ids,
1076
+ attention_mask=attention_mask,
1077
+ position_ids=position_ids,
1078
+ past_key_values=past_key_values,
1079
+ inputs_embeds=inputs_embeds,
1080
+ use_cache=use_cache,
1081
+ output_attentions=output_attentions,
1082
+ output_hidden_states=output_hidden_states,
1083
+ return_dict=return_dict,
1084
+ )
1085
+ sequence_output = outputs[0]
1086
+ sequence_output = self.dropout(sequence_output)
1087
+ logits = self.score(sequence_output)
1088
+
1089
+ loss = None
1090
+ if labels is not None:
1091
+ loss = self.loss_function(logits, labels, self.config)
1092
+
1093
+ if not return_dict:
1094
+ output = (logits,) + outputs[2:]
1095
+ return ((loss,) + output) if loss is not None else output
1096
+
1097
+ return TokenClassifierOutput(
1098
+ loss=loss,
1099
+ logits=logits,
1100
+ hidden_states=outputs.hidden_states,
1101
+ attentions=outputs.attentions,
1102
+ )
1103
+
1104
+
1105
+ @add_start_docstrings(
1106
+ """
1107
+ The RWKV6Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
1108
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1109
+ """,
1110
+ RWKV6QWEN2_START_DOCSTRING,
1111
+ )
1112
+ # Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->RWKV6Qwen2, MISTRAL->RWKV6QWEN2
1113
+ class RWKV6Qwen2ForQuestionAnswering(RWKV6Qwen2PreTrainedModel):
1114
+ base_model_prefix = "model"
1115
+
1116
+ # Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->RWKV6Qwen2
1117
+ def __init__(self, config):
1118
+ super().__init__(config)
1119
+ self.model = RWKV6Qwen2Model(config)
1120
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1121
+
1122
+ # Initialize weights and apply final processing
1123
+ self.post_init()
1124
+
1125
+ def get_input_embeddings(self):
1126
+ return self.model.embed_tokens
1127
+
1128
+ def set_input_embeddings(self, value):
1129
+ self.model.embed_tokens = value
1130
+
1131
+ @add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
1132
+ def forward(
1133
+ self,
1134
+ input_ids: Optional[torch.LongTensor] = None,
1135
+ attention_mask: Optional[torch.FloatTensor] = None,
1136
+ position_ids: Optional[torch.LongTensor] = None,
1137
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1138
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1139
+ start_positions: Optional[torch.LongTensor] = None,
1140
+ end_positions: Optional[torch.LongTensor] = None,
1141
+ output_attentions: Optional[bool] = None,
1142
+ output_hidden_states: Optional[bool] = None,
1143
+ return_dict: Optional[bool] = None,
1144
+ **kwargs,
1145
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1146
+ r"""
1147
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1148
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1149
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1150
+ are not taken into account for computing the loss.
1151
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1152
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1153
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1154
+ are not taken into account for computing the loss.
1155
+ """
1156
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1157
+
1158
+ outputs = self.model(
1159
+ input_ids,
1160
+ attention_mask=attention_mask,
1161
+ position_ids=position_ids,
1162
+ past_key_values=past_key_values,
1163
+ inputs_embeds=inputs_embeds,
1164
+ output_attentions=output_attentions,
1165
+ output_hidden_states=output_hidden_states,
1166
+ return_dict=return_dict,
1167
+ )
1168
+
1169
+ sequence_output = outputs[0]
1170
+
1171
+ logits = self.qa_outputs(sequence_output)
1172
+ start_logits, end_logits = logits.split(1, dim=-1)
1173
+ start_logits = start_logits.squeeze(-1).contiguous()
1174
+ end_logits = end_logits.squeeze(-1).contiguous()
1175
+
1176
+ loss = None
1177
+ if start_positions is not None and end_positions is not None:
1178
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1179
+
1180
+ if not return_dict:
1181
+ output = (start_logits, end_logits) + outputs[2:]
1182
+ return ((loss,) + output) if loss is not None else output
1183
+
1184
+ return QuestionAnsweringModelOutput(
1185
+ loss=loss,
1186
+ start_logits=start_logits,
1187
+ end_logits=end_logits,
1188
+ hidden_states=outputs.hidden_states,
1189
+ attentions=outputs.attentions,
1190
  )