intervitens commited on
Commit
65bf19f
·
verified ·
1 Parent(s): 0176247

Upload folder using huggingface_hub

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