nuojohnchen commited on
Commit
6de0b52
·
verified ·
1 Parent(s): 7b08fb3

Create modeling_upcycling_qwen2_moe.py

Browse files
Files changed (1) hide show
  1. modeling_upcycling_qwen2_moe.py +1664 -0
modeling_upcycling_qwen2_moe.py ADDED
@@ -0,0 +1,1664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
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 Qwen2MoE model."""
21
+
22
+ import inspect
23
+ import math
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
34
+ from transformers.modeling_attn_mask_utils import (
35
+ AttentionMaskConverter,
36
+ )
37
+ from transformers.modeling_outputs import (
38
+ MoeCausalLMOutputWithPast,
39
+ MoeModelOutputWithPast,
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.utils import (
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from configuration_upcycling_qwen2_moe import UpcyclingQwen2MoeConfig
49
+ from transformers import AutoModelForCausalLM,AutoConfig,AutoModel
50
+
51
+
52
+ if is_flash_attn_2_available():
53
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
55
+
56
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CHECKPOINT_FOR_DOC = "UpcyclingQwen2MoE"
61
+ _CONFIG_FOR_DOC = "UpcyclingQwen2MoeConfig"
62
+
63
+
64
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
65
+ def load_balancing_loss_func(
66
+ gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2, attention_mask: Optional[torch.Tensor] = None
67
+ ) -> float:
68
+ r"""
69
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
70
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
71
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
72
+ experts is too unbalanced.
73
+ Args:
74
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
75
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
76
+ shape [batch_size X sequence_length, num_experts].
77
+ attention_mask (`torch.Tensor`, None):
78
+ The attention_mask used in forward function
79
+ shape [batch_size X sequence_length] if not None.
80
+ num_experts (`int`, *optional*):
81
+ Number of experts
82
+ Returns:
83
+ The auxiliary loss.
84
+ """
85
+ if gate_logits is None or not isinstance(gate_logits, tuple):
86
+ return 0
87
+
88
+ if isinstance(gate_logits, tuple):
89
+ compute_device = gate_logits[0].device
90
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
91
+
92
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
93
+
94
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
95
+
96
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
97
+
98
+ if attention_mask is None:
99
+ # Compute the percentage of tokens routed to each experts
100
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
101
+
102
+ # Compute the average probability of routing to these experts
103
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
104
+ else:
105
+ batch_size, sequence_length = attention_mask.shape
106
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
107
+
108
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
109
+ expert_attention_mask = (
110
+ attention_mask[None, :, :, None, None]
111
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
112
+ .reshape(-1, top_k, num_experts)
113
+ .to(compute_device)
114
+ )
115
+
116
+ # Compute the percentage of tokens routed to each experts
117
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
118
+ expert_attention_mask, dim=0
119
+ )
120
+
121
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
122
+ router_per_expert_attention_mask = (
123
+ attention_mask[None, :, :, None]
124
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
125
+ .reshape(-1, num_experts)
126
+ .to(compute_device)
127
+ )
128
+
129
+ # Compute the average probability of routing to these experts
130
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
131
+ router_per_expert_attention_mask, dim=0
132
+ )
133
+
134
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
135
+ return overall_loss * num_experts
136
+
137
+
138
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
139
+ def _get_unpad_data(attention_mask):
140
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
141
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
142
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
143
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
144
+ return (
145
+ indices,
146
+ cu_seqlens,
147
+ max_seqlen_in_batch,
148
+ )
149
+
150
+
151
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Qwen2Moe
152
+ class Qwen2MoeRMSNorm(nn.Module):
153
+ def __init__(self, hidden_size, eps=1e-6):
154
+ """
155
+ Qwen2MoeRMSNorm is equivalent to T5LayerNorm
156
+ """
157
+ super().__init__()
158
+ self.weight = nn.Parameter(torch.ones(hidden_size))
159
+ self.variance_epsilon = eps
160
+
161
+ def forward(self, hidden_states):
162
+ input_dtype = hidden_states.dtype
163
+ hidden_states = hidden_states.to(torch.float32)
164
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
165
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
166
+ return self.weight * hidden_states.to(input_dtype)
167
+
168
+
169
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralRotaryEmbedding with Mixtral->Qwen2Moe
170
+ class Qwen2MoeRotaryEmbedding(nn.Module):
171
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
172
+ super().__init__()
173
+
174
+ self.dim = dim
175
+ self.max_position_embeddings = max_position_embeddings
176
+ self.base = base
177
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
178
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
179
+
180
+ # Build here to make `torch.jit.trace` work.
181
+ self._set_cos_sin_cache(
182
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
183
+ )
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
188
+
189
+ freqs = torch.outer(t, self.inv_freq)
190
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
191
+ emb = torch.cat((freqs, freqs), dim=-1)
192
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
193
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
194
+
195
+ def forward(self, x, seq_len=None):
196
+ # x: [bs, num_attention_heads, seq_len, head_size]
197
+ if seq_len > self.max_seq_len_cached:
198
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
199
+
200
+ return (
201
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
202
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
203
+ )
204
+
205
+
206
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
207
+ def rotate_half(x):
208
+ """Rotates half the hidden dims of the input."""
209
+ x1 = x[..., : x.shape[-1] // 2]
210
+ x2 = x[..., x.shape[-1] // 2 :]
211
+ return torch.cat((-x2, x1), dim=-1)
212
+
213
+
214
+ # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
215
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
216
+ """Applies Rotary Position Embedding to the query and key tensors.
217
+ Args:
218
+ q (`torch.Tensor`): The query tensor.
219
+ k (`torch.Tensor`): The key tensor.
220
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
221
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
222
+ position_ids (`torch.Tensor`):
223
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
224
+ used to pass offsetted position ids when working with a KV-cache.
225
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
226
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
227
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
228
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
229
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
230
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
231
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
232
+ Returns:
233
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
234
+ """
235
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
236
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
237
+ q_embed = (q * cos) + (rotate_half(q) * sin)
238
+ k_embed = (k * cos) + (rotate_half(k) * sin)
239
+ return q_embed, k_embed
240
+
241
+
242
+ # Modified from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Qwen2Moe
243
+ class Qwen2MoeMLP(nn.Module):
244
+ def __init__(self, config, intermediate_size=None):
245
+ super().__init__()
246
+ self.config = config
247
+ self.hidden_size = config.hidden_size
248
+ self.intermediate_size = intermediate_size
249
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
250
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
251
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
252
+ self.act_fn = ACT2FN[config.hidden_act]
253
+
254
+ def forward(self, x,language_ids:Optional[torch.LongTensor]=None):
255
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
256
+
257
+
258
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
259
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
260
+ """
261
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
262
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
263
+ """
264
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
265
+ if n_rep == 1:
266
+ return hidden_states
267
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
268
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
269
+
270
+
271
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2Attention with Qwen2->Qwen2Moe
272
+ class Qwen2MoeAttention(nn.Module):
273
+ """
274
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
275
+ and "Generating Long Sequences with Sparse Transformers".
276
+ """
277
+
278
+ def __init__(self, config: UpcyclingQwen2MoeConfig, layer_idx: Optional[int] = None):
279
+ super().__init__()
280
+ self.config = config
281
+ self.layer_idx = layer_idx
282
+ if layer_idx is None:
283
+ logger.warning_once(
284
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
285
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
286
+ "when creating this class."
287
+ )
288
+
289
+ self.hidden_size = config.hidden_size
290
+ self.num_heads = config.num_attention_heads
291
+ self.head_dim = self.hidden_size // self.num_heads
292
+ self.num_key_value_heads = config.num_key_value_heads
293
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
294
+ self.max_position_embeddings = config.max_position_embeddings
295
+ self.rope_theta = config.rope_theta
296
+ self.is_causal = True
297
+ self.attention_dropout = config.attention_dropout
298
+
299
+ if (self.head_dim * self.num_heads) != self.hidden_size:
300
+ raise ValueError(
301
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
302
+ f" and `num_heads`: {self.num_heads})."
303
+ )
304
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
305
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
306
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
307
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
308
+
309
+ self.rotary_emb = Qwen2MoeRotaryEmbedding(
310
+ self.head_dim,
311
+ max_position_embeddings=self.max_position_embeddings,
312
+ base=self.rope_theta,
313
+ )
314
+
315
+ def forward(
316
+ self,
317
+ hidden_states: torch.Tensor,
318
+ attention_mask: Optional[torch.Tensor] = None,
319
+ position_ids: Optional[torch.LongTensor] = None,
320
+ past_key_value: Optional[Cache] = None,
321
+ output_attentions: bool = False,
322
+ use_cache: bool = False,
323
+ cache_position: Optional[torch.LongTensor] = None,
324
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
325
+ bsz, q_len, _ = hidden_states.size()
326
+
327
+ query_states = self.q_proj(hidden_states)
328
+ key_states = self.k_proj(hidden_states)
329
+ value_states = self.v_proj(hidden_states)
330
+
331
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
332
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
333
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
334
+
335
+ kv_seq_len = key_states.shape[-2]
336
+ if past_key_value is not None:
337
+ if self.layer_idx is None:
338
+ raise ValueError(
339
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
340
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
341
+ "with a layer index."
342
+ )
343
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
344
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
345
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
346
+
347
+ if past_key_value is not None:
348
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
349
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
350
+
351
+ # repeat k/v heads if n_kv_heads < n_heads
352
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
353
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
354
+
355
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
356
+
357
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
360
+ f" {attn_weights.size()}"
361
+ )
362
+
363
+ if attention_mask is not None: # no matter the length, we just slice it
364
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
365
+ attn_weights = attn_weights + causal_mask
366
+
367
+ # upcast attention to fp32
368
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
369
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
370
+ attn_output = torch.matmul(attn_weights, value_states)
371
+
372
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
373
+ raise ValueError(
374
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
375
+ f" {attn_output.size()}"
376
+ )
377
+
378
+ attn_output = attn_output.transpose(1, 2).contiguous()
379
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
380
+
381
+ attn_output = self.o_proj(attn_output)
382
+
383
+ if not output_attentions:
384
+ attn_weights = None
385
+
386
+ return attn_output, attn_weights, past_key_value
387
+
388
+
389
+ # Copied from transformers.models.qwen2.modeling_qwen2.Qwen2FlashAttention2 with Qwen2->Qwen2Moe
390
+ class Qwen2MoeFlashAttention2(Qwen2MoeAttention):
391
+ """
392
+ Qwen2Moe flash attention module, following Qwen2Moe attention module. This module inherits from `Qwen2MoeAttention`
393
+ as the weights of the module stays untouched. The only required change would be on the forward pass
394
+ where it needs to correctly call the public API of flash attention and deal with padding tokens
395
+ in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
396
+ config.max_window_layers layers.
397
+ """
398
+
399
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
400
+ def __init__(self, *args, **kwargs):
401
+ super().__init__(*args, **kwargs)
402
+
403
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
404
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
405
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
406
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
407
+
408
+ def forward(
409
+ self,
410
+ hidden_states: torch.Tensor,
411
+ attention_mask: Optional[torch.Tensor] = None,
412
+ position_ids: Optional[torch.LongTensor] = None,
413
+ past_key_value: Optional[Cache] = None,
414
+ output_attentions: bool = False,
415
+ use_cache: bool = False,
416
+ cache_position: Optional[torch.LongTensor] = None,
417
+ ):
418
+ bsz, q_len, _ = hidden_states.size()
419
+
420
+ query_states = self.q_proj(hidden_states)
421
+ key_states = self.k_proj(hidden_states)
422
+ value_states = self.v_proj(hidden_states)
423
+
424
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
425
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
426
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
427
+
428
+ kv_seq_len = key_states.shape[-2]
429
+ if past_key_value is not None:
430
+ if self.layer_idx is None:
431
+ raise ValueError(
432
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
433
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
434
+ "with a layer index."
435
+ )
436
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
437
+
438
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
439
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
440
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
441
+
442
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
443
+
444
+ use_sliding_windows = (
445
+ _flash_supports_window_size
446
+ and getattr(self.config, "sliding_window", None) is not None
447
+ and kv_seq_len > self.config.sliding_window
448
+ and self.config.use_sliding_window
449
+ )
450
+
451
+ if not _flash_supports_window_size:
452
+ logger.warning_once(
453
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
454
+ " make sure to upgrade flash-attn library."
455
+ )
456
+
457
+ if past_key_value is not None:
458
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
459
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
460
+ if (
461
+ getattr(self.config, "sliding_window", None) is not None
462
+ and kv_seq_len > self.config.sliding_window
463
+ and cache_has_contents
464
+ ):
465
+ slicing_tokens = 1 - self.config.sliding_window
466
+
467
+ past_key = past_key_value[self.layer_idx][0]
468
+ past_value = past_key_value[self.layer_idx][1]
469
+
470
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
471
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
472
+
473
+ if past_key.shape[-2] != self.config.sliding_window - 1:
474
+ raise ValueError(
475
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
476
+ f" {past_key.shape}"
477
+ )
478
+
479
+ if attention_mask is not None:
480
+ attention_mask = attention_mask[:, slicing_tokens:]
481
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
482
+
483
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
484
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
485
+
486
+ # repeat k/v heads if n_kv_heads < n_heads
487
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
488
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
489
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
490
+
491
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
492
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
493
+ # cast them back in float16 just to be sure everything works as expected.
494
+ input_dtype = query_states.dtype
495
+ if input_dtype == torch.float32:
496
+ if torch.is_autocast_enabled():
497
+ target_dtype = torch.get_autocast_gpu_dtype()
498
+ # Handle the case where the model is quantized
499
+ elif hasattr(self.config, "_pre_quantization_dtype"):
500
+ target_dtype = self.config._pre_quantization_dtype
501
+ else:
502
+ target_dtype = self.q_proj.weight.dtype
503
+
504
+ logger.warning_once(
505
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
506
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
507
+ f" {target_dtype}."
508
+ )
509
+
510
+ query_states = query_states.to(target_dtype)
511
+ key_states = key_states.to(target_dtype)
512
+ value_states = value_states.to(target_dtype)
513
+
514
+ # Reashape to the expected shape for Flash Attention
515
+ query_states = query_states.transpose(1, 2)
516
+ key_states = key_states.transpose(1, 2)
517
+ value_states = value_states.transpose(1, 2)
518
+
519
+ attn_output = self._flash_attention_forward(
520
+ query_states,
521
+ key_states,
522
+ value_states,
523
+ attention_mask,
524
+ q_len,
525
+ dropout=dropout_rate,
526
+ use_sliding_windows=use_sliding_windows,
527
+ )
528
+
529
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
530
+ attn_output = self.o_proj(attn_output)
531
+
532
+ if not output_attentions:
533
+ attn_weights = None
534
+
535
+ return attn_output, attn_weights, past_key_value
536
+
537
+ def _flash_attention_forward(
538
+ self,
539
+ query_states,
540
+ key_states,
541
+ value_states,
542
+ attention_mask,
543
+ query_length,
544
+ dropout=0.0,
545
+ softmax_scale=None,
546
+ use_sliding_windows=False,
547
+ ):
548
+ """
549
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
550
+ first unpad the input, then computes the attention scores and pad the final attention scores.
551
+ Args:
552
+ query_states (`torch.Tensor`):
553
+ Input query states to be passed to Flash Attention API
554
+ key_states (`torch.Tensor`):
555
+ Input key states to be passed to Flash Attention API
556
+ value_states (`torch.Tensor`):
557
+ Input value states to be passed to Flash Attention API
558
+ attention_mask (`torch.Tensor`):
559
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
560
+ position of padding tokens and 1 for the position of non-padding tokens.
561
+ dropout (`float`):
562
+ Attention dropout
563
+ softmax_scale (`float`, *optional*):
564
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
565
+ use_sliding_windows (`bool`, *optional*):
566
+ Whether to activate sliding window attention.
567
+ """
568
+ if not self._flash_attn_uses_top_left_mask:
569
+ causal = self.is_causal
570
+ else:
571
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
572
+ causal = self.is_causal and query_length != 1
573
+
574
+ # Decide whether to use SWA or not by layer index.
575
+ if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
576
+ use_sliding_windows = False
577
+
578
+ # Contains at least one padding token in the sequence
579
+ if attention_mask is not None:
580
+ batch_size = query_states.shape[0]
581
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
582
+ query_states, key_states, value_states, attention_mask, query_length
583
+ )
584
+
585
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
586
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
587
+
588
+ if not use_sliding_windows:
589
+ attn_output_unpad = flash_attn_varlen_func(
590
+ query_states,
591
+ key_states,
592
+ value_states,
593
+ cu_seqlens_q=cu_seqlens_q,
594
+ cu_seqlens_k=cu_seqlens_k,
595
+ max_seqlen_q=max_seqlen_in_batch_q,
596
+ max_seqlen_k=max_seqlen_in_batch_k,
597
+ dropout_p=dropout,
598
+ softmax_scale=softmax_scale,
599
+ causal=causal,
600
+ )
601
+ else:
602
+ attn_output_unpad = flash_attn_varlen_func(
603
+ query_states,
604
+ key_states,
605
+ value_states,
606
+ cu_seqlens_q=cu_seqlens_q,
607
+ cu_seqlens_k=cu_seqlens_k,
608
+ max_seqlen_q=max_seqlen_in_batch_q,
609
+ max_seqlen_k=max_seqlen_in_batch_k,
610
+ dropout_p=dropout,
611
+ softmax_scale=softmax_scale,
612
+ causal=causal,
613
+ window_size=(self.config.sliding_window, self.config.sliding_window),
614
+ )
615
+
616
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
617
+ else:
618
+ if not use_sliding_windows:
619
+ attn_output = flash_attn_func(
620
+ query_states,
621
+ key_states,
622
+ value_states,
623
+ dropout,
624
+ softmax_scale=softmax_scale,
625
+ causal=causal,
626
+ )
627
+ else:
628
+ attn_output = flash_attn_func(
629
+ query_states,
630
+ key_states,
631
+ value_states,
632
+ dropout,
633
+ softmax_scale=softmax_scale,
634
+ causal=causal,
635
+ window_size=(self.config.sliding_window, self.config.sliding_window),
636
+ )
637
+
638
+ return attn_output
639
+
640
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
641
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
642
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
643
+
644
+ # On the first iteration we need to properly re-create the padding mask
645
+ # by slicing it on the proper place
646
+ if kv_seq_len != attention_mask.shape[-1]:
647
+ attention_mask_num_tokens = attention_mask.shape[-1]
648
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
649
+
650
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
651
+
652
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
653
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
654
+
655
+ if query_length == kv_seq_len:
656
+ query_layer = index_first_axis(
657
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
658
+ )
659
+ cu_seqlens_q = cu_seqlens_k
660
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
661
+ indices_q = indices_k
662
+ elif query_length == 1:
663
+ max_seqlen_in_batch_q = 1
664
+ cu_seqlens_q = torch.arange(
665
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
666
+ ) # There is a memcpy here, that is very bad.
667
+ indices_q = cu_seqlens_q[:-1]
668
+ query_layer = query_layer.squeeze(1)
669
+ else:
670
+ # The -q_len: slice assumes left padding.
671
+ attention_mask = attention_mask[:, -query_length:]
672
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
673
+
674
+ return (
675
+ query_layer,
676
+ key_layer,
677
+ value_layer,
678
+ indices_q,
679
+ (cu_seqlens_q, cu_seqlens_k),
680
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
681
+ )
682
+
683
+
684
+ # Copied from transformers.models.mixtral.modeling_mixtral.MixtralSdpaAttention with Mixtral->Qwen2Moe
685
+ class Qwen2MoeSdpaAttention(Qwen2MoeAttention):
686
+ """
687
+ Qwen2Moe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
688
+ `Qwen2MoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
689
+ SDPA API.
690
+ """
691
+
692
+ # Adapted from Qwen2MoeAttention.forward
693
+ def forward(
694
+ self,
695
+ hidden_states: torch.Tensor,
696
+ attention_mask: Optional[torch.Tensor] = None,
697
+ position_ids: Optional[torch.LongTensor] = None,
698
+ past_key_value: Optional[Cache] = None,
699
+ output_attentions: bool = False,
700
+ use_cache: bool = False,
701
+ cache_position: Optional[torch.LongTensor] = None,
702
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
703
+ if output_attentions:
704
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
705
+ logger.warning_once(
706
+ "Qwen2MoeModel is using Qwen2MoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
707
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
708
+ )
709
+ return super().forward(
710
+ hidden_states=hidden_states,
711
+ attention_mask=attention_mask,
712
+ position_ids=position_ids,
713
+ past_key_value=past_key_value,
714
+ output_attentions=output_attentions,
715
+ use_cache=use_cache,
716
+ )
717
+
718
+ bsz, q_len, _ = hidden_states.size()
719
+
720
+ query_states = self.q_proj(hidden_states)
721
+ key_states = self.k_proj(hidden_states)
722
+ value_states = self.v_proj(hidden_states)
723
+
724
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
725
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
726
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
727
+
728
+ kv_seq_len = key_states.shape[-2]
729
+ if past_key_value is not None:
730
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
731
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
732
+
733
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
734
+
735
+ if past_key_value is not None:
736
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
737
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
738
+
739
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
740
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
741
+
742
+ causal_mask = attention_mask
743
+ if attention_mask is not None: # no matter the length, we just slice it
744
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
745
+
746
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
747
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
748
+ if query_states.device.type == "cuda" and attention_mask is not None:
749
+ query_states = query_states.contiguous()
750
+ key_states = key_states.contiguous()
751
+ value_states = value_states.contiguous()
752
+
753
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
754
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
755
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
756
+ is_causal = True if causal_mask is None and q_len > 1 else False
757
+
758
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
759
+ query_states,
760
+ key_states,
761
+ value_states,
762
+ attn_mask=causal_mask,
763
+ dropout_p=self.attention_dropout if self.training else 0.0,
764
+ is_causal=is_causal,
765
+ )
766
+
767
+ attn_output = attn_output.transpose(1, 2).contiguous()
768
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
769
+
770
+ attn_output = self.o_proj(attn_output)
771
+
772
+ return attn_output, None, past_key_value
773
+
774
+
775
+ QWEN2MOE_ATTENTION_CLASSES = {
776
+ "eager": Qwen2MoeAttention,
777
+ "flash_attention_2": Qwen2MoeFlashAttention2,
778
+ "sdpa": Qwen2MoeSdpaAttention,
779
+ }
780
+
781
+
782
+ class Qwen2MoeSparseMoeBlock(nn.Module):
783
+ def __init__(self, config):
784
+ super().__init__()
785
+ self.num_experts = config.num_experts
786
+ self.top_k = config.num_experts_per_tok
787
+ self.norm_topk_prob = config.norm_topk_prob
788
+
789
+ # gating
790
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
791
+ self.experts = nn.ModuleList(
792
+ [Qwen2MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
793
+ )
794
+ #share
795
+ self.share_flag=config.share_flag
796
+
797
+ if self.share_flag:
798
+ self.shared_expert = Qwen2MoeMLP(config, intermediate_size=config.shared_expert_intermediate_size)
799
+ self.shared_expert_gate = torch.nn.Linear(config.hidden_size, 1, bias=False)
800
+
801
+ #language-specific
802
+ self.language_gate=config.language_gate
803
+
804
+ def forward(self, hidden_states: torch.Tensor,language_ids:Optional[torch.LongTensor] = None) -> torch.Tensor:
805
+
806
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
807
+ hidden_states = hidden_states.view(-1, hidden_dim)
808
+ if self.language_gate and self.training :
809
+ if language_ids is None:
810
+ raise ValueError('language_ids is not initialized')
811
+ language_ids=language_ids.view(batch_size*sequence_length,-1)
812
+ # router_logits: (batch * sequence_length, n_experts)
813
+ router_logits = self.gate(hidden_states)
814
+
815
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
816
+
817
+ _, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
818
+
819
+ #language specific select one expert
820
+ if self.language_gate and self.training:
821
+ if language_ids is None:
822
+ raise ValueError('language_ids is not initialized')
823
+ assert language_ids.shape[0]==selected_experts.shape[0],f'{language_ids.shape},{selected_experts.shape}'
824
+ language_experts=language_ids.to(selected_experts.dtype)
825
+ mask=torch.sum((language_experts==selected_experts).int(),dim=1,keepdims=True).bool()
826
+ selected_experts[:,-1]=torch.where(mask.squeeze(),selected_experts[:,-1],language_experts.squeeze())
827
+ routing_weights=torch.gather(routing_weights,1,selected_experts)
828
+ else:
829
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
830
+
831
+ if self.norm_topk_prob:
832
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
833
+ # we cast back to the input dtype
834
+ routing_weights = routing_weights.to(hidden_states.dtype)
835
+
836
+ final_hidden_states = torch.zeros(
837
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
838
+ )
839
+
840
+ # One hot encode the selected experts to create an expert mask
841
+ # this will be used to easily index which expert is going to be sollicitated
842
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
843
+
844
+ # Loop over all available experts in the model and perform the computation on each expert
845
+ for expert_idx in range(self.num_experts):
846
+ expert_layer = self.experts[expert_idx]
847
+ idx, top_x = torch.where(expert_mask[expert_idx])
848
+
849
+ # Index the correct hidden states and compute the expert hidden state for
850
+ # the current expert. We need to make sure to multiply the output hidden
851
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
852
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
853
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
854
+
855
+ # However `index_add_` only support torch tensors for indexing so we'll use
856
+ # the `top_x` tensor here.
857
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
858
+
859
+ if self.share_flag:
860
+
861
+ shared_expert_output = self.shared_expert(hidden_states)
862
+ shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_output
863
+
864
+ final_hidden_states = final_hidden_states + shared_expert_output
865
+
866
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
867
+ return final_hidden_states, router_logits
868
+
869
+
870
+ class Qwen2MoeDecoderLayer(nn.Module):
871
+ def __init__(self, config: UpcyclingQwen2MoeConfig, layer_idx: int):
872
+ super().__init__()
873
+ self.hidden_size = config.hidden_size
874
+
875
+ self.self_attn = QWEN2MOE_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
876
+
877
+ if (layer_idx not in config.mlp_only_layers) and (
878
+ config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
879
+ ):
880
+ self.mlp = Qwen2MoeSparseMoeBlock(config)
881
+ else:
882
+ self.mlp = Qwen2MoeMLP(config, intermediate_size=config.intermediate_size)
883
+
884
+ self.input_layernorm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
885
+ self.post_attention_layernorm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
886
+
887
+ def forward(
888
+ self,
889
+ hidden_states: torch.Tensor,
890
+ language_ids:Optional[torch.LongTensor] = None,
891
+ attention_mask: Optional[torch.Tensor] = None,
892
+ position_ids: Optional[torch.LongTensor] = None,
893
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
894
+ output_attentions: Optional[bool] = False,
895
+ output_router_logits: Optional[bool] = False,
896
+ use_cache: Optional[bool] = False,
897
+ cache_position: Optional[torch.LongTensor] = None,
898
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
899
+ """
900
+ Args:
901
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
902
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
903
+ `(batch, sequence_length)` where padding elements are indicated by 0.
904
+ output_attentions (`bool`, *optional*):
905
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
906
+ returned tensors for more detail.
907
+ output_router_logits (`bool`, *optional*):
908
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
909
+ and should not be returned during inference.
910
+ use_cache (`bool`, *optional*):
911
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
912
+ (see `past_key_values`).
913
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
914
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
915
+ Indices depicting the position of the input sequence tokens in the sequence.
916
+ """
917
+
918
+ residual = hidden_states
919
+
920
+ hidden_states = self.input_layernorm(hidden_states)
921
+
922
+ # Self Attention
923
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
924
+ hidden_states=hidden_states,
925
+ attention_mask=attention_mask,
926
+ position_ids=position_ids,
927
+ past_key_value=past_key_value,
928
+ output_attentions=output_attentions,
929
+ use_cache=use_cache,
930
+ cache_position=cache_position,
931
+ )
932
+ hidden_states = residual + hidden_states
933
+
934
+ # Fully Connected
935
+ residual = hidden_states
936
+ hidden_states = self.post_attention_layernorm(hidden_states)
937
+
938
+ hidden_states = self.mlp(hidden_states,language_ids)
939
+ if isinstance(hidden_states, tuple):
940
+ hidden_states, router_logits = hidden_states
941
+ else:
942
+ router_logits = None
943
+
944
+ hidden_states = residual + hidden_states
945
+
946
+ outputs = (hidden_states,)
947
+
948
+ if output_attentions:
949
+ outputs += (self_attn_weights,)
950
+
951
+ if use_cache:
952
+ outputs += (present_key_value,)
953
+
954
+ if output_router_logits:
955
+ outputs += (router_logits,)
956
+
957
+ return outputs
958
+
959
+
960
+ class UpcyclingQwen2MoePreTrainedModel(PreTrainedModel):
961
+ config_class = UpcyclingQwen2MoeConfig
962
+ base_model_prefix = "model"
963
+ supports_gradient_checkpointing = True
964
+ _no_split_modules = ["Qwen2MoeDecoderLayer"]
965
+ _skip_keys_device_placement = "past_key_values"
966
+ _supports_flash_attn_2 = True
967
+ _supports_sdpa = True
968
+ _supports_cache_class = True
969
+
970
+ def _init_weights(self, module):
971
+ std = self.config.initializer_range
972
+ if isinstance(module, nn.Linear):
973
+ module.weight.data.normal_(mean=0.0, std=std)
974
+ if module.bias is not None:
975
+ module.bias.data.zero_()
976
+ elif isinstance(module, nn.Embedding):
977
+ module.weight.data.normal_(mean=0.0, std=std)
978
+ if module.padding_idx is not None:
979
+ module.weight.data[module.padding_idx].zero_()
980
+
981
+ @classmethod
982
+ def from_qwen(cls, pretrained_model_name_or_path, *model_args, **kwargs):
983
+ share_flag=kwargs.pop('share_flag')
984
+ attn_init_change=kwargs.pop('attn_init_change')
985
+ language_gate=kwargs.pop('language_gate')
986
+
987
+ config = cls.config_class.from_pretrained(pretrained_model_name_or_path)
988
+
989
+ config.share_flag=True if isinstance(share_flag,bool) and share_flag else False
990
+ config.attn_init_change=True if isinstance(attn_init_change,bool) and attn_init_change else False
991
+ config.language_gate=True if isinstance(language_gate,bool) and language_gate else False
992
+
993
+ print('share_flag',config.share_flag)
994
+ print('attn_init_change',config.attn_init_change)
995
+ print('language_gate',config.language_gate)
996
+
997
+ config.num_experts_per_tok = config.num_experts_per_tok if not config.share_flag else config.num_experts_per_tok-1
998
+ config.num_experts = config.num_experts if not config.share_flag else config.num_experts-1
999
+
1000
+ base_model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
1001
+ base_cls = type(base_model)
1002
+
1003
+ print(cls.config_class,cls)
1004
+
1005
+ #create auto_map
1006
+ #allows you to use your custom model with the auto-API (but doesn’t share any custom code with other users).
1007
+ cls.config_class.register_for_auto_class()
1008
+ cls.register_for_auto_class('AutoModelForCausalLM')
1009
+
1010
+ # assert base_cls.__name__ == "Qwen2ForCausalLM", f"Invalid convert base model type: {base_cls}"
1011
+
1012
+ model = cls(config)
1013
+ print(f"converting {base_cls.__name__} to {cls.__name__}")
1014
+
1015
+ #MoE architechture
1016
+ model_dict=model.state_dict()
1017
+ base_model_dict = base_model.state_dict()
1018
+
1019
+ #lm_head
1020
+ print('lm_head.weight',model_dict['lm_head.weight'],base_model_dict['lm_head.weight'])
1021
+
1022
+ shared_keys=set(model_dict)&set(base_model_dict)
1023
+ init_keys=[]
1024
+ #attention
1025
+ for k in shared_keys:
1026
+ if k not in init_keys and 'self_attn' in k:
1027
+ init_keys.append(k)
1028
+ if not config.attn_init_change:
1029
+ model_dict[k]=base_model_dict[k]
1030
+
1031
+ if config.attn_init_change:
1032
+ #initilization with upper and lower
1033
+ for layer_id in range(config.num_hidden_layers):
1034
+ if layer_id ==0 or config.num_hidden_layers-1:
1035
+ model_dict[f'model.layers.{layer_id}.self_attn.q_proj.bias']=base_model_dict[f'model.layers.{layer_id}.self_attn.q_proj.bias']
1036
+ model_dict[f'model.layers.{layer_id}.self_attn.q_proj.weight']=base_model_dict[f'model.layers.{layer_id}.self_attn.q_proj.weight']
1037
+ model_dict[f'model.layers.{layer_id}.self_attn.k_proj.bias']=base_model_dict[f'model.layers.{layer_id}.self_attn.k_proj.bias']
1038
+ model_dict[f'model.layers.{layer_id}.self_attn.k_proj.weight']=base_model_dict[f'model.layers.{layer_id}.self_attn.k_proj.weight']
1039
+ model_dict[f'model.layers.{layer_id}.self_attn.v_proj.bias']=base_model_dict[f'model.layers.{layer_id}.self_attn.v_proj.bias']
1040
+ model_dict[f'model.layers.{layer_id}.self_attn.v_proj.weight']=base_model_dict[f'model.layers.{layer_id}.self_attn.v_proj.weight']
1041
+ model_dict[f'model.layers.{layer_id}.self_attn.o_proj.weight']=base_model_dict[f'model.layers.{layer_id}.self_attn.o_proj.weight']
1042
+ else:
1043
+ model_dict[f'model.layers.{layer_id}.self_attn.q_proj.bias']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.q_proj.bias']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.q_proj.bias']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.q_proj.bias'])
1044
+ model_dict[f'model.layers.{layer_id}.self_attn.q_proj.weight']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.q_proj.weight']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.q_proj.weight']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.q_proj.weight'])
1045
+ model_dict[f'model.layers.{layer_id}.self_attn.k_proj.bias']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.k_proj.bias']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.k_proj.bias']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.k_proj.bias'])
1046
+ model_dict[f'model.layers.{layer_id}.self_attn.k_proj.weight']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.k_proj.weight']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.k_proj.weight']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.k_proj.weight'])
1047
+ model_dict[f'model.layers.{layer_id}.self_attn.v_proj.bias']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.v_proj.bias']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.v_proj.bias']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.v_proj.bias'])
1048
+ model_dict[f'model.layers.{layer_id}.self_attn.v_proj.weight']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.v_proj.weight']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.v_proj.weight']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.v_proj.weight'])
1049
+ model_dict[f'model.layers.{layer_id}.self_attn.o_proj.weight']=1/3*(base_model_dict[f'model.layers.{layer_id}.self_attn.o_proj.weight']+base_model_dict[f'model.layers.{layer_id+1}.self_attn.o_proj.weight']+base_model_dict[f'model.layers.{layer_id-1}.self_attn.o_proj.weight'])
1050
+
1051
+ #mlp
1052
+ if config.mlp_only_layers:
1053
+ for layer_id in config.mlp_only_layers:
1054
+ key_mapping=sum([
1055
+ [
1056
+ (f'model.layers.{layer_id}.mlp.down_proj.weight',f'model.layers.{layer_id}.mlp.down_proj.weight'),
1057
+ (f'model.layers.{layer_id}.mlp.gate_proj.weight',f'model.layers.{layer_id}.mlp.gate_proj.weight'),
1058
+ (f'model.layers.{layer_id}.mlp.up_proj.weight',f'model.layers.{layer_id}.mlp.up_proj.weight'),
1059
+ ]]
1060
+ ,[])
1061
+ for model_key,base_model_key in key_mapping:
1062
+ model_dict[model_key]=base_model_dict[base_model_key]
1063
+ init_keys.append(model_key)
1064
+ moe_only_layers=list(set(range(config.num_hidden_layers))-set(config.mlp_only_layers)) if config.mlp_only_layers else config.num_hidden_layers
1065
+ #moe-mlp-expert
1066
+ for layer_id in moe_only_layers:
1067
+ key_mapping=sum([
1068
+ [
1069
+ (f'model.layers.{layer_id}.mlp.experts.{expert_id}.down_proj.weight',f'model.layers.{layer_id}.mlp.down_proj.weight'),
1070
+ (f'model.layers.{layer_id}.mlp.experts.{expert_id}.gate_proj.weight',f'model.layers.{layer_id}.mlp.gate_proj.weight'),
1071
+ (f'model.layers.{layer_id}.mlp.experts.{expert_id}.up_proj.weight',f'model.layers.{layer_id}.mlp.up_proj.weight'),
1072
+ ] for expert_id in range(config.num_experts)]
1073
+ ,[])
1074
+ for model_key,base_model_key in key_mapping:
1075
+ model_dict[model_key]=base_model_dict[base_model_key]
1076
+ init_keys.append(model_key)
1077
+ #model_dict[f'model.layers.{layer_id}.mlp.gate.weight']
1078
+
1079
+ #share expert
1080
+ if config.share_flag:
1081
+ shared_key_mapping=sum([[
1082
+ (f'model.layers.{layer_id}.mlp.shared_expert.down_proj.weight',f'model.layers.{layer_id}.mlp.down_proj.weight'),
1083
+ (f'model.layers.{layer_id}.mlp.shared_expert.gate_proj.weight',f'model.layers.{layer_id}.mlp.gate_proj.weight'),
1084
+ (f'model.layers.{layer_id}.mlp.shared_expert.up_proj.weight',f'model.layers.{layer_id}.mlp.up_proj.weight'),
1085
+ ]for layer_id in range(config.num_hidden_layers)],
1086
+ [])
1087
+ for model_key,base_model_key in shared_key_mapping:
1088
+ model_dict[model_key]=base_model_dict[base_model_key]
1089
+ init_keys.append(model_key)
1090
+ # model_dict[f'model.layers.{layer_id}.mlp.shared_expert_gate.weight']
1091
+
1092
+ #norm
1093
+ for k in shared_keys:
1094
+ if k not in init_keys:
1095
+ #input_layernorm.weight,post_attention_layernorm.weight,norm.weight
1096
+ # embed_token.weight,lm_head.weight
1097
+ model_dict[k]=base_model_dict[k]
1098
+ init_keys.append(k)
1099
+
1100
+ gate_initialized = False
1101
+ shared_gate_initilizaed=False
1102
+ for key in model_dict.keys():
1103
+ if key in init_keys:
1104
+ continue
1105
+ if "mlp.gate.weight" in key:
1106
+ if gate_initialized:
1107
+ continue
1108
+ gate_initialized = True
1109
+ print(f"{cls.__name__} key [{cls.base_model_prefix}.layers.[0-{config.num_hidden_layers-1}].mlp.gate.weight] is not initialized from {base_cls.__name__}. e.g, {key}")
1110
+ continue
1111
+ if 'shared_expert_gate.weight' in key:
1112
+ if shared_gate_initilizaed:
1113
+ continue
1114
+ shared_gate_initilizaed = True
1115
+ print(f"{cls.__name__} key [{cls.base_model_prefix}.layers.[0-{config.num_hidden_layers-1}].mlp.shared_expert_gate.weight] is not initialized from {base_cls.__name__}. e.g, {key}")
1116
+ continue
1117
+
1118
+ raise NotImplementedError(f"{cls.__name__} key [{key}] is not correctly initilized from {base_cls.__name__}.")
1119
+
1120
+ model.load_state_dict(model_dict)
1121
+ print(f"Done converted, alreadly check all parameters of {cls.__name__} are initialized from {base_cls.__name__}.")
1122
+
1123
+ del base_model
1124
+ return model
1125
+
1126
+ @classmethod
1127
+ def from_btx(cls, pretrained_model_name_or_path, *model_args, **kwargs):
1128
+ share_flag=kwargs.pop('share_flag')
1129
+ attn_init_change=kwargs.pop('attn_init_change')
1130
+ language_gate=kwargs.pop('language_gate')
1131
+
1132
+ config = cls.config_class.from_pretrained(pretrained_model_name_or_path)
1133
+
1134
+ config.share_flag=True if isinstance(share_flag,bool) and share_flag else False
1135
+ config.attn_init_change=True if isinstance(attn_init_change,bool) and attn_init_change else False
1136
+ config.language_gate=True if isinstance(language_gate,bool) and language_gate else False
1137
+
1138
+ print('share_flag',config.share_flag)
1139
+ print('attn_init_change',config.attn_init_change)
1140
+ print('language_gate',config.language_gate)
1141
+
1142
+ config.num_experts_per_tok = config.num_experts_per_tok if not config.share_flag else config.num_experts_per_tok-1
1143
+ config.num_experts = config.num_experts if not config.share_flag else config.num_experts-1
1144
+
1145
+ base_model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
1146
+ base_cls = type(base_model)
1147
+
1148
+ print(cls.config_class,cls)
1149
+
1150
+ #create auto_map
1151
+ #allows you to use your custom model with the auto-API (but doesn’t share any custom code with other users).
1152
+ cls.config_class.register_for_auto_class()
1153
+ cls.register_for_auto_class('AutoModelForCausalLM')
1154
+
1155
+ # assert base_cls.__name__ == "Qwen2ForCausalLM", f"Invalid convert base model type: {base_cls}"
1156
+
1157
+ model = cls(config)
1158
+ print(f"converting {base_cls.__name__} to {cls.__name__}")
1159
+
1160
+ #MoE architechture
1161
+ model_dict=model.state_dict()
1162
+ base_model_dict = base_model.state_dict()
1163
+
1164
+ #lm_head
1165
+ print('lm_head.weight',model_dict['lm_head.weight'],base_model_dict['lm_head.weight'])
1166
+
1167
+ shared_keys=set(model_dict)&set(base_model_dict)
1168
+ init_keys=[]
1169
+ #attention
1170
+ for k in shared_keys:
1171
+ init_keys.append(k)
1172
+ model_dict[k]=base_model_dict[k]
1173
+
1174
+ gate_initialized = False
1175
+ shared_gate_initilizaed=False
1176
+ for key in model_dict.keys():
1177
+ if key in init_keys:
1178
+ continue
1179
+ if "mlp.gate.weight" in key:
1180
+ if gate_initialized:
1181
+ continue
1182
+ gate_initialized = True
1183
+ print(f"{cls.__name__} key [{cls.base_model_prefix}.layers.[0-{config.num_hidden_layers-1}].mlp.gate.weight] is not initialized from {base_cls.__name__}. e.g, {key}")
1184
+ continue
1185
+ if 'shared_expert_gate.weight' in key:
1186
+ if shared_gate_initilizaed:
1187
+ continue
1188
+ shared_gate_initilizaed = True
1189
+ print(f"{cls.__name__} key [{cls.base_model_prefix}.layers.[0-{config.num_hidden_layers-1}].mlp.shared_expert_gate.weight] is not initialized from {base_cls.__name__}. e.g, {key}")
1190
+ continue
1191
+
1192
+ raise NotImplementedError(f"{cls.__name__} key [{key}] is not correctly initilized from {base_cls.__name__}.")
1193
+
1194
+ model.load_state_dict(model_dict)
1195
+ print(f"Done converted, alreadly check all parameters of {cls.__name__} are initialized from {base_cls.__name__}.")
1196
+
1197
+ del base_model
1198
+ return model
1199
+
1200
+ class UpcyclingQwen2MoeModel(UpcyclingQwen2MoePreTrainedModel):
1201
+ """
1202
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2MoeDecoderLayer`]
1203
+ Args:
1204
+ config: Qwen2MoeConfig
1205
+ """
1206
+
1207
+ def __init__(self, config: UpcyclingQwen2MoeConfig):
1208
+ super().__init__(config)
1209
+ self.padding_idx = config.pad_token_id
1210
+ self.vocab_size = config.vocab_size
1211
+
1212
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1213
+ self.layers = nn.ModuleList(
1214
+ [Qwen2MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1215
+ )
1216
+ self._attn_implementation = config._attn_implementation
1217
+ self.norm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1218
+
1219
+ self.gradient_checkpointing = False
1220
+ # Initialize weights and apply final processing
1221
+ self.post_init()
1222
+
1223
+ def get_input_embeddings(self):
1224
+ return self.embed_tokens
1225
+
1226
+ def set_input_embeddings(self, value):
1227
+ self.embed_tokens = value
1228
+
1229
+ def forward(
1230
+ self,
1231
+ input_ids: torch.LongTensor = None,
1232
+ language_ids :Optional[torch.LongTensor]= None,
1233
+ attention_mask: Optional[torch.Tensor] = None,
1234
+ position_ids: Optional[torch.LongTensor] = None,
1235
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1236
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1237
+ use_cache: Optional[bool] = None,
1238
+ output_attentions: Optional[bool] = None,
1239
+ output_hidden_states: Optional[bool] = None,
1240
+ output_router_logits: Optional[bool] = None,
1241
+ return_dict: Optional[bool] = None,
1242
+ cache_position: Optional[torch.LongTensor] = None,
1243
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1244
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1245
+ output_router_logits = (
1246
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1247
+ )
1248
+ output_hidden_states = (
1249
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1250
+ )
1251
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1252
+
1253
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1254
+
1255
+ if (input_ids is None) ^ (inputs_embeds is not None):
1256
+ raise ValueError(
1257
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
1258
+ )
1259
+
1260
+ if self.gradient_checkpointing and self.training:
1261
+ if use_cache:
1262
+ logger.warning_once(
1263
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1264
+ )
1265
+ use_cache = False
1266
+
1267
+ use_legacy_cache = False
1268
+ if use_cache and not isinstance(past_key_values, Cache):
1269
+ use_legacy_cache = True
1270
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1271
+ logger.warning_once(
1272
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1273
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
1274
+ )
1275
+
1276
+ if inputs_embeds is None:
1277
+ inputs_embeds = self.embed_tokens(input_ids)
1278
+
1279
+ if cache_position is None:
1280
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1281
+ cache_position = torch.arange(
1282
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1283
+ )
1284
+ if position_ids is None:
1285
+ position_ids = cache_position.unsqueeze(0)
1286
+
1287
+ causal_mask = self._update_causal_mask(
1288
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1289
+ )
1290
+
1291
+ hidden_states = inputs_embeds
1292
+
1293
+ # decoder layers
1294
+ all_hidden_states = () if output_hidden_states else None
1295
+ all_self_attns = () if output_attentions else None
1296
+ all_router_logits = () if output_router_logits else None
1297
+ next_decoder_cache = None
1298
+
1299
+ for decoder_layer in self.layers:
1300
+ if output_hidden_states:
1301
+ all_hidden_states += (hidden_states,)
1302
+
1303
+ if self.gradient_checkpointing and self.training:
1304
+ layer_outputs = self._gradient_checkpointing_func(
1305
+ decoder_layer.__call__,
1306
+ hidden_states,
1307
+ language_ids,
1308
+ causal_mask,
1309
+ position_ids,
1310
+ past_key_values,
1311
+ output_attentions,
1312
+ output_router_logits,
1313
+ use_cache,
1314
+ cache_position,
1315
+ )
1316
+ else:
1317
+ layer_outputs = decoder_layer(
1318
+ hidden_states,
1319
+ language_ids,
1320
+ attention_mask=causal_mask,
1321
+ position_ids=position_ids,
1322
+ past_key_value=past_key_values,
1323
+ output_attentions=output_attentions,
1324
+ output_router_logits=output_router_logits,
1325
+ use_cache=use_cache,
1326
+ cache_position=cache_position,
1327
+ )
1328
+
1329
+ hidden_states = layer_outputs[0]
1330
+
1331
+ if use_cache:
1332
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1333
+
1334
+ if output_attentions:
1335
+ all_self_attns += (layer_outputs[1],)
1336
+
1337
+ if output_router_logits and layer_outputs[-1] is not None:
1338
+ all_router_logits += (layer_outputs[-1],)
1339
+
1340
+ hidden_states = self.norm(hidden_states)
1341
+
1342
+ # add hidden states from the last decoder layer
1343
+ if output_hidden_states:
1344
+ all_hidden_states += (hidden_states,)
1345
+
1346
+ next_cache = None
1347
+ if use_cache:
1348
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1349
+
1350
+ if not return_dict:
1351
+ return tuple(
1352
+ v
1353
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1354
+ if v is not None
1355
+ )
1356
+ return MoeModelOutputWithPast(
1357
+ last_hidden_state=hidden_states,
1358
+ past_key_values=next_cache,
1359
+ hidden_states=all_hidden_states,
1360
+ attentions=all_self_attns,
1361
+ router_logits=all_router_logits,
1362
+ )
1363
+
1364
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1365
+ def _update_causal_mask(
1366
+ self,
1367
+ attention_mask: torch.Tensor,
1368
+ input_tensor: torch.Tensor,
1369
+ cache_position: torch.Tensor,
1370
+ past_key_values: Cache,
1371
+ output_attentions: bool,
1372
+ ):
1373
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1374
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1375
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1376
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1377
+
1378
+ if self.config._attn_implementation == "flash_attention_2":
1379
+ if attention_mask is not None and 0.0 in attention_mask:
1380
+ return attention_mask
1381
+ return None
1382
+
1383
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1384
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1385
+ # to infer the attention mask.
1386
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1387
+ using_static_cache = isinstance(past_key_values, StaticCache)
1388
+
1389
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1390
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1391
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1392
+ attention_mask,
1393
+ inputs_embeds=input_tensor,
1394
+ past_key_values_length=past_seen_tokens,
1395
+ is_training=self.training,
1396
+ ):
1397
+ return None
1398
+
1399
+ dtype, device = input_tensor.dtype, input_tensor.device
1400
+ min_dtype = torch.finfo(dtype).min
1401
+ sequence_length = input_tensor.shape[1]
1402
+ if using_static_cache:
1403
+ target_length = past_key_values.get_max_length()
1404
+ else:
1405
+ target_length = (
1406
+ attention_mask.shape[-1]
1407
+ if isinstance(attention_mask, torch.Tensor)
1408
+ else past_seen_tokens + sequence_length + 1
1409
+ )
1410
+
1411
+ if attention_mask is not None and attention_mask.dim() == 4:
1412
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1413
+ if attention_mask.max() != 0:
1414
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1415
+ causal_mask = attention_mask
1416
+ else:
1417
+ causal_mask = torch.full(
1418
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1419
+ )
1420
+ if sequence_length != 1:
1421
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1422
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1423
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1424
+ if attention_mask is not None:
1425
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1426
+ mask_length = attention_mask.shape[-1]
1427
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1428
+ padding_mask = padding_mask == 0
1429
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1430
+ padding_mask, min_dtype
1431
+ )
1432
+ if (
1433
+ self.config._attn_implementation == "sdpa"
1434
+ and attention_mask is not None
1435
+ and attention_mask.device.type == "cuda"
1436
+ and not output_attentions
1437
+ ):
1438
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1439
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1440
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1441
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1442
+
1443
+ return causal_mask
1444
+
1445
+
1446
+ class UpcyclingQwen2MoeForCausalLM(UpcyclingQwen2MoePreTrainedModel):
1447
+ _tied_weights_keys = ["lm_head.weight"]
1448
+
1449
+ def __init__(self, config):
1450
+ super().__init__(config)
1451
+ self.model = UpcyclingQwen2MoeModel(config)
1452
+ self.vocab_size = config.vocab_size
1453
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1454
+
1455
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1456
+ self.num_experts = config.num_experts
1457
+ self.num_experts_per_tok = config.num_experts_per_tok
1458
+
1459
+ self.language_gate=config.language_gate
1460
+ # Initialize weights and apply final processing
1461
+ self.post_init()
1462
+
1463
+ def get_input_embeddings(self):
1464
+ return self.model.embed_tokens
1465
+
1466
+ def set_input_embeddings(self, value):
1467
+ self.model.embed_tokens = value
1468
+
1469
+ def get_output_embeddings(self):
1470
+ return self.lm_head
1471
+
1472
+ def set_output_embeddings(self, new_embeddings):
1473
+ self.lm_head = new_embeddings
1474
+
1475
+ def set_decoder(self, decoder):
1476
+ self.model = decoder
1477
+
1478
+ def get_decoder(self):
1479
+ return self.model
1480
+
1481
+ # @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1482
+ def forward(
1483
+ self,
1484
+ input_ids: torch.LongTensor = None,
1485
+ language_ids: Optional[torch.LongTensor] = None,
1486
+ attention_mask: Optional[torch.Tensor] = None,
1487
+ position_ids: Optional[torch.LongTensor] = None,
1488
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1489
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1490
+ labels: Optional[torch.LongTensor] = None,
1491
+ use_cache: Optional[bool] = None,
1492
+ output_attentions: Optional[bool] = None,
1493
+ output_hidden_states: Optional[bool] = None,
1494
+ output_router_logits: Optional[bool] = None,
1495
+ return_dict: Optional[bool] = None,
1496
+ cache_position: Optional[torch.LongTensor] = None,
1497
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1498
+
1499
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1500
+ output_router_logits = (
1501
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1502
+ )
1503
+ output_hidden_states = (
1504
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1505
+ )
1506
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1507
+
1508
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1509
+ outputs = self.model(
1510
+ input_ids=input_ids,
1511
+ language_ids=language_ids,
1512
+ attention_mask=attention_mask,
1513
+ position_ids=position_ids,
1514
+ past_key_values=past_key_values,
1515
+ inputs_embeds=inputs_embeds,
1516
+ use_cache=use_cache,
1517
+ output_attentions=output_attentions,
1518
+ output_hidden_states=output_hidden_states,
1519
+ output_router_logits=output_router_logits,
1520
+ return_dict=return_dict,
1521
+ cache_position=cache_position,
1522
+ )
1523
+
1524
+ hidden_states = outputs[0]
1525
+ logits = self.lm_head(hidden_states)
1526
+ logits = logits.float()
1527
+
1528
+ loss = None
1529
+ if labels is not None:
1530
+ # Shift so that tokens < n predict n
1531
+ shift_logits = logits[..., :-1, :].contiguous()
1532
+ shift_labels = labels[..., 1:].contiguous()
1533
+ # Flatten the tokens
1534
+ loss_fct = CrossEntropyLoss()
1535
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1536
+ shift_labels = shift_labels.view(-1)
1537
+ # Enable model parallelism
1538
+ shift_labels = shift_labels.to(shift_logits.device)
1539
+ loss = loss_fct(shift_logits, shift_labels)
1540
+
1541
+ aux_loss = None
1542
+ if output_router_logits:
1543
+ aux_loss = load_balancing_loss_func(
1544
+ outputs.router_logits if return_dict else outputs[-1],
1545
+ self.num_experts,
1546
+ self.num_experts_per_tok,
1547
+ attention_mask,
1548
+ )
1549
+ if labels is not None:
1550
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1551
+
1552
+ if not return_dict:
1553
+ output = (logits,) + outputs[1:]
1554
+ if output_router_logits:
1555
+ output = (aux_loss,) + output
1556
+ return (loss,) + output if loss is not None else output
1557
+
1558
+ return MoeCausalLMOutputWithPast(
1559
+ loss=loss,
1560
+ aux_loss=aux_loss,
1561
+ logits=logits,
1562
+ past_key_values=outputs.past_key_values,
1563
+ hidden_states=outputs.hidden_states,
1564
+ attentions=outputs.attentions,
1565
+ router_logits=outputs.router_logits,
1566
+ )
1567
+
1568
+ def prepare_inputs_for_generation(
1569
+ self,
1570
+ input_ids,
1571
+ past_key_values=None,
1572
+ attention_mask=None,
1573
+ inputs_embeds=None,
1574
+ cache_position=None,
1575
+ use_cache=True,
1576
+ **kwargs,
1577
+ ):
1578
+ past_length = 0
1579
+
1580
+ # ##### by own
1581
+ if past_key_values is not None:
1582
+ if isinstance(past_key_values,Cache):
1583
+ # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1584
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1585
+ max_cache_length = (
1586
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1587
+ if past_key_values.get_max_length() is not None
1588
+ else None
1589
+ )
1590
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1591
+ else:
1592
+ cache_length=past_length=past_key_values[0][0].shape[2]
1593
+ max_cache_length=None
1594
+ # # #####
1595
+ # Omit tokens covered by past_key_values
1596
+ # if past_key_values is not None:
1597
+ # # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1598
+ # past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1599
+ # max_cache_length = (
1600
+ # torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1601
+ # if past_key_values.get_max_length() is not None
1602
+ # else None
1603
+ # )
1604
+ # cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1605
+
1606
+ # Keep only the unprocessed tokens:
1607
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1608
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1609
+ # input)
1610
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1611
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1612
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1613
+ # input_ids based on the past_length.
1614
+ elif past_length < input_ids.shape[1]:
1615
+ input_ids = input_ids[:, past_length:]
1616
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1617
+
1618
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1619
+ if (
1620
+ max_cache_length is not None
1621
+ and attention_mask is not None
1622
+ and cache_length + input_ids.shape[1] > max_cache_length
1623
+ ):
1624
+ attention_mask = attention_mask[:, -max_cache_length:]
1625
+
1626
+ position_ids = kwargs.get("position_ids", None)
1627
+ if attention_mask is not None and position_ids is None:
1628
+ # create position_ids on the fly for batch generation
1629
+ position_ids = attention_mask.long().cumsum(-1) - 1
1630
+ position_ids.masked_fill_(attention_mask == 0, 1)
1631
+ if past_key_values:
1632
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1633
+
1634
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1635
+ if inputs_embeds is not None and past_length == 0:
1636
+ model_inputs = {"inputs_embeds": inputs_embeds}
1637
+ else:
1638
+ model_inputs = {"input_ids": input_ids}
1639
+
1640
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1641
+ if cache_position is None:
1642
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1643
+ elif use_cache:
1644
+ cache_position = cache_position[-input_length:]
1645
+
1646
+ model_inputs.update(
1647
+ {
1648
+ "position_ids": position_ids,
1649
+ "past_key_values": past_key_values,
1650
+ "use_cache": use_cache,
1651
+ "attention_mask": attention_mask,
1652
+ "cache_position": cache_position,
1653
+ }
1654
+ )
1655
+ return model_inputs
1656
+
1657
+ @staticmethod
1658
+ def _reorder_cache(past_key_values, beam_idx):
1659
+ reordered_past = ()
1660
+ for layer_past in past_key_values:
1661
+ reordered_past += (
1662
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1663
+ )
1664
+ return reordered_past