rulixiang commited on
Commit
7f802aa
·
1 Parent(s): b735a17

update modeling and readme

Browse files
README.md CHANGED
@@ -1,3 +1,276 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model:
4
+ - inclusionAI/Ling-mini-base-2.0
5
+ ---
6
+
7
+
8
+
9
+ <p align="center">
10
+ <img src="https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*4QxcQrBlTiAAAAAAQXAAAAgAemJ7AQ/original" width="100"/>
11
+ <p>
12
+
13
+ <p align="center">🤗 <a href="https://huggingface.co/inclusionAI">Hugging Face</a>&nbsp&nbsp | &nbsp&nbsp🤖 <a href="https://modelscope.cn/organization/inclusionAI">ModelScope</a></p>
14
+
15
+
16
+ ## Introduction
17
+
18
+ Today, we are excited to announce the open-sourcing of __Ling 2.0__ — a family of MoE-based large language models that combine __SOTA performance__ with __high efficiency__.
19
+ The first released version, Ling-mini-2.0, is compact yet powerful. It has __16B total parameters__, but only __1.4B__ are activated per input token (non-embedding 789M). Trained on more than __20T tokens__ of high-quality data and enhanced through multi-stage supervised fine-tuning and reinforcement learning, Ling-mini-2.0 achieves remarkable improvements in complex reasoning and instruction following. With just 1.4B activated parameters, it still reaches the top-tier level of sub-10B dense LLMs and even matches or surpasses much larger MoE models.
20
+
21
+ <p align="center"><img src="https://mdn.alipayobjects.com/huamei_fi95qp/afts/img/2NKZS5LVXzcAAAAASBAAAAgADkZ7AQFr/fmt.webp" /></p>
22
+
23
+ ### Strong General and Professional Reasoning
24
+
25
+ We evaluated Ling-mini-2.0 on challenging general reasoning tasks in coding (LiveCodeBench, CodeForces) and mathematics (AIME 2025, HMMT 2025), as well as knowledge-intensive reasoning tasks across multiple domains (MMLU-Pro, Humanity's Last Exam). Compared with sub-10B dense models (e.g., Qwen3-4B-instruct-2507, Qwen3-8B-nothinking) and larger-scale MoE models (Ernie-4.5-21B-A3B-PT, GPT-OSS-20B/low), Ling-mini-2.0 demonstrated outstanding overall reasoning capabilities.
26
+
27
+ ### 7× Equivalent Dense Performance Leverage
28
+
29
+ Guided by [Ling Scaling Laws](https://arxiv.org/abs/2507.17702), Ling 2.0 adopts a __1/32 activation ratio__ MoE architecture, with empirically optimized design choices in expert granularity, shared expert ratio, attention ratio, aux-loss free + sigmoid routing strategy, MTP loss, QK-Norm, half RoPE, and more. This enables small-activation MoE models to achieve over __7× equivalent dense performance__. In other words, __Ling-mini-2.0 with only 1.4B activated parameters (non-embedding 789M) can deliver performance equivalent to a 7–8B dense model__.
30
+
31
+ ### High-speed Generation at 300+ token/s
32
+
33
+ <p align="center"><img src="https://mdn.alipayobjects.com/huamei_fi95qp/afts/img/bnxIRaK9tzcAAAAAgSAAAAgADkZ7AQFr/original" /></p>
34
+
35
+ The highly sparse small-activation MoE architecture also delivers significant training and inference efficiency. In simple QA scenarios (within 2000 tokens), __Ling-mini-2.0 generates at 300+ token/s (on H20 deployment)__ — more than __2× faster__ than an 8B dense model. Ling-mini-2.0 is able to handle __128K context length__ with YaRN, as sequence length increases, the relative speedup can reach __over 7×__.
36
+
37
+ <p align="center"><img src="https://raw.githubusercontent.com/inclusionAI/Ling-V2/refs/heads/main/figures/needle_in_a_haystack.webp" /></p>
38
+
39
+ ### Open-sourced FP8 Efficient Training Solution
40
+
41
+ Ling 2.0 employs __FP8 mixed-precision training__ throughout. Compared with BF16, experiments with over 1T training tokens show nearly identical loss curves and downstream benchmark performance. To support the community in efficient continued pretraining and fine-tuning under limited compute, we are also open-sourcing our __FP8 training solution__. Based on tile/blockwise FP8 scaling, it further introduces FP8 optimizer, FP8 on-demand transpose weight, and FP8 padding routing map for extreme memory optimization. On 8/16/32 80G GPUs, compared with LLaMA 3.1 8B and Qwen3 8B, __Ling-mini-2.0 achieved 30–60% throughput gains with MTP enabled, and 90–120% throughput gains with MTP disabled__.
42
+
43
+ ### A More Open Opensource Strategy
44
+
45
+ We believe Ling-mini-2.0 is an ideal starting point for MoE research. For the first time at this scale, it integrates 1/32 sparsity, MTP layers, and FP8 training — achieving both strong effectiveness and efficient training/inference performance, making it a prime candidate for the small-size LLM segment.
46
+ To further foster community research, in addition to releasing the post-trained version, we are also open-sourcing __five pretraining checkpoints__: the pre-finetuning Ling-mini-2.0-base, along with four base models trained on 5T, 10T, 15T, and 20T tokens, enabling deeper research and broader applications.
47
+
48
+
49
+ ## Model Downloads
50
+
51
+ You can download the following table to see the various stage of Ling-mini-2.0 models(1.43B activated of 16.26B total params). If you are located in mainland China, we also provide the model on ModelScope.cn to speed up the download process.
52
+
53
+ <center>
54
+
55
+ | **Model** | **Context Length** | **Download** |
56
+ |:----------------------:| :----------------: |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
57
+ | Ling-mini-base-2.0 | 32K -> 128K (YaRN) | [🤗 HuggingFace](https://huggingface.co/inclusionAI/Ling-mini-base-2.0) <br>[🤖 ModelScope](https://www.modelscope.cn/models/inclusionAI/Ling-mini-base-2.0) |
58
+ | Ling-mini-base-2.0-5T | 4K | [🤗 HuggingFace](https://huggingface.co/inclusionAI/Ling-mini-base-2.0-5T) <br>[🤖 ModelScope](https://www.modelscope.cn/models/inclusionAI/Ling-mini-base-2.0-5T) |
59
+ | Ling-mini-base-2.0-10T | 4K | [🤗 HuggingFace](https://huggingface.co/inclusionAI/Ling-mini-base-2.0-10T) <br>[🤖 ModelScope](https://www.modelscope.cn/models/inclusionAI/Ling-mini-base-2.0-10T) |
60
+ | Ling-mini-base-2.0-15T | 4K | [🤗 HuggingFace](https://huggingface.co/inclusionAI/Ling-mini-base-2.0-15T) <br>[🤖 ModelScope](https://www.modelscope.cn/models/inclusionAI/Ling-mini-base-2.0-15T) |
61
+ | Ling-mini-base-2.0-20T | 4K | [🤗 HuggingFace](https://huggingface.co/inclusionAI/Ling-mini-base-2.0-20T) <br>[🤖 ModelScope](https://www.modelscope.cn/models/inclusionAI/Ling-mini-base-2.0-20T) |
62
+ | Ling-mini-2.0 | 32K -> 128K (YaRN) | [🤗 HuggingFace](https://huggingface.co/inclusionAI/Ling-mini-2.0) <br>[🤖 ModelScope](https://www.modelscope.cn/models/inclusionAI/Ling-mini-2.0) |
63
+
64
+ </center>
65
+
66
+ Note: If you are interested in previous version, please visit the past model collections in [Huggingface](https://huggingface.co/inclusionAI) or [ModelScope](https://modelscope.cn/organization/inclusionAI).
67
+
68
+
69
+ ## Quickstart
70
+
71
+ ### Convert to safetensors
72
+
73
+ Models with safetensors format can be downloaded from [HuggingFace](https://huggingface.co/inclusionAI) or [ModelScope](https://modelscope.cn/organization/inclusionAI).
74
+ If you want to train your model and eval it, you can convert from dcp produced by training.
75
+ ```shell
76
+ python tools/convert_dcp_to_safe_tensors.py --checkpoint-path ${DCP_PATH} --target-path ${SAFETENSORS_PATH}
77
+ ```
78
+
79
+ Currently, BF16 and FP8 formats are supported, you can use convert parameter to handle it:
80
+ - `--force-bf16` for BF16 format.
81
+ - `--force-fp8` for FP8 format.
82
+
83
+ ### 🤗 Hugging Face Transformers
84
+
85
+ Here is a code snippet to show you how to use the chat model with `transformers`:
86
+
87
+ ```python
88
+ from transformers import AutoModelForCausalLM, AutoTokenizer
89
+
90
+ model_name = "inclusionAI/Ling-mini-2.0"
91
+
92
+ model = AutoModelForCausalLM.from_pretrained(
93
+ model_name,
94
+ dtype="auto",
95
+ device_map="auto",
96
+ trust_remote_code=True,
97
+ )
98
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
99
+
100
+ prompt = "Give me a short introduction to large language models."
101
+ messages = [
102
+ {"role": "system", "content": "You are Ling, an assistant created by inclusionAI"},
103
+ {"role": "user", "content": prompt}
104
+ ]
105
+ text = tokenizer.apply_chat_template(
106
+ messages,
107
+ tokenize=False,
108
+ add_generation_prompt=True
109
+ )
110
+ model_inputs = tokenizer([text], return_tensors="pt", return_token_type_ids=False).to(model.device)
111
+
112
+ generated_ids = model.generate(
113
+ **model_inputs,
114
+ max_new_tokens=512
115
+ )
116
+ generated_ids = [
117
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
118
+ ]
119
+
120
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
121
+ ```
122
+
123
+ ### 🤖 ModelScope
124
+
125
+ If you're in mainland China, we strongly recommend you to use our model from 🤖 <a href="https://modelscope.cn/organization/inclusionAI">ModelScope</a>.
126
+
127
+ ## Deployment
128
+
129
+ ### vLLM
130
+
131
+ vLLM supports offline batched inference or launching an OpenAI-Compatible API Service for online inference.
132
+
133
+ #### Environment Preparation
134
+
135
+ Since the Pull Request (PR) has not been submitted to the vLLM community at this stage, please prepare the environment by following the steps below:
136
+
137
+ ```bash
138
+ git clone -b v0.10.0 https://github.com/vllm-project/vllm.git
139
+ cd vllm
140
+ git apply Ling-V2/inference/vllm/bailing_moe_v2.patch
141
+ pip install -e .
142
+ ```
143
+
144
+ #### Offline Inference:
145
+
146
+ ```bash
147
+ from transformers import AutoTokenizer
148
+ from vllm import LLM, SamplingParams
149
+
150
+ tokenizer = AutoTokenizer.from_pretrained("inclusionAI/Ling-mini-2.0")
151
+
152
+ sampling_params = SamplingParams(temperature=0.7, top_p=0.8, repetition_penalty=1.05, max_tokens=16384)
153
+
154
+ llm = LLM(model="inclusionAI/Ling-mini-2.0", dtype='bfloat16')
155
+ prompt = "Give me a short introduction to large language models."
156
+ messages = [
157
+ {"role": "system", "content": "You are Ling, an assistant created by inclusionAI"},
158
+ {"role": "user", "content": prompt}
159
+ ]
160
+
161
+ text = tokenizer.apply_chat_template(
162
+ messages,
163
+ tokenize=False,
164
+ add_generation_prompt=True
165
+ )
166
+ outputs = llm.generate([text], sampling_params)
167
+
168
+ ```
169
+
170
+ #### Online Inference:
171
+
172
+ ```bash
173
+ vllm serve inclusionAI/Ling-mini-2.0 \
174
+ --tensor-parallel-size 2 \
175
+ --pipeline-parallel-size 1 \
176
+ --use-v2-block-manager \
177
+ --gpu-memory-utilization 0.90
178
+ ```
179
+
180
+ To handle long context in vLLM using YaRN, we need to follow these two steps:
181
+ 1. Add a `rope_scaling` field to the model's `config.json` file, for example:
182
+ ```json
183
+ {
184
+ ...,
185
+ "rope_scaling": {
186
+ "factor": 4.0,
187
+ "original_max_position_embeddings": 32768,
188
+ "type": "yarn"
189
+ }
190
+ }
191
+ ```
192
+ 2. Use an additional parameter `--max-model-len` to specify the desired maximum context length when starting the vLLM service.
193
+
194
+ For detailed guidance, please refer to the vLLM [`instructions`](https://docs.vllm.ai/en/latest/).
195
+
196
+
197
+ ### SGLang
198
+
199
+ #### Environment Preparation
200
+
201
+ We will later submit our model to SGLang official release, now we can prepare the environment following steps:
202
+ ```shell
203
+ pip3 install sglang==0.5.2rc0 sgl-kernel==0.3.7.post1
204
+ ```
205
+ You can use docker image as well:
206
+ ```shell
207
+ docker pull lmsysorg/sglang:v0.5.2rc0-cu126
208
+ ```
209
+ Then you should apply patch to sglang installation:
210
+ ```shell
211
+ # patch command is needed, run `yum install -y patch` if needed
212
+ patch -d `python -c 'import sglang;import os; print(os.path.dirname(sglang.__file__))'` -p3 < inference/sglang/bailing_moe_v2.patch
213
+ ```
214
+
215
+ #### Run Inference
216
+
217
+ BF16 and FP8 models are supported by SGLang now, it depends on the dtype of the model in ${MODEL_PATH}. They both share the same command in the following:
218
+
219
+ - Start server:
220
+ ```shell
221
+ python -m sglang.launch_server \
222
+ --model-path $MODLE_PATH \
223
+ --host 0.0.0.0 --port $PORT \
224
+ --trust-remote-code \
225
+ --attention-backend fa3
226
+ ```
227
+ MTP is supported for base model, and not yet for chat model. You can add parameter `--speculative-algorithm NEXTN`
228
+ to start command.
229
+
230
+ - Client:
231
+ ```shell
232
+ curl -s http://localhost:${PORT}/v1/chat/completions \
233
+ -H "Content-Type: application/json" \
234
+ -d '{"model": "auto", "messages": [{"role": "user", "content": "What is the capital of France?"}]}'
235
+ """
236
+ ```
237
+ More usage can be found [here](https://docs.sglang.ai/basic_usage/send_request.html)
238
+
239
+ ## Training
240
+
241
+ We also provide a complete and efficient training framework that covers both pre-training and finetune. Based on this framework, continue training can be performed on the Ling-mini-2.0 checkpoint. With our training framework, the training throughput of the Ling-mini-2.0 model is significantly better than that of the existing Dense 8B model (Qwen3-8B, Llama3-8B).
242
+
243
+ ### Pre-training
244
+
245
+ [Pretraining demo](https://github.com/inclusionAI/Ling-V2/blob/main/docs/gpu_based_training.md) to Continue pretraining Ling models.
246
+
247
+ #### Performance Benchmark
248
+
249
+ The table below shows the pre-training performance of several models, measured in **tokens per second** on 8, 16, and 32 80G GPUs. Ling-mini-2.0 achieves significantly higher training efficiency compared to the baseline, making it easier and more cost-effective to continue pre-training with our [demo scripts](https://github.com/inclusionAI/Ling-V2/blob/main/docs/gpu_based_training.md).
250
+
251
+ <center>
252
+
253
+ | **Model** | **8 x 80G GPUs (GBS=128)** | **16 x 80G GPUs (GBS=256)** | **32 x 80G GPUs (GBS=512)** |
254
+ |:-----------------------:| :--------------------: | :---------------------: | :---------------------: |
255
+ | LLaMA 3.1 8B (baseline) | 81222 | 161319 | 321403 |
256
+ | Qwen3 8B | 55775 (-31.33%) | 109799 (-31.94%) | 219943 (-31.57%) |
257
+ | Ling-mini-2.0 | 109532 (+34.86%) | 221585 (+37.36%) | 448726 (+39.61%) |
258
+ | Ling-mini-2.0 w/o MTP | 128298 (+57.96%) | 307264 (+90.47%) | 611466 (+90.25%) |
259
+
260
+ </center>
261
+
262
+ ### Finetuning
263
+
264
+ We recommend you to use [Llama-Factory](https://github.com/hiyouga/LLaMA-Factory) to [finetune Ling](https://github.com/inclusionAI/Ling-V2/blob/main/docs/llamafactory_finetuning.md). In addition to that, you can also use [Megatron for finetuning](https://github.com/inclusionAI/Ling-V2/blob/main/docs/megatron_sft_training.md).
265
+
266
+ ## License
267
+
268
+ This code repository is licensed under [the MIT License](https://github.com/inclusionAI/Ling-V2/blob/master/LICENCE).
269
+
270
+ ## Citation
271
+
272
+ If you find our work helpful, feel free to give us a cite.
273
+
274
+ ```
275
+
276
+ ```
config.json CHANGED
@@ -47,5 +47,5 @@
47
  "use_qk_norm": true,
48
  "score_function": "sigmoid",
49
  "moe_shared_expert_intermediate_size": 512,
50
- "num_nextn_predict_layers": 1
51
  }
 
47
  "use_qk_norm": true,
48
  "score_function": "sigmoid",
49
  "moe_shared_expert_intermediate_size": 512,
50
+ "num_nextn_predict_layers": 0
51
  }
configuration_bailing_moe_v2.py CHANGED
@@ -5,8 +5,6 @@ from transformers.configuration_utils import PretrainedConfig
5
 
6
  class BailingMoeV2Config(PretrainedConfig):
7
 
8
- model_type = "bailing_moe"
9
-
10
  def __init__(
11
  self,
12
  vocab_size=157184,
@@ -41,7 +39,7 @@ class BailingMoeV2Config(PretrainedConfig):
41
  head_dim=128,
42
  output_router_logits=False,
43
  use_qk_norm=True,
44
- num_mtp_layers=0,
45
  mtp_loss_scaling_factor=0,
46
  moe_router_enable_expert_bias=True,
47
  routed_scaling_factor=1.0,
@@ -60,7 +58,7 @@ class BailingMoeV2Config(PretrainedConfig):
60
  self.embedding_dropout = embedding_dropout
61
  self.attention_dropout = attention_dropout
62
  self.output_dropout = output_dropout
63
- self.num_mtp_layers = num_mtp_layers
64
  self.mtp_loss_scaling_factor = mtp_loss_scaling_factor
65
  self.initializer_range = initializer_range
66
  self.max_position_embeddings = max_position_embeddings
@@ -84,4 +82,3 @@ class BailingMoeV2Config(PretrainedConfig):
84
  self.output_router_logits = output_router_logits
85
 
86
  super().__init__(pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
87
-
 
5
 
6
  class BailingMoeV2Config(PretrainedConfig):
7
 
 
 
8
  def __init__(
9
  self,
10
  vocab_size=157184,
 
39
  head_dim=128,
40
  output_router_logits=False,
41
  use_qk_norm=True,
42
+ num_nextn_predict_layers=0,
43
  mtp_loss_scaling_factor=0,
44
  moe_router_enable_expert_bias=True,
45
  routed_scaling_factor=1.0,
 
58
  self.embedding_dropout = embedding_dropout
59
  self.attention_dropout = attention_dropout
60
  self.output_dropout = output_dropout
61
+ self.num_nextn_predict_layers = num_nextn_predict_layers
62
  self.mtp_loss_scaling_factor = mtp_loss_scaling_factor
63
  self.initializer_range = initializer_range
64
  self.max_position_embeddings = max_position_embeddings
 
82
  self.output_router_logits = output_router_logits
83
 
84
  super().__init__(pad_token_id=pad_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
 
modeling_bailing_moe_v2.py CHANGED
@@ -25,9 +25,7 @@ from typing import List, Optional, Tuple, Union
25
 
26
  import torch
27
  import torch.nn.functional as F
28
- import torch.utils.checkpoint
29
  from torch import nn
30
- from torch.nn import CrossEntropyLoss
31
 
32
  from transformers.activations import ACT2FN
33
  from transformers.cache_utils import Cache, DynamicCache
@@ -234,7 +232,7 @@ def rotate_half(x):
234
 
235
 
236
  # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
237
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
238
  """Applies Rotary Position Embedding to the query and key tensors.
239
 
240
  Args:
@@ -242,9 +240,6 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
242
  k (`torch.Tensor`): The key tensor.
243
  cos (`torch.Tensor`): The cosine part of the rotary embedding.
244
  sin (`torch.Tensor`): The sine part of the rotary embedding.
245
- position_ids (`torch.Tensor`):
246
- The position indices of the tokens corresponding to the query and key tensors. For example, this can be
247
- used to pass offsetted position ids when working with a KV-cache.
248
  unsqueeze_dim (`int`, *optional*, defaults to 1):
249
  The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
250
  sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
@@ -403,7 +398,6 @@ class BailingMoeV2SparseMoeBlock(nn.Module):
403
  tokens_per_expert = cnts.sum(dim=0)
404
  idxs = topk_ids.view(-1).argsort()
405
  sorted_tokens = x[idxs // topk_ids.shape[1]]
406
- sorted_tokens_shape = sorted_tokens.shape
407
  tokens_per_expert = tokens_per_expert.cpu().numpy()
408
  outputs = []
409
  start_idx = 0
@@ -495,10 +489,6 @@ class BailingMoeV2Attention(nn.Module):
495
  position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
496
  **kwargs,
497
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
498
- if "padding_mask" in kwargs:
499
- warnings.warn(
500
- "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
501
- )
502
 
503
  bsz, q_len, _ = hidden_states.size()
504
 
@@ -516,7 +506,9 @@ class BailingMoeV2Attention(nn.Module):
516
  query_states = self.query_layernorm(query_states)
517
  key_states = self.key_layernorm(key_states)
518
 
519
- kv_seq_len = key_states.shape[-2]
 
 
520
  if past_key_value is not None:
521
  if self.layer_idx is None:
522
  raise ValueError(
@@ -524,12 +516,7 @@ class BailingMoeV2Attention(nn.Module):
524
  "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
525
  "with a layer index."
526
  )
527
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
528
- cos, sin = position_embeddings
529
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
530
-
531
- if past_key_value is not None:
532
- cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
533
  key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
534
 
535
  key_states = repeat_kv(key_states, self.num_key_value_groups)
@@ -537,6 +524,7 @@ class BailingMoeV2Attention(nn.Module):
537
 
538
  attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
539
 
 
540
  if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
541
  raise ValueError(
542
  f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
@@ -601,14 +589,6 @@ class BailingMoeV2FlashAttention2(BailingMoeV2Attention):
601
  **kwargs,
602
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
603
  # BailingMoeV2FlashAttention2 attention does not support output_attentions
604
- if "padding_mask" in kwargs:
605
- warnings.warn(
606
- "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
607
- )
608
-
609
- # overwrite attention_mask with padding_mask
610
- attention_mask = kwargs.pop("padding_mask")
611
-
612
  output_attentions = False
613
 
614
  bsz, q_len, _ = hidden_states.size()
@@ -631,14 +611,11 @@ class BailingMoeV2FlashAttention2(BailingMoeV2Attention):
631
  query_states = self.query_layernorm(query_states)
632
  key_states = self.key_layernorm(key_states)
633
 
634
- kv_seq_len = key_states.shape[-2]
635
- if past_key_value is not None:
636
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
637
  cos, sin = position_embeddings
638
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
639
 
640
  if past_key_value is not None:
641
- cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
642
  key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
643
 
644
  # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
@@ -840,21 +817,18 @@ class BailingMoeV2SdpaAttention(BailingMoeV2Attention):
840
  query_states = self.query_layernorm(query_states)
841
  key_states = self.key_layernorm(key_states)
842
 
843
- kv_seq_len = key_states.shape[-2]
844
- if past_key_value is not None:
845
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
846
  cos, sin = position_embeddings
847
-
848
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
849
 
850
  if past_key_value is not None:
851
- cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
852
  key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
853
 
854
  key_states = repeat_kv(key_states, self.num_key_value_groups)
855
  value_states = repeat_kv(value_states, self.num_key_value_groups)
856
 
857
  if attention_mask is not None:
 
858
  if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
859
  raise ValueError(
860
  f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
@@ -1012,10 +986,6 @@ class BailingMoeV2DecoderLayer(nn.Module):
1012
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1013
  (see `past_key_values`).
1014
  """
1015
- if "padding_mask" in kwargs:
1016
- warnings.warn(
1017
- "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1018
- )
1019
  residual = hidden_states
1020
 
1021
  hidden_states = self.input_layernorm(hidden_states)
@@ -1185,11 +1155,11 @@ class BailingMoeV2Model(BailingMoeV2PreTrainedModel):
1185
  super().__init__(config)
1186
  self.padding_idx = config.pad_token_id
1187
  self.vocab_size = config.vocab_size
1188
- self.num_mtp_layers = config.num_mtp_layers
1189
 
1190
  self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1191
  self.layers = []
1192
- for layer_idx in range(config.num_hidden_layers + config.num_mtp_layers):
1193
  layer_cls = BailingMoeV2DecoderLayer if layer_idx < config.num_hidden_layers else BailingMoeV2MTPLayer
1194
  self.layers.append(layer_cls(config, layer_idx))
1195
 
@@ -1252,23 +1222,20 @@ class BailingMoeV2Model(BailingMoeV2PreTrainedModel):
1252
  )
1253
  use_cache = False
1254
 
1255
- past_key_values_length = 0
1256
- if use_cache:
1257
- use_legacy_cache = not isinstance(past_key_values, Cache)
1258
- if use_legacy_cache:
1259
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1260
- past_key_values_length = past_key_values.get_usable_length(seq_length)
 
1261
 
1262
  if position_ids is None:
1263
- device = input_ids.device if input_ids is not None else inputs_embeds.device
1264
  position_ids = torch.arange(
1265
- past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1266
  )
1267
  position_ids = position_ids.unsqueeze(0)
1268
 
1269
- if inputs_embeds is None:
1270
- inputs_embeds = self.word_embeddings(input_ids)
1271
-
1272
  if self._use_flash_attention_2:
1273
  # 2d mask is passed through the layers
1274
  attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
@@ -1279,12 +1246,12 @@ class BailingMoeV2Model(BailingMoeV2PreTrainedModel):
1279
  attention_mask,
1280
  (batch_size, seq_length),
1281
  inputs_embeds,
1282
- past_key_values_length,
1283
  )
1284
  else:
1285
  # 4d mask is passed through the layers
1286
  attention_mask = _prepare_4d_causal_attention_mask(
1287
- attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1288
  )
1289
 
1290
  # embed positions
@@ -1298,8 +1265,8 @@ class BailingMoeV2Model(BailingMoeV2PreTrainedModel):
1298
  all_self_attns = () if output_attentions else None
1299
  all_router_logits = () if output_router_logits else None
1300
  next_decoder_cache = None
1301
- layers = self.layers[: -self.num_mtp_layers] if self.num_mtp_layers > 0 else self.layers
1302
- mtp_layers = self.layers[-self.num_mtp_layers :] if self.num_mtp_layers > 0 else None
1303
 
1304
  for decoder_layer in layers:
1305
  if output_hidden_states:
@@ -1397,7 +1364,7 @@ class BailingMoeV2Model(BailingMoeV2PreTrainedModel):
1397
 
1398
  next_cache = None
1399
  if use_cache:
1400
- next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1401
  if not return_dict:
1402
  return tuple(
1403
  v
@@ -1422,7 +1389,7 @@ class BailingMoeV2ForCausalLM(BailingMoeV2PreTrainedModel, GenerationMixin):
1422
  self.model = BailingMoeV2Model(config)
1423
  self.vocab_size = config.vocab_size
1424
  self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1425
- self.num_mtp_layers = config.num_mtp_layers
1426
  self.mtp_loss_scaling_factor = config.mtp_loss_scaling_factor
1427
 
1428
  # Initialize weights and apply final processing
@@ -1519,29 +1486,24 @@ class BailingMoeV2ForCausalLM(BailingMoeV2PreTrainedModel, GenerationMixin):
1519
  logits = logits.float()
1520
 
1521
  if labels is not None:
1522
- # Shift so that tokens < n predict n
1523
- # Flatten the tokens
1524
- loss_fct = CrossEntropyLoss()
1525
- logits = logits.view(-1, self.config.vocab_size)
1526
- # Enable model parallelism
1527
- loss = loss_fct(logits, labels.to(logits.device).view(-1))
1528
 
1529
  all_mtp_logits = None
1530
- if self.num_mtp_layers > 0:
1531
  mtp_hidden_states = outputs.mtp_hidden_states
1532
- for i in range(self.num_mtp_layers):
 
1533
  mtp_hidden_states = mtp_hidden_states[i]
1534
  mtp_logits = self.lm_head(mtp_hidden_states).float()
1535
  if all_mtp_logits is None:
1536
  all_mtp_logits = []
1537
  all_mtp_logits.append(mtp_logits)
1538
  if labels is not None:
1539
- labels, _ = roll_tensor(labels, shifts=-1, dims=-1, fill_value=-100)
1540
- # Flatten the tokens
1541
- loss_fct = CrossEntropyLoss()
1542
  mtp_logits_ = mtp_logits.view(-1, self.config.vocab_size)
1543
- # Enable model parallelism
1544
- mtp_loss = loss_fct(mtp_logits_, labels.to(mtp_logits_.device).view(-1))
1545
  if loss is not None:
1546
  loss += self.mtp_loss_scaling_factor * mtp_loss
1547
  else:
@@ -1569,70 +1531,3 @@ class BailingMoeV2ForCausalLM(BailingMoeV2PreTrainedModel, GenerationMixin):
1569
  router_logits=outputs.router_logits,
1570
  )
1571
 
1572
- def prepare_inputs_for_generation(
1573
- self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, token_type_ids=None, **kwargs
1574
- ):
1575
- if past_key_values is not None:
1576
- if isinstance(past_key_values, Cache):
1577
- cache_length = past_key_values.get_seq_length()
1578
- past_length = past_key_values.seen_tokens
1579
- max_cache_length = (
1580
- past_key_values.get_max_length()
1581
- if hasattr(past_key_values, "get_max_length")
1582
- else past_key_values.get_max_cache_shape()
1583
- )
1584
- else:
1585
- cache_length = past_length = past_key_values[0][0].shape[2]
1586
- max_cache_length = None
1587
-
1588
- # Keep only the unprocessed tokens:
1589
- # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1590
- # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as input)
1591
- if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1592
- input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1593
- # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1594
- # input_ids based on the past_length.
1595
- elif past_length < input_ids.shape[1]:
1596
- input_ids = input_ids[:, past_length:]
1597
- # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1598
-
1599
- # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1600
- if (
1601
- max_cache_length is not None
1602
- and attention_mask is not None
1603
- and cache_length + input_ids.shape[1] > max_cache_length
1604
- ):
1605
- attention_mask = attention_mask[:, -max_cache_length:]
1606
-
1607
- position_ids = kwargs.get("position_ids", None)
1608
- if attention_mask is not None and position_ids is None:
1609
- # create position_ids on the fly for batch generation
1610
- position_ids = attention_mask.long().cumsum(-1) - 1
1611
- position_ids.masked_fill_(attention_mask == 0, 1)
1612
- if past_key_values:
1613
- position_ids = position_ids[:, -input_ids.shape[1] :]
1614
-
1615
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1616
- if inputs_embeds is not None and past_key_values is None:
1617
- model_inputs = {"inputs_embeds": inputs_embeds}
1618
- else:
1619
- model_inputs = {"input_ids": input_ids}
1620
-
1621
- model_inputs.update(
1622
- {
1623
- "position_ids": position_ids,
1624
- "past_key_values": past_key_values,
1625
- "use_cache": kwargs.get("use_cache"),
1626
- "attention_mask": attention_mask,
1627
- }
1628
- )
1629
- return model_inputs
1630
-
1631
- @staticmethod
1632
- def _reorder_cache(past_key_values, beam_idx):
1633
- reordered_past = ()
1634
- for layer_past in past_key_values:
1635
- reordered_past += (
1636
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1637
- )
1638
- return reordered_past
 
25
 
26
  import torch
27
  import torch.nn.functional as F
 
28
  from torch import nn
 
29
 
30
  from transformers.activations import ACT2FN
31
  from transformers.cache_utils import Cache, DynamicCache
 
232
 
233
 
234
  # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
235
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
236
  """Applies Rotary Position Embedding to the query and key tensors.
237
 
238
  Args:
 
240
  k (`torch.Tensor`): The key tensor.
241
  cos (`torch.Tensor`): The cosine part of the rotary embedding.
242
  sin (`torch.Tensor`): The sine part of the rotary embedding.
 
 
 
243
  unsqueeze_dim (`int`, *optional*, defaults to 1):
244
  The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
245
  sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
 
398
  tokens_per_expert = cnts.sum(dim=0)
399
  idxs = topk_ids.view(-1).argsort()
400
  sorted_tokens = x[idxs // topk_ids.shape[1]]
 
401
  tokens_per_expert = tokens_per_expert.cpu().numpy()
402
  outputs = []
403
  start_idx = 0
 
489
  position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
490
  **kwargs,
491
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
 
 
 
 
492
 
493
  bsz, q_len, _ = hidden_states.size()
494
 
 
506
  query_states = self.query_layernorm(query_states)
507
  key_states = self.key_layernorm(key_states)
508
 
509
+ cos, sin = position_embeddings
510
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
511
+
512
  if past_key_value is not None:
513
  if self.layer_idx is None:
514
  raise ValueError(
 
516
  "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
517
  "with a layer index."
518
  )
519
+ cache_kwargs = {"sin": sin, "cos": cos}
 
 
 
 
 
520
  key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
521
 
522
  key_states = repeat_kv(key_states, self.num_key_value_groups)
 
524
 
525
  attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
526
 
527
+ kv_seq_len = key_states.shape[-2]
528
  if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
529
  raise ValueError(
530
  f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
 
589
  **kwargs,
590
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
591
  # BailingMoeV2FlashAttention2 attention does not support output_attentions
 
 
 
 
 
 
 
 
592
  output_attentions = False
593
 
594
  bsz, q_len, _ = hidden_states.size()
 
611
  query_states = self.query_layernorm(query_states)
612
  key_states = self.key_layernorm(key_states)
613
 
 
 
 
614
  cos, sin = position_embeddings
615
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
616
 
617
  if past_key_value is not None:
618
+ cache_kwargs = {"sin": sin, "cos": cos}
619
  key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
620
 
621
  # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
 
817
  query_states = self.query_layernorm(query_states)
818
  key_states = self.key_layernorm(key_states)
819
 
 
 
 
820
  cos, sin = position_embeddings
821
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
 
822
 
823
  if past_key_value is not None:
824
+ cache_kwargs = {"sin": sin, "cos": cos}
825
  key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
826
 
827
  key_states = repeat_kv(key_states, self.num_key_value_groups)
828
  value_states = repeat_kv(value_states, self.num_key_value_groups)
829
 
830
  if attention_mask is not None:
831
+ kv_seq_len = key_states.shape[-2]
832
  if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
833
  raise ValueError(
834
  f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
 
986
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
987
  (see `past_key_values`).
988
  """
 
 
 
 
989
  residual = hidden_states
990
 
991
  hidden_states = self.input_layernorm(hidden_states)
 
1155
  super().__init__(config)
1156
  self.padding_idx = config.pad_token_id
1157
  self.vocab_size = config.vocab_size
1158
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1159
 
1160
  self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1161
  self.layers = []
1162
+ for layer_idx in range(config.num_hidden_layers + config.num_nextn_predict_layers):
1163
  layer_cls = BailingMoeV2DecoderLayer if layer_idx < config.num_hidden_layers else BailingMoeV2MTPLayer
1164
  self.layers.append(layer_cls(config, layer_idx))
1165
 
 
1222
  )
1223
  use_cache = False
1224
 
1225
+ if use_cache and past_key_values is None:
1226
+ past_key_values = DynamicCache()
1227
+
1228
+ if inputs_embeds is None:
1229
+ inputs_embeds = self.word_embeddings(input_ids)
1230
+
1231
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1232
 
1233
  if position_ids is None:
 
1234
  position_ids = torch.arange(
1235
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1236
  )
1237
  position_ids = position_ids.unsqueeze(0)
1238
 
 
 
 
1239
  if self._use_flash_attention_2:
1240
  # 2d mask is passed through the layers
1241
  attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
 
1246
  attention_mask,
1247
  (batch_size, seq_length),
1248
  inputs_embeds,
1249
+ past_seen_tokens,
1250
  )
1251
  else:
1252
  # 4d mask is passed through the layers
1253
  attention_mask = _prepare_4d_causal_attention_mask(
1254
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_seen_tokens
1255
  )
1256
 
1257
  # embed positions
 
1265
  all_self_attns = () if output_attentions else None
1266
  all_router_logits = () if output_router_logits else None
1267
  next_decoder_cache = None
1268
+ layers = self.layers[: -self.num_nextn_predict_layers] if self.num_nextn_predict_layers > 0 else self.layers
1269
+ mtp_layers = self.layers[-self.num_nextn_predict_layers :] if self.num_nextn_predict_layers > 0 else None
1270
 
1271
  for decoder_layer in layers:
1272
  if output_hidden_states:
 
1364
 
1365
  next_cache = None
1366
  if use_cache:
1367
+ next_cache = next_decoder_cache
1368
  if not return_dict:
1369
  return tuple(
1370
  v
 
1389
  self.model = BailingMoeV2Model(config)
1390
  self.vocab_size = config.vocab_size
1391
  self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1392
+ self.num_nextn_predict_layers = config.num_nextn_predict_layers
1393
  self.mtp_loss_scaling_factor = config.mtp_loss_scaling_factor
1394
 
1395
  # Initialize weights and apply final processing
 
1486
  logits = logits.float()
1487
 
1488
  if labels is not None:
1489
+ loss = self.loss_function(logits, labels, self.config.vocab_size, **kwargs)
 
 
 
 
 
1490
 
1491
  all_mtp_logits = None
1492
+ if self.num_nextn_predict_layers > 0:
1493
  mtp_hidden_states = outputs.mtp_hidden_states
1494
+ shift_labels_mtp = None
1495
+ for i in range(self.num_nextn_predict_layers):
1496
  mtp_hidden_states = mtp_hidden_states[i]
1497
  mtp_logits = self.lm_head(mtp_hidden_states).float()
1498
  if all_mtp_logits is None:
1499
  all_mtp_logits = []
1500
  all_mtp_logits.append(mtp_logits)
1501
  if labels is not None:
1502
+ if shift_labels_mtp is None:
1503
+ shift_labels_mtp = labels.clone()
1504
+ shift_labels_mtp, _ = roll_tensor(shift_labels_mtp, shifts=-1, dims=-1, fill_value=-100)
1505
  mtp_logits_ = mtp_logits.view(-1, self.config.vocab_size)
1506
+ mtp_loss = self.loss_function(mtp_logits_, shift_labels_mtp.to(mtp_logits_.device).view(-1), self.config.vocab_size, **kwargs)
 
1507
  if loss is not None:
1508
  loss += self.mtp_loss_scaling_factor * mtp_loss
1509
  else:
 
1531
  router_logits=outputs.router_logits,
1532
  )
1533