mattmengli commited on
Commit
e8aa6e2
·
1 Parent(s): 93215a8

First model version

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