lushuai commited on
Commit
64ed0bb
·
1 Parent(s): 8b33bd1

init model

Browse files
config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BailingMoeForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_bailing_moe.BailingMoeConfig",
8
+ "AutoModel": "modeling_bailing_moe.BailingMoeModel",
9
+ "AutoModelForCausalLM": "modeling_bailing_moe.BailingMoeForCausalLM"
10
+ },
11
+ "eos_token_id": 126081,
12
+ "pad_token_id": 126081,
13
+ "first_k_dense_replace": 0,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 2048,
16
+ "initializer_range": 0.006,
17
+ "intermediate_size": 5632,
18
+ "max_position_embeddings": 16384,
19
+ "model_type": "bailing_moe",
20
+ "moe_intermediate_size": 1408,
21
+ "num_experts": 64,
22
+ "num_shared_experts": 2,
23
+ "norm_topk_prob": true,
24
+ "num_attention_heads": 16,
25
+ "num_experts_per_tok": 6,
26
+ "num_hidden_layers": 28,
27
+ "num_key_value_heads": 4,
28
+ "pretraining_tp": 1,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": null,
31
+ "rope_theta": 600000,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.36.0",
35
+ "use_cache": true,
36
+ "use_bias": false,
37
+ "use_qkv_bias": false,
38
+ "vocab_size": 126464,
39
+ "output_router_logits": false,
40
+ "embedding_dropout": 0.1,
41
+ "norm_head": true,
42
+ "norm_softmax": false,
43
+ "output_dropout": 0.1,
44
+ "head_dim": 0
45
+ }
configuration_bailing_moe.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Bailing MoE model configuration """
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class BailingMoeConfig(PretrainedConfig):
7
+ model_type = "bailing_moe"
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=30592,
12
+ hidden_size=1024,
13
+ intermediate_size=None,
14
+ num_hidden_layers=24,
15
+ num_attention_heads=16,
16
+ num_key_value_heads=0,
17
+ hidden_act="silu",
18
+ use_qkv_bias=False, # bailing only
19
+ use_bias=True, # bailing only
20
+ rms_norm_eps=1e-05,
21
+ norm_head=False, # bailing only
22
+ tie_word_embeddings=False, # PretrainedConfig key, here change default value.
23
+ embedding_dropout=0.1,
24
+ attention_dropout=0.1,
25
+ output_dropout=0.1,
26
+ initializer_range=0.02,
27
+ max_position_embeddings=16384,
28
+ rope_theta=10000.0,
29
+ use_cache=True,
30
+ use_sliding_window=False,
31
+ sliding_window=4096,
32
+ max_window_layers=28,
33
+ rope_scaling=None,
34
+ pad_token_id=126081,
35
+ num_experts=16,
36
+ num_shared_experts=0,
37
+ num_experts_per_tok=2,
38
+ norm_topk_prob=True,
39
+ moe_intermediate_size=None,
40
+ first_k_dense_replace=0,
41
+ head_dim=None,
42
+ output_router_logits=False,
43
+ **kwargs,
44
+ ):
45
+ self.num_hidden_layers = num_hidden_layers
46
+ self.vocab_size = vocab_size
47
+ self.hidden_size = hidden_size
48
+ self.intermediate_size = intermediate_size
49
+ self.num_attention_heads = num_attention_heads
50
+ self.num_key_value_heads = num_key_value_heads
51
+ self.hidden_act = hidden_act
52
+ self.use_qkv_bias = use_qkv_bias
53
+ self.use_bias = use_bias
54
+ self.norm_head = norm_head
55
+ self.rms_norm_eps = rms_norm_eps
56
+ self.embedding_dropout = embedding_dropout
57
+ self.attention_dropout = attention_dropout
58
+ self.output_dropout = output_dropout
59
+ self.initializer_range = initializer_range
60
+ self.max_position_embeddings = max_position_embeddings
61
+ self.rope_theta = rope_theta
62
+ self.use_cache = use_cache
63
+ self.use_sliding_window = use_sliding_window
64
+ self.sliding_window = sliding_window
65
+ self.max_window_layers = max_window_layers
66
+ self.head_dim = head_dim
67
+ self.rope_scaling = rope_scaling
68
+
69
+ # MoE configs
70
+ self.num_experts = num_experts
71
+ self.num_shared_experts = num_shared_experts
72
+ self.num_experts_per_tok = num_experts_per_tok
73
+ self.norm_topk_prob = norm_topk_prob
74
+ self.moe_intermediate_size = moe_intermediate_size
75
+ self.first_k_dense_replace = first_k_dense_replace
76
+ self.output_router_logits = output_router_logits
77
+
78
+ super().__init__(pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
modeling_bailing_moe.py ADDED
@@ -0,0 +1,1439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import CrossEntropyLoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import (
40
+ MoeModelOutputWithPast,
41
+ MoeCausalLMOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
45
+ from transformers.utils import (
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ is_flash_attn_2_available,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from transformers.utils.import_utils import is_torch_fx_available
54
+ from .configuration_bailing_moe import BailingMoeConfig
55
+
56
+
57
+ if is_flash_attn_2_available():
58
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
59
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
60
+
61
+
62
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
63
+ # It means that the function will not be traced through and simply appear as a node in the graph.
64
+ if is_torch_fx_available():
65
+ if not is_torch_greater_or_equal_than_1_13:
66
+ import torch.fx
67
+
68
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
69
+
70
+
71
+ logger = logging.get_logger(__name__)
72
+
73
+ _CONFIG_FOR_DOC = "BailingMoeConfig"
74
+
75
+
76
+ def _get_unpad_data(attention_mask):
77
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
78
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
79
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
80
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
81
+ return (
82
+ indices,
83
+ cu_seqlens,
84
+ max_seqlen_in_batch,
85
+ )
86
+
87
+
88
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
89
+ warnings.warn(
90
+ "Calling `transformers.models.BailingMoe.modeling_BailingMoe._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
91
+ )
92
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
93
+
94
+
95
+ def _make_causal_mask(
96
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
97
+ ):
98
+ warnings.warn(
99
+ "Calling `transformers.models.BailingMoe.modeling_BailingMoe._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.BailingMoe.modeling_BailingMoe.AttentionMaskConverter._make_causal_mask"
100
+ )
101
+ return AttentionMaskConverter._make_causal_mask(
102
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
103
+ )
104
+
105
+
106
+ class BailingMoeRMSNorm(nn.Module):
107
+ def __init__(self, hidden_size, eps=1e-6):
108
+ """
109
+ BailingMoeRMSNorm is equivalent to T5LayerNorm
110
+ """
111
+ super().__init__()
112
+ self.weight = nn.Parameter(torch.ones(hidden_size))
113
+ self.variance_epsilon = eps
114
+
115
+ def forward(self, hidden_states):
116
+ input_dtype = hidden_states.dtype
117
+ hidden_states = hidden_states.to(torch.float32)
118
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
119
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
120
+
121
+ return (self.weight.float() * hidden_states).to(input_dtype)
122
+
123
+ ALL_LAYERNORM_LAYERS.append(BailingMoeRMSNorm)
124
+
125
+
126
+ class BailingMoeRotaryEmbedding(nn.Module):
127
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
128
+ super().__init__()
129
+
130
+ self.dim = dim
131
+ self.max_position_embeddings = max_position_embeddings
132
+ self.base = base
133
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
134
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
135
+
136
+ # Build here to make `torch.jit.trace` work.
137
+ self._set_cos_sin_cache(
138
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
139
+ )
140
+ self.max_seq_len_cached = None
141
+
142
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
143
+ self.max_seq_len_cached = seq_len
144
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
145
+
146
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
150
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
151
+
152
+ def forward(self, x, seq_len=None):
153
+ # x: [bs, num_attention_heads, seq_len, head_size]
154
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
155
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
156
+
157
+ return (
158
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
159
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
160
+ )
161
+
162
+
163
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->BailingMoe
164
+ class BailingMoeLinearScalingRotaryEmbedding(BailingMoeRotaryEmbedding):
165
+ """BailingMoeRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
166
+
167
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
168
+ self.scaling_factor = scaling_factor
169
+ super().__init__(dim, max_position_embeddings, base, device)
170
+
171
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
172
+ self.max_seq_len_cached = seq_len
173
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
174
+ t = t / self.scaling_factor
175
+
176
+ freqs = torch.outer(t, self.inv_freq)
177
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
178
+ emb = torch.cat((freqs, freqs), dim=-1)
179
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
180
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
181
+
182
+
183
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->BailingMoe
184
+ class BailingMoeDynamicNTKScalingRotaryEmbedding(BailingMoeRotaryEmbedding):
185
+ """BailingMoeRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
186
+
187
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
188
+ self.scaling_factor = scaling_factor
189
+ super().__init__(dim, max_position_embeddings, base, device)
190
+
191
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
192
+ self.max_seq_len_cached = seq_len
193
+
194
+ if seq_len > self.max_position_embeddings:
195
+ base = self.base * (
196
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
197
+ ) ** (self.dim / (self.dim - 2))
198
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
199
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
200
+
201
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
202
+
203
+ freqs = torch.outer(t, self.inv_freq)
204
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
205
+ emb = torch.cat((freqs, freqs), dim=-1)
206
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
207
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
208
+
209
+
210
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
211
+ def rotate_half(x):
212
+ """Rotates half the hidden dims of the input."""
213
+ x1 = x[..., : x.shape[-1] // 2]
214
+ x2 = x[..., x.shape[-1] // 2 :]
215
+ return torch.cat((-x2, x1), dim=-1)
216
+
217
+
218
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
219
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
220
+ """Applies Rotary Position Embedding to the query and key tensors.
221
+
222
+ Args:
223
+ q (`torch.Tensor`): The query tensor.
224
+ k (`torch.Tensor`): The key tensor.
225
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
226
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
227
+ position_ids (`torch.Tensor`):
228
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
229
+ used to pass offsetted position ids when working with a KV-cache.
230
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
231
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
232
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
233
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
234
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
235
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
236
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
237
+ Returns:
238
+ `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding.
239
+ """
240
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
241
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
242
+ q_embed = (q * cos) + (rotate_half(q) * sin)
243
+ k_embed = (k * cos) + (rotate_half(k) * sin)
244
+ return q_embed, k_embed
245
+
246
+
247
+ class BailingMoeMLP(nn.Module):
248
+ def __init__(self, config: BailingMoeConfig, intermediate_size: int):
249
+ super().__init__()
250
+ self.config = config
251
+ self.hidden_size = config.hidden_size
252
+ self.intermediate_size = intermediate_size
253
+
254
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
255
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
256
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
257
+ self.act_fn = ACT2FN[config.hidden_act]
258
+
259
+ def forward(self, x):
260
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
261
+
262
+
263
+ class BailingMoeGate(nn.Module):
264
+ def __init__(self, config):
265
+ super().__init__()
266
+ self.config = config
267
+ self.top_k = config.num_experts_per_tok
268
+ self.num_experts = config.num_experts
269
+
270
+ # topk selection algorithm
271
+ self.norm_topk_prob = config.norm_topk_prob
272
+ self.gating_dim = config.hidden_size
273
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
274
+ self.reset_parameters()
275
+
276
+ def reset_parameters(self) -> None:
277
+ import torch.nn.init as init
278
+
279
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
280
+
281
+ def forward(self, hidden_states):
282
+ bsz, seq_len, h = hidden_states.shape
283
+ # compute gating score
284
+ hidden_states = hidden_states.view(-1, h)
285
+ logits = F.linear(hidden_states, self.weight, None)
286
+ scores = logits.softmax(dim=-1, dtype=torch.float32)
287
+
288
+ # select top-k experts
289
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
290
+
291
+ # norm gate to sum 1
292
+ if self.top_k > 1 and self.norm_topk_prob:
293
+ denominator = topk_weight.sum(dim=-1, keepdim=True)
294
+ topk_weight = topk_weight / denominator
295
+
296
+ return topk_idx, topk_weight, logits
297
+
298
+
299
+ class BailingMoeSparseMoeBlock(nn.Module):
300
+ """
301
+ A mixed expert module containing shared experts.
302
+ """
303
+
304
+ def __init__(self, config: BailingMoeConfig):
305
+ super().__init__()
306
+ self.config = config
307
+ self.num_experts_per_tok = config.num_experts_per_tok
308
+ self.experts = self._setup_experts()
309
+ self.gate = BailingMoeGate(config)
310
+ if config.num_shared_experts is not None:
311
+ self.shared_experts = BailingMoeMLP(
312
+ config=config, intermediate_size=config.moe_intermediate_size * config.num_shared_experts
313
+ )
314
+
315
+ def _setup_experts(self):
316
+ return nn.ModuleList(
317
+ [
318
+ BailingMoeMLP(config=self.config, intermediate_size=self.config.moe_intermediate_size)
319
+ for _ in range(self.config.num_experts)
320
+ ]
321
+ )
322
+
323
+ def forward(self, hidden_states):
324
+ identity = hidden_states
325
+ bsz, seq_len, h = hidden_states.shape
326
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
327
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
328
+ flat_topk_idx = topk_idx.view(-1)
329
+ if self.training:
330
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
331
+ y = torch.empty_like(hidden_states)
332
+ for i, expert in enumerate(self.experts):
333
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
334
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
335
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
336
+ else:
337
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(bsz, seq_len, h)
338
+ if self.config.num_shared_experts is not None:
339
+ y = y + self.shared_experts(identity)
340
+ return y, (router_logits.view(bsz, seq_len, -1), topk_idx.view(bsz, seq_len, -1))
341
+
342
+ @torch.no_grad()
343
+ def moe_infer(self, x, topk_ids, topk_weight):
344
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
345
+ cnts.scatter_(1, topk_ids, 1)
346
+ tokens_per_expert = cnts.sum(dim=0)
347
+ idxs = topk_ids.view(-1).argsort()
348
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
349
+ sorted_tokens_shape = sorted_tokens.shape
350
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
351
+ outputs = []
352
+ start_idx = 0
353
+ for i, num_tokens in enumerate(tokens_per_expert):
354
+ end_idx = start_idx + num_tokens
355
+ if num_tokens == 0:
356
+ continue
357
+ expert = self.experts[i]
358
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
359
+ expert_out = expert(tokens_for_this_expert)
360
+ outputs.append(expert_out)
361
+ start_idx = end_idx
362
+
363
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
364
+ new_x = torch.empty_like(outs)
365
+ new_x[idxs] = outs
366
+ final_out = (
367
+ new_x.view(*topk_ids.shape, -1)
368
+ .type(topk_weight.dtype)
369
+ .mul_(topk_weight.unsqueeze(dim=-1))
370
+ .sum(dim=1)
371
+ .type(new_x.dtype)
372
+ )
373
+ return final_out
374
+
375
+
376
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
377
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
378
+ """
379
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
380
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
381
+ """
382
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
383
+ if n_rep == 1:
384
+ return hidden_states
385
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
386
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
387
+
388
+
389
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->BailingMoe
390
+ class BailingMoeAttention(nn.Module):
391
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
392
+
393
+ def __init__(self, config: BailingMoeConfig, layer_idx: Optional[int] = None):
394
+ super().__init__()
395
+ self.config = config
396
+ self.layer_idx = layer_idx
397
+ if layer_idx is None:
398
+ logger.warning_once(
399
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
400
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
401
+ "when creating this class."
402
+ )
403
+
404
+ self.attention_dropout = config.attention_dropout
405
+ self.hidden_size = config.hidden_size
406
+ self.num_heads = config.num_attention_heads
407
+ self.head_dim = config.head_dim or self.hidden_size // self.num_heads
408
+ self.num_key_value_heads = config.num_key_value_heads
409
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
410
+ self.max_position_embeddings = config.max_position_embeddings
411
+ self.rope_theta = config.rope_theta
412
+ self.is_causal = True
413
+
414
+ self.query_key_value = nn.Linear(
415
+ self.hidden_size,
416
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
417
+ bias=config.use_qkv_bias,
418
+ )
419
+ self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias)
420
+ self._init_rope()
421
+
422
+ def _init_rope(self):
423
+ if self.config.rope_scaling is None:
424
+ self.rotary_emb = BailingMoeRotaryEmbedding(
425
+ self.head_dim,
426
+ max_position_embeddings=self.max_position_embeddings,
427
+ base=self.rope_theta,
428
+ )
429
+ else:
430
+ scaling_type = self.config.rope_scaling["type"]
431
+ scaling_factor = self.config.rope_scaling["factor"]
432
+ if scaling_type == "linear":
433
+ self.rotary_emb = BailingMoeLinearScalingRotaryEmbedding(
434
+ self.head_dim,
435
+ max_position_embeddings=self.max_position_embeddings,
436
+ scaling_factor=scaling_factor,
437
+ base=self.rope_theta,
438
+ )
439
+ elif scaling_type == "dynamic":
440
+ self.rotary_emb = BailingMoeDynamicNTKScalingRotaryEmbedding(
441
+ self.head_dim,
442
+ max_position_embeddings=self.max_position_embeddings,
443
+ scaling_factor=scaling_factor,
444
+ base=self.rope_theta,
445
+ )
446
+ else:
447
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
448
+
449
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
450
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
451
+
452
+ def forward(
453
+ self,
454
+ hidden_states: torch.Tensor,
455
+ attention_mask: Optional[torch.Tensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ past_key_value: Optional[Cache] = None,
458
+ output_attentions: bool = False,
459
+ use_cache: bool = False,
460
+ **kwargs,
461
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
462
+ if "padding_mask" in kwargs:
463
+ warnings.warn(
464
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
465
+ )
466
+
467
+ bsz, q_len, _ = hidden_states.size()
468
+
469
+ qkv = self.query_key_value(hidden_states)
470
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
471
+
472
+ query_states, key_states, value_states = qkv.split(
473
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
474
+ )
475
+ query_states = query_states.transpose(1, 2)
476
+ key_states = key_states.transpose(1, 2)
477
+ value_states = value_states.transpose(1, 2)
478
+
479
+ kv_seq_len = key_states.shape[-2]
480
+ if past_key_value is not None:
481
+ if self.layer_idx is None:
482
+ raise ValueError(
483
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
484
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
485
+ "with a layer index."
486
+ )
487
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
488
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
489
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
490
+
491
+ if past_key_value is not None:
492
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
493
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
494
+
495
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
496
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
497
+
498
+ attn_weights = torch.matmul(query_states / math.sqrt(self.head_dim), key_states.transpose(2, 3))
499
+
500
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
501
+ raise ValueError(
502
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
503
+ f" {attn_weights.size()}"
504
+ )
505
+
506
+ if attention_mask is not None:
507
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
508
+ raise ValueError(
509
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
510
+ )
511
+ attn_weights = attn_weights + attention_mask
512
+
513
+ # upcast attention to fp32
514
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
515
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
516
+ attn_output = torch.matmul(attn_weights, value_states)
517
+
518
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
519
+ raise ValueError(
520
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
521
+ f" {attn_output.size()}"
522
+ )
523
+
524
+ attn_output = attn_output.transpose(1, 2).contiguous()
525
+
526
+ attn_output = attn_output.reshape(bsz, q_len, -1)
527
+
528
+ attn_output = self.dense(attn_output)
529
+
530
+ if not output_attentions:
531
+ attn_weights = None
532
+
533
+ return attn_output, attn_weights, past_key_value
534
+
535
+
536
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->BailingMoe
537
+ class BailingMoeFlashAttention2(BailingMoeAttention):
538
+ """
539
+ BailingMoe flash attention module. This module inherits from `BailingMoeAttention` as the weights of the module stays
540
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
541
+ flash attention and deal with padding tokens in case the input contains any of them.
542
+ """
543
+
544
+ def __init__(self, *args, **kwargs):
545
+ super().__init__(*args, **kwargs)
546
+
547
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
548
+ # 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.
549
+ # 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).
550
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
551
+
552
+ def forward(
553
+ self,
554
+ hidden_states: torch.Tensor,
555
+ attention_mask: Optional[torch.LongTensor] = None,
556
+ position_ids: Optional[torch.LongTensor] = None,
557
+ past_key_value: Optional[Cache] = None,
558
+ output_attentions: bool = False,
559
+ use_cache: bool = False,
560
+ **kwargs,
561
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
562
+ # BailingMoeFlashAttention2 attention does not support output_attentions
563
+ if "padding_mask" in kwargs:
564
+ warnings.warn(
565
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
566
+ )
567
+
568
+ # overwrite attention_mask with padding_mask
569
+ attention_mask = kwargs.pop("padding_mask")
570
+
571
+ output_attentions = False
572
+
573
+ bsz, q_len, _ = hidden_states.size()
574
+
575
+ # Flash attention requires the input to have the shape
576
+ # batch_size x seq_length x head_dim x hidden_dim
577
+ # therefore we just need to keep the original shape
578
+
579
+ qkv = self.query_key_value(hidden_states)
580
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
581
+
582
+ query_states, key_states, value_states = qkv.split(
583
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
584
+ )
585
+ query_states = query_states.transpose(1, 2)
586
+ key_states = key_states.transpose(1, 2)
587
+ value_states = value_states.transpose(1, 2)
588
+
589
+ kv_seq_len = key_states.shape[-2]
590
+ if past_key_value is not None:
591
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
592
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
593
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
594
+
595
+ if past_key_value is not None:
596
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
597
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
598
+
599
+ # 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
600
+ # to be able to avoid many of these transpose/reshape/view.
601
+ query_states = query_states.transpose(1, 2)
602
+ key_states = key_states.transpose(1, 2)
603
+ value_states = value_states.transpose(1, 2)
604
+
605
+ dropout_rate = self.attention_dropout if self.training else 0.0
606
+
607
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
608
+ # therefore the input hidden states gets silently cast in float32. Hence, we need
609
+ # cast them back in the correct dtype just to be sure everything works as expected.
610
+ # This might slow down training & inference so it is recommended to not cast the LayerNorms
611
+ # in fp32. (BailingMoeRMSNorm handles it correctly)
612
+
613
+ input_dtype = query_states.dtype
614
+ if input_dtype == torch.float32:
615
+ # Handle the case where the model is quantized
616
+ if hasattr(self.config, "_pre_quantization_dtype"):
617
+ target_dtype = self.config._pre_quantization_dtype
618
+ elif torch.is_autocast_enabled():
619
+ target_dtype = torch.get_autocast_gpu_dtype()
620
+ else:
621
+ target_dtype = self.q_proj.weight.dtype
622
+
623
+ logger.warning_once(
624
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
625
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
626
+ f" {target_dtype}."
627
+ )
628
+
629
+ query_states = query_states.to(target_dtype)
630
+ key_states = key_states.to(target_dtype)
631
+ value_states = value_states.to(target_dtype)
632
+
633
+ attn_output = self._flash_attention_forward(
634
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
635
+ )
636
+
637
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
638
+ attn_output = self.dense(attn_output)
639
+
640
+ if not output_attentions:
641
+ attn_weights = None
642
+
643
+ return attn_output, attn_weights, past_key_value
644
+
645
+ def _flash_attention_forward(
646
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
647
+ ):
648
+ """
649
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
650
+ first unpad the input, then computes the attention scores and pad the final attention scores.
651
+
652
+ Args:
653
+ query_states (`torch.Tensor`):
654
+ Input query states to be passed to Flash Attention API
655
+ key_states (`torch.Tensor`):
656
+ Input key states to be passed to Flash Attention API
657
+ value_states (`torch.Tensor`):
658
+ Input value states to be passed to Flash Attention API
659
+ attention_mask (`torch.Tensor`):
660
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
661
+ position of padding tokens and 1 for the position of non-padding tokens.
662
+ dropout (`int`, *optional*):
663
+ Attention dropout
664
+ softmax_scale (`float`, *optional*):
665
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
666
+ query_length (`int`):
667
+ The length of the query sequence in terms of tokens. This represents the number of tokens in the
668
+ `query_states` tensor along the sequence dimension. It is used to determine the effective sequence
669
+ length for attention computations.
670
+ """
671
+ if not self._flash_attn_uses_top_left_mask:
672
+ causal = self.is_causal
673
+ else:
674
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in BailingMoeFlashAttention2 __init__.
675
+ causal = self.is_causal and query_length != 1
676
+
677
+ # Contains at least one padding token in the sequence
678
+ if attention_mask is not None:
679
+ batch_size = query_states.shape[0]
680
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
681
+ query_states, key_states, value_states, attention_mask, query_length
682
+ )
683
+
684
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
685
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
686
+
687
+ attn_output_unpad = flash_attn_varlen_func(
688
+ query_states,
689
+ key_states,
690
+ value_states,
691
+ cu_seqlens_q=cu_seqlens_q,
692
+ cu_seqlens_k=cu_seqlens_k,
693
+ max_seqlen_q=max_seqlen_in_batch_q,
694
+ max_seqlen_k=max_seqlen_in_batch_k,
695
+ dropout_p=dropout,
696
+ softmax_scale=softmax_scale,
697
+ causal=causal,
698
+ )
699
+
700
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
701
+ else:
702
+ attn_output = flash_attn_func(
703
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
704
+ )
705
+
706
+ return attn_output
707
+
708
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
709
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
710
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
711
+
712
+ key_layer = index_first_axis(
713
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
714
+ )
715
+ value_layer = index_first_axis(
716
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
717
+ )
718
+ if query_length == kv_seq_len:
719
+ query_layer = index_first_axis(
720
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
721
+ )
722
+ cu_seqlens_q = cu_seqlens_k
723
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
724
+ indices_q = indices_k
725
+ elif query_length == 1:
726
+ max_seqlen_in_batch_q = 1
727
+ cu_seqlens_q = torch.arange(
728
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
729
+ ) # There is a memcpy here, that is very bad.
730
+ indices_q = cu_seqlens_q[:-1]
731
+ query_layer = query_layer.squeeze(1)
732
+ else:
733
+ # The -q_len: slice assumes left padding.
734
+ attention_mask = attention_mask[:, -query_length:]
735
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
736
+
737
+ return (
738
+ query_layer,
739
+ key_layer,
740
+ value_layer,
741
+ indices_q,
742
+ (cu_seqlens_q, cu_seqlens_k),
743
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
744
+ )
745
+
746
+
747
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->BailingMoe
748
+ class BailingMoeSdpaAttention(BailingMoeAttention):
749
+ """
750
+ BailingMoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
751
+ `BailingMoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
752
+ SDPA API.
753
+ """
754
+
755
+ # Adapted from BailingMoeAttention.forward
756
+ def forward(
757
+ self,
758
+ hidden_states: torch.Tensor,
759
+ attention_mask: Optional[torch.Tensor] = None,
760
+ position_ids: Optional[torch.LongTensor] = None,
761
+ past_key_value: Optional[Cache] = None,
762
+ output_attentions: bool = False,
763
+ use_cache: bool = False,
764
+ **kwargs,
765
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
766
+ if output_attentions:
767
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
768
+ logger.warning_once(
769
+ "BailingMoeModel is using BailingMoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
770
+ '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.'
771
+ )
772
+ return super().forward(
773
+ hidden_states=hidden_states,
774
+ attention_mask=attention_mask,
775
+ position_ids=position_ids,
776
+ past_key_value=past_key_value,
777
+ output_attentions=output_attentions,
778
+ use_cache=use_cache,
779
+ )
780
+
781
+ bsz, q_len, _ = hidden_states.size()
782
+
783
+ qkv = self.query_key_value(hidden_states)
784
+ qkv = qkv.view(bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
785
+
786
+ query_states, key_states, value_states = qkv.split(
787
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
788
+ )
789
+ query_states = query_states.transpose(1, 2)
790
+ key_states = key_states.transpose(1, 2)
791
+ value_states = value_states.transpose(1, 2)
792
+
793
+ kv_seq_len = key_states.shape[-2]
794
+ if past_key_value is not None:
795
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
796
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
797
+
798
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
799
+
800
+ if past_key_value is not None:
801
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
802
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
803
+
804
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
805
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
806
+
807
+ if attention_mask is not None:
808
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
809
+ raise ValueError(
810
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
811
+ )
812
+
813
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
814
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
815
+ if query_states.device.type == "cuda" and attention_mask is not None:
816
+ query_states = query_states.contiguous()
817
+ key_states = key_states.contiguous()
818
+ value_states = value_states.contiguous()
819
+
820
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
821
+ query_states,
822
+ key_states,
823
+ value_states,
824
+ attn_mask=attention_mask,
825
+ dropout_p=self.attention_dropout if self.training else 0.0,
826
+ # 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.
827
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
828
+ # enable_gqa=True
829
+ )
830
+
831
+ attn_output = attn_output.transpose(1, 2).contiguous()
832
+ attn_output = attn_output.reshape(bsz, q_len, -1)
833
+
834
+ attn_output = self.dense(attn_output)
835
+
836
+ return attn_output, None, past_key_value
837
+
838
+
839
+ BAILING_MOE_ATTENTION_CLASSES = {
840
+ "eager": BailingMoeAttention,
841
+ "flash_attention_2": BailingMoeFlashAttention2,
842
+ "sdpa": BailingMoeSdpaAttention,
843
+ }
844
+
845
+
846
+ class BailingMoeDecoderLayer(nn.Module):
847
+ def __init__(self, config: BailingMoeConfig, layer_idx: int):
848
+ super().__init__()
849
+ self.hidden_size = config.hidden_size
850
+ self.attention = BAILING_MOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
851
+
852
+ self.mlp = (
853
+ BailingMoeSparseMoeBlock(config)
854
+ if (config.num_experts is not None and layer_idx >= config.first_k_dense_replace)
855
+ else BailingMoeMLP(config=config, intermediate_size=config.intermediate_size)
856
+ )
857
+ self.input_layernorm = BailingMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
858
+ self.post_attention_layernorm = BailingMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
859
+
860
+ def forward(
861
+ self,
862
+ hidden_states: torch.Tensor,
863
+ attention_mask: Optional[torch.Tensor] = None,
864
+ position_ids: Optional[torch.LongTensor] = None,
865
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
866
+ output_attentions: Optional[bool] = False,
867
+ output_router_logits: Optional[bool] = False,
868
+ use_cache: Optional[bool] = False,
869
+ **kwargs,
870
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
871
+ """
872
+ Args:
873
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
874
+ attention_mask (`torch.FloatTensor`, *optional*):
875
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
876
+ query_sequence_length, key_sequence_length)` if default attention is used.
877
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
878
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
879
+ config.n_positions - 1]`.
880
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
881
+ cached past key and value projection states
882
+ output_attentions (`bool`, *optional*):
883
+ Whether to return the attentions tensors of all attention layers. See `attentions` under
884
+ returned tensors for more detail.
885
+ output_router_logits (`bool`, *optional*):
886
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
887
+ and should not be returned during inference.
888
+ use_cache (`bool`, *optional*):
889
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
890
+ (see `past_key_values`).
891
+ """
892
+ if "padding_mask" in kwargs:
893
+ warnings.warn(
894
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
895
+ )
896
+ residual = hidden_states
897
+
898
+ hidden_states = self.input_layernorm(hidden_states)
899
+
900
+ # Self Attention
901
+ hidden_states, self_attn_weights, present_key_value = self.attention(
902
+ hidden_states=hidden_states,
903
+ attention_mask=attention_mask,
904
+ position_ids=position_ids,
905
+ past_key_value=past_key_value,
906
+ output_attentions=output_attentions,
907
+ use_cache=use_cache,
908
+ )
909
+ hidden_states = residual + hidden_states
910
+
911
+ # Fully Connected
912
+ residual = hidden_states
913
+ hidden_states = self.post_attention_layernorm(hidden_states)
914
+ hidden_states = self.mlp(hidden_states)
915
+ if isinstance(hidden_states, tuple):
916
+ hidden_states, router_logits = hidden_states
917
+ else:
918
+ router_logits = None
919
+ hidden_states = residual + hidden_states
920
+
921
+ outputs = (hidden_states,)
922
+
923
+ if output_attentions:
924
+ outputs += (self_attn_weights,)
925
+
926
+ if use_cache:
927
+ outputs += (present_key_value,)
928
+
929
+ if output_router_logits:
930
+ outputs += (router_logits,)
931
+
932
+ return outputs
933
+
934
+
935
+ BAILINGMOE_START_DOCSTRING = r"""
936
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
937
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
938
+ etc.)
939
+
940
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
941
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
942
+ and behavior.
943
+
944
+ Parameters:
945
+ config ([`BailingMoeConfig`]):
946
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
947
+ load the weights associated with the model, only the configuration. Check out the
948
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
949
+ """
950
+
951
+
952
+ @add_start_docstrings(
953
+ "The bare BailingMoe Model outputting raw hidden-states without any specific head on top.",
954
+ BAILINGMOE_START_DOCSTRING,
955
+ )
956
+ class BailingMoePreTrainedModel(PreTrainedModel):
957
+ config_class = BailingMoeConfig
958
+ base_model_prefix = "model"
959
+ supports_gradient_checkpointing = True
960
+ _no_split_modules = ["BailingMoeDecoderLayer"]
961
+ _skip_keys_device_placement = "past_key_values"
962
+ _supports_flash_attn_2 = True
963
+ _supports_sdpa = True
964
+ _supports_cache_class = True
965
+
966
+ def _init_weights(self, module):
967
+ std = self.config.initializer_range
968
+ if isinstance(module, nn.Linear):
969
+ module.weight.data.normal_(mean=0.0, std=std)
970
+ if module.bias is not None:
971
+ module.bias.data.zero_()
972
+ elif isinstance(module, nn.Embedding):
973
+ module.weight.data.normal_(mean=0.0, std=std)
974
+ if module.padding_idx is not None:
975
+ module.weight.data[module.padding_idx].zero_()
976
+
977
+
978
+ BAILINGMOE_INPUTS_DOCSTRING = r"""
979
+ Args:
980
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
981
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
982
+ it.
983
+
984
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
985
+ [`PreTrainedTokenizer.__call__`] for details.
986
+
987
+ [What are input IDs?](../glossary#input-ids)
988
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
989
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
990
+
991
+ - 1 for tokens that are **not masked**,
992
+ - 0 for tokens that are **masked**.
993
+
994
+ [What are attention masks?](../glossary#attention-mask)
995
+
996
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
997
+ [`PreTrainedTokenizer.__call__`] for details.
998
+
999
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1000
+ `past_key_values`).
1001
+
1002
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1003
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1004
+ information on the default strategy.
1005
+
1006
+ - 1 indicates the head is **not masked**,
1007
+ - 0 indicates the head is **masked**.
1008
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1009
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1010
+ config.n_positions - 1]`.
1011
+
1012
+ [What are position IDs?](../glossary#position-ids)
1013
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1014
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1015
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1016
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1017
+
1018
+ Two formats are allowed:
1019
+ - a [`~cache_utils.Cache`] instance;
1020
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1021
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1022
+ cache format.
1023
+
1024
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1025
+ legacy cache format will be returned.
1026
+
1027
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1028
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1029
+ of shape `(batch_size, sequence_length)`.
1030
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1031
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1032
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1033
+ model's internal embedding lookup matrix.
1034
+ use_cache (`bool`, *optional*):
1035
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1036
+ `past_key_values`).
1037
+ output_attentions (`bool`, *optional*):
1038
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1039
+ tensors for more detail.
1040
+ output_hidden_states (`bool`, *optional*):
1041
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1042
+ more detail.
1043
+ return_dict (`bool`, *optional*):
1044
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1045
+ """
1046
+
1047
+
1048
+ @add_start_docstrings(
1049
+ "The bare BailingMoe Model outputting raw hidden-states without any specific head on top.",
1050
+ BAILINGMOE_START_DOCSTRING,
1051
+ )
1052
+ class BailingMoeModel(BailingMoePreTrainedModel):
1053
+ """
1054
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeDecoderLayer`]
1055
+
1056
+ Args:
1057
+ config: BailingMoeConfig
1058
+ """
1059
+
1060
+ def __init__(self, config: BailingMoeConfig):
1061
+ super().__init__(config)
1062
+ self.padding_idx = config.pad_token_id
1063
+ self.vocab_size = config.vocab_size
1064
+
1065
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1066
+ self.layers = nn.ModuleList(
1067
+ [BailingMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1068
+ )
1069
+ self._use_sdpa = config._attn_implementation == "sdpa"
1070
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1071
+ self.norm = BailingMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1072
+
1073
+ self.gradient_checkpointing = False
1074
+ # Initialize weights and apply final processing
1075
+ self.post_init()
1076
+
1077
+ def get_input_embeddings(self):
1078
+ return self.word_embeddings
1079
+
1080
+ def set_input_embeddings(self, value):
1081
+ self.word_embeddings = value
1082
+
1083
+ @add_start_docstrings_to_model_forward(BAILINGMOE_INPUTS_DOCSTRING)
1084
+ def forward(
1085
+ self,
1086
+ input_ids: torch.LongTensor = None,
1087
+ attention_mask: Optional[torch.Tensor] = None,
1088
+ position_ids: Optional[torch.LongTensor] = None,
1089
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1090
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1091
+ use_cache: Optional[bool] = None,
1092
+ output_attentions: Optional[bool] = None,
1093
+ output_hidden_states: Optional[bool] = None,
1094
+ output_router_logits: Optional[bool] = None,
1095
+ return_dict: Optional[bool] = None,
1096
+ **kwargs,
1097
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1098
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1099
+ output_hidden_states = (
1100
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1101
+ )
1102
+ output_router_logits = (
1103
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1104
+ )
1105
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1106
+
1107
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1108
+
1109
+ # retrieve input_ids and inputs_embeds
1110
+ if input_ids is not None and inputs_embeds is not None:
1111
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1112
+ elif input_ids is not None:
1113
+ batch_size, seq_length = input_ids.shape[:2]
1114
+ elif inputs_embeds is not None:
1115
+ batch_size, seq_length = inputs_embeds.shape[:2]
1116
+ else:
1117
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1118
+
1119
+ if self.gradient_checkpointing and self.training:
1120
+ if use_cache:
1121
+ logger.warning_once(
1122
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1123
+ )
1124
+ use_cache = False
1125
+
1126
+ past_key_values_length = 0
1127
+ if use_cache:
1128
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1129
+ if use_legacy_cache:
1130
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1131
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1132
+
1133
+ if position_ids is None:
1134
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1135
+ position_ids = torch.arange(
1136
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1137
+ )
1138
+ position_ids = position_ids.unsqueeze(0)
1139
+
1140
+ if inputs_embeds is None:
1141
+ inputs_embeds = self.word_embeddings(input_ids)
1142
+
1143
+ if self._use_flash_attention_2:
1144
+ # 2d mask is passed through the layers
1145
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1146
+ elif self._use_sdpa and not output_attentions:
1147
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1148
+ # the manual implementation that requires a 4D causal mask in all cases.
1149
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1150
+ attention_mask,
1151
+ (batch_size, seq_length),
1152
+ inputs_embeds,
1153
+ past_key_values_length,
1154
+ )
1155
+ else:
1156
+ # 4d mask is passed through the layers
1157
+ attention_mask = _prepare_4d_causal_attention_mask(
1158
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1159
+ )
1160
+
1161
+ # embed positions
1162
+ hidden_states = inputs_embeds
1163
+
1164
+ # decoder layers
1165
+ all_hidden_states = () if output_hidden_states else None
1166
+ all_self_attns = () if output_attentions else None
1167
+ all_router_logits = () if output_router_logits else None
1168
+ next_decoder_cache = None
1169
+
1170
+ for layer_idx, decoder_layer in enumerate(self.layers):
1171
+ if output_hidden_states:
1172
+ all_hidden_states += (hidden_states,)
1173
+
1174
+ if self.gradient_checkpointing and self.training:
1175
+ layer_outputs = self._gradient_checkpointing_func(
1176
+ decoder_layer.__call__,
1177
+ hidden_states,
1178
+ attention_mask,
1179
+ position_ids,
1180
+ past_key_values,
1181
+ output_attentions,
1182
+ output_router_logits,
1183
+ use_cache,
1184
+ )
1185
+ else:
1186
+ layer_outputs = decoder_layer(
1187
+ hidden_states,
1188
+ attention_mask=attention_mask,
1189
+ position_ids=position_ids,
1190
+ past_key_value=past_key_values,
1191
+ output_attentions=output_attentions,
1192
+ output_router_logits=output_router_logits,
1193
+ use_cache=use_cache,
1194
+ )
1195
+ hidden_states = layer_outputs[0]
1196
+
1197
+ if use_cache:
1198
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1199
+
1200
+ if output_attentions:
1201
+ all_self_attns += (layer_outputs[1],)
1202
+
1203
+ if output_router_logits and layer_outputs[-1] is not None:
1204
+ all_router_logits += (layer_outputs[-1],)
1205
+
1206
+ hidden_states = self.norm(hidden_states)
1207
+
1208
+ # add hidden states from the last decoder layer
1209
+ if output_hidden_states:
1210
+ all_hidden_states += (hidden_states,)
1211
+
1212
+ next_cache = None
1213
+ if use_cache:
1214
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1215
+ if not return_dict:
1216
+ return tuple(
1217
+ v
1218
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1219
+ if v is not None
1220
+ )
1221
+ return MoeModelOutputWithPast(
1222
+ last_hidden_state=hidden_states,
1223
+ past_key_values=next_cache,
1224
+ hidden_states=all_hidden_states,
1225
+ attentions=all_self_attns,
1226
+ router_logits=all_router_logits,
1227
+ )
1228
+
1229
+
1230
+ class BailingMoeForCausalLM(BailingMoePreTrainedModel):
1231
+ _tied_weights_keys = ["lm_head.weight"]
1232
+
1233
+ def __init__(self, config: BailingMoeConfig):
1234
+ super().__init__(config)
1235
+ self.model = BailingMoeModel(config)
1236
+ self.vocab_size = config.vocab_size
1237
+ self.norm_head = config.norm_head
1238
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1239
+
1240
+ # Initialize weights and apply final processing
1241
+ self.post_init()
1242
+
1243
+ def get_input_embeddings(self):
1244
+ return self.model.word_embeddings
1245
+
1246
+ def set_input_embeddings(self, value):
1247
+ self.model.word_embeddings = value
1248
+
1249
+ def get_output_embeddings(self):
1250
+ return self.lm_head
1251
+
1252
+ def set_output_embeddings(self, new_embeddings):
1253
+ self.lm_head = new_embeddings
1254
+
1255
+ def set_decoder(self, decoder):
1256
+ self.model = decoder
1257
+
1258
+ def get_decoder(self):
1259
+ return self.model
1260
+
1261
+ @add_start_docstrings_to_model_forward(BAILINGMOE_INPUTS_DOCSTRING)
1262
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1263
+ def forward(
1264
+ self,
1265
+ input_ids: torch.LongTensor = None,
1266
+ attention_mask: Optional[torch.Tensor] = None,
1267
+ position_ids: Optional[torch.LongTensor] = None,
1268
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1269
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1270
+ labels: Optional[torch.LongTensor] = None,
1271
+ use_cache: Optional[bool] = None,
1272
+ output_attentions: Optional[bool] = None,
1273
+ output_hidden_states: Optional[bool] = None,
1274
+ output_router_logits: Optional[bool] = None,
1275
+ return_dict: Optional[bool] = None,
1276
+ **kwargs,
1277
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1278
+ r"""
1279
+ Args:
1280
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1281
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1282
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1283
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1284
+
1285
+ Returns:
1286
+
1287
+ Example:
1288
+
1289
+ ```python
1290
+ >>> from transformers import AutoTokenizer
1291
+
1292
+ >>> model = BailingMoeForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1293
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1294
+
1295
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1296
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1297
+
1298
+ >>> # Generate
1299
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1300
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1301
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1302
+ ```"""
1303
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1304
+ output_hidden_states = (
1305
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1306
+ )
1307
+ output_router_logits = (
1308
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1309
+ )
1310
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1311
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1312
+ outputs = self.model(
1313
+ input_ids=input_ids,
1314
+ attention_mask=attention_mask,
1315
+ position_ids=position_ids,
1316
+ past_key_values=past_key_values,
1317
+ inputs_embeds=inputs_embeds,
1318
+ use_cache=use_cache,
1319
+ output_attentions=output_attentions,
1320
+ output_hidden_states=output_hidden_states,
1321
+ output_router_logits=output_router_logits,
1322
+ return_dict=return_dict,
1323
+ **kwargs,
1324
+ )
1325
+
1326
+ hidden_states = outputs[0]
1327
+
1328
+ if self.norm_head:
1329
+ if self.training:
1330
+ norm_weight = (
1331
+ self.lm_head.weight / (torch.norm(self.lm_head.weight, p=2, dim=0, keepdim=True) + 1e-7).detach()
1332
+ )
1333
+ logits = F.linear(hidden_states, norm_weight, None)
1334
+ else:
1335
+ self.lm_head.weight.data = (self.lm_head.weight.data.float() / (
1336
+ torch.norm(self.lm_head.weight.data.float(), p=2, dim=0, keepdim=True) + 1e-7
1337
+ )).to(hidden_states.dtype)
1338
+ logits = F.linear(hidden_states, self.lm_head.weight.data, None)
1339
+ self.norm_head = False
1340
+ else:
1341
+ logits = self.lm_head(hidden_states)
1342
+
1343
+ logits = logits.float()
1344
+
1345
+ loss = None
1346
+ aux_loss = None
1347
+
1348
+ if labels is not None:
1349
+ # Shift so that tokens < n predict n
1350
+ shift_logits = logits[..., :-1, :].contiguous()
1351
+ shift_labels = labels[..., 1:].contiguous()
1352
+ # Flatten the tokens
1353
+ loss_fct = CrossEntropyLoss()
1354
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1355
+ shift_labels = shift_labels.view(-1)
1356
+ # Enable model parallelism
1357
+ shift_labels = shift_labels.to(shift_logits.device)
1358
+ loss = loss_fct(shift_logits, shift_labels)
1359
+
1360
+ if not return_dict:
1361
+ output = (logits,) + outputs[1:]
1362
+ if output_router_logits:
1363
+ output = (aux_loss,) + output
1364
+ return (loss,) + output if loss is not None else output
1365
+
1366
+ return MoeCausalLMOutputWithPast(
1367
+ loss=loss,
1368
+ aux_loss=aux_loss,
1369
+ logits=logits,
1370
+ past_key_values=outputs.past_key_values,
1371
+ hidden_states=outputs.hidden_states,
1372
+ attentions=outputs.attentions,
1373
+ router_logits=outputs.router_logits,
1374
+ )
1375
+
1376
+ def prepare_inputs_for_generation(
1377
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, token_type_ids=None, **kwargs
1378
+ ):
1379
+ if past_key_values is not None:
1380
+ if isinstance(past_key_values, Cache):
1381
+ cache_length = past_key_values.get_seq_length()
1382
+ past_length = past_key_values.seen_tokens
1383
+ max_cache_length = past_key_values.get_max_length()
1384
+ else:
1385
+ cache_length = past_length = past_key_values[0][0].shape[2]
1386
+ max_cache_length = None
1387
+
1388
+ # Keep only the unprocessed tokens:
1389
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1390
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1391
+ # input)
1392
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1393
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1394
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1395
+ # input_ids based on the past_length.
1396
+ elif past_length < input_ids.shape[1]:
1397
+ input_ids = input_ids[:, past_length:]
1398
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1399
+
1400
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1401
+ if (
1402
+ max_cache_length is not None
1403
+ and attention_mask is not None
1404
+ and cache_length + input_ids.shape[1] > max_cache_length
1405
+ ):
1406
+ attention_mask = attention_mask[:, -max_cache_length:]
1407
+
1408
+ position_ids = kwargs.get("position_ids", None)
1409
+ if attention_mask is not None and position_ids is None:
1410
+ # create position_ids on the fly for batch generation
1411
+ position_ids = attention_mask.long().cumsum(-1) - 1
1412
+ position_ids.masked_fill_(attention_mask == 0, 1)
1413
+ if past_key_values:
1414
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1415
+
1416
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1417
+ if inputs_embeds is not None and past_key_values is None:
1418
+ model_inputs = {"inputs_embeds": inputs_embeds}
1419
+ else:
1420
+ model_inputs = {"input_ids": input_ids}
1421
+
1422
+ model_inputs.update(
1423
+ {
1424
+ "position_ids": position_ids,
1425
+ "past_key_values": past_key_values,
1426
+ "use_cache": kwargs.get("use_cache"),
1427
+ "attention_mask": attention_mask,
1428
+ }
1429
+ )
1430
+ return model_inputs
1431
+
1432
+ @staticmethod
1433
+ def _reorder_cache(past_key_values, beam_idx):
1434
+ reordered_past = ()
1435
+ for layer_past in past_key_values:
1436
+ reordered_past += (
1437
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1438
+ )
1439
+ return reordered_past
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:724f5e0b5ff15fb377a86f5cadda88bb7bdbbb64cb90fec5254396847ad2dd71
3
+ size 33604756142
special_tokens_map.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|startoftext|>",
3
+ "cls_token": "[CLS]",
4
+ "eos_token": "<|endoftext|>",
5
+ "gmask_token": "[gMASK]",
6
+ "additional_special_tokens": [
7
+ "<role>",
8
+ "</role>"
9
+ ]
10
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "bos_token": "<|startoftext|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "cls_token": "[CLS]",
7
+ "eos_token": "<|endoftext|>",
8
+ "gmask_token": "[gMASK]",
9
+ "merges_file": null,
10
+ "model_max_length": 1000000000000000019884624838656,
11
+ "tokenizer_class": "PreTrainedTokenizerFast",
12
+ "vocab_file": null,
13
+ "pad_token": "<|endoftext|>",
14
+ "fast_tokenizer": true
15
+ }