zhanghanxiao commited on
Commit
6e02e22
·
verified ·
1 Parent(s): e764dbf

Add files using upload-large-folder tool

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