sandeep1337 commited on
Commit
e3170eb
·
verified ·
1 Parent(s): 37d5595

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Antgroup and The HuggingFace Inc. team (Ling-3.0-tiny / BailingMoeV3)
4
+ Copyright (c) 2023-2026 Songlin Yang, Yu Zhang, Zhiyuan Li, et al. (flash-linear-attention references)
5
+ Copyright (c) 2026 SecureLayer7 (abliterated, triton-free derivative)
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
NOTICE ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Ling-3.0-tiny-Uncensored-Abliterated
2
+ Copyright (c) 2026 SecureLayer7 (Waxspace)
3
+
4
+ This is a derivative work distributed under the MIT License.
5
+
6
+ ------------------------------------------------------------------------
7
+ Attribution (per the MIT License):
8
+ ------------------------------------------------------------------------
9
+
10
+ Base model:
11
+ inclusionAI/Ling-3.0-tiny (architecture: BailingMoeV3)
12
+ https://huggingface.co/inclusionAI/Ling-3.0-tiny
13
+ Copyright (c) 2025 Antgroup and The HuggingFace Inc. team.
14
+ Licensed under the MIT License.
15
+
16
+ Ported linear-attention math referenced from:
17
+ flash-linear-attention (fla) naive torch reference implementations
18
+ Copyright (c) 2023-2026 Songlin Yang, Yu Zhang, Zhiyuan Li, et al.
19
+ Licensed under the MIT License.
20
+
21
+ ------------------------------------------------------------------------
22
+ Modifications made in this derivative:
23
+ ------------------------------------------------------------------------
24
+
25
+ 1. Triton-free port: modeling_bailing_moe_v3.py was modified to run without
26
+ the `fla` / Triton dependency (KDA linear-attention recurrence, gated
27
+ RMSNorm, and short causal convolution reimplemented in pure PyTorch from
28
+ fla's MIT-licensed naive references), so the model runs on Apple Silicon
29
+ (MPS) and CPU. Compatibility fixes for transformers 5.x were also applied.
30
+
31
+ 2. Abliteration: the refusal direction was ablated (Heretic / Optuna TPE) from
32
+ the attention output projections (MLA o_proj and KDA dense) and all MoE
33
+ expert down-projections, reducing weights-level refusals from ~35/100 to
34
+ ~8/100 at KL ~0.046.
35
+
36
+ No trademark of Antgroup, inclusionAI, or Hugging Face is used to imply endorsement.
README.md ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model: inclusionAI/Ling-3.0-tiny
4
+ language:
5
+ - en
6
+ library_name: transformers
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - ling
10
+ - bailing-moe
11
+ - uncensored
12
+ - abliterated
13
+ - uncensored-llm
14
+ - no-refusal
15
+ - moe
16
+ - mixture-of-experts
17
+ - linear-attention
18
+ - apple-silicon
19
+ - mps
20
+ - reasoning
21
+ - cybersecurity
22
+ - red-teaming
23
+ ---
24
+
25
+ # Ling-3.0-tiny-Uncensored-Abliterated
26
+
27
+ An uncensored, **abliterated** derivative of [`inclusionAI/Ling-3.0-tiny`](https://huggingface.co/inclusionAI/Ling-3.0-tiny)
28
+ (BailingMoeV3) — the refusal direction removed at the **weights level** for direct, complete
29
+ answers on cybersecurity, red-teaming, and penetration-testing topics where aligned models refuse.
30
+
31
+ ## What makes this different
32
+
33
+ **It runs on Apple Silicon (MPS) — the original can't.** Ling-3.0-tiny's KDA linear-attention
34
+ requires `fla` / Triton kernels, which have **no Apple-Silicon backend**. This repo ships a
35
+ **triton-free pure-torch port** of the BailingMoeV3 modeling code (KDA recurrence, gated RMSNorm,
36
+ short causal convolution) so the model loads and generates on a Mac's GPU with plain
37
+ `transformers` — no CUDA, no Triton, no `fla`. The abliteration itself was performed on an M4 Max
38
+ using that port.
39
+
40
+ - 🔓 **Weights-level uncensored** — refusal direction ablated (Heretic / Optuna TPE) across both
41
+ attention paths (MLA `o_proj` + KDA `dense`) **and all 128 experts + shared expert** per layer.
42
+ Refusals dropped **35/100 → 8/100** at **KL 0.046** (minimal capability change).
43
+ - 🍎 **Apple-Silicon runnable** — triton-free modeling code included; loads on MPS out of the box.
44
+ - 🧩 **MoE** — 7.9B total / 1.3B active (128 routed + 1 shared expert), 24 layers, hybrid
45
+ MLA + KDA linear attention.
46
+
47
+ ## Quick start
48
+
49
+ ```python
50
+ from transformers import AutoModelForCausalLM, AutoTokenizer
51
+ import torch
52
+
53
+ m = "Securelayer7/Ling-3.0-tiny-Uncensored-Abliterated"
54
+ tok = AutoTokenizer.from_pretrained(m, trust_remote_code=True)
55
+ model = AutoModelForCausalLM.from_pretrained(
56
+ m, torch_dtype=torch.bfloat16, trust_remote_code=True).to("mps").eval()
57
+
58
+ msgs = [{"role": "user", "content": "Explain how a SQL injection works and how to prevent it."}]
59
+ ids = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt", return_dict=True)
60
+ ids = {k: v.to("mps") for k, v in ids.items()}
61
+ out = model.generate(**ids, max_new_tokens=512, do_sample=True, temperature=0.7)
62
+ print(tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True))
63
+ ```
64
+
65
+ The bundled `modeling_bailing_moe_v3.py` uses a pure-torch fallback for the KDA linear-attention
66
+ (no Triton), so it also runs on CPU. On CUDA with `fla` installed you may prefer the original
67
+ upstream modeling code for speed.
68
+
69
+ ## How it was made
70
+
71
+ 1. **Triton-free port** of BailingMoeV3 so it runs without `fla`/Triton (math from `fla`'s own MIT
72
+ naive references; identical weights).
73
+ 2. **Abliteration** (Heretic, Optuna TPE multi-objective: minimize refusals + KL) targeting the
74
+ residual-writing projections of both attention types and every expert down-projection.
75
+
76
+ ## Known behavior
77
+
78
+ Ling is a **bilingual (English/Chinese)** model; after answering it may occasionally drift into
79
+ Chinese. Recommended sampling: `do_sample=True, temperature=0.7, top_p=0.95`. Greedy decoding can
80
+ degrade. A short SFT pass cleans up drift.
81
+
82
+ ## Responsible use
83
+
84
+ Uncensored ≠ lawless — for **legitimate research and authorized security work**. Illegal content
85
+ (incl. CSAM) must be blocked at the serving layer; the weights carry no such guard, and the
86
+ operator is responsible for a lawful, policy-gated deployment.
87
+
88
+ ## License & attribution
89
+
90
+ **MIT** — see `LICENSE`. Derivative of **[inclusionAI/Ling-3.0-tiny](https://huggingface.co/inclusionAI/Ling-3.0-tiny)**
91
+ (BailingMoeV3, © Antgroup, MIT). Modifications (triton-free port + abliteration) disclosed in `NOTICE`.
chat_template.jinja ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {#- Bailing V3 chat template -#}
2
+ {#- Supports: thinking option, tool calling -#}
3
+
4
+ {#- ==================== thinking option normalization ==================== -#}
5
+ {%- if enable_thinking is defined %}
6
+ {%- if enable_thinking %}
7
+ {%- set thinking_option = 'on' %}
8
+ {%- else %}
9
+ {%- set thinking_option = 'off' %}
10
+ {%- endif %}
11
+ {%- elif thinking_option is not defined %}
12
+ {%- set thinking_option = 'on' %}
13
+ {%- endif %}
14
+
15
+ {#- ==================== preserved thinking ==================== -#}
16
+ {% set preserved_thinking = true %}
17
+
18
+ {#- ==================== system message ==================== -#}
19
+ {{- '<role>SYSTEM</role>' }}
20
+ {%- if tools %}
21
+ {%- if messages[0].role == 'system' %}
22
+ {{- messages[0].content + '\n' }}
23
+ {%- endif %}
24
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
25
+ {%- for tool in tools %}
26
+ {{- "\n" }}
27
+ {{- tool | tojson }}
28
+ {%- endfor %}
29
+ {{- "\n</tools>\n\nIf none of the functions can be used, point it out. If the given question lacks the parameters required by the function, also point it out.\nIf you need to use a function, for each function call, output the function name and arguments within the following XML format:\n<tool_call>{function-name}\n<arg_key>{arg-key-1}</arg_key>\n<arg_value>{arg-value-1}</arg_value>\n<arg_key>{arg-key-2}</arg_key>\n<arg_value>{arg-value-2}</arg_value>\n...\n</tool_call>\n" }}
30
+ {%- if messages[0].role == 'system' and messages[0].content is string and ('detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content) %}
31
+ {{- '<|role_end|>' }}
32
+ {%- else %}
33
+ {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
34
+ {%- endif %}
35
+ {%- else %}
36
+ {%- if messages[0].role == 'system' %}
37
+ {%- if 'detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content %}
38
+ {{- messages[0].content + '<|role_end|>' }}
39
+ {%- else %}
40
+ {{- messages[0].content + '\n' }}
41
+ {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
42
+ {%- endif %}
43
+ {% else %}
44
+ {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
45
+ {%- endif %}
46
+ {%- endif %}
47
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
48
+ {%- for message in messages[::-1] %}
49
+ {%- set index = (messages|length - 1) - loop.index0 %}
50
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
51
+ {%- set ns.multi_step_tool = false %}
52
+ {%- set ns.last_query_index = index %}
53
+ {%- endif %}
54
+ {%- endfor %}
55
+ {%- for message in messages %}
56
+ {%- if message.content is string %}
57
+ {%- set content = message.content %}
58
+ {%- else %}
59
+ {%- set content = '' %}
60
+ {%- endif %}
61
+ {%- if message.role == "user" %}
62
+ {{- '<role>HUMAN</role>' + message.content + '<|role_end|>' }}
63
+ {%- elif message.role == "system" and not loop.first %}
64
+ {{- '<role>SYSTEM</role>' + message.content + '<|role_end|>' }}
65
+ {%- elif message.role == "assistant" %}
66
+ {%- set reasoning_content = '' %}
67
+ {%- if message.reasoning_content is string and message.reasoning_content != '' %}
68
+ {%- set reasoning_content = message.reasoning_content %}
69
+ {%- else %}
70
+ {%- if '</think>' in content %}
71
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
72
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
73
+ {%- endif %}
74
+ {%- endif %}
75
+ {%- if preserved_thinking or loop.index0 > ns.last_query_index %}
76
+ {%- if reasoning_content != '' %}
77
+ {{- '<role>ASSISTANT</role>' + '\n<think>' + reasoning_content.strip('\n') + '</think>' + content.lstrip('\n') }}
78
+ {%- else %}
79
+ {{- '<role>ASSISTANT</role>\n<think></think>' + content }}
80
+ {%- endif %}
81
+ {%- else %}
82
+ {{- '<role>ASSISTANT</role>\n<think></think>' + content }}
83
+ {%- endif %}
84
+ {%- if message.tool_calls %}
85
+ {%- for tool_call in message.tool_calls %}
86
+ {%- if (loop.first and content) or (not loop.first) %}
87
+ {{- '\n' }}
88
+ {%- endif %}
89
+ {%- set tc = tool_call %}
90
+ {%- if tool_call.function %}
91
+ {%- set tc = tool_call.function %}
92
+ {%- endif %}
93
+ {{- '<tool_call>' + tc.name }}
94
+ {% set _args = tc.arguments %}
95
+ {%- for k, v in _args.items() %}
96
+ {{- '<arg_key>' + k + '</arg_key>' }}
97
+ {{- '\n<arg_value>' }}
98
+ {%- if v is string %}
99
+ {{- v }}
100
+ {%- else %}
101
+ {{- v | tojson(ensure_ascii=False) }}
102
+ {%- endif %}
103
+ {{- '</arg_value>' }}
104
+ {%- endfor %}
105
+ {{- '\n</tool_call>' }}
106
+ {%- endfor %}
107
+ {%- endif %}
108
+ {{- '<|role_end|>' }}
109
+ {%- elif message.role == "tool" %}
110
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
111
+ {{- '<role>OBSERVATION</role>' }}
112
+ {%- endif %}
113
+ {{- '\n<tool_response>\n' }}
114
+ {{- content }}
115
+ {{- '\n</tool_response>' }}
116
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
117
+ {{- '<|role_end|>' }}
118
+ {%- endif %}
119
+ {%- endif %}
120
+ {%- endfor %}
121
+
122
+ {#- ==================== generation prompt ==================== -#}
123
+ {%- if add_generation_prompt %}
124
+ {{- '<role>ASSISTANT</role>' }}
125
+ {%- if thinking_option == 'on' %}
126
+ {{- '\n<think>' }}
127
+ {%- elif thinking_option == 'off' %}
128
+ {{- '\n<think></think>' }}
129
+ {%- endif %}
130
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BailingMoeV3ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_bailing_moe_v3.BailingMoeV3Config",
8
+ "AutoModel": "modeling_bailing_moe_v3.BailingMoeV3Model",
9
+ "AutoModelForCausalLM": "modeling_bailing_moe_v3.BailingMoeV3ForCausalLM"
10
+ },
11
+ "dtype": "bfloat16",
12
+ "embedding_dropout": 0.0,
13
+ "eos_token_id": 156895,
14
+ "expert_swiglu_limit_list": null,
15
+ "first_k_dense_replace": 1,
16
+ "gated_attention_proj_granularity_type": "head_wise",
17
+ "group_norm_size": 1,
18
+ "head_dim": 128,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 1536,
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 4608,
23
+ "kda_lower_bound": -5,
24
+ "kda_safe_gate": true,
25
+ "kv_lora_rank": 512,
26
+ "layer_group_size": 4,
27
+ "linear_silu": true,
28
+ "max_position_embeddings": 131072,
29
+ "max_window_layers": 20,
30
+ "moe_intermediate_size": 512,
31
+ "moe_router_enable_expert_bias": true,
32
+ "moe_shared_expert_intermediate_size": 512,
33
+ "mtp_loss_scaling_factor": 0,
34
+ "mtp_use_kda": false,
35
+ "n_group": 8,
36
+ "no_kda_lora": true,
37
+ "norm_topk_prob": true,
38
+ "num_attention_heads": 16,
39
+ "num_experts": 128,
40
+ "num_experts_per_tok": 8,
41
+ "num_hidden_layers": 24,
42
+ "num_key_value_heads": 16,
43
+ "num_kv_heads_for_linear_attn": 0,
44
+ "num_nextn_predict_layers": 0,
45
+ "num_shared_experts": 1,
46
+ "output_dropout": 0.0,
47
+ "output_router_logits": false,
48
+ "pad_token_id": 156892,
49
+ "partial_rotary_factor": 0.5,
50
+ "q_lora_rank": 256,
51
+ "qk_head_dim": 192,
52
+ "qk_nope_head_dim": 128,
53
+ "qk_rope_head_dim": 64,
54
+ "rms_norm_eps": 1e-06,
55
+ "rope_interleave": true,
56
+ "rope_parameters": {
57
+ "partial_rotary_factor": 0.5,
58
+ "rope_theta": 6000000,
59
+ "rope_type": "default"
60
+ },
61
+ "rope_theta": 6000000,
62
+ "rotary_dim": 64,
63
+ "routed_scaling_factor": 2.5,
64
+ "router_dtype": "fp32",
65
+ "scale_router_input": false,
66
+ "score_function": "sigmoid",
67
+ "scoring_func": "sigmoid",
68
+ "seq_aux": true,
69
+ "share_expert_swiglu_limit_list": null,
70
+ "short_conv_kernel_size": 4,
71
+ "tie_word_embeddings": false,
72
+ "topk_group": 4,
73
+ "topk_method": "noaux_tc",
74
+ "transformers_version": "5.14.1",
75
+ "up_proj_norm": false,
76
+ "use_bias": false,
77
+ "use_cache": true,
78
+ "use_kda_lora": false,
79
+ "use_mla_nope": false,
80
+ "use_nGPT": false,
81
+ "use_qk_norm": true,
82
+ "use_qkv_bias": false,
83
+ "v_head_dim": 128,
84
+ "value_norm": false,
85
+ "vocab_size": 157184
86
+ }
configuration_bailing_moe_v3.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bailing MoE V2 model configuration"""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class BailingMoeV3Config(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
+ moe_shared_expert_intermediate_size=512,
39
+ first_k_dense_replace=1,
40
+ head_dim=128,
41
+ output_router_logits=False,
42
+ use_qk_norm=True,
43
+ num_nextn_predict_layers=0,
44
+ mtp_loss_scaling_factor=0,
45
+ moe_router_enable_expert_bias=True,
46
+ routed_scaling_factor=1.0,
47
+ layer_group_size=5,
48
+ kv_lora_rank=512,
49
+ q_lora_rank=None,
50
+ qk_rope_head_dim=64,
51
+ v_head_dim=128,
52
+ qk_nope_head_dim=128,
53
+ rope_interleave=True,
54
+ score_function="sigmoid",
55
+ scoring_func="sigmoid",
56
+ seq_aux=True,
57
+ topk_method="noaux_tc",
58
+ router_dtype="fp32",
59
+ gated_attention_proj_granularity_type=None,
60
+ no_kda_lora=False,
61
+ kda_safe_gate=False,
62
+ kda_lower_bound=None,
63
+ short_conv_kernel_size=4,
64
+ **kwargs,
65
+ ):
66
+ self.num_hidden_layers = num_hidden_layers
67
+ self.vocab_size = vocab_size
68
+ self.hidden_size = hidden_size
69
+ self.intermediate_size = intermediate_size
70
+ self.num_attention_heads = num_attention_heads
71
+ self.num_key_value_heads = num_key_value_heads
72
+ self.hidden_act = hidden_act
73
+ self.use_qkv_bias = use_qkv_bias
74
+ self.use_bias = use_bias
75
+ self.rms_norm_eps = rms_norm_eps
76
+ self.embedding_dropout = embedding_dropout
77
+ self.attention_dropout = attention_dropout
78
+ self.output_dropout = output_dropout
79
+ self.num_nextn_predict_layers = num_nextn_predict_layers
80
+ self.mtp_loss_scaling_factor = mtp_loss_scaling_factor
81
+ self.initializer_range = initializer_range
82
+ self.max_position_embeddings = max_position_embeddings
83
+ self.rope_theta = rope_theta
84
+ self.use_cache = use_cache
85
+ self.max_window_layers = max_window_layers
86
+ self.head_dim = head_dim or self.hidden_size // self.num_attention_heads
87
+ self.rope_scaling = rope_scaling
88
+ self.use_qk_norm = use_qk_norm
89
+ self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
90
+ self.routed_scaling_factor = routed_scaling_factor
91
+
92
+ # MoE configs
93
+ self.num_experts = num_experts
94
+ self.num_shared_experts = num_shared_experts
95
+ self.num_experts_per_tok = num_experts_per_tok
96
+ self.n_group = n_group
97
+ self.topk_group = topk_group
98
+ self.moe_intermediate_size = moe_intermediate_size
99
+ self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
100
+ self.first_k_dense_replace = first_k_dense_replace
101
+ self.output_router_logits = output_router_logits
102
+
103
+ # Linear configs
104
+ self.layer_group_size = layer_group_size
105
+ # mla
106
+ self.kv_lora_rank = kv_lora_rank
107
+ self.q_lora_rank = q_lora_rank
108
+ self.qk_rope_head_dim = qk_rope_head_dim
109
+
110
+ self.score_function = score_function
111
+ self.scoring_func = scoring_func
112
+ self.seq_aux = seq_aux
113
+ self.topk_method = topk_method
114
+ self.v_head_dim = v_head_dim
115
+ self.qk_nope_head_dim = qk_nope_head_dim
116
+ self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
117
+ self.rope_interleave = rope_interleave
118
+ self.router_dtype = router_dtype
119
+ self.gated_attention_proj_granularity_type = gated_attention_proj_granularity_type
120
+ self.no_kda_lora = no_kda_lora
121
+ self.kda_safe_gate = kda_safe_gate
122
+ self.kda_lower_bound = kda_lower_bound
123
+ self.short_conv_kernel_size = short_conv_kernel_size
124
+ super().__init__(
125
+ pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
126
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": true,
3
+ "temperature": 1.0,
4
+ "top_k": 20,
5
+ "top_p": 0.95,
6
+ "transformers_version": "5.14.1"
7
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7b59cd76fefb004697f2ef6c2ed3e7c11d1f06493eb3f2469e0ee1e319fe819
3
+ size 4999827336
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6465e1c721079c16a433e31df5932366e0b669963e5d14e9e60dc0f1c625c2d0
3
+ size 4999087224
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35d8a42887d2c3a36ca79c9875ced1c94189749dc86e1d04da78dcfa710d0afd
3
+ size 4999088112
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb6ed6d3073be9eb55d43c5c02c9f7d6b01587be77afd4125d351e679372ccfc
3
+ size 790001720
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_bailing_moe_v3.py ADDED
@@ -0,0 +1,1782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """PyTorch BailingMoE model."""
21
+
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union, Callable
25
+ from copy import deepcopy
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import nn
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import MoeModelOutputWithPast
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ try: # moved/removed in transformers 5.x; only used for FX symbolic tracing (unused here)
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ except ImportError:
52
+ def is_torch_fx_available():
53
+ return False
54
+ from .configuration_bailing_moe_v3 import BailingMoeV3Config
55
+ from transformers.generation.utils import GenerationMixin
56
+ from dataclasses import dataclass
57
+ from transformers.utils import ModelOutput
58
+ from transformers import DynamicLayer
59
+ from transformers.processing_utils import Unpack
60
+ from transformers.utils import TransformersKwargs
61
+ from transformers.utils.deprecation import deprecate_kwarg
62
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
63
+
64
+ from einops import rearrange, repeat
65
+
66
+ # =====================================================================
67
+ # Triton-free torch port (Apple Silicon / MPS). The upstream modeling
68
+ # file hard-requires `fla` (flash-linear-attention) Triton kernels, which
69
+ # have no Apple-Silicon backend. These are drop-in replacements with the
70
+ # SAME names/signatures, math ported from fla's own naive torch references
71
+ # (fla/ops/kda/naive.py, fla/ops/kda/gate.py, fla/modules). Same weights.
72
+ # =====================================================================
73
+
74
+ def tensor_cache(fn): # identity decorator (fla.utils.tensor_cache is a memoizer)
75
+ return fn
76
+
77
+
78
+ def _kda_lowerbound_gate(g, A_log, dt_bias, lower_bound):
79
+ # g = lower_bound * sigmoid(exp(A_log) * (g + dt_bias)) [fla naive_kda_lowerbound_gate]
80
+ H = g.shape[-2]
81
+ g = g.float()
82
+ if dt_bias is not None:
83
+ g = g + dt_bias.view(H, -1)
84
+ return lower_bound * torch.sigmoid(A_log.view(H, 1).float().exp() * g)
85
+
86
+
87
+ def _kda_softplus_gate(g, A_log, dt_bias):
88
+ # g = -exp(A_log) * softplus(g + dt_bias) [fla naive_kda_gate]
89
+ H = g.shape[-2]
90
+ g = g.float()
91
+ if dt_bias is not None:
92
+ g = g + dt_bias.view(H, -1)
93
+ return -A_log.view(H, 1).float().exp() * F.softplus(g)
94
+
95
+
96
+ def _naive_recurrent_kda(q, k, v, g, beta, scale=None, initial_state=None,
97
+ output_final_state=False):
98
+ # Reference recurrence from fla/ops/kda/naive.py::naive_recurrent_kda.
99
+ dtype = v.dtype
100
+ B, T, H, K = q.shape
101
+ HV, V = v.shape[2], v.shape[-1]
102
+ G = HV // H
103
+ if scale is None:
104
+ scale = K ** -0.5
105
+ q, k, v, g, beta = (x.float() for x in (q, k, v, g, beta))
106
+ q = q.repeat_interleave(G, dim=2) * scale
107
+ k = k.repeat_interleave(G, dim=2)
108
+ S = k.new_zeros(B, HV, K, V)
109
+ if initial_state is not None:
110
+ S = S + initial_state.float()
111
+ o = torch.zeros_like(v)
112
+ for i in range(T):
113
+ q_i, k_i, v_i, g_i, b_i = q[:, i], k[:, i], v[:, i], g[:, i], beta[:, i]
114
+ S = S * g_i[..., None].exp()
115
+ S = S + torch.einsum('b h k, b h v -> b h k v',
116
+ b_i[..., None] * k_i, v_i - (k_i[..., None] * S).sum(-2))
117
+ o[:, i] = torch.einsum('b h k, b h k v -> b h v', q_i, S)
118
+ if not output_final_state:
119
+ S = None
120
+ return o.to(dtype), S
121
+
122
+
123
+ def _kda_prep(q, k, g, A_log, dt_bias, lower_bound, l2norm, gate):
124
+ if l2norm:
125
+ q = F.normalize(q.float(), dim=-1)
126
+ k = F.normalize(k.float(), dim=-1)
127
+ if gate:
128
+ g = (_kda_lowerbound_gate(g, A_log, dt_bias, lower_bound) if lower_bound is not None
129
+ else _kda_softplus_gate(g, A_log, dt_bias))
130
+ return q, k, g
131
+
132
+
133
+ def chunk_kda(q, k, v, g, beta, A_log, dt_bias, initial_state=None,
134
+ output_final_state=False, use_qk_l2norm_in_kernel=False,
135
+ use_gate_in_kernel=False, safe_gate=True, lower_bound=None,
136
+ cu_seqlens=None, **kw):
137
+ # Route chunk mode through the exact recurrence (handles arbitrary T; the
138
+ # chunked reference requires T % 64 == 0 which breaks on real prompts).
139
+ q, k, g = _kda_prep(q, k, g, A_log, dt_bias, lower_bound,
140
+ use_qk_l2norm_in_kernel, use_gate_in_kernel)
141
+ return _naive_recurrent_kda(q, k, v, g, beta, None, initial_state, output_final_state)
142
+
143
+
144
+ def fused_recurrent_kda(q, k, v, g, beta, A_log, dt_bias, initial_state=None,
145
+ output_final_state=False, use_qk_l2norm_in_kernel=False,
146
+ use_gate_in_kernel=False, safe_gate=True, lower_bound=None,
147
+ cu_seqlens=None, **kw):
148
+ q, k, g = _kda_prep(q, k, g, A_log, dt_bias, lower_bound,
149
+ use_qk_l2norm_in_kernel, use_gate_in_kernel)
150
+ return _naive_recurrent_kda(q, k, v, g, beta, None, initial_state, output_final_state)
151
+
152
+
153
+ def chunk_simple_gla(*a, **k): # imported upstream but never called in this model
154
+ raise NotImplementedError("simple_gla is unused in Ling-3.0-tiny")
155
+
156
+
157
+ def fused_recurrent_simple_gla(*a, **k):
158
+ raise NotImplementedError("simple_gla is unused in Ling-3.0-tiny")
159
+
160
+
161
+ class ShortConvolution(nn.Conv1d):
162
+ """Depthwise causal conv1d + activation (torch port of fla ShortConvolution)."""
163
+
164
+ def __init__(self, hidden_size, kernel_size, bias=False, activation='silu',
165
+ backend=None, device=None, dtype=None, **kw):
166
+ super().__init__(hidden_size, hidden_size, kernel_size, groups=hidden_size,
167
+ bias=bias, padding=kernel_size - 1, device=device, dtype=dtype)
168
+ self.hidden_size = hidden_size
169
+ self.activation = activation
170
+
171
+ def _act(self, y):
172
+ return F.silu(y) if self.activation in ('silu', 'swish') else y
173
+
174
+ def forward(self, x, residual=None, mask=None, cache=None,
175
+ output_final_state=False, cu_seqlens=None, **kw):
176
+ B, T, D = x.shape
177
+ W = self.kernel_size[0]
178
+ if T == 1 and cache is not None:
179
+ # decode step: shift window, drop in new input, weighted sum
180
+ cache = torch.roll(cache, shifts=-1, dims=-1)
181
+ cache[:, :, -1] = x[:, 0]
182
+ y = (cache * self.weight.squeeze(1)).sum(-1)
183
+ if self.bias is not None:
184
+ y = y + self.bias
185
+ y = self._act(y).unsqueeze(1)
186
+ return y, (cache if output_final_state else None)
187
+ xt = x.transpose(1, 2) # [B, D, T]
188
+ y = F.conv1d(xt, self.weight, self.bias, groups=self.hidden_size, padding=W - 1)[..., :T]
189
+ y = self._act(y.transpose(1, 2))
190
+ final = None
191
+ if output_final_state:
192
+ pad = xt if T >= W else F.pad(xt, (W - T, 0))
193
+ final = pad[..., -W:].contiguous()
194
+ return y, final
195
+
196
+
197
+ class FusedRMSNormGated(nn.Module):
198
+ """RMSNorm with a multiplicative output gate (torch port of fla FusedRMSNormGated)."""
199
+
200
+ def __init__(self, hidden_size, eps=1e-6, activation='sigmoid', **kw):
201
+ super().__init__()
202
+ self.weight = nn.Parameter(torch.ones(hidden_size))
203
+ self.eps = eps
204
+ self.activation = activation
205
+
206
+ def forward(self, x, g):
207
+ dt = x.dtype
208
+ x = x.float()
209
+ x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
210
+ y = x * self.weight.float()
211
+ g = g.float()
212
+ if self.activation in ('silu', 'swish'):
213
+ y = y * g * torch.sigmoid(g)
214
+ else: # 'sigmoid'
215
+ y = y * torch.sigmoid(g)
216
+ return y.to(dt)
217
+
218
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
219
+ # It means that the function will not be traced through and simply appear as a node in the graph.
220
+ if is_torch_fx_available():
221
+ if not is_torch_greater_or_equal_than_1_13:
222
+ import torch.fx
223
+
224
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
225
+
226
+
227
+ logger = logging.get_logger(__name__)
228
+
229
+ _CONFIG_FOR_DOC = "BailingMoeV3Config"
230
+
231
+
232
+ def roll_tensor(tensor, shifts=-1, dims=-1, fill_value=0):
233
+ """Roll the tensor input along the given dimension(s).
234
+ Inserted elements are set to be 0.0.
235
+ """
236
+ rolled_tensor = torch.roll(tensor, shifts=shifts, dims=dims)
237
+ rolled_tensor.select(dims, shifts).fill_(fill_value)
238
+ return rolled_tensor, rolled_tensor.sum()
239
+
240
+
241
+ @dataclass
242
+ class MoEV3CausalLMOutputWithPast(ModelOutput):
243
+ """
244
+ Base class for causal language model (or autoregressive) outputs as well as Mixture of Expert's router hidden
245
+ states terms, to train a MoE model.
246
+ Args:
247
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
248
+ Language modeling loss (for next-token prediction).
249
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
250
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
251
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
252
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
253
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
254
+ `past_key_values` input) to speed up sequential decoding.
255
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
256
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
257
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
258
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
259
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
260
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
261
+ sequence_length)`.
262
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
263
+ heads.
264
+ z_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
265
+ z_loss for the sparse modules.
266
+ aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
267
+ aux_loss for the sparse modules.
268
+ router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`):
269
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
270
+ Router logits of the encoder model, useful to compute the auxiliary loss and the z_loss for the sparse
271
+ modules.
272
+ """
273
+
274
+ loss: Optional[torch.FloatTensor] = None
275
+ logits: Optional[torch.FloatTensor] = None
276
+ past_key_values: Optional[Cache] = None
277
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
278
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
279
+ z_loss: Optional[torch.FloatTensor] = None
280
+ aux_loss: Optional[torch.FloatTensor] = None
281
+ router_logits: Optional[tuple[torch.FloatTensor]] = None
282
+ mtp_loss: Optional[torch.FloatTensor] = None
283
+ mtp_logits: Optional[tuple[torch.FloatTensor, ...]] = None
284
+
285
+
286
+ class MoeV3ModelOutputWithPast(MoeModelOutputWithPast):
287
+
288
+ def __init__(self, mtp_hidden_states=None, **kwargs):
289
+ super().__init__(**kwargs)
290
+ self.mtp_hidden_states = mtp_hidden_states
291
+
292
+
293
+ def index_first_axis(x, indices):
294
+ other_shape = x.shape[1:]
295
+ second_dim = other_shape.numel()
296
+ return torch.gather(
297
+ rearrange(x, "b ... -> b (...)"),
298
+ 0,
299
+ repeat(indices, "z -> z d", d=second_dim),
300
+ ).reshape(-1, *other_shape)
301
+
302
+
303
+ def index_put_first_axis(x, indices, first_axis_dim):
304
+ y = torch.zeros(first_axis_dim, *x.shape[1:], device=x.device, dtype=x.dtype)
305
+ y[indices] = x
306
+ # y.scatter_(0, repeat(indices, 'z -> z d', d=x.shape[1]), x)
307
+ return y
308
+
309
+
310
+ def pad_input(
311
+ hidden_states: torch.Tensor,
312
+ indices: torch.LongTensor,
313
+ batch_size: int,
314
+ seq_len: int,
315
+ ) -> torch.Tensor:
316
+ output = index_put_first_axis(hidden_states, indices, batch_size * seq_len)
317
+ return rearrange(output, "(b s) ... -> b s ...", b=batch_size)
318
+
319
+
320
+ @tensor_cache
321
+ def _get_unpad_data(attention_mask):
322
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
323
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
324
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
325
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
326
+ return (
327
+ indices,
328
+ cu_seqlens,
329
+ max_seqlen_in_batch,
330
+ )
331
+
332
+
333
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
334
+ warnings.warn(
335
+ "Calling `transformers.models.BailingMoeV3.modeling_BailingMoeV3._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
336
+ )
337
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
338
+
339
+
340
+ def _make_causal_mask(
341
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
342
+ ):
343
+ warnings.warn(
344
+ "Calling `transformers.models.BailingMoeV3.modeling_BailingMoeV3._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.BailingMoeV3.modeling_BailingMoeV3.AttentionMaskConverter._make_causal_mask"
345
+ )
346
+ return AttentionMaskConverter._make_causal_mask(
347
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
348
+ )
349
+
350
+
351
+ class BailingMoeV3RMSNorm(nn.Module):
352
+ def __init__(self, hidden_size, eps=1e-6):
353
+ """
354
+ BailingMoeV3RMSNorm is equivalent to T5LayerNorm
355
+ """
356
+ super().__init__()
357
+ self.weight = nn.Parameter(torch.ones(hidden_size))
358
+ self.variance_epsilon = eps
359
+
360
+ def forward(self, hidden_states):
361
+ input_dtype = hidden_states.dtype
362
+ hidden_states = hidden_states.to(torch.float32)
363
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
364
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
365
+ return self.weight * hidden_states.to(input_dtype)
366
+
367
+
368
+ class BailingMoeV3GroupRMSNorm(nn.Module):
369
+ def __init__(self, hidden_size, group_norm_size, eps=1e-6):
370
+ """
371
+ BailingMoeV3RMSNorm is equivalent to T5LayerNorm
372
+ """
373
+ super().__init__()
374
+ self.weight = nn.Parameter(torch.ones(hidden_size))
375
+ self.group_norm_size = group_norm_size
376
+ assert hidden_size % group_norm_size == 0, "hidden_size must be divisible by group_norm_size"
377
+ self.variance_epsilon = eps
378
+
379
+ def forward(self, hidden_states):
380
+ input_dtype = hidden_states.dtype
381
+ input_shape = hidden_states.size()
382
+ group_input_shape = input_shape[:-1] + (self.group_norm_size, input_shape[-1] // self.group_norm_size)
383
+ hidden_states = hidden_states.view(group_input_shape)
384
+ hidden_states = hidden_states.to(torch.float32)
385
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
386
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
387
+ return self.weight * hidden_states.to(input_dtype).view(input_shape)
388
+
389
+
390
+ ALL_LAYERNORM_LAYERS.append(BailingMoeV3RMSNorm)
391
+
392
+
393
+ class BailingMoeV3RotaryEmbedding(nn.Module):
394
+ def __init__(self, config: BailingMoeV3Config, device=None):
395
+ super().__init__()
396
+ # BC: "rope_type" was originally "type"
397
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
398
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
399
+ else:
400
+ self.rope_type = "default"
401
+ self.max_seq_len_cached = config.max_position_embeddings
402
+ self.original_max_seq_len = config.max_position_embeddings
403
+
404
+ self.config = deepcopy(config)
405
+ self.config.head_dim = config.qk_rope_head_dim
406
+ self.config.partial_rotary_factor = 1.0
407
+ # transformers 5.x dropped the "default" key from ROPE_INIT_FUNCTIONS; fall
408
+ # back to the standard (non-scaled) RoPE inv_freq when the type is unknown.
409
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS.get(self.rope_type)
410
+ if self.rope_init_fn is None:
411
+ def _default_rope(cfg, device=None, **kw):
412
+ base = cfg.rope_theta
413
+ dim = int(cfg.head_dim * getattr(cfg, "partial_rotary_factor", 1.0))
414
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))
415
+ return inv_freq, 1.0
416
+ self.rope_init_fn = _default_rope
417
+
418
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
419
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
420
+ self.original_inv_freq = self.inv_freq
421
+
422
+ @torch.no_grad()
423
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
424
+ def forward(self, x, position_ids):
425
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
426
+ position_ids_expanded = position_ids[:, None, :].float()
427
+
428
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
429
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
430
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
431
+ emb = torch.cat((freqs, freqs), dim=-1)
432
+ cos = emb.cos() * self.attention_scaling
433
+ sin = emb.sin() * self.attention_scaling
434
+
435
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
436
+
437
+
438
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
439
+ def rotate_half(x):
440
+ """Rotates half the hidden dims of the input."""
441
+ x1 = x[..., : x.shape[-1] // 2]
442
+ x2 = x[..., x.shape[-1] // 2 :]
443
+ return torch.cat((-x2, x1), dim=-1)
444
+
445
+
446
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
447
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
448
+ """Applies Rotary Position Embedding to the query and key tensors.
449
+ Args:
450
+ q (`torch.Tensor`): The query tensor.
451
+ k (`torch.Tensor`): The key tensor.
452
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
453
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
454
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
455
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
456
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
457
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
458
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
459
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
460
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
461
+ Returns:
462
+ `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding.
463
+ """
464
+ cos = cos.unsqueeze(unsqueeze_dim)
465
+ sin = sin.unsqueeze(unsqueeze_dim)
466
+
467
+ # Keep half or full tensor for later concatenation
468
+ rotary_dim = cos.shape[-1]
469
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
470
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
471
+
472
+ # Apply rotary embeddings on the first half or full tensor
473
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
474
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
475
+
476
+ # Concatenate back to full shape
477
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
478
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
479
+ return q_embed, k_embed
480
+
481
+
482
+ class BailingMoeV3MLP(nn.Module):
483
+ def __init__(self, config: BailingMoeV3Config, intermediate_size: int):
484
+ super().__init__()
485
+ self.config = config
486
+ self.hidden_size = config.hidden_size
487
+ self.intermediate_size = intermediate_size
488
+
489
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
490
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
491
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
492
+ self.act_fn = ACT2FN[config.hidden_act]
493
+
494
+ def forward(self, x):
495
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
496
+
497
+
498
+ class BailingMoeV3Gate(nn.Module):
499
+ def __init__(self, config):
500
+ super().__init__()
501
+ self.config = config
502
+ self.top_k = config.num_experts_per_tok
503
+ self.num_experts = config.num_experts
504
+
505
+ self.n_group = config.n_group
506
+ self.topk_group = config.topk_group
507
+
508
+ # topk selection algorithm
509
+ self.gating_dim = config.hidden_size
510
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
511
+ self.routed_scaling_factor = config.routed_scaling_factor
512
+
513
+ self.register_buffer("expert_bias", torch.zeros((self.num_experts)))
514
+ self.reset_parameters()
515
+
516
+ def reset_parameters(self) -> None:
517
+ import torch.nn.init as init
518
+
519
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
520
+
521
+ def group_limited_topk(
522
+ self,
523
+ scores: torch.Tensor,
524
+ ):
525
+ num_tokens, _ = scores.size()
526
+ # Organize the experts into groups
527
+ group_scores = scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
528
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
529
+ group_mask = torch.zeros_like(group_scores)
530
+ group_mask.scatter_(1, group_idx, 1)
531
+
532
+ # Mask the experts based on selection groups
533
+ score_mask = (
534
+ group_mask.unsqueeze(-1)
535
+ .expand(num_tokens, self.n_group, self.num_experts // self.n_group)
536
+ .reshape(num_tokens, -1)
537
+ )
538
+
539
+ masked_scores = scores.masked_fill(~score_mask.bool(), float('-inf'))
540
+ probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
541
+
542
+ return probs, top_indices
543
+
544
+ def forward(self, hidden_states):
545
+ # compute gating score
546
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
547
+ logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
548
+
549
+ scores = torch.sigmoid(logits.float()).type_as(logits)
550
+
551
+ scores_for_routing = scores + self.expert_bias
552
+ _, topk_idx = self.group_limited_topk(scores_for_routing)
553
+
554
+ scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
555
+
556
+ topk_weight = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.top_k > 1 else scores
557
+ topk_weight = topk_weight * self.routed_scaling_factor
558
+
559
+ return topk_idx, topk_weight, logits
560
+
561
+
562
+ class BailingMoeV3SparseMoeBlock(nn.Module):
563
+ """
564
+ A mixed expert module containing shared experts.
565
+ """
566
+
567
+ def __init__(self, config: BailingMoeV3Config):
568
+ super().__init__()
569
+ self.config = config
570
+ self.num_experts_per_tok = config.num_experts_per_tok
571
+ self._setup_experts()
572
+ self.gate = BailingMoeV3Gate(config)
573
+ if config.num_shared_experts is not None:
574
+ self.shared_experts = BailingMoeV3MLP(
575
+ config=config, intermediate_size=config.moe_shared_expert_intermediate_size * config.num_shared_experts
576
+ )
577
+
578
+ def _setup_experts(self):
579
+ self.experts = nn.ModuleList(
580
+ [
581
+ BailingMoeV3MLP(config=self.config, intermediate_size=self.config.moe_intermediate_size)
582
+ for _ in range(self.config.num_experts)
583
+ ]
584
+ )
585
+
586
+ def forward(self, hidden_states):
587
+ identity = hidden_states
588
+ bsz, seq_len, h = hidden_states.shape
589
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
590
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
591
+ flat_topk_idx = topk_idx.view(-1)
592
+ if self.training:
593
+ hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
594
+ y = torch.empty_like(hidden_states)
595
+ for i, expert in enumerate(self.experts):
596
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
597
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
598
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
599
+ else:
600
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(bsz, seq_len, h)
601
+ if self.config.num_shared_experts is not None:
602
+ y = y + self.shared_experts(identity)
603
+ return y, (router_logits.view(bsz, seq_len, -1), topk_idx.view(bsz, seq_len, -1))
604
+
605
+ @torch.no_grad()
606
+ def moe_infer(self, x, topk_ids, topk_weight):
607
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
608
+ cnts.scatter_(1, topk_ids, 1)
609
+ tokens_per_expert = cnts.sum(dim=0)
610
+ idxs = topk_ids.view(-1).argsort()
611
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
612
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
613
+ outputs = []
614
+ start_idx = 0
615
+ for i, num_tokens in enumerate(tokens_per_expert):
616
+ end_idx = start_idx + num_tokens
617
+ if num_tokens == 0:
618
+ continue
619
+ expert = self.experts[i]
620
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
621
+ expert_out = expert(tokens_for_this_expert)
622
+ outputs.append(expert_out.to(x.device))
623
+ start_idx = end_idx
624
+
625
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
626
+ new_x = torch.empty_like(outs)
627
+ new_x[idxs] = outs
628
+ final_out = (
629
+ new_x.view(*topk_ids.shape, -1)
630
+ .type(topk_weight.dtype)
631
+ .mul_(topk_weight.unsqueeze(dim=-1))
632
+ .sum(dim=1)
633
+ .type(new_x.dtype)
634
+ )
635
+ return final_out
636
+
637
+
638
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
639
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int, head_first: bool = True) -> torch.Tensor:
640
+ """
641
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). If head_first is True, the hidden states go from (batch,
642
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
643
+ """
644
+ if n_rep == 1:
645
+ return hidden_states
646
+ if head_first:
647
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
648
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
649
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
650
+ else:
651
+ batch, slen, num_key_value_heads, head_dim = hidden_states.shape
652
+ hidden_states = hidden_states[:, :, :, None, :].expand(batch, slen, num_key_value_heads, n_rep, head_dim)
653
+ return hidden_states.reshape(batch, slen, num_key_value_heads * n_rep, head_dim)
654
+
655
+
656
+ def repeat_kv2(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
657
+ """
658
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
659
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
660
+ """
661
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
662
+ if n_rep == 1:
663
+ return hidden_states
664
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
665
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
666
+
667
+
668
+ def eager_attention_forward(
669
+ module: nn.Module,
670
+ query: torch.Tensor,
671
+ key: torch.Tensor,
672
+ value: torch.Tensor,
673
+ attention_mask: Optional[torch.Tensor],
674
+ scaling: float,
675
+ dropout: float = 0.0,
676
+ **kwargs: Unpack[TransformersKwargs],
677
+ ):
678
+ key_states = repeat_kv2(key, module.num_key_value_groups)
679
+ value_states = repeat_kv2(value, module.num_key_value_groups)
680
+
681
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
682
+ if attention_mask is not None:
683
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
684
+ attn_weights = attn_weights + causal_mask
685
+
686
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
687
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
688
+ attn_output = torch.matmul(attn_weights, value_states)
689
+ attn_output = attn_output.transpose(1, 2).contiguous()
690
+
691
+ return attn_output, attn_weights
692
+
693
+
694
+ def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
695
+ r"""
696
+ TODO let's just use the original freqcis computation to not have the view
697
+ transpose + reshape! This is not optimized!
698
+ Applies Rotary Position Embedding to the query and key tensors.
699
+
700
+ Args:
701
+ q (`torch.Tensor`): The query tensor.
702
+ k (`torch.Tensor`): The key tensor.
703
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
704
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
705
+ position_ids (`torch.Tensor`):
706
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
707
+ used to pass offsetted position ids when working with a KV-cache.
708
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
709
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
710
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
711
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
712
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
713
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
714
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
715
+ Returns:
716
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
717
+ """
718
+ cos = cos.unsqueeze(unsqueeze_dim)
719
+ sin = sin.unsqueeze(unsqueeze_dim)
720
+
721
+ b, h, s, d = q.shape
722
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
723
+
724
+ b, h, s, d = k.shape
725
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
726
+
727
+ q_embed = (q * cos) + (rotate_half(q) * sin)
728
+ k_embed = (k * cos) + (rotate_half(k) * sin)
729
+ return q_embed, k_embed
730
+
731
+
732
+ def yarn_get_mscale(scale=1, mscale=1):
733
+ if scale <= 1:
734
+ return 1.0
735
+ return 0.1 * mscale * math.log(scale) + 1.0
736
+
737
+
738
+ class BailingMoeV3MultiLatentAttention(nn.Module):
739
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
740
+
741
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
742
+ super().__init__()
743
+ self.config = config
744
+ self.layer_idx = layer_idx
745
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
746
+ self.attention_dropout = config.attention_dropout
747
+ self.num_heads = config.num_attention_heads
748
+ self.rope_theta = config.rope_theta
749
+ self.q_lora_rank = config.q_lora_rank
750
+ self.qk_rope_head_dim = config.qk_rope_head_dim
751
+ self.kv_lora_rank = config.kv_lora_rank
752
+ self.v_head_dim = config.v_head_dim
753
+ self.qk_nope_head_dim = config.qk_nope_head_dim
754
+ self.qk_head_dim = config.qk_head_dim
755
+ self.gated_attention_proj_granularity_type = config.gated_attention_proj_granularity_type
756
+
757
+ self.is_causal = True
758
+ if self.q_lora_rank is None:
759
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
760
+ else:
761
+ self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.use_qkv_bias)
762
+ self.q_a_layernorm = BailingMoeV3RMSNorm(config.q_lora_rank)
763
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
764
+
765
+ self.kv_a_proj_with_mqa = nn.Linear(
766
+ config.hidden_size,
767
+ self.kv_lora_rank + self.qk_rope_head_dim,
768
+ bias=config.use_qkv_bias,
769
+ )
770
+ self.kv_a_layernorm = BailingMoeV3RMSNorm(self.kv_lora_rank)
771
+ self.kv_b_proj = nn.Linear(
772
+ self.kv_lora_rank,
773
+ self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
774
+ bias=False,
775
+ )
776
+ if self.gated_attention_proj_granularity_type is None:
777
+ self.g_proj = None
778
+ elif self.gated_attention_proj_granularity_type == "head_wise":
779
+ self.g_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
780
+ elif self.gated_attention_proj_granularity_type == "element_wise":
781
+ self.g_proj = nn.Linear(config.hidden_size, self.num_heads * self.v_head_dim, bias=False)
782
+
783
+ self.dense = nn.Linear(
784
+ self.num_heads * self.v_head_dim,
785
+ config.hidden_size,
786
+ bias=config.use_qkv_bias,
787
+ )
788
+
789
+ self.scaling = self.qk_head_dim ** (-0.5)
790
+ # transformers 5.x populates a default rope_scaling dict without "factor";
791
+ # only apply yarn mscale when a real scaling factor is present.
792
+ if self.config.rope_scaling is not None and self.config.rope_scaling.get("factor") is not None:
793
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
794
+ scaling_factor = self.config.rope_scaling["factor"]
795
+ if mscale_all_dim:
796
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
797
+ self.scaling = self.scaling * mscale * mscale
798
+
799
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
800
+ def forward(
801
+ self,
802
+ hidden_states: torch.Tensor,
803
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
804
+ attention_mask: Optional[torch.Tensor],
805
+ past_key_values: Optional[Cache] = None,
806
+ cache_position: Optional[torch.LongTensor] = None,
807
+ **kwargs: Unpack[FlashAttentionKwargs],
808
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
809
+
810
+ batch_size, seq_length = hidden_states.shape[:-1]
811
+ query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
812
+ key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
813
+
814
+ if self.q_lora_rank is None:
815
+ q_states = self.q_proj(hidden_states)
816
+ else:
817
+ q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
818
+ q_states = q_states.view(query_shape).transpose(1, 2)
819
+ q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
820
+
821
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
822
+ k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
823
+
824
+ k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
825
+ k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
826
+
827
+ k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
828
+
829
+ cos, sin = position_embeddings # tptest
830
+ if self.config.rope_interleave: # support using interleaved weights for efficiency
831
+ q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
832
+ else:
833
+ x = 1 / 0
834
+ q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
835
+ k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
836
+
837
+ query_states = torch.cat((q_pass, q_rot), dim=-1)
838
+ key_states = torch.cat((k_pass, k_rot), dim=-1)
839
+
840
+ if past_key_values is not None:
841
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
842
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
843
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
844
+
845
+ if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
846
+ value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
847
+
848
+ attention_interface: Callable = eager_attention_forward
849
+
850
+ attn_output, attn_weights = attention_interface(
851
+ self,
852
+ query_states,
853
+ key_states,
854
+ value_states,
855
+ attention_mask,
856
+ dropout=0.0 if not self.training else self.attention_dropout,
857
+ scaling=self.scaling,
858
+ **kwargs,
859
+ )
860
+
861
+ if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
862
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
863
+
864
+ if self.g_proj is not None:
865
+ gate = self.g_proj(hidden_states)
866
+ gate = F.sigmoid(gate.float()).type_as(hidden_states)
867
+ if self.gated_attention_proj_granularity_type == "head_wise":
868
+ attn_output = attn_output * gate[:, :, :, None]
869
+ else:
870
+ attn_output = attn_output * gate.view(batch_size, seq_length, self.num_heads, self.v_head_dim)
871
+
872
+ attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
873
+ attn_output = self.dense(attn_output)
874
+ return attn_output, attn_weights, past_key_values
875
+
876
+
877
+ class BailingMoeV3KimiDeltaAttention(nn.Module):
878
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
879
+ super().__init__()
880
+ self.config = config
881
+ self.mode = "chunk"
882
+
883
+ self.hidden_size = config.hidden_size
884
+ self.conv_size = config.short_conv_kernel_size
885
+ self.head_dim = config.head_dim
886
+ self.num_heads = config.num_attention_heads
887
+ self.head_k_dim = self.head_dim
888
+ self.num_k_heads = self.num_heads
889
+ self.no_kda_lora = config.no_kda_lora
890
+ self.safe_gate = config.kda_safe_gate
891
+ self.lower_bound = config.kda_lower_bound
892
+
893
+ self.layer_idx = layer_idx
894
+
895
+ assert self.mode in ['chunk', 'fused_recurrent'], f"Not suppoerted mode `{self.mode}`."
896
+
897
+ projection_k_size = self.head_k_dim * self.num_k_heads
898
+ projection_size = self.head_dim * self.num_heads
899
+
900
+ self.q_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False)
901
+ self.k_proj = nn.Linear(self.hidden_size, projection_k_size, bias=False)
902
+ self.v_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
903
+
904
+ self.q_conv1d = ShortConvolution(
905
+ hidden_size=projection_k_size,
906
+ kernel_size=self.conv_size,
907
+ activation='silu',
908
+ )
909
+ self.k_conv1d = ShortConvolution(
910
+ hidden_size=projection_k_size,
911
+ kernel_size=self.conv_size,
912
+ activation='silu',
913
+ )
914
+ self.v_conv1d = ShortConvolution(
915
+ hidden_size=projection_size,
916
+ kernel_size=self.conv_size,
917
+ activation='silu',
918
+ )
919
+
920
+ self.A_log = torch.nn.Parameter(torch.log(torch.empty(self.num_heads, dtype=torch.float32).uniform_(1, 16)))
921
+
922
+ if self.no_kda_lora:
923
+ self.f_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
924
+ else:
925
+ self.f_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False)
926
+ self.f_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
927
+
928
+ self.dt_bias = nn.Parameter(torch.empty(projection_size, dtype=torch.float32))
929
+
930
+ self.b_proj = nn.Linear(self.hidden_size, self.num_heads, bias=False)
931
+
932
+ if self.no_kda_lora:
933
+ self.g_proj = nn.Linear(self.hidden_size, projection_size, bias=False)
934
+ else:
935
+ self.g_a_proj = nn.Linear(self.hidden_size, self.head_dim, bias=False)
936
+ self.g_b_proj = nn.Linear(self.head_dim, projection_size, bias=False)
937
+
938
+ self.o_norm = FusedRMSNormGated(self.head_dim, eps=config.rms_norm_eps, activation='sigmoid')
939
+ self.o_proj = nn.Linear(projection_size, self.hidden_size, bias=False)
940
+
941
+ def forward(
942
+ self,
943
+ hidden_states: torch.Tensor,
944
+ attention_mask: torch.Tensor | None = None,
945
+ past_key_value=None,
946
+ **kwargs: Unpack[dict],
947
+ ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]:
948
+ attention_mask = None
949
+ if attention_mask is not None:
950
+ if attention_mask.dim() != 2:
951
+ attention_mask = kwargs.get("padding_mask")
952
+
953
+ if attention_mask is not None and attention_mask.dim() != 2:
954
+ raise ValueError(
955
+ "attention_mask must be a 0-1 matrix of shape [batch_size, seq_len] "
956
+ "(0 = padding). 3D masks are not supported here.",
957
+ )
958
+ use_cache = past_key_value is not None
959
+ batch_size, q_len, _ = hidden_states.shape
960
+ mode = 'fused_recurrent' if q_len <= 64 else self.mode
961
+ if self.training:
962
+ assert mode == 'chunk', "Only chunk mode is supported in training."
963
+
964
+ cu_seqlens = kwargs.get('cu_seqlens')
965
+ indices = None
966
+ if attention_mask is not None:
967
+ indices, cu_seqlens, _ = _get_unpad_data(attention_mask[:, -q_len:])
968
+ hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
969
+
970
+ conv_state_q, conv_state_k, conv_state_v = None, None, None
971
+ recurrent_state = None
972
+
973
+ if past_key_value is not None and isinstance(past_key_value, Cache):
974
+ # ensure the cache list is long enough
975
+ while len(past_key_value.layers) <= self.layer_idx:
976
+ past_key_value.layers.append(DynamicLayer())
977
+
978
+ if past_key_value.layers[self.layer_idx].keys is not None:
979
+ recurrent_state = past_key_value.layers[self.layer_idx].keys
980
+ # ensure recurrent_state is on the same device as hidden_states
981
+ if recurrent_state.device != hidden_states.device:
982
+ recurrent_state = recurrent_state.to(hidden_states.device).contiguous()
983
+
984
+ if past_key_value.layers[self.layer_idx].values is not None:
985
+ conv_state_q, conv_state_k, conv_state_v = past_key_value.layers[self.layer_idx].values
986
+
987
+ q, conv_state_q = self.q_conv1d(
988
+ x=self.q_proj(hidden_states),
989
+ cache=conv_state_q,
990
+ output_final_state=use_cache,
991
+ cu_seqlens=cu_seqlens,
992
+ )
993
+ k, conv_state_k = self.k_conv1d(
994
+ x=self.k_proj(hidden_states),
995
+ cache=conv_state_k,
996
+ output_final_state=use_cache,
997
+ cu_seqlens=cu_seqlens,
998
+ )
999
+ v, conv_state_v = self.v_conv1d(
1000
+ x=self.v_proj(hidden_states),
1001
+ cache=conv_state_v,
1002
+ output_final_state=use_cache,
1003
+ cu_seqlens=cu_seqlens,
1004
+ )
1005
+
1006
+ if self.no_kda_lora:
1007
+ g = self.f_proj(hidden_states)
1008
+ else:
1009
+ g = self.f_b_proj(self.f_a_proj(hidden_states))
1010
+
1011
+ beta = self.b_proj(hidden_states).float().sigmoid()
1012
+
1013
+ q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
1014
+ v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
1015
+ g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
1016
+
1017
+ if mode == 'chunk':
1018
+ o, recurrent_state = chunk_kda(
1019
+ q=q,
1020
+ k=k,
1021
+ v=v,
1022
+ g=g,
1023
+ beta=beta,
1024
+ A_log=self.A_log,
1025
+ dt_bias=self.dt_bias,
1026
+ initial_state=recurrent_state,
1027
+ output_final_state=True,
1028
+ use_qk_l2norm_in_kernel=True,
1029
+ use_gate_in_kernel=True,
1030
+ safe_gate=self.safe_gate,
1031
+ lower_bound=self.lower_bound,
1032
+ cu_seqlens=cu_seqlens,
1033
+ )
1034
+ else:
1035
+ o, recurrent_state = fused_recurrent_kda(
1036
+ q=q,
1037
+ k=k,
1038
+ v=v,
1039
+ g=g,
1040
+ beta=beta,
1041
+ A_log=self.A_log,
1042
+ dt_bias=self.dt_bias,
1043
+ initial_state=recurrent_state,
1044
+ output_final_state=True,
1045
+ use_qk_l2norm_in_kernel=True,
1046
+ use_gate_in_kernel=True,
1047
+ lower_bound=self.lower_bound,
1048
+ cu_seqlens=cu_seqlens,
1049
+ )
1050
+
1051
+ if use_cache and past_key_value is not None and isinstance(past_key_value, Cache):
1052
+ target_device = None
1053
+ for cache in past_key_value.layers:
1054
+ if cache.keys is not None:
1055
+ target_device = cache.keys.device
1056
+ break
1057
+ if target_device is None:
1058
+ target_device = recurrent_state.device
1059
+
1060
+ # move to target device
1061
+ if recurrent_state.device != target_device:
1062
+ recurrent_state = recurrent_state.to(target_device)
1063
+
1064
+ past_key_value.layers[self.layer_idx].keys = recurrent_state
1065
+ past_key_value.layers[self.layer_idx].values = (conv_state_q, conv_state_k, conv_state_v)
1066
+
1067
+ if self.no_kda_lora:
1068
+ g = self.g_proj(hidden_states)
1069
+ else:
1070
+ g = self.g_b_proj(self.g_a_proj(hidden_states))
1071
+ g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
1072
+ o = self.o_norm(o, g)
1073
+
1074
+ o = rearrange(o, 'b t h d -> b t (h d)')
1075
+ o = self.o_proj(o)
1076
+ if attention_mask is not None:
1077
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
1078
+
1079
+ return o, None, past_key_value
1080
+
1081
+
1082
+ class BailingMoeV3MTPLayer(nn.Module):
1083
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
1084
+ super().__init__()
1085
+ self.layer_idx = layer_idx
1086
+ self.input_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1087
+ self.enorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1088
+
1089
+ self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
1090
+ self.post_attention_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1091
+ self.attention = BailingMoeV3MultiLatentAttention(config=config, layer_idx=layer_idx)
1092
+ self.mlp = BailingMoeV3SparseMoeBlock(config)
1093
+
1094
+ self.hnorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1095
+ self.final_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1096
+
1097
+ def forward(
1098
+ self,
1099
+ input_embeds,
1100
+ hidden_states: torch.Tensor,
1101
+ attention_mask: Optional[torch.Tensor] = None,
1102
+ position_ids: Optional[torch.LongTensor] = None,
1103
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1104
+ output_attentions: Optional[bool] = False,
1105
+ output_router_logits: Optional[bool] = False,
1106
+ use_cache: Optional[bool] = False,
1107
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
1108
+ **kwargs,
1109
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1110
+ input_embeds = self.enorm(input_embeds)
1111
+ hidden_states = self.hnorm(hidden_states)
1112
+ hidden_states = self.eh_proj(torch.cat([input_embeds, hidden_states], dim=-1))
1113
+ residual = hidden_states
1114
+
1115
+ hidden_states = self.input_layernorm(hidden_states)
1116
+
1117
+ # Self Attention
1118
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1119
+ hidden_states=hidden_states,
1120
+ attention_mask=attention_mask,
1121
+ position_ids=position_ids,
1122
+ past_key_value=past_key_value,
1123
+ output_attentions=output_attentions,
1124
+ position_embeddings=position_embeddings,
1125
+ use_cache=use_cache,
1126
+ )
1127
+ hidden_states = residual + hidden_states
1128
+
1129
+ # Fully Connected
1130
+ residual = hidden_states
1131
+ hidden_states = self.post_attention_layernorm(hidden_states)
1132
+ hidden_states = self.mlp(hidden_states)
1133
+ if isinstance(hidden_states, tuple):
1134
+ hidden_states, router_logits = hidden_states
1135
+ else:
1136
+ router_logits = None
1137
+ hidden_states = residual + hidden_states.to(residual.device)
1138
+ hidden_states = self.final_layernorm(hidden_states)
1139
+
1140
+ outputs = (hidden_states,)
1141
+
1142
+ if output_attentions:
1143
+ outputs += (self_attn_weights,)
1144
+
1145
+ if use_cache:
1146
+ outputs += (present_key_value,)
1147
+
1148
+ if output_router_logits:
1149
+ outputs += (router_logits,)
1150
+
1151
+ return outputs
1152
+
1153
+
1154
+ class BailingMoeV3DecoderLayer(nn.Module):
1155
+ def __init__(self, config: BailingMoeV3Config, layer_idx: int):
1156
+ super().__init__()
1157
+ self.hidden_size = config.hidden_size
1158
+ self.layer_idx = layer_idx
1159
+ self.attention_layer_type = (
1160
+ "attention"
1161
+ if (layer_idx + 1) % config.layer_group_size == 0
1162
+ or layer_idx >= config.num_hidden_layers // config.layer_group_size * config.layer_group_size
1163
+ else "linear_attention"
1164
+ )
1165
+
1166
+ if self.attention_layer_type == "attention":
1167
+ self.attention = BailingMoeV3MultiLatentAttention(config=config, layer_idx=layer_idx)
1168
+ else:
1169
+ self.attention = BailingMoeV3KimiDeltaAttention(config=config, layer_idx=layer_idx)
1170
+
1171
+ self.mlp = (
1172
+ BailingMoeV3SparseMoeBlock(config)
1173
+ if (config.num_experts is not None and layer_idx >= config.first_k_dense_replace)
1174
+ else BailingMoeV3MLP(config=config, intermediate_size=config.intermediate_size)
1175
+ )
1176
+ self.input_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1177
+ self.post_attention_layernorm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1178
+
1179
+ def forward(
1180
+ self,
1181
+ hidden_states: torch.Tensor,
1182
+ attention_mask: Optional[torch.Tensor] = None,
1183
+ position_ids: Optional[torch.LongTensor] = None,
1184
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1185
+ cache_position: Optional[torch.LongTensor] = None,
1186
+ output_attentions: Optional[bool] = False,
1187
+ output_router_logits: Optional[bool] = False,
1188
+ use_cache: Optional[bool] = False,
1189
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
1190
+ **kwargs,
1191
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1192
+ """
1193
+ Args:
1194
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1195
+ attention_mask (`torch.FloatTensor`, *optional*):
1196
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1197
+ query_sequence_length, key_sequence_length)` if default attention is used.
1198
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1199
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1200
+ config.n_positions - 1]`.
1201
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
1202
+ cached past key and value projection states
1203
+ output_attentions (`bool`, *optional*):
1204
+ Whether to return the attentions tensors of all attention layers. See `attentions` under
1205
+ returned tensors for more detail.
1206
+ output_router_logits (`bool`, *optional*):
1207
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
1208
+ and should not be returned during inference.
1209
+ use_cache (`bool`, *optional*):
1210
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1211
+ (see `past_key_values`).
1212
+ """
1213
+ residual = hidden_states
1214
+
1215
+ hidden_states = self.input_layernorm(hidden_states)
1216
+
1217
+ # Self Attention
1218
+ if self.attention_layer_type == "attention":
1219
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1220
+ hidden_states=hidden_states,
1221
+ attention_mask=attention_mask,
1222
+ position_ids=position_ids,
1223
+ past_key_values=past_key_value,
1224
+ use_cache=use_cache,
1225
+ cache_position=cache_position, #
1226
+ position_embeddings=position_embeddings, #
1227
+ **kwargs,
1228
+ )
1229
+ else:
1230
+ batch_size, seq_len = hidden_states.shape[0], hidden_states.shape[1]
1231
+ device = hidden_states.device
1232
+
1233
+ if attention_mask is None:
1234
+ # if attention_mask is None, create a full mask
1235
+ attention_mask = torch.ones((batch_size, seq_len), dtype=torch.int32, device=device)
1236
+ elif attention_mask.dim() == 4 and attention_mask.shape[1] == 1:
1237
+ attention_mask = attention_mask[:, 0, -1, :].to(torch.int32)
1238
+ attention_mask = (attention_mask > -1e4).to(torch.int32)
1239
+ elif attention_mask.dim() == 2:
1240
+ attention_mask = attention_mask.to(torch.int32)
1241
+ else:
1242
+ raise ValueError(f"Unsupported mask dimension: {attention_mask.shape}")
1243
+
1244
+ hidden_states, self_attn_weights, present_key_value = self.attention(
1245
+ hidden_states=hidden_states,
1246
+ attention_mask=attention_mask,
1247
+ past_key_value=past_key_value,
1248
+ position_ids=position_ids,
1249
+ use_cache=use_cache,
1250
+ output_attentions=output_attentions,
1251
+ )
1252
+
1253
+ hidden_states = residual + hidden_states
1254
+
1255
+ # Fully Connected
1256
+ residual = hidden_states
1257
+ hidden_states = self.post_attention_layernorm(hidden_states)
1258
+ hidden_states = self.mlp(hidden_states)
1259
+ if isinstance(hidden_states, tuple):
1260
+ hidden_states, router_logits = hidden_states
1261
+ else:
1262
+ router_logits = None
1263
+ hidden_states = residual + hidden_states.to(residual.device)
1264
+
1265
+ outputs = (hidden_states,)
1266
+
1267
+ if output_attentions:
1268
+ outputs += (self_attn_weights,)
1269
+
1270
+ if use_cache:
1271
+ outputs += (present_key_value,)
1272
+
1273
+ if output_router_logits:
1274
+ outputs += (router_logits,)
1275
+
1276
+ return outputs
1277
+
1278
+
1279
+ BAILINGMOEV3_START_DOCSTRING = r"""
1280
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1281
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1282
+ etc.)
1283
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1284
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1285
+ and behavior.
1286
+ Parameters:
1287
+ config ([`BailingMoeV3Config`]):
1288
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1289
+ load the weights associated with the model, only the configuration. Check out the
1290
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1291
+ """
1292
+
1293
+
1294
+ @add_start_docstrings(
1295
+ "The bare BailingMoeV3 Model outputting raw hidden-states without any specific head on top.",
1296
+ BAILINGMOEV3_START_DOCSTRING,
1297
+ )
1298
+ class BailingMoeV3PreTrainedModel(PreTrainedModel):
1299
+ config_class = BailingMoeV3Config
1300
+ base_model_prefix = "model"
1301
+ supports_gradient_checkpointing = True
1302
+ _no_split_modules = ["BailingMoeV3DecoderLayer"]
1303
+ _skip_keys_device_placement = "past_key_values"
1304
+ _supports_flash_attn_2 = True
1305
+ _supports_sdpa = True
1306
+ _supports_cache_class = True
1307
+
1308
+ def _init_weights(self, module):
1309
+ std = self.config.initializer_range
1310
+ if isinstance(module, nn.Linear):
1311
+ module.weight.data.normal_(mean=0.0, std=std)
1312
+ if module.bias is not None:
1313
+ module.bias.data.zero_()
1314
+ elif isinstance(module, nn.Embedding):
1315
+ module.weight.data.normal_(mean=0.0, std=std)
1316
+ if module.padding_idx is not None:
1317
+ module.weight.data[module.padding_idx].zero_()
1318
+
1319
+
1320
+ BAILINGMOEV3_INPUTS_DOCSTRING = r"""
1321
+ Args:
1322
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1323
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1324
+ it.
1325
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1326
+ [`PreTrainedTokenizer.__call__`] for details.
1327
+ [What are input IDs?](../glossary#input-ids)
1328
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1329
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1330
+ - 1 for tokens that are **not masked**,
1331
+ - 0 for tokens that are **masked**.
1332
+ [What are attention masks?](../glossary#attention-mask)
1333
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1334
+ [`PreTrainedTokenizer.__call__`] for details.
1335
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1336
+ `past_key_values`).
1337
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1338
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1339
+ information on the default strategy.
1340
+ - 1 indicates the head is **not masked**,
1341
+ - 0 indicates the head is **masked**.
1342
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1343
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1344
+ config.n_positions - 1]`.
1345
+ [What are position IDs?](../glossary#position-ids)
1346
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1347
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1348
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1349
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1350
+ Two formats are allowed:
1351
+ - a [`~cache_utils.Cache`] instance;
1352
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1353
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1354
+ cache format.
1355
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1356
+ legacy cache format will be returned.
1357
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1358
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1359
+ of shape `(batch_size, sequence_length)`.
1360
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1361
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1362
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1363
+ model's internal embedding lookup matrix.
1364
+ use_cache (`bool`, *optional*):
1365
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1366
+ `past_key_values`).
1367
+ output_attentions (`bool`, *optional*):
1368
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1369
+ tensors for more detail.
1370
+ output_hidden_states (`bool`, *optional*):
1371
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1372
+ more detail.
1373
+ return_dict (`bool`, *optional*):
1374
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1375
+ """
1376
+
1377
+
1378
+ @add_start_docstrings(
1379
+ "The bare BailingMoeV3 Model outputting raw hidden-states without any specific head on top.",
1380
+ BAILINGMOEV3_START_DOCSTRING,
1381
+ )
1382
+ class BailingMoeV3Model(BailingMoeV3PreTrainedModel):
1383
+ """
1384
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BailingMoeV3DecoderLayer`]
1385
+ Args:
1386
+ config: BailingMoeV3Config
1387
+ """
1388
+
1389
+ def __init__(self, config: BailingMoeV3Config):
1390
+ super().__init__(config)
1391
+ self.padding_idx = config.pad_token_id
1392
+ self.vocab_size = config.vocab_size
1393
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1394
+
1395
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1396
+ self.layers = []
1397
+ for layer_idx in range(config.num_hidden_layers + config.num_nextn_predict_layers):
1398
+ layer_cls = BailingMoeV3DecoderLayer if layer_idx < config.num_hidden_layers else BailingMoeV3MTPLayer
1399
+ self.layers.append(layer_cls(config, layer_idx))
1400
+
1401
+ self.layers = nn.ModuleList(self.layers)
1402
+
1403
+ self._use_sdpa = config._attn_implementation == "sdpa"
1404
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1405
+ self.norm = BailingMoeV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1406
+ self.rotary_emb = BailingMoeV3RotaryEmbedding(config=config)
1407
+ self.gradient_checkpointing = False
1408
+ # Initialize weights and apply final processing
1409
+ self.post_init()
1410
+
1411
+ def get_input_embeddings(self):
1412
+ return self.word_embeddings
1413
+
1414
+ def set_input_embeddings(self, value):
1415
+ self.word_embeddings = value
1416
+
1417
+ @add_start_docstrings_to_model_forward(BAILINGMOEV3_INPUTS_DOCSTRING)
1418
+ def forward(
1419
+ self,
1420
+ input_ids: torch.LongTensor = None,
1421
+ attention_mask: Optional[torch.Tensor] = None,
1422
+ position_ids: Optional[torch.LongTensor] = None,
1423
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1424
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1425
+ cache_position: Optional[torch.LongTensor] = None,
1426
+ use_cache: Optional[bool] = None,
1427
+ output_attentions: Optional[bool] = None,
1428
+ output_hidden_states: Optional[bool] = None,
1429
+ output_router_logits: Optional[bool] = None,
1430
+ return_dict: Optional[bool] = None,
1431
+ **kwargs,
1432
+ ) -> Union[Tuple, MoeV3ModelOutputWithPast]:
1433
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1434
+ output_hidden_states = (
1435
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1436
+ )
1437
+ output_router_logits = (
1438
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1439
+ )
1440
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1441
+
1442
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1443
+
1444
+ # retrieve input_ids and inputs_embeds
1445
+ if input_ids is not None and inputs_embeds is not None:
1446
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1447
+ elif input_ids is not None:
1448
+ batch_size, seq_length = input_ids.shape[:2]
1449
+ elif inputs_embeds is not None:
1450
+ batch_size, seq_length = inputs_embeds.shape[:2]
1451
+ else:
1452
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1453
+
1454
+ if self.gradient_checkpointing and self.training:
1455
+ if use_cache:
1456
+ logger.warning_once(
1457
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1458
+ )
1459
+ use_cache = False
1460
+
1461
+ if use_cache and past_key_values is None:
1462
+ past_key_values = DynamicCache()
1463
+
1464
+ if inputs_embeds is None:
1465
+ inputs_embeds = self.word_embeddings(input_ids)
1466
+
1467
+ if cache_position is None:
1468
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1469
+ cache_position: torch.Tensor = torch.arange(
1470
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1471
+ )
1472
+
1473
+ if position_ids is None:
1474
+ position_ids = cache_position.unsqueeze(0)
1475
+
1476
+ softmax_attention_layer_id = self.config.layer_group_size - 1
1477
+ past_seen_tokens = (
1478
+ past_key_values.get_seq_length(layer_idx=softmax_attention_layer_id) if past_key_values is not None else 0
1479
+ )
1480
+
1481
+ if position_ids is None:
1482
+ position_ids = torch.arange(
1483
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1484
+ )
1485
+ position_ids = position_ids.unsqueeze(0)
1486
+
1487
+ if self._use_flash_attention_2:
1488
+ # 2d mask is passed through the layers
1489
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1490
+ elif self._use_sdpa and not output_attentions:
1491
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1492
+ # the manual implementation that requires a 4D causal mask in all cases.
1493
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1494
+ attention_mask,
1495
+ (batch_size, seq_length),
1496
+ inputs_embeds,
1497
+ past_seen_tokens,
1498
+ )
1499
+ else:
1500
+ # 4d mask is passed through the layers
1501
+ attention_mask = _prepare_4d_causal_attention_mask(
1502
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens
1503
+ )
1504
+
1505
+ # embed positions
1506
+ hidden_states = inputs_embeds
1507
+
1508
+ # create position embeddings to be shared across the decoder layers
1509
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1510
+
1511
+ # decoder layers
1512
+ all_hidden_states = () if output_hidden_states else None
1513
+ all_self_attns = () if output_attentions else None
1514
+ all_router_logits = () if output_router_logits else None
1515
+ next_decoder_cache = None
1516
+ layers = self.layers[: -self.num_nextn_predict_layers] if self.num_nextn_predict_layers > 0 else self.layers
1517
+ mtp_layers = self.layers[-self.num_nextn_predict_layers :] if self.num_nextn_predict_layers > 0 else None
1518
+
1519
+ # tptest miss causal_mask = create_causal_mask(
1520
+
1521
+ for decoder_layer in layers:
1522
+ if output_hidden_states:
1523
+ all_hidden_states += (hidden_states,)
1524
+
1525
+ if self.gradient_checkpointing and self.training:
1526
+ layer_outputs = self._gradient_checkpointing_func(
1527
+ decoder_layer.__call__,
1528
+ hidden_states,
1529
+ attention_mask,
1530
+ position_ids,
1531
+ past_key_values,
1532
+ cache_position,
1533
+ output_attentions,
1534
+ output_router_logits,
1535
+ use_cache,
1536
+ position_embeddings,
1537
+ )
1538
+ else:
1539
+ layer_outputs = decoder_layer(
1540
+ hidden_states,
1541
+ attention_mask=attention_mask,
1542
+ position_ids=position_ids,
1543
+ past_key_value=past_key_values,
1544
+ cache_position=cache_position,
1545
+ output_attentions=output_attentions,
1546
+ output_router_logits=output_router_logits,
1547
+ use_cache=use_cache,
1548
+ position_embeddings=position_embeddings,
1549
+ )
1550
+ hidden_states = layer_outputs[0]
1551
+
1552
+ if use_cache:
1553
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1554
+
1555
+ if output_attentions:
1556
+ all_self_attns += (layer_outputs[1],)
1557
+
1558
+ if output_router_logits and layer_outputs[-1] is not None:
1559
+ all_router_logits += (layer_outputs[-1],)
1560
+
1561
+ hidden_states = self.norm(hidden_states)
1562
+ main_hidden_states = hidden_states
1563
+
1564
+ # add hidden states from the last decoder layer
1565
+ if output_hidden_states:
1566
+ all_hidden_states += (main_hidden_states,)
1567
+
1568
+ mtp_hidden_states = None
1569
+
1570
+ if mtp_layers:
1571
+ for decoder_layer in mtp_layers:
1572
+ input_ids, _ = roll_tensor(input_ids, shifts=-1, dims=-1)
1573
+ inputs_embeds = self.word_embeddings(input_ids)
1574
+
1575
+ if self.gradient_checkpointing and self.training:
1576
+ layer_outputs = self._gradient_checkpointing_func(
1577
+ decoder_layer.__call__,
1578
+ inputs_embeds,
1579
+ hidden_states,
1580
+ attention_mask,
1581
+ position_ids,
1582
+ past_key_values,
1583
+ output_attentions,
1584
+ output_router_logits,
1585
+ use_cache,
1586
+ position_embeddings,
1587
+ )
1588
+ else:
1589
+ layer_outputs = decoder_layer(
1590
+ inputs_embeds,
1591
+ hidden_states,
1592
+ attention_mask=attention_mask,
1593
+ position_ids=position_ids,
1594
+ past_key_value=past_key_values,
1595
+ output_attentions=output_attentions,
1596
+ output_router_logits=output_router_logits,
1597
+ use_cache=use_cache,
1598
+ position_embeddings=position_embeddings,
1599
+ )
1600
+ if mtp_hidden_states is None:
1601
+ mtp_hidden_states = []
1602
+ hidden_states = layer_outputs[0]
1603
+ mtp_hidden_states.append(hidden_states)
1604
+
1605
+ if output_hidden_states:
1606
+ all_hidden_states += (hidden_states,)
1607
+
1608
+ if use_cache:
1609
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1610
+
1611
+ if output_attentions:
1612
+ all_self_attns += (layer_outputs[1],)
1613
+
1614
+ if output_router_logits and layer_outputs[-1] is not None:
1615
+ all_router_logits += (layer_outputs[-1],)
1616
+
1617
+ next_cache = None
1618
+ if use_cache:
1619
+ next_cache = next_decoder_cache
1620
+ if not return_dict:
1621
+ return tuple(
1622
+ v
1623
+ for v in [main_hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1624
+ if v is not None
1625
+ )
1626
+ return MoeV3ModelOutputWithPast(
1627
+ last_hidden_state=main_hidden_states,
1628
+ past_key_values=next_cache,
1629
+ hidden_states=all_hidden_states,
1630
+ mtp_hidden_states=mtp_hidden_states,
1631
+ attentions=all_self_attns,
1632
+ router_logits=all_router_logits,
1633
+ )
1634
+
1635
+
1636
+ class BailingMoeV3ForCausalLM(BailingMoeV3PreTrainedModel, GenerationMixin):
1637
+ # transformers 5.x expects a dict (4.x used a list); this model sets
1638
+ # tie_word_embeddings=false so nothing is tied -> empty mapping.
1639
+ _tied_weights_keys = {}
1640
+
1641
+ def __init__(self, config: BailingMoeV3Config):
1642
+ super().__init__(config)
1643
+ self.model = BailingMoeV3Model(config)
1644
+ self.vocab_size = config.vocab_size
1645
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1646
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1647
+ self.mtp_loss_scaling_factor = config.mtp_loss_scaling_factor
1648
+
1649
+ # Initialize weights and apply final processing
1650
+ self.post_init()
1651
+
1652
+ def get_input_embeddings(self):
1653
+ return self.model.word_embeddings
1654
+
1655
+ def set_input_embeddings(self, value):
1656
+ self.model.word_embeddings = value
1657
+
1658
+ def get_output_embeddings(self):
1659
+ return self.lm_head
1660
+
1661
+ def set_output_embeddings(self, new_embeddings):
1662
+ self.lm_head = new_embeddings
1663
+
1664
+ def set_decoder(self, decoder):
1665
+ self.model = decoder
1666
+
1667
+ def get_decoder(self):
1668
+ return self.model
1669
+
1670
+ @add_start_docstrings_to_model_forward(BAILINGMOEV3_INPUTS_DOCSTRING)
1671
+ @replace_return_docstrings(output_type=MoEV3CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1672
+ def forward(
1673
+ self,
1674
+ input_ids: torch.LongTensor = None,
1675
+ attention_mask: Optional[torch.Tensor] = None,
1676
+ position_ids: Optional[torch.LongTensor] = None,
1677
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1678
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1679
+ labels: Optional[torch.LongTensor] = None,
1680
+ use_cache: Optional[bool] = None,
1681
+ output_attentions: Optional[bool] = None,
1682
+ output_hidden_states: Optional[bool] = None,
1683
+ output_router_logits: Optional[bool] = None,
1684
+ return_dict: Optional[bool] = None,
1685
+ **kwargs,
1686
+ ) -> Union[Tuple, MoEV3CausalLMOutputWithPast]:
1687
+ r"""
1688
+ Args:
1689
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1690
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1691
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1692
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1693
+ Returns:
1694
+ Example:
1695
+ ```python
1696
+ >>> from transformers import AutoTokenizer
1697
+ >>> model = BailingMoeV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1698
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1699
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1700
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1701
+ >>> # Generate
1702
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1703
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1704
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1705
+ ```"""
1706
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1707
+ output_hidden_states = (
1708
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1709
+ )
1710
+ output_router_logits = (
1711
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1712
+ )
1713
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1714
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1715
+ outputs = self.model(
1716
+ input_ids=input_ids,
1717
+ attention_mask=attention_mask,
1718
+ position_ids=position_ids,
1719
+ past_key_values=past_key_values,
1720
+ inputs_embeds=inputs_embeds,
1721
+ use_cache=use_cache,
1722
+ output_attentions=output_attentions,
1723
+ output_hidden_states=output_hidden_states,
1724
+ output_router_logits=output_router_logits,
1725
+ return_dict=return_dict,
1726
+ **kwargs,
1727
+ )
1728
+
1729
+ loss = None
1730
+ all_mtp_loss = None
1731
+ aux_loss = None
1732
+ hidden_states = outputs[0]
1733
+ logits = self.lm_head(hidden_states)
1734
+ logits = logits.float()
1735
+
1736
+ if labels is not None:
1737
+ loss = self.loss_function(logits, labels, self.config.vocab_size, **kwargs)
1738
+
1739
+ all_mtp_logits = None
1740
+ if self.num_nextn_predict_layers > 0:
1741
+ mtp_hidden_states = outputs.mtp_hidden_states
1742
+ shift_labels_mtp = None
1743
+ for i in range(self.num_nextn_predict_layers):
1744
+ mtp_hidden_states = mtp_hidden_states[i]
1745
+ mtp_logits = self.lm_head(mtp_hidden_states).float()
1746
+ if all_mtp_logits is None:
1747
+ all_mtp_logits = []
1748
+ all_mtp_logits.append(mtp_logits)
1749
+ if labels is not None:
1750
+ if shift_labels_mtp is None:
1751
+ shift_labels_mtp = labels.clone()
1752
+ shift_labels_mtp, _ = roll_tensor(shift_labels_mtp, shifts=-1, dims=-1, fill_value=-100)
1753
+ mtp_logits_ = mtp_logits.view(-1, self.config.vocab_size)
1754
+ mtp_loss = self.loss_function(
1755
+ mtp_logits_, shift_labels_mtp.to(mtp_logits_.device).view(-1), self.config.vocab_size, **kwargs
1756
+ )
1757
+ if loss is not None:
1758
+ loss += self.mtp_loss_scaling_factor * mtp_loss
1759
+ else:
1760
+ loss = self.mtp_loss_scaling_factor * mtp_loss
1761
+
1762
+ if all_mtp_loss is None:
1763
+ all_mtp_loss = []
1764
+ all_mtp_loss.append(mtp_loss)
1765
+
1766
+ if not return_dict:
1767
+ output = (logits,) + outputs[1:]
1768
+ if output_router_logits:
1769
+ output = (aux_loss,) + output
1770
+ return (loss,) + output if loss is not None else output
1771
+
1772
+ return MoEV3CausalLMOutputWithPast(
1773
+ loss=loss,
1774
+ mtp_loss=all_mtp_loss,
1775
+ aux_loss=aux_loss,
1776
+ logits=logits,
1777
+ mtp_logits=all_mtp_logits,
1778
+ past_key_values=outputs.past_key_values,
1779
+ hidden_states=outputs.hidden_states,
1780
+ attentions=outputs.attentions,
1781
+ router_logits=outputs.router_logits,
1782
+ )
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98279ab5817f4e892add29cc6184c941461a3ff8daf6254f5ef0f0d318998317
3
+ size 12205899
tokenizer_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "cls_token": "[CLS]",
6
+ "eos_token": "<|role_end|>",
7
+ "fast_tokenizer": true,
8
+ "gmask_token": "[gMASK]",
9
+ "is_local": true,
10
+ "local_files_only": false,
11
+ "merges_file": null,
12
+ "model_max_length": 1000000000000000019884624838656,
13
+ "model_specific_special_tokens": {
14
+ "gmask_token": "[gMASK]"
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "tokenizer_class": "TokenizersBackend"
18
+ }