zhanghanxiao commited on
Commit
b735a17
·
verified ·
1 Parent(s): bd43ea2

Add files using upload-large-folder tool

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