TomLucidor commited on
Commit
d49e4a7
·
verified ·
1 Parent(s): 3cbdaa7

Upload modeling_bailing_moe_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_bailing_moe_v2.py +1904 -0
modeling_bailing_moe_v2.py ADDED
@@ -0,0 +1,1904 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Antgroup 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 BailingMoE model."""
21
+
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.cache_utils import Cache, DynamicCache
32
+ from transformers.modeling_attn_mask_utils import (
33
+ AttentionMaskConverter,
34
+ _prepare_4d_attention_mask,
35
+ _prepare_4d_causal_attention_mask,
36
+ _prepare_4d_causal_attention_mask_for_sdpa,
37
+ )
38
+ from transformers.modeling_outputs import MoeModelOutputWithPast
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_bailing_moe_v2 import BailingMoeV2Config
52
+ from transformers.generation.utils import GenerationMixin
53
+ from dataclasses import dataclass
54
+ from transformers.utils import ModelOutput
55
+ from einops import rearrange
56
+ from functools import lru_cache
57
+
58
+ if is_flash_attn_2_available():
59
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
60
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
61
+
62
+
63
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
64
+ # It means that the function will not be traced through and simply appear as a node in the graph.
65
+ if is_torch_fx_available():
66
+ if not is_torch_greater_or_equal_than_1_13:
67
+ import torch.fx
68
+
69
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
70
+
71
+
72
+ logger = logging.get_logger(__name__)
73
+
74
+ _CONFIG_FOR_DOC = "BailingMoeV2Config"
75
+
76
+
77
+ def nonzero(x):
78
+ return x.nonzero(as_tuple=True)
79
+
80
+
81
+ @lru_cache(maxsize=16)
82
+ def calc_chunks(cu_seqlen, moba_chunk_size):
83
+ """calc chunks that needs moba attention"""
84
+
85
+ # batch_sizes[batch_idx] = batch size ( seqlen ) of batch idx
86
+ batch_sizes = cu_seqlen[1:] - cu_seqlen[:-1]
87
+ # batch_num_chunk[batch_idx] = how many chunk in batch idx
88
+ batch_num_chunk = (batch_sizes + (moba_chunk_size - 1)) // moba_chunk_size
89
+ # cu_num_chunk[batch_idx] = first chunk id of this batch
90
+ cu_num_chunk = torch.ones(
91
+ batch_num_chunk.numel() + 1,
92
+ device=cu_seqlen.device,
93
+ dtype=batch_num_chunk.dtype,
94
+ )
95
+ cu_num_chunk[1:] = batch_num_chunk.cumsum(dim=0)
96
+ # total chunk ( for all batch )
97
+ num_chunk = cu_num_chunk[-1]
98
+ # chunk_sizes[chunk_idx] = chunk_size of chunk idx
99
+ chunk_sizes = torch.full((num_chunk + 1,), moba_chunk_size, dtype=torch.int32, device=cu_seqlen.device)
100
+ chunk_sizes[0] = 0 # for calc cu chunk
101
+ batch_last_chunk_size = batch_sizes - (batch_num_chunk - 1) * moba_chunk_size
102
+ chunk_sizes[cu_num_chunk[1:]] = batch_last_chunk_size
103
+ # cu_chunk[chunk_idx] = the start chunk offset of chunk idx
104
+ cu_chunk = chunk_sizes.cumsum(dim=-1, dtype=torch.int32)
105
+ # chunk_to_batch[chunk_idx] = batch idx of the chunk idx
106
+ chunk_to_batch = torch.zeros((num_chunk,), dtype=torch.int32, device=cu_seqlen.device)
107
+ chunk_to_batch[cu_num_chunk[1:-1]] = 1
108
+ chunk_to_batch = chunk_to_batch.cumsum(dim=0, dtype=torch.int32)
109
+
110
+ """ filter chunks that need moba attn """
111
+
112
+ # filter chunks ( remove last chunk of each batch )
113
+ # filtered_chunk_indices: chunk index list that excludes the last chunk of each batch
114
+ chunk_to_remove = cu_num_chunk[1:] - 1
115
+ chunk_to_remain = torch.ones((num_chunk,), dtype=torch.bool, device=cu_seqlen.device)
116
+ chunk_to_remain[chunk_to_remove] = False
117
+ filtered_chunk_indices = chunk_to_remain.nonzero(as_tuple=True)[0]
118
+ num_filtered_chunk = len(filtered_chunk_indices)
119
+
120
+ return (
121
+ cu_chunk,
122
+ filtered_chunk_indices,
123
+ num_filtered_chunk,
124
+ chunk_to_batch,
125
+ )
126
+
127
+
128
+ def _prepare_for_moba(
129
+ q: torch.Tensor,
130
+ k: torch.Tensor,
131
+ v: torch.Tensor,
132
+ cu_seqlens: torch.Tensor,
133
+ max_seqlen: int,
134
+ moba_chunk_size: int,
135
+ moba_topk: int,
136
+ is_decode: bool = False
137
+ ) -> torch.Tensor:
138
+ """An efficient version of moba implementation with triton kernels and flash-attn, the core logic:
139
+ 1. Calculate the chunks and the number of chunks, n = floor(data_size / chunk_size)
140
+ - tokens in the tail chunk are reserved for self attn
141
+ - tokens in other chunks will be processed in later steps
142
+ 2. K in each chunk will calculate mean value as the representative k, and Q will attend to these representative
143
+ k to get the gate logit, which will be used to select topk chunks
144
+ 3. Select the topk chunks and get the dense q for each kv chunk pair and do the varlen attention
145
+ 4. Combine the varlen attn and self attn results via online softmax to get the final result
146
+
147
+ Args:
148
+ q (torch.Tensor): [seqlen, head, head_dim]
149
+ k (torch.Tensor): [seqlen, head, head_dim]
150
+ v (torch.Tensor): [seqlen, head, head_dim]
151
+ cu_seqlens (torch.Tensor): the cumulative sequence length tensor, same definition in flash attn
152
+ max_seqlen (int): the max sequence length of the batch, same definition in flash attn
153
+
154
+ Returns:
155
+ attn_output (torch.Tensor): [seqlen, head, head_dim]
156
+ """
157
+
158
+ kv = torch.stack((k, v), dim=1)
159
+
160
+ """ some basic variables """
161
+ # qkv shape = [ S, H, D ]
162
+ seqlen_q, num_head, head_dim = q.shape
163
+ seqlen_kv, num_head_kv, _ = k.shape
164
+ replicas = num_head // num_head_kv
165
+
166
+ """ prepare chunk meta """
167
+ (
168
+ cu_chunk,
169
+ filtered_chunk_indices,
170
+ num_filtered_chunk,
171
+ chunk_to_batch,
172
+ ) = calc_chunks(cu_seqlens, moba_chunk_size)
173
+ # cu_chunk: [num_chunks + 1], the start position of each chunk
174
+ # filtered_chunk_indices: [num_filtered_chunk], the indices of filtered chunk (filter out last in each batch)
175
+ # chunk_to_batch: [total_num_chunks], chunk_to_batch[i] stands for the batch index of i-th chunk
176
+
177
+ self_attn_cu_seqlen = cu_chunk
178
+ # filtered_kv is a dense matrix that only contains filtered chunk of kv
179
+ filtered_kv_indices = torch.arange(0, moba_chunk_size, dtype=torch.int64, device=q.device)[None, :].repeat(
180
+ num_filtered_chunk, 1
181
+ )
182
+ filtered_kv_indices += cu_chunk[filtered_chunk_indices][:, None]
183
+ index_expanded = filtered_kv_indices.view(-1).view(-1, 1, 1, 1).expand(-1, 2, kv.shape[-2], kv.shape[-1])
184
+ filtered_kv = torch.gather(kv, 0, index_expanded)
185
+
186
+ """ calc key_gate_weight and gate """
187
+
188
+ # key_gate_weight [ F_N_CHUNK, HEAD, HEAD_DIM ]
189
+ key_gate_weight = (
190
+ filtered_kv[:, 0].view(num_filtered_chunk, moba_chunk_size, num_head_kv, head_dim).mean(dim=1)
191
+ )
192
+
193
+ # we will adjust selective topk to moba_topk - 1, as the last chunk is always chosen
194
+ moba_topk = min(moba_topk - 1, num_filtered_chunk)
195
+ need_moba_attn = moba_topk > 0
196
+ # corner case: if no moba attn needed, just return self attn
197
+ if not need_moba_attn:
198
+ return None, None, None, None, None, None, None
199
+
200
+ query_gate_weight = q.view(seqlen_q, num_head_kv, replicas, head_dim).mean(dim=2).float()
201
+ key_gate_weight = key_gate_weight.type(torch.float32) # float logit for better gate logit perception
202
+ gate = torch.einsum("nhd,shd->nhs", key_gate_weight, query_gate_weight) # gate [ F_N_CHUNK, HEAD, SEQ ]
203
+ key_gate_weight = key_gate_weight.type_as(k)
204
+ q = q.type_as(k)
205
+
206
+ # pose process gate, masking unchosen batch and apply causal mask to current chunk
207
+ gate_seq_idx = torch.arange(0, seqlen_q, device=q.device, dtype=torch.int32)[None, :].repeat(num_filtered_chunk, 1)
208
+ chunk_end = cu_chunk[filtered_chunk_indices + 1]
209
+ batch_end = cu_seqlens[chunk_to_batch[filtered_chunk_indices] + 1]
210
+ gate_chunk_end_mask = gate_seq_idx < chunk_end[:, None]
211
+ gate_batch_end_mask = gate_seq_idx >= batch_end[:, None]
212
+ gate_inf_mask = gate_chunk_end_mask | gate_batch_end_mask
213
+ gate.masked_fill_(gate_inf_mask.unsqueeze(1), -float("inf"))
214
+
215
+ """ find moba q that needs moba attn """
216
+ # find topk chunks
217
+ # gate_mask [ N_CHUNK, HEAD, SEQ ], true indicates that needs attention
218
+ _, gate_top_k_idx = torch.topk(gate, k=moba_topk, dim=0, largest=True, sorted=False)
219
+ # apply causal mask
220
+ gate_mask = torch.logical_not(gate.isinf())
221
+ # select topk chunks
222
+ gate_idx_mask = torch.zeros(gate_mask.shape, dtype=torch.bool, device=q.device)
223
+ gate_idx_mask = gate_idx_mask.scatter_(dim=0, index=gate_top_k_idx, value=True)
224
+ gate_mask = torch.logical_and(gate_mask, gate_idx_mask)
225
+
226
+ moba_q_indices = nonzero(gate_mask.reshape(gate_mask.shape[0], -1))[-1] # .nonzero(as_tuple=True)[
227
+ # -1
228
+ # ] # [ HS indices ] * N
229
+ # moba_seqlen_q indicates that how many q chunks are selected for each kv chunk - head
230
+ moba_seqlen_q = gate_mask.sum(dim=-1).flatten()
231
+ # select all q that needs moba attn based on the moba_q_indices
232
+
233
+ # GQA
234
+ # moba_q_pre = q.transpose(0, 1).reshape(-1, q.size(-1))
235
+ moba_q = q.view(seqlen_q, num_head_kv, replicas, head_dim)
236
+ moba_q_pre = moba_q.transpose(0, 1).reshape(-1, *moba_q.shape[2:])
237
+
238
+ # GQA
239
+ index_expanded = moba_q_indices.view(-1, 1, 1).expand(-1, replicas, moba_q_pre.size(-1))
240
+
241
+ moba_q = torch.gather(moba_q_pre, 0, index_expanded)
242
+
243
+ # moba_q_sh_indices represents the position in the origin q tensor of each q token inside moba_q
244
+ # GQA
245
+ moba_q_sh_indices = moba_q_indices % seqlen_q * num_head_kv + moba_q_indices // seqlen_q
246
+
247
+ """ prepare moba kv """
248
+ # Since moba_q is organized as HS * N, we need to reorganize kv to adapt to q
249
+
250
+ # cut off zero experts
251
+ q_zero_mask = moba_seqlen_q == 0
252
+ valid_expert_mask = ~q_zero_mask
253
+ zero_expert_count = q_zero_mask.sum()
254
+ # only keep the kv that has q select > 0
255
+ if zero_expert_count > 0:
256
+ moba_seqlen_q = moba_seqlen_q[valid_expert_mask]
257
+ # moba cu_seqlen for flash attn
258
+ moba_cu_seqlen_q = torch.cat(
259
+ (
260
+ torch.tensor([0], device=q.device, dtype=moba_seqlen_q.dtype),
261
+ moba_seqlen_q.cumsum(dim=0),
262
+ ),
263
+ dim=0,
264
+ ).to(torch.int32)
265
+ moba_kv = filtered_kv.permute(2, 0, 1, 3)
266
+ moba_kv = moba_kv.split(moba_chunk_size, dim=1)
267
+ moba_kv = torch.cat(moba_kv, dim=0)
268
+
269
+ if zero_expert_count > 0:
270
+ assert valid_expert_mask.sum() == moba_kv.shape[0] - zero_expert_count
271
+ moba_kv = moba_kv[valid_expert_mask] # cut off zero Q expert from kv , or the grad may be nan
272
+ moba_kv = moba_kv.flatten(start_dim=0, end_dim=1).unsqueeze(2)
273
+ moba_cu_seqlen_kv = (
274
+ torch.arange(
275
+ 0,
276
+ num_filtered_chunk * num_head_kv + 1 - zero_expert_count,
277
+ dtype=torch.int32,
278
+ device=q.device,
279
+ )
280
+ * moba_chunk_size
281
+ )
282
+
283
+ return self_attn_cu_seqlen, moba_q, moba_kv, moba_cu_seqlen_q, moba_cu_seqlen_kv, moba_chunk_size, moba_q_sh_indices
284
+
285
+
286
+ def _moba_attn_varlen_prefill(
287
+ q: torch.Tensor,
288
+ k: torch.Tensor,
289
+ v: torch.Tensor,
290
+ cu_seqlens: torch.Tensor,
291
+ max_seqlen: int,
292
+ moba_chunk_size: int,
293
+ moba_topk: int,
294
+ ) -> torch.Tensor:
295
+ """An efficient version of moba implementation with triton kernels and flash-attn, the core logic:
296
+ 1. Calculate the chunks and the number of chunks, n = floor(data_size / chunk_size)
297
+ - tokens in the tail chunk are reserved for self attn
298
+ - tokens in other chunks will be processed in later steps
299
+ 2. K in each chunk will calculate mean value as the representative k, and Q will attend to these representative
300
+ k to get the gate logit, which will be used to select topk chunks
301
+ 3. Select the topk chunks and get the dense q for each kv chunk pair and do the varlen attention
302
+ 4. Combine the varlen attn and self attn results via online softmax to get the final result
303
+
304
+ Args:
305
+ q (torch.Tensor): [seqlen, head, head_dim]
306
+ k (torch.Tensor): [seqlen, head, head_dim]
307
+ v (torch.Tensor): [seqlen, head, head_dim]
308
+ cu_seqlens (torch.Tensor): the cumulative sequence length tensor, same definition in flash attn
309
+ max_seqlen (int): the max sequence length of the batch, same definition in flash attn
310
+
311
+ Returns:
312
+ attn_output (torch.Tensor): [seqlen, head, head_dim]
313
+ """
314
+
315
+ self_attn_cu_seqlen, moba_q, moba_kv, moba_cu_seqlen_q, moba_cu_seqlen_kv, moba_chunk_size, moba_q_sh_indices = (
316
+ _prepare_for_moba(q, k, v, cu_seqlens, max_seqlen, moba_chunk_size, moba_topk)
317
+ )
318
+
319
+ if moba_q is None:
320
+ return flash_attn_varlen_func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, causal=True)
321
+ softmax_scale = q.shape[-1] ** (-0.5)
322
+
323
+ # self attn
324
+ self_attn_out_sh, self_attn_lse_hs, *rest = flash_attn_varlen_func(
325
+ q=q,
326
+ k=k,
327
+ v=v,
328
+ cu_seqlens_q=self_attn_cu_seqlen,
329
+ cu_seqlens_k=self_attn_cu_seqlen,
330
+ max_seqlen_q=max_seqlen,
331
+ max_seqlen_k=max_seqlen,
332
+ softmax_scale=softmax_scale,
333
+ causal=True,
334
+ return_attn_probs=True
335
+ )
336
+
337
+ # moba attn
338
+ moba_attn_out, moba_attn_lse_hs, *rest = flash_attn_varlen_func(
339
+ q=moba_q,
340
+ k=moba_kv[:, 0],
341
+ v=moba_kv[:, 1],
342
+ cu_seqlens_q=moba_cu_seqlen_q,
343
+ cu_seqlens_k=moba_cu_seqlen_kv,
344
+ max_seqlen_q=max_seqlen,
345
+ max_seqlen_k=moba_chunk_size,
346
+ softmax_scale=softmax_scale,
347
+ causal=False,
348
+ return_attn_probs=True
349
+ )
350
+
351
+ kv_replicas = q.shape[1] // k.shape[1]
352
+ h, s = self_attn_lse_hs.shape
353
+
354
+ # convert lse shape hs -> sh ( follow the legacy mix attn logic )
355
+ self_attn_lse_sh = self_attn_lse_hs.t().view(s, k.shape[1], kv_replicas).contiguous()
356
+ moba_attn_lse = moba_attn_lse_hs.t().contiguous()
357
+
358
+ max_lse_1d = self_attn_lse_sh.view(-1, kv_replicas)
359
+ max_lse_1d = max_lse_1d.index_reduce(0, moba_q_sh_indices, moba_attn_lse, "amax")
360
+ self_attn_lse_sh = self_attn_lse_sh - max_lse_1d.view_as(self_attn_lse_sh)
361
+
362
+ moba_attn_lse = (
363
+ moba_attn_lse.view(-1, kv_replicas).sub(max_lse_1d.index_select(0, moba_q_sh_indices)).reshape_as(moba_attn_lse)
364
+ )
365
+
366
+ mixed_attn_se_sh = self_attn_lse_sh.exp()
367
+ moba_attn_se = moba_attn_lse.exp()
368
+
369
+ mixed_view = mixed_attn_se_sh.view(-1, kv_replicas)
370
+ result_view = mixed_view.index_add(0, moba_q_sh_indices, moba_attn_se.view(-1, kv_replicas))
371
+
372
+ mixed_attn_se_sh = result_view.view_as(mixed_attn_se_sh)
373
+ mixed_attn_lse_sh = mixed_attn_se_sh.log()
374
+
375
+ # add attn output
376
+ factor = (self_attn_lse_sh - mixed_attn_lse_sh).exp() # [ vS, H ]
377
+ self_attn_out_sh = self_attn_out_sh * factor.view(self_attn_out_sh.shape[0], self_attn_out_sh.shape[1], 1)
378
+ output_2d = self_attn_out_sh.reshape(q.shape[0] * k.shape[1], kv_replicas, q.shape[2])
379
+
380
+ # add moba output
381
+ mixed_attn_lse = mixed_attn_lse_sh.view(-1, kv_replicas).index_select(0, moba_q_sh_indices).view_as(moba_attn_lse)
382
+ factor = (moba_attn_lse - mixed_attn_lse).exp() # [ vS, H ]
383
+ moba_attn_out = moba_attn_out * factor.unsqueeze(-1)
384
+ raw_attn_out = moba_attn_out.view(-1, kv_replicas, moba_attn_out.shape[-1])
385
+ output_2d.index_add_(0, moba_q_sh_indices, raw_attn_out)
386
+
387
+ # add back max lse
388
+ mixed_attn_lse_sh = mixed_attn_lse_sh + max_lse_1d.view_as(mixed_attn_se_sh)
389
+
390
+ return output_2d.view(q.shape[0], q.shape[1], q.shape[2]).to(q.dtype)
391
+
392
+
393
+ def roll_tensor(tensor, shifts=-1, dims=-1, fill_value=0):
394
+ """Roll the tensor input along the given dimension(s).
395
+ Inserted elements are set to be 0.0.
396
+ """
397
+ rolled_tensor = torch.roll(tensor, shifts=shifts, dims=dims)
398
+ rolled_tensor.select(dims, shifts).fill_(fill_value)
399
+ return rolled_tensor, rolled_tensor.sum()
400
+
401
+
402
+ @dataclass
403
+ class MoEV2CausalLMOutputWithPast(ModelOutput):
404
+ """
405
+ Base class for causal language model (or autoregressive) outputs as well as Mixture of Expert's router hidden
406
+ states terms, to train a MoE model.
407
+ Args:
408
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
409
+ Language modeling loss (for next-token prediction).
410
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
411
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
412
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
413
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
414
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
415
+ `past_key_values` input) to speed up sequential decoding.
416
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
417
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
418
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
419
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
420
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
421
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
422
+ sequence_length)`.
423
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
424
+ heads.
425
+ z_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
426
+ z_loss for the sparse modules.
427
+ aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
428
+ aux_loss for the sparse modules.
429
+ router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`):
430
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
431
+ Router logits of the encoder model, useful to compute the auxiliary loss and the z_loss for the sparse
432
+ modules.
433
+ """
434
+
435
+ loss: Optional[torch.FloatTensor] = None
436
+ logits: Optional[torch.FloatTensor] = None
437
+ past_key_values: Optional[Cache] = None
438
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
439
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
440
+ z_loss: Optional[torch.FloatTensor] = None
441
+ aux_loss: Optional[torch.FloatTensor] = None
442
+ router_logits: Optional[tuple[torch.FloatTensor]] = None
443
+ mtp_loss: Optional[torch.FloatTensor] = None
444
+ mtp_logits: Optional[tuple[torch.FloatTensor, ...]] = None
445
+
446
+
447
+ class MoeV2ModelOutputWithPast(MoeModelOutputWithPast):
448
+
449
+ def __init__(self, mtp_hidden_states=None, **kwargs):
450
+ super().__init__(**kwargs)
451
+ self.mtp_hidden_states = mtp_hidden_states
452
+
453
+
454
+ def _get_unpad_data(attention_mask):
455
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
456
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
457
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
458
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
459
+ return (
460
+ indices,
461
+ cu_seqlens,
462
+ max_seqlen_in_batch,
463
+ )
464
+
465
+
466
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
467
+ warnings.warn(
468
+ "Calling `transformers.models.BailingMoeV2.modeling_BailingMoeV2._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
469
+ )
470
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
471
+
472
+
473
+ def _make_causal_mask(
474
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
475
+ ):
476
+ warnings.warn(
477
+ "Calling `transformers.models.BailingMoeV2.modeling_BailingMoeV2._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.BailingMoeV2.modeling_BailingMoeV2.AttentionMaskConverter._make_causal_mask"
478
+ )
479
+ return AttentionMaskConverter._make_causal_mask(
480
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
481
+ )
482
+
483
+
484
+ class BailingMoeV2RMSNorm(nn.Module):
485
+ def __init__(self, hidden_size, eps=1e-6):
486
+ """
487
+ BailingMoeV2RMSNorm is equivalent to T5LayerNorm
488
+ """
489
+ super().__init__()
490
+ self.weight = nn.Parameter(torch.ones(hidden_size))
491
+ self.variance_epsilon = eps
492
+
493
+ def forward(self, hidden_states):
494
+ input_dtype = hidden_states.dtype
495
+ hidden_states = hidden_states.to(torch.float32)
496
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
497
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
498
+ return self.weight * hidden_states.to(input_dtype)
499
+
500
+
501
+ ALL_LAYERNORM_LAYERS.append(BailingMoeV2RMSNorm)
502
+
503
+
504
+ class BailingMoeV2RotaryEmbedding(nn.Module):
505
+ def __init__(self, config: BailingMoeV2Config, device=None):
506
+ super().__init__()
507
+ # BC: "rope_type" was originally "type"
508
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
509
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
510
+ else:
511
+ self.rope_type = "default"
512
+ self.max_seq_len_cached = config.max_position_embeddings
513
+ self.original_max_seq_len = config.max_position_embeddings
514
+
515
+ self.config = config
516
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
517
+
518
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
519
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
520
+ self.original_inv_freq = self.inv_freq
521
+
522
+ @torch.no_grad()
523
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
524
+ def forward(self, x, position_ids):
525
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
526
+ position_ids_expanded = position_ids[:, None, :].float()
527
+
528
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
529
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
530
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
531
+ emb = torch.cat((freqs, freqs), dim=-1)
532
+ cos = emb.cos() * self.attention_scaling
533
+ sin = emb.sin() * self.attention_scaling
534
+
535
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
536
+
537
+
538
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
539
+ def rotate_half(x):
540
+ """Rotates half the hidden dims of the input."""
541
+ x1 = x[..., : x.shape[-1] // 2]
542
+ x2 = x[..., x.shape[-1] // 2 :]
543
+ return torch.cat((-x2, x1), dim=-1)
544
+
545
+
546
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
547
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
548
+ """Applies Rotary Position Embedding to the query and key tensors.
549
+ Args:
550
+ q (`torch.Tensor`): The query tensor.
551
+ k (`torch.Tensor`): The key tensor.
552
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
553
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
554
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
555
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
556
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
557
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
558
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
559
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
560
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
561
+ Returns:
562
+ `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding.
563
+ """
564
+ cos = cos.unsqueeze(unsqueeze_dim)
565
+ sin = sin.unsqueeze(unsqueeze_dim)
566
+
567
+ # Keep half or full tensor for later concatenation
568
+ rotary_dim = cos.shape[-1]
569
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
570
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
571
+
572
+ # Apply rotary embeddings on the first half or full tensor
573
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
574
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
575
+
576
+ # Concatenate back to full shape
577
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
578
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
579
+ return q_embed, k_embed
580
+
581
+
582
+ class BailingMoeV2MLP(nn.Module):
583
+ def __init__(self, config: BailingMoeV2Config, intermediate_size: int):
584
+ super().__init__()
585
+ self.config = config
586
+ self.hidden_size = config.hidden_size
587
+ self.intermediate_size = intermediate_size
588
+
589
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
590
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
591
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
592
+ self.act_fn = ACT2FN[config.hidden_act]
593
+
594
+ def forward(self, x):
595
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
596
+
597
+
598
+ class BailingMoeV2Gate(nn.Module):
599
+ def __init__(self, config):
600
+ super().__init__()
601
+ self.config = config
602
+ self.top_k = config.num_experts_per_tok
603
+ self.num_experts = config.num_experts
604
+
605
+ self.n_group = config.n_group
606
+ self.topk_group = config.topk_group
607
+
608
+ # topk selection algorithm
609
+ self.gating_dim = config.hidden_size
610
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
611
+ self.routed_scaling_factor = config.routed_scaling_factor
612
+
613
+ self.register_buffer("expert_bias", torch.zeros((self.num_experts)))
614
+ self.reset_parameters()
615
+
616
+ def reset_parameters(self) -> None:
617
+ import torch.nn.init as init
618
+
619
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
620
+
621
+ def group_limited_topk(
622
+ self,
623
+ scores: torch.Tensor,
624
+ ):
625
+ num_tokens, _ = scores.size()
626
+ # Organize the experts into groups
627
+ group_scores = scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
628
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
629
+ group_mask = torch.zeros_like(group_scores)
630
+ group_mask.scatter_(1, group_idx, 1)
631
+
632
+ # Mask the experts based on selection groups
633
+ score_mask = (
634
+ group_mask.unsqueeze(-1)
635
+ .expand(num_tokens, self.n_group, self.num_experts // self.n_group)
636
+ .reshape(num_tokens, -1)
637
+ )
638
+
639
+ masked_scores = scores.masked_fill(~score_mask.bool(), float('-inf'))
640
+ probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
641
+
642
+ return probs, top_indices
643
+
644
+ def forward(self, hidden_states):
645
+ # compute gating score
646
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
647
+ logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
648
+
649
+ scores = torch.sigmoid(logits.float()).type_as(logits)
650
+
651
+ scores_for_routing = scores + self.expert_bias
652
+ _, topk_idx = self.group_limited_topk(scores_for_routing)
653
+
654
+ scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
655
+
656
+ topk_weight = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.top_k > 1 else scores
657
+ topk_weight = topk_weight * self.routed_scaling_factor
658
+
659
+ return topk_idx, topk_weight, logits
660
+
661
+
662
+ class BailingMoeV2SparseMoeBlock(nn.Module):
663
+ """
664
+ A mixed expert module containing shared experts.
665
+ """
666
+
667
+ def __init__(self, config: BailingMoeV2Config):
668
+ super().__init__()
669
+ self.config = config
670
+ self.num_experts_per_tok = config.num_experts_per_tok
671
+ self._setup_experts()
672
+ self.gate = BailingMoeV2Gate(config)
673
+ if config.num_shared_experts is not None:
674
+ self.shared_experts = BailingMoeV2MLP(
675
+ config=config, intermediate_size=config.moe_intermediate_size * config.num_shared_experts
676
+ )
677
+
678
+ def _setup_experts(self):
679
+ self.experts = nn.ModuleList(
680
+ [
681
+ BailingMoeV2MLP(config=self.config, intermediate_size=self.config.moe_intermediate_size)
682
+ for _ in range(self.config.num_experts)
683
+ ]
684
+ )
685
+
686
+ def forward(self, hidden_states):
687
+ identity = hidden_states
688
+ bsz, seq_len, h = hidden_states.shape
689
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
690
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
691
+ flat_topk_idx = topk_idx.view(-1)
692
+ if self.training:
693
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
694
+ y = torch.empty_like(hidden_states)
695
+ for i, expert in enumerate(self.experts):
696
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
697
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
698
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
699
+ else:
700
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(bsz, seq_len, h)
701
+ if self.config.num_shared_experts is not None:
702
+ y = y + self.shared_experts(identity)
703
+ return y, (router_logits.view(bsz, seq_len, -1), topk_idx.view(bsz, seq_len, -1))
704
+
705
+ @torch.no_grad()
706
+ def moe_infer(self, x, topk_ids, topk_weight):
707
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
708
+ cnts.scatter_(1, topk_ids, 1)
709
+ tokens_per_expert = cnts.sum(dim=0)
710
+ idxs = topk_ids.view(-1).argsort()
711
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
712
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
713
+ outputs = []
714
+ start_idx = 0
715
+ for i, num_tokens in enumerate(tokens_per_expert):
716
+ end_idx = start_idx + num_tokens
717
+ if num_tokens == 0:
718
+ continue
719
+ expert = self.experts[i]
720
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
721
+ expert_out = expert(tokens_for_this_expert)
722
+ outputs.append(expert_out.to(x.device))
723
+ start_idx = end_idx
724
+
725
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
726
+ new_x = torch.empty_like(outs)
727
+ new_x[idxs] = outs
728
+ final_out = (
729
+ new_x.view(*topk_ids.shape, -1)
730
+ .type(topk_weight.dtype)
731
+ .mul_(topk_weight.unsqueeze(dim=-1))
732
+ .sum(dim=1)
733
+ .type(new_x.dtype)
734
+ )
735
+ return final_out
736
+
737
+
738
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
739
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
740
+ """
741
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
742
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
743
+ """
744
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
745
+ if n_rep == 1:
746
+ return hidden_states
747
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
748
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
749
+
750
+
751
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->BailingMoeV2
752
+ class BailingMoeV2Attention(nn.Module):
753
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
754
+
755
+ def __init__(self, config: BailingMoeV2Config, layer_idx: Optional[int] = None):
756
+ super().__init__()
757
+ self.config = config
758
+ self.layer_idx = layer_idx
759
+ if layer_idx is None:
760
+ logger.warning_once(
761
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
762
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
763
+ "when creating this class."
764
+ )
765
+
766
+ self.attention_dropout = config.attention_dropout
767
+ self.hidden_size = config.hidden_size
768
+ self.num_heads = config.num_attention_heads
769
+ self.head_dim = config.head_dim or self.hidden_size // self.num_heads
770
+ partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
771
+ self.rope_dim = int(self.head_dim * partial_rotary_factor)
772
+ self.num_key_value_heads = config.num_key_value_heads
773
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
774
+ self.max_position_embeddings = config.max_position_embeddings
775
+ self.rope_theta = config.rope_theta
776
+ self.is_causal = True
777
+
778
+ self.query_key_value = nn.Linear(
779
+ self.hidden_size,
780
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
781
+ bias=config.use_qkv_bias,
782
+ )
783
+
784
+ if self.config.use_qk_norm:
785
+ self.query_layernorm = BailingMoeV2RMSNorm(self.head_dim, eps=config.rms_norm_eps)
786
+ self.key_layernorm = BailingMoeV2RMSNorm(self.head_dim, eps=config.rms_norm_eps)
787
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias)
788
+
789
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
790
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
791
+
792
+ def forward(
793
+ self,
794
+ hidden_states: torch.Tensor,
795
+ attention_mask: Optional[torch.Tensor] = None,
796
+ position_ids: Optional[torch.LongTensor] = None,
797
+ past_key_value: Optional[Cache] = None,
798
+ output_attentions: bool = False,
799
+ use_cache: bool = False,
800
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
801
+ **kwargs,
802
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
803
+
804
+ bsz, q_len, _ = hidden_states.size()
805
+
806
+ qkv = self.query_key_value(hidden_states)
807
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
808
+
809
+ query_states, key_states, value_states = qkv.split(
810
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
811
+ )
812
+ query_states = query_states.transpose(1, 2)
813
+ key_states = key_states.transpose(1, 2)
814
+ value_states = value_states.transpose(1, 2)
815
+
816
+ if self.config.use_qk_norm:
817
+ query_states = self.query_layernorm(query_states)
818
+ key_states = self.key_layernorm(key_states)
819
+
820
+ cos, sin = position_embeddings
821
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
822
+
823
+ if past_key_value is not None:
824
+ if self.layer_idx is None:
825
+ raise ValueError(
826
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
827
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
828
+ "with a layer index."
829
+ )
830
+ cache_kwargs = {"sin": sin, "cos": cos}
831
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
832
+
833
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
834
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
835
+
836
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
837
+
838
+ kv_seq_len = key_states.shape[-2]
839
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
840
+ raise ValueError(
841
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
842
+ f" {attn_weights.size()}"
843
+ )
844
+
845
+ if attention_mask is not None:
846
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
847
+ raise ValueError(
848
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
849
+ )
850
+ attn_weights = attn_weights + attention_mask
851
+
852
+ # upcast attention to fp32
853
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
854
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
855
+ attn_output = torch.matmul(attn_weights, value_states)
856
+
857
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
858
+ raise ValueError(
859
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
860
+ f" {attn_output.size()}"
861
+ )
862
+
863
+ attn_output = attn_output.transpose(1, 2).contiguous()
864
+
865
+ attn_output = attn_output.reshape(bsz, q_len, -1)
866
+
867
+ attn_output = self.dense(attn_output)
868
+
869
+ if not output_attentions:
870
+ attn_weights = None
871
+
872
+ return attn_output, attn_weights, past_key_value
873
+
874
+
875
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->BailingMoeV2
876
+ class BailingMoeV2FlashAttention2(BailingMoeV2Attention):
877
+ """
878
+ BailingMoeV2 flash attention module. This module inherits from `BailingMoeV2Attention` as the weights of the module stays
879
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
880
+ flash attention and deal with padding tokens in case the input contains any of them.
881
+ """
882
+
883
+ def __init__(self, *args, **kwargs):
884
+ super().__init__(*args, **kwargs)
885
+
886
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
887
+ # 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.
888
+ # 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).
889
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
890
+
891
+ def forward(
892
+ self,
893
+ hidden_states: torch.Tensor,
894
+ attention_mask: Optional[torch.LongTensor] = None,
895
+ position_ids: Optional[torch.LongTensor] = None,
896
+ past_key_value: Optional[Cache] = None,
897
+ output_attentions: bool = False,
898
+ use_cache: bool = False,
899
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
900
+ **kwargs,
901
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
902
+ # BailingMoeV2FlashAttention2 attention does not support output_attentions
903
+ output_attentions = False
904
+
905
+ bsz, q_len, _ = hidden_states.size()
906
+
907
+ # Flash attention requires the input to have the shape
908
+ # batch_size x seq_length x head_dim x hidden_dim
909
+ # therefore we just need to keep the original shape
910
+
911
+ qkv = self.query_key_value(hidden_states)
912
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
913
+
914
+ query_states, key_states, value_states = qkv.split(
915
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
916
+ )
917
+ query_states = query_states.transpose(1, 2)
918
+ key_states = key_states.transpose(1, 2)
919
+ value_states = value_states.transpose(1, 2)
920
+
921
+ if self.config.use_qk_norm:
922
+ query_states = self.query_layernorm(query_states)
923
+ key_states = self.key_layernorm(key_states)
924
+
925
+ cos, sin = position_embeddings
926
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
927
+
928
+ if past_key_value is not None:
929
+ cache_kwargs = {"sin": sin, "cos": cos}
930
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
931
+
932
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
933
+ # to be able to avoid many of these transpose/reshape/view.
934
+ query_states = query_states.transpose(1, 2)
935
+ key_states = key_states.transpose(1, 2)
936
+ value_states = value_states.transpose(1, 2)
937
+
938
+ dropout_rate = self.attention_dropout if self.training else 0.0
939
+
940
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
941
+ # therefore the input hidden states gets silently cast in float32. Hence, we need
942
+ # cast them back in the correct dtype just to be sure everything works as expected.
943
+ # This might slow down training & inference so it is recommended to not cast the LayerNorms
944
+ # in fp32. (BailingMoeV2RMSNorm handles it correctly)
945
+
946
+ input_dtype = query_states.dtype
947
+ if input_dtype == torch.float32:
948
+ # Handle the case where the model is quantized
949
+ if hasattr(self.config, "_pre_quantization_dtype"):
950
+ target_dtype = self.config._pre_quantization_dtype
951
+ elif torch.is_autocast_enabled():
952
+ target_dtype = torch.get_autocast_gpu_dtype()
953
+ else:
954
+ target_dtype = self.query_key_value.weight.dtype
955
+
956
+ logger.warning_once(
957
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
958
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
959
+ f" {target_dtype}."
960
+ )
961
+
962
+ query_states = query_states.to(target_dtype)
963
+ key_states = key_states.to(target_dtype)
964
+ value_states = value_states.to(target_dtype)
965
+ if hasattr(self.config, "moba_topk"):
966
+ attn_output = self._mixture_attention_forward(
967
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
968
+ )
969
+ else:
970
+ attn_output = self._flash_attention_forward(
971
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
972
+ )
973
+
974
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
975
+ attn_output = self.dense(attn_output)
976
+
977
+ if not output_attentions:
978
+ attn_weights = None
979
+
980
+ return attn_output, attn_weights, past_key_value
981
+
982
+ def _mixture_attention_forward(
983
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
984
+ ):
985
+ """
986
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
987
+ first unpad the input, then computes the attention scores and pad the final attention scores.
988
+ Args:
989
+ query_states (`torch.Tensor`):
990
+ Input query states to be passed to Flash Attention API
991
+ key_states (`torch.Tensor`):
992
+ Input key states to be passed to Flash Attention API
993
+ value_states (`torch.Tensor`):
994
+ Input value states to be passed to Flash Attention API
995
+ attention_mask (`torch.Tensor`):
996
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
997
+ position of padding tokens and 1 for the position of non-padding tokens.
998
+ dropout (`int`, *optional*):
999
+ Attention dropout
1000
+ softmax_scale (`float`, *optional*):
1001
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1002
+ query_length (`int`):
1003
+ The length of the query sequence in terms of tokens. This represents the number of tokens in the
1004
+ `query_states` tensor along the sequence dimension. It is used to determine the effective sequence
1005
+ length for attention computations.
1006
+ """
1007
+ if not self._flash_attn_uses_top_left_mask:
1008
+ causal = self.is_causal
1009
+ else:
1010
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in BailingMoeV2FlashAttention2 __init__.
1011
+ causal = self.is_causal and query_length != 1
1012
+
1013
+ if query_length != 1:
1014
+ # prefill
1015
+ # Contains at least one padding token in the sequence
1016
+ if attention_mask is not None:
1017
+ batch_size = query_states.shape[0]
1018
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1019
+ query_states, key_states, value_states, attention_mask, query_length
1020
+ )
1021
+
1022
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1023
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1024
+ attn_output_unpad = _moba_attn_varlen_prefill(
1025
+ query_states,
1026
+ key_states,
1027
+ value_states,
1028
+ cu_seqlens=cu_seqlens_k,
1029
+ max_seqlen=max_seqlen_in_batch_k,
1030
+ moba_chunk_size=self.config.moba_block_size,
1031
+ moba_topk=self.config.moba_topk
1032
+ )
1033
+
1034
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1035
+ else:
1036
+ batch_size = query_states.shape[0]
1037
+ cu_seqlens_k = torch.cumsum(
1038
+ torch.tensor([0] + [query_length] * batch_size, device=query_states.device),
1039
+ dim=0,
1040
+ dtype=torch.int32,
1041
+ )
1042
+ query_states = query_states.view(-1, self.num_heads, self.head_dim)
1043
+ key_states = key_states.view(-1, self.num_key_value_heads, self.head_dim)
1044
+ value_states = value_states.view(-1, self.num_key_value_heads, self.head_dim)
1045
+ attn_output = _moba_attn_varlen_prefill(
1046
+ query_states,
1047
+ key_states,
1048
+ value_states,
1049
+ cu_seqlens=cu_seqlens_k,
1050
+ max_seqlen=query_length,
1051
+ moba_chunk_size=self.config.moba_block_size,
1052
+ moba_topk=self.config.moba_topk
1053
+ ).view(batch_size, query_length, -1)
1054
+ else:
1055
+ # decode
1056
+ attn_output = self._flash_attention_forward(
1057
+ query_states, key_states, value_states, attention_mask, query_length, dropout, softmax_scale
1058
+ )
1059
+ return attn_output
1060
+
1061
+ def _flash_attention_forward(
1062
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
1063
+ ):
1064
+ """
1065
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1066
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1067
+ Args:
1068
+ query_states (`torch.Tensor`):
1069
+ Input query states to be passed to Flash Attention API
1070
+ key_states (`torch.Tensor`):
1071
+ Input key states to be passed to Flash Attention API
1072
+ value_states (`torch.Tensor`):
1073
+ Input value states to be passed to Flash Attention API
1074
+ attention_mask (`torch.Tensor`):
1075
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1076
+ position of padding tokens and 1 for the position of non-padding tokens.
1077
+ dropout (`int`, *optional*):
1078
+ Attention dropout
1079
+ softmax_scale (`float`, *optional*):
1080
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1081
+ query_length (`int`):
1082
+ The length of the query sequence in terms of tokens. This represents the number of tokens in the
1083
+ `query_states` tensor along the sequence dimension. It is used to determine the effective sequence
1084
+ length for attention computations.
1085
+ """
1086
+ if not self._flash_attn_uses_top_left_mask:
1087
+ causal = self.is_causal
1088
+ else:
1089
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in BailingMoeV2FlashAttention2 __init__.
1090
+ causal = self.is_causal and query_length != 1
1091
+
1092
+ # Contains at least one padding token in the sequence
1093
+ if attention_mask is not None:
1094
+ batch_size = query_states.shape[0]
1095
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
1096
+ query_states, key_states, value_states, attention_mask, query_length
1097
+ )
1098
+
1099
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1100
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1101
+
1102
+ attn_output_unpad = flash_attn_varlen_func(
1103
+ query_states,
1104
+ key_states,
1105
+ value_states,
1106
+ cu_seqlens_q=cu_seqlens_q,
1107
+ cu_seqlens_k=cu_seqlens_k,
1108
+ max_seqlen_q=max_seqlen_in_batch_q,
1109
+ max_seqlen_k=max_seqlen_in_batch_k,
1110
+ dropout_p=dropout,
1111
+ softmax_scale=softmax_scale,
1112
+ causal=causal,
1113
+ )
1114
+
1115
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
1116
+ else:
1117
+ attn_output = flash_attn_func(
1118
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
1119
+ )
1120
+
1121
+ return attn_output
1122
+
1123
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
1124
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1125
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1126
+
1127
+ key_layer = index_first_axis(
1128
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
1129
+ )
1130
+ value_layer = index_first_axis(
1131
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
1132
+ )
1133
+ if query_length == kv_seq_len:
1134
+ query_layer = index_first_axis(
1135
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
1136
+ )
1137
+ cu_seqlens_q = cu_seqlens_k
1138
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1139
+ indices_q = indices_k
1140
+ elif query_length == 1:
1141
+ max_seqlen_in_batch_q = 1
1142
+ cu_seqlens_q = torch.arange(
1143
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1144
+ ) # There is a memcpy here, that is very bad.
1145
+ indices_q = cu_seqlens_q[:-1]
1146
+ query_layer = query_layer.squeeze(1)
1147
+ else:
1148
+ # The -q_len: slice assumes left padding.
1149
+ attention_mask = attention_mask[:, -query_length:]
1150
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
1151
+
1152
+ return (
1153
+ query_layer,
1154
+ key_layer,
1155
+ value_layer,
1156
+ indices_q,
1157
+ (cu_seqlens_q, cu_seqlens_k),
1158
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1159
+ )
1160
+
1161
+
1162
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->BailingMoeV2
1163
+ class BailingMoeV2SdpaAttention(BailingMoeV2Attention):
1164
+ """
1165
+ BailingMoeV2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1166
+ `BailingMoeV2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1167
+ SDPA API.
1168
+ """
1169
+
1170
+ # Adapted from BailingMoeV2Attention.forward
1171
+ def forward(
1172
+ self,
1173
+ hidden_states: torch.Tensor,
1174
+ attention_mask: Optional[torch.Tensor] = None,
1175
+ position_ids: Optional[torch.LongTensor] = None,
1176
+ past_key_value: Optional[Cache] = None,
1177
+ output_attentions: bool = False,
1178
+ use_cache: bool = False,
1179
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
1180
+ **kwargs,
1181
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1182
+ if output_attentions:
1183
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1184
+ logger.warning_once(
1185
+ "BailingMoeV2Model is using BailingMoeV2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1186
+ '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.'
1187
+ )
1188
+ return super().forward(
1189
+ hidden_states=hidden_states,
1190
+ attention_mask=attention_mask,
1191
+ position_ids=position_ids,
1192
+ past_key_value=past_key_value,
1193
+ output_attentions=output_attentions,
1194
+ use_cache=use_cache,
1195
+ )
1196
+
1197
+ bsz, q_len, _ = hidden_states.size()
1198
+
1199
+ qkv = self.query_key_value(hidden_states)
1200
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
1201
+
1202
+ query_states, key_states, value_states = qkv.split(
1203
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
1204
+ )
1205
+ query_states = query_states.transpose(1, 2)
1206
+ key_states = key_states.transpose(1, 2)
1207
+ value_states = value_states.transpose(1, 2)
1208
+
1209
+ if self.config.use_qk_norm:
1210
+ query_states = self.query_layernorm(query_states)
1211
+ key_states = self.key_layernorm(key_states)
1212
+
1213
+ cos, sin = position_embeddings
1214
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
1215
+
1216
+ if past_key_value is not None:
1217
+ cache_kwargs = {"sin": sin, "cos": cos}
1218
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1219
+
1220
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1221
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1222
+
1223
+ if attention_mask is not None:
1224
+ kv_seq_len = key_states.shape[-2]
1225
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1226
+ raise ValueError(
1227
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1228
+ )
1229
+
1230
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1231
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1232
+ if query_states.device.type == "cuda" and attention_mask is not None:
1233
+ query_states = query_states.contiguous()
1234
+ key_states = key_states.contiguous()
1235
+ value_states = value_states.contiguous()
1236
+
1237
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1238
+ query_states,
1239
+ key_states,
1240
+ value_states,
1241
+ attn_mask=attention_mask,
1242
+ dropout_p=self.attention_dropout if self.training else 0.0,
1243
+ # 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.
1244
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1245
+ )
1246
+
1247
+ attn_output = attn_output.transpose(1, 2).contiguous()
1248
+ attn_output = attn_output.reshape(bsz, q_len, -1)
1249
+
1250
+ attn_output = self.dense(attn_output)
1251
+
1252
+ return attn_output, None, past_key_value
1253
+
1254
+
1255
+ ATTENTION_CLASSES = {
1256
+ "eager": BailingMoeV2Attention,
1257
+ "flash_attention_2": BailingMoeV2FlashAttention2,
1258
+ "sdpa": BailingMoeV2SdpaAttention,
1259
+ }
1260
+
1261
+
1262
+ class BailingMoeV2MTPLayer(nn.Module):
1263
+ def __init__(self, config: BailingMoeV2Config, layer_idx: int):
1264
+ super().__init__()
1265
+ self.layer_idx = layer_idx
1266
+ self.input_layernorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1267
+ self.enorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1268
+
1269
+ self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
1270
+ self.post_attention_layernorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1271
+ self.attention = ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
1272
+ self.mlp = BailingMoeV2SparseMoeBlock(config)
1273
+
1274
+ self.hnorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1275
+ self.final_layernorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1276
+
1277
+ def forward(
1278
+ self,
1279
+ input_embeds,
1280
+ hidden_states: torch.Tensor,
1281
+ attention_mask: Optional[torch.Tensor] = None,
1282
+ position_ids: Optional[torch.LongTensor] = None,
1283
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1284
+ output_attentions: Optional[bool] = False,
1285
+ output_router_logits: Optional[bool] = False,
1286
+ use_cache: Optional[bool] = False,
1287
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
1288
+ **kwargs,
1289
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1290
+ input_embeds = self.enorm(input_embeds)
1291
+ hidden_states = self.hnorm(hidden_states)
1292
+ hidden_states = self.eh_proj(torch.cat([input_embeds, hidden_states], dim=-1))
1293
+ residual = hidden_states
1294
+
1295
+ hidden_states = self.input_layernorm(hidden_states)
1296
+
1297
+ # Self Attention
1298
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1299
+ hidden_states=hidden_states,
1300
+ attention_mask=attention_mask,
1301
+ position_ids=position_ids,
1302
+ past_key_value=past_key_value,
1303
+ output_attentions=output_attentions,
1304
+ position_embeddings=position_embeddings,
1305
+ use_cache=use_cache,
1306
+ )
1307
+ hidden_states = residual + hidden_states
1308
+
1309
+ # Fully Connected
1310
+ residual = hidden_states
1311
+ hidden_states = self.post_attention_layernorm(hidden_states)
1312
+ hidden_states = self.mlp(hidden_states)
1313
+ if isinstance(hidden_states, tuple):
1314
+ hidden_states, router_logits = hidden_states
1315
+ else:
1316
+ router_logits = None
1317
+ hidden_states = residual + hidden_states.to(residual.device)
1318
+ hidden_states = self.final_layernorm(hidden_states)
1319
+
1320
+ outputs = (hidden_states,)
1321
+
1322
+ if output_attentions:
1323
+ outputs += (self_attn_weights,)
1324
+
1325
+ if use_cache:
1326
+ outputs += (present_key_value,)
1327
+
1328
+ if output_router_logits:
1329
+ outputs += (router_logits,)
1330
+
1331
+ return outputs
1332
+
1333
+
1334
+ class BailingMoeV2DecoderLayer(nn.Module):
1335
+ def __init__(self, config: BailingMoeV2Config, layer_idx: int):
1336
+ super().__init__()
1337
+ self.hidden_size = config.hidden_size
1338
+
1339
+ self.attention = ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
1340
+
1341
+ self.mlp = (
1342
+ BailingMoeV2SparseMoeBlock(config)
1343
+ if (config.num_experts is not None and layer_idx >= config.first_k_dense_replace)
1344
+ else BailingMoeV2MLP(config=config, intermediate_size=config.intermediate_size)
1345
+ )
1346
+ self.input_layernorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1347
+ self.post_attention_layernorm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1348
+
1349
+ def forward(
1350
+ self,
1351
+ hidden_states: torch.Tensor,
1352
+ attention_mask: Optional[torch.Tensor] = None,
1353
+ position_ids: Optional[torch.LongTensor] = None,
1354
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1355
+ output_attentions: Optional[bool] = False,
1356
+ output_router_logits: Optional[bool] = False,
1357
+ use_cache: Optional[bool] = False,
1358
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
1359
+ **kwargs,
1360
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1361
+ """
1362
+ Args:
1363
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1364
+ attention_mask (`torch.FloatTensor`, *optional*):
1365
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1366
+ query_sequence_length, key_sequence_length)` if default attention is used.
1367
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1368
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1369
+ config.n_positions - 1]`.
1370
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
1371
+ cached past key and value projection states
1372
+ output_attentions (`bool`, *optional*):
1373
+ Whether to return the attentions tensors of all attention layers. See `attentions` under
1374
+ returned tensors for more detail.
1375
+ output_router_logits (`bool`, *optional*):
1376
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1377
+ and should not be returned during inference.
1378
+ use_cache (`bool`, *optional*):
1379
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1380
+ (see `past_key_values`).
1381
+ """
1382
+ residual = hidden_states
1383
+
1384
+ hidden_states = self.input_layernorm(hidden_states)
1385
+
1386
+ # Self Attention
1387
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1388
+ hidden_states=hidden_states,
1389
+ attention_mask=attention_mask,
1390
+ position_ids=position_ids,
1391
+ past_key_value=past_key_value,
1392
+ output_attentions=output_attentions,
1393
+ position_embeddings=position_embeddings,
1394
+ use_cache=use_cache,
1395
+ )
1396
+ hidden_states = residual + hidden_states
1397
+
1398
+ # Fully Connected
1399
+ residual = hidden_states
1400
+ hidden_states = self.post_attention_layernorm(hidden_states)
1401
+ hidden_states = self.mlp(hidden_states)
1402
+ if isinstance(hidden_states, tuple):
1403
+ hidden_states, router_logits = hidden_states
1404
+ else:
1405
+ router_logits = None
1406
+ hidden_states = residual + hidden_states.to(residual.device)
1407
+
1408
+ outputs = (hidden_states,)
1409
+
1410
+ if output_attentions:
1411
+ outputs += (self_attn_weights,)
1412
+
1413
+ if use_cache:
1414
+ outputs += (present_key_value,)
1415
+
1416
+ if output_router_logits:
1417
+ outputs += (router_logits,)
1418
+
1419
+ return outputs
1420
+
1421
+
1422
+ BAILINGMOEV2_START_DOCSTRING = r"""
1423
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1424
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1425
+ etc.)
1426
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1427
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1428
+ and behavior.
1429
+ Parameters:
1430
+ config ([`BailingMoeV2Config`]):
1431
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1432
+ load the weights associated with the model, only the configuration. Check out the
1433
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1434
+ """
1435
+
1436
+
1437
+ @add_start_docstrings(
1438
+ "The bare BailingMoeV2 Model outputting raw hidden-states without any specific head on top.",
1439
+ BAILINGMOEV2_START_DOCSTRING,
1440
+ )
1441
+ class BailingMoeV2PreTrainedModel(PreTrainedModel):
1442
+ config_class = BailingMoeV2Config
1443
+ base_model_prefix = "model"
1444
+ supports_gradient_checkpointing = True
1445
+ _no_split_modules = ["BailingMoeV2DecoderLayer"]
1446
+ _skip_keys_device_placement = "past_key_values"
1447
+ _supports_flash_attn_2 = True
1448
+ _supports_sdpa = True
1449
+ _supports_cache_class = True
1450
+
1451
+ def _init_weights(self, module):
1452
+ std = self.config.initializer_range
1453
+ if isinstance(module, nn.Linear):
1454
+ module.weight.data.normal_(mean=0.0, std=std)
1455
+ if module.bias is not None:
1456
+ module.bias.data.zero_()
1457
+ elif isinstance(module, nn.Embedding):
1458
+ module.weight.data.normal_(mean=0.0, std=std)
1459
+ if module.padding_idx is not None:
1460
+ module.weight.data[module.padding_idx].zero_()
1461
+
1462
+
1463
+ BAILINGMOEV2_INPUTS_DOCSTRING = r"""
1464
+ Args:
1465
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1466
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1467
+ it.
1468
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1469
+ [`PreTrainedTokenizer.__call__`] for details.
1470
+ [What are input IDs?](../glossary#input-ids)
1471
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1472
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1473
+ - 1 for tokens that are **not masked**,
1474
+ - 0 for tokens that are **masked**.
1475
+ [What are attention masks?](../glossary#attention-mask)
1476
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1477
+ [`PreTrainedTokenizer.__call__`] for details.
1478
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1479
+ `past_key_values`).
1480
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1481
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1482
+ information on the default strategy.
1483
+ - 1 indicates the head is **not masked**,
1484
+ - 0 indicates the head is **masked**.
1485
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1486
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1487
+ config.n_positions - 1]`.
1488
+ [What are position IDs?](../glossary#position-ids)
1489
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1490
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1491
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1492
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1493
+ Two formats are allowed:
1494
+ - a [`~cache_utils.Cache`] instance;
1495
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1496
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1497
+ cache format.
1498
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1499
+ legacy cache format will be returned.
1500
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1501
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1502
+ of shape `(batch_size, sequence_length)`.
1503
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1504
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1505
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1506
+ model's internal embedding lookup matrix.
1507
+ use_cache (`bool`, *optional*):
1508
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1509
+ `past_key_values`).
1510
+ output_attentions (`bool`, *optional*):
1511
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1512
+ tensors for more detail.
1513
+ output_hidden_states (`bool`, *optional*):
1514
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1515
+ more detail.
1516
+ return_dict (`bool`, *optional*):
1517
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1518
+ """
1519
+
1520
+
1521
+ @add_start_docstrings(
1522
+ "The bare BailingMoeV2 Model outputting raw hidden-states without any specific head on top.",
1523
+ BAILINGMOEV2_START_DOCSTRING,
1524
+ )
1525
+ class BailingMoeV2Model(BailingMoeV2PreTrainedModel):
1526
+ """
1527
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeV2DecoderLayer`]
1528
+ Args:
1529
+ config: BailingMoeV2Config
1530
+ """
1531
+
1532
+ def __init__(self, config: BailingMoeV2Config):
1533
+ super().__init__(config)
1534
+ self.padding_idx = config.pad_token_id
1535
+ self.vocab_size = config.vocab_size
1536
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1537
+
1538
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1539
+ self.layers = []
1540
+ for layer_idx in range(config.num_hidden_layers + config.num_nextn_predict_layers):
1541
+ layer_cls = BailingMoeV2DecoderLayer if layer_idx < config.num_hidden_layers else BailingMoeV2MTPLayer
1542
+ self.layers.append(layer_cls(config, layer_idx))
1543
+
1544
+ self.layers = nn.ModuleList(self.layers)
1545
+
1546
+ self._use_sdpa = config._attn_implementation == "sdpa"
1547
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1548
+ self.norm = BailingMoeV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1549
+ self.rotary_emb = BailingMoeV2RotaryEmbedding(config=config)
1550
+ self.gradient_checkpointing = False
1551
+ # Initialize weights and apply final processing
1552
+ self.post_init()
1553
+
1554
+ def get_input_embeddings(self):
1555
+ return self.word_embeddings
1556
+
1557
+ def set_input_embeddings(self, value):
1558
+ self.word_embeddings = value
1559
+
1560
+ @add_start_docstrings_to_model_forward(BAILINGMOEV2_INPUTS_DOCSTRING)
1561
+ def forward(
1562
+ self,
1563
+ input_ids: torch.LongTensor = None,
1564
+ attention_mask: Optional[torch.Tensor] = None,
1565
+ position_ids: Optional[torch.LongTensor] = None,
1566
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1567
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1568
+ use_cache: Optional[bool] = None,
1569
+ output_attentions: Optional[bool] = None,
1570
+ output_hidden_states: Optional[bool] = None,
1571
+ output_router_logits: Optional[bool] = None,
1572
+ return_dict: Optional[bool] = None,
1573
+ **kwargs,
1574
+ ) -> Union[Tuple, MoeV2ModelOutputWithPast]:
1575
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1576
+ output_hidden_states = (
1577
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1578
+ )
1579
+ output_router_logits = (
1580
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1581
+ )
1582
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1583
+
1584
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1585
+
1586
+ # retrieve input_ids and inputs_embeds
1587
+ if input_ids is not None and inputs_embeds is not None:
1588
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1589
+ elif input_ids is not None:
1590
+ batch_size, seq_length = input_ids.shape[:2]
1591
+ elif inputs_embeds is not None:
1592
+ batch_size, seq_length = inputs_embeds.shape[:2]
1593
+ else:
1594
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1595
+
1596
+ if self.gradient_checkpointing and self.training:
1597
+ if use_cache:
1598
+ logger.warning_once(
1599
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1600
+ )
1601
+ use_cache = False
1602
+
1603
+ if use_cache and past_key_values is None:
1604
+ past_key_values = DynamicCache()
1605
+
1606
+ if inputs_embeds is None:
1607
+ inputs_embeds = self.word_embeddings(input_ids)
1608
+
1609
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1610
+
1611
+ if position_ids is None:
1612
+ position_ids = torch.arange(
1613
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1614
+ )
1615
+ position_ids = position_ids.unsqueeze(0)
1616
+
1617
+ if self._use_flash_attention_2:
1618
+ # 2d mask is passed through the layers
1619
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1620
+ elif self._use_sdpa and not output_attentions:
1621
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1622
+ # the manual implementation that requires a 4D causal mask in all cases.
1623
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1624
+ attention_mask,
1625
+ (batch_size, seq_length),
1626
+ inputs_embeds,
1627
+ past_seen_tokens,
1628
+ )
1629
+ else:
1630
+ # 4d mask is passed through the layers
1631
+ attention_mask = _prepare_4d_causal_attention_mask(
1632
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens
1633
+ )
1634
+
1635
+ # embed positions
1636
+ hidden_states = inputs_embeds
1637
+
1638
+ # create position embeddings to be shared across the decoder layers
1639
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1640
+
1641
+ # decoder layers
1642
+ all_hidden_states = () if output_hidden_states else None
1643
+ all_self_attns = () if output_attentions else None
1644
+ all_router_logits = () if output_router_logits else None
1645
+ next_decoder_cache = None
1646
+ layers = self.layers[: -self.num_nextn_predict_layers] if self.num_nextn_predict_layers > 0 else self.layers
1647
+ mtp_layers = self.layers[-self.num_nextn_predict_layers :] if self.num_nextn_predict_layers > 0 else None
1648
+
1649
+ for decoder_layer in layers:
1650
+ if output_hidden_states:
1651
+ all_hidden_states += (hidden_states,)
1652
+
1653
+ if self.gradient_checkpointing and self.training:
1654
+ layer_outputs = self._gradient_checkpointing_func(
1655
+ decoder_layer.__call__,
1656
+ hidden_states,
1657
+ attention_mask,
1658
+ position_ids,
1659
+ past_key_values,
1660
+ output_attentions,
1661
+ output_router_logits,
1662
+ use_cache,
1663
+ position_embeddings,
1664
+ )
1665
+ else:
1666
+ layer_outputs = decoder_layer(
1667
+ hidden_states,
1668
+ attention_mask=attention_mask,
1669
+ position_ids=position_ids,
1670
+ past_key_value=past_key_values,
1671
+ output_attentions=output_attentions,
1672
+ output_router_logits=output_router_logits,
1673
+ use_cache=use_cache,
1674
+ position_embeddings=position_embeddings,
1675
+ )
1676
+ hidden_states = layer_outputs[0]
1677
+
1678
+ if use_cache:
1679
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1680
+
1681
+ if output_attentions:
1682
+ all_self_attns += (layer_outputs[1],)
1683
+
1684
+ if output_router_logits and layer_outputs[-1] is not None:
1685
+ all_router_logits += (layer_outputs[-1],)
1686
+
1687
+ hidden_states = self.norm(hidden_states)
1688
+ main_hidden_states = hidden_states
1689
+
1690
+ # add hidden states from the last decoder layer
1691
+ if output_hidden_states:
1692
+ all_hidden_states += (main_hidden_states,)
1693
+
1694
+ mtp_hidden_states = None
1695
+
1696
+ if mtp_layers:
1697
+ for decoder_layer in mtp_layers:
1698
+ input_ids, _ = roll_tensor(input_ids, shifts=-1, dims=-1)
1699
+ inputs_embeds = self.word_embeddings(input_ids)
1700
+
1701
+ if self.gradient_checkpointing and self.training:
1702
+ layer_outputs = self._gradient_checkpointing_func(
1703
+ decoder_layer.__call__,
1704
+ inputs_embeds,
1705
+ hidden_states,
1706
+ attention_mask,
1707
+ position_ids,
1708
+ past_key_values,
1709
+ output_attentions,
1710
+ output_router_logits,
1711
+ use_cache,
1712
+ position_embeddings,
1713
+ )
1714
+ else:
1715
+ layer_outputs = decoder_layer(
1716
+ inputs_embeds,
1717
+ hidden_states,
1718
+ attention_mask=attention_mask,
1719
+ position_ids=position_ids,
1720
+ past_key_value=past_key_values,
1721
+ output_attentions=output_attentions,
1722
+ output_router_logits=output_router_logits,
1723
+ use_cache=use_cache,
1724
+ position_embeddings=position_embeddings,
1725
+ )
1726
+ if mtp_hidden_states is None:
1727
+ mtp_hidden_states = []
1728
+ hidden_states = layer_outputs[0]
1729
+ mtp_hidden_states.append(hidden_states)
1730
+
1731
+ if output_hidden_states:
1732
+ all_hidden_states += (hidden_states,)
1733
+
1734
+ if use_cache:
1735
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1736
+
1737
+ if output_attentions:
1738
+ all_self_attns += (layer_outputs[1],)
1739
+
1740
+ if output_router_logits and layer_outputs[-1] is not None:
1741
+ all_router_logits += (layer_outputs[-1],)
1742
+
1743
+ next_cache = None
1744
+ if use_cache:
1745
+ next_cache = next_decoder_cache
1746
+ if not return_dict:
1747
+ return tuple(
1748
+ v
1749
+ for v in [main_hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1750
+ if v is not None
1751
+ )
1752
+ return MoeV2ModelOutputWithPast(
1753
+ last_hidden_state=main_hidden_states,
1754
+ past_key_values=next_cache,
1755
+ hidden_states=all_hidden_states,
1756
+ mtp_hidden_states=mtp_hidden_states,
1757
+ attentions=all_self_attns,
1758
+ router_logits=all_router_logits,
1759
+ )
1760
+
1761
+
1762
+ class BailingMoeV2ForCausalLM(BailingMoeV2PreTrainedModel, GenerationMixin):
1763
+ _tied_weights_keys = ["lm_head.weight"]
1764
+
1765
+ def __init__(self, config: BailingMoeV2Config):
1766
+ super().__init__(config)
1767
+ self.model = BailingMoeV2Model(config)
1768
+ self.vocab_size = config.vocab_size
1769
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1770
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1771
+ self.mtp_loss_scaling_factor = config.mtp_loss_scaling_factor
1772
+
1773
+ # Initialize weights and apply final processing
1774
+ self.post_init()
1775
+
1776
+ def get_input_embeddings(self):
1777
+ return self.model.word_embeddings
1778
+
1779
+ def set_input_embeddings(self, value):
1780
+ self.model.word_embeddings = value
1781
+
1782
+ def get_output_embeddings(self):
1783
+ return self.lm_head
1784
+
1785
+ def set_output_embeddings(self, new_embeddings):
1786
+ self.lm_head = new_embeddings
1787
+
1788
+ def set_decoder(self, decoder):
1789
+ self.model = decoder
1790
+
1791
+ def get_decoder(self):
1792
+ return self.model
1793
+
1794
+ @add_start_docstrings_to_model_forward(BAILINGMOEV2_INPUTS_DOCSTRING)
1795
+ @replace_return_docstrings(output_type=MoEV2CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1796
+ def forward(
1797
+ self,
1798
+ input_ids: torch.LongTensor = None,
1799
+ attention_mask: Optional[torch.Tensor] = None,
1800
+ position_ids: Optional[torch.LongTensor] = None,
1801
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1802
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1803
+ labels: Optional[torch.LongTensor] = None,
1804
+ use_cache: Optional[bool] = None,
1805
+ output_attentions: Optional[bool] = None,
1806
+ output_hidden_states: Optional[bool] = None,
1807
+ output_router_logits: Optional[bool] = None,
1808
+ return_dict: Optional[bool] = None,
1809
+ **kwargs,
1810
+ ) -> Union[Tuple, MoEV2CausalLMOutputWithPast]:
1811
+ r"""
1812
+ Args:
1813
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1814
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1815
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1816
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1817
+ Returns:
1818
+ Example:
1819
+ ```python
1820
+ >>> from transformers import AutoTokenizer
1821
+ >>> model = BailingMoeV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1822
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1823
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1824
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1825
+ >>> # Generate
1826
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1827
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1828
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1829
+ ```"""
1830
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1831
+ output_hidden_states = (
1832
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1833
+ )
1834
+ output_router_logits = (
1835
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1836
+ )
1837
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1838
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1839
+ outputs = self.model(
1840
+ input_ids=input_ids,
1841
+ attention_mask=attention_mask,
1842
+ position_ids=position_ids,
1843
+ past_key_values=past_key_values,
1844
+ inputs_embeds=inputs_embeds,
1845
+ use_cache=use_cache,
1846
+ output_attentions=output_attentions,
1847
+ output_hidden_states=output_hidden_states,
1848
+ output_router_logits=output_router_logits,
1849
+ return_dict=return_dict,
1850
+ **kwargs,
1851
+ )
1852
+
1853
+ loss = None
1854
+ all_mtp_loss = None
1855
+ aux_loss = None
1856
+ hidden_states = outputs[0]
1857
+ logits = self.lm_head(hidden_states)
1858
+ logits = logits.float()
1859
+
1860
+ if labels is not None:
1861
+ loss = self.loss_function(logits, labels, self.config.vocab_size, **kwargs)
1862
+
1863
+ all_mtp_logits = None
1864
+ if self.num_nextn_predict_layers > 0:
1865
+ mtp_hidden_states = outputs.mtp_hidden_states
1866
+ shift_labels_mtp = None
1867
+ for i in range(self.num_nextn_predict_layers):
1868
+ mtp_hidden_states = mtp_hidden_states[i]
1869
+ mtp_logits = self.lm_head(mtp_hidden_states).float()
1870
+ if all_mtp_logits is None:
1871
+ all_mtp_logits = []
1872
+ all_mtp_logits.append(mtp_logits)
1873
+ if labels is not None:
1874
+ if shift_labels_mtp is None:
1875
+ shift_labels_mtp = labels.clone()
1876
+ shift_labels_mtp, _ = roll_tensor(shift_labels_mtp, shifts=-1, dims=-1, fill_value=-100)
1877
+ mtp_logits_ = mtp_logits.view(-1, self.config.vocab_size)
1878
+ mtp_loss = self.loss_function(mtp_logits_, shift_labels_mtp.to(mtp_logits_.device).view(-1), self.config.vocab_size, **kwargs)
1879
+ if loss is not None:
1880
+ loss += self.mtp_loss_scaling_factor * mtp_loss
1881
+ else:
1882
+ loss = self.mtp_loss_scaling_factor * mtp_loss
1883
+
1884
+ if all_mtp_loss is None:
1885
+ all_mtp_loss = []
1886
+ all_mtp_loss.append(mtp_loss)
1887
+
1888
+ if not return_dict:
1889
+ output = (logits,) + outputs[1:]
1890
+ if output_router_logits:
1891
+ output = (aux_loss,) + output
1892
+ return (loss,) + output if loss is not None else output
1893
+
1894
+ return MoEV2CausalLMOutputWithPast(
1895
+ loss=loss,
1896
+ mtp_loss=all_mtp_loss,
1897
+ aux_loss=aux_loss,
1898
+ logits=logits,
1899
+ mtp_logits=all_mtp_logits,
1900
+ past_key_values=outputs.past_key_values,
1901
+ hidden_states=outputs.hidden_states,
1902
+ attentions=outputs.attentions,
1903
+ router_logits=outputs.router_logits,
1904
+ )