fredzzp commited on
Commit
aac0a08
·
verified ·
1 Parent(s): 35253e7

Initial model upload with custom code

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
README.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - code
5
+ library_name: transformers
6
+ tags:
7
+ - masked-diffusion
8
+ - code-generation
9
+ - qwen2
10
+ ---
11
+
12
+ # Model: fredzzp/open-dcoder-0.5B
13
+
14
+ This repository contains the weights and custom code for the **fredzzp/open-dcoder-0.5B** model, a masked diffusion model for code generation based on the Qwen2 architecture.
15
+
16
+ This model uses bidirectional attention and must be used with the custom `diffusion_generate` method.
17
+
18
+ ## How to Use
19
+
20
+ First, make sure you have the latest `transformers` library installed.
21
+
22
+ ```bash
23
+ pip install transformers torch huggingface_hub
24
+
25
+ You can then use the model for generation. Note: You must pass trust_remote_code=True to load the custom model architecture.
26
+
27
+ import torch
28
+ from transformers import AutoTokenizer, AutoModelForCausalLM
29
+
30
+ model_id = "fredzzp/open-dcoder-0.5B"
31
+ device = "cuda" if torch.cuda.is_available() else "cpu"
32
+
33
+ # trust_remote_code=True is essential
34
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
35
+ model = AutoModelForCausalLM.from_pretrained(
36
+ model_id,
37
+ torch_dtype=torch.bfloat16,
38
+ trust_remote_code=True
39
+ ).to(device)
40
+
41
+ prompt = "def fibonacci(n):"
42
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
43
+
44
+ # The model will use the generation_config.json from the repo by default
45
+ # You can also override parameters here
46
+ outputs = model.diffusion_generate(
47
+ inputs=input_ids,
48
+ max_new_tokens=100,
49
+ steps=16,
50
+ temperature=0.8
51
+ )
52
+
53
+ # Decode the output
54
+ prompt_len = input_ids.shape[1]
55
+ generated_text = tokenizer.decode(outputs.sequences[0][prompt_len:], skip_special_tokens=True)
56
+
57
+ print("--- Generated Code ---")
58
+ print(generated_text)
__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
added_tokens.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<M>": 151665,
4
+ "<tool_call>": 151657,
5
+ "<|box_end|>": 151649,
6
+ "<|box_start|>": 151648,
7
+ "<|endoftext|>": 151643,
8
+ "<|file_sep|>": 151664,
9
+ "<|fim_middle|>": 151660,
10
+ "<|fim_pad|>": 151662,
11
+ "<|fim_prefix|>": 151659,
12
+ "<|fim_suffix|>": 151661,
13
+ "<|im_end|>": 151645,
14
+ "<|im_start|>": 151644,
15
+ "<|image_pad|>": 151655,
16
+ "<|object_ref_end|>": 151647,
17
+ "<|object_ref_start|>": 151646,
18
+ "<|quad_end|>": 151651,
19
+ "<|quad_start|>": 151650,
20
+ "<|repo_name|>": 151663,
21
+ "<|video_pad|>": 151656,
22
+ "<|vision_end|>": 151653,
23
+ "<|vision_pad|>": 151654,
24
+ "<|vision_start|>": 151652
25
+ }
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "architectures": [
4
+ "Qwen2ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "eos_token_id": 151643,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 896,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 4864,
13
+ "max_position_embeddings": 32768,
14
+ "max_window_layers": 24,
15
+ "model_type": "qwen2",
16
+ "num_attention_heads": 14,
17
+ "num_hidden_layers": 24,
18
+ "num_key_value_heads": 2,
19
+ "rms_norm_eps": 1e-06,
20
+ "rope_scaling": null,
21
+ "rope_theta": 1000000.0,
22
+ "sliding_window": 32768,
23
+ "tie_word_embeddings": true,
24
+ "torch_dtype": "bfloat16",
25
+ "transformers_version": "4.51.3",
26
+ "use_cache": true,
27
+ "use_sliding_window": false,
28
+ "vocab_size": 151936,
29
+ "auto_map": {
30
+ "AutoModelForCausalLM": "modeling_qwen2.Qwen2ForCausalLM"
31
+ }
32
+ }
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mask_token_id": 151643,
3
+ "max_new_tokens": 256,
4
+ "steps": 24,
5
+ "temperature": 0.7,
6
+ "top_k": 500,
7
+ "alg": "entropy",
8
+ "alg_temp": 0.6
9
+ }
generation_utils.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # veomni/models/transformers/qwen2/generation_utils.py
2
+
3
+ import warnings
4
+ import copy
5
+ from dataclasses import dataclass
6
+ from typing import Any, Dict, Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.distributions as dists
10
+ from torch.nn import functional as F
11
+ from transformers import __version__
12
+ from transformers.generation.configuration_utils import GenerationConfig
13
+ from transformers.utils import ModelOutput, is_torchdynamo_compiling, logging
14
+
15
+ logger = logging.get_logger(__name__)
16
+
17
+
18
+ def top_p_logits(logits, top_p=None):
19
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
20
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
21
+ sorted_indices_to_remove = cumulative_probs > top_p
22
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
23
+ sorted_indices_to_remove[..., 0] = 0
24
+ mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
25
+ mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
26
+ logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
27
+ return logits
28
+
29
+ def top_k_logits(logits, top_k=None):
30
+ if top_k is None or top_k == 0:
31
+ return logits
32
+ top_k = min(top_k, logits.size(-1))
33
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
34
+ logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
35
+ return logits
36
+
37
+ def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
38
+ if temperature > 0:
39
+ logits = logits / temperature
40
+ if top_p is not None and top_p < 1:
41
+ logits = top_p_logits(logits, top_p)
42
+ if top_k is not None:
43
+ logits = top_k_logits(logits, top_k)
44
+ probs = torch.softmax(logits.float(), dim=-1)
45
+ if temperature > 0:
46
+ x0 = dists.Categorical(probs=probs).sample()
47
+ else:
48
+ _, x0 = probs.max(dim=-1)
49
+
50
+ confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
51
+
52
+ if margin_confidence:
53
+ sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
54
+ top1_probs = sorted_probs[..., 0]
55
+ top2_probs = sorted_probs[..., 1]
56
+ confidence = top1_probs - top2_probs
57
+ elif neg_entropy:
58
+ log_probs = torch.log(probs.clamp(min=1e-10))
59
+ confidence = (probs * log_probs).sum(dim=-1)
60
+
61
+ return confidence, x0
62
+
63
+
64
+ @dataclass
65
+ class MDMModelOutput(ModelOutput):
66
+ sequences: torch.LongTensor = None
67
+ history: Optional[Tuple[torch.FloatTensor]] = None
68
+
69
+ class MDMGenerationConfig(GenerationConfig):
70
+ def __init__(self, **kwargs):
71
+ super().__init__(**kwargs)
72
+ self.temperature: float = kwargs.pop("temperature", 0.0)
73
+ self.top_p: Optional[float] = kwargs.pop("top_p", None)
74
+ self.top_k: Optional[int] = kwargs.pop("top_k", None)
75
+ self.eps: float = kwargs.pop("eps", 1e-3)
76
+ self.steps: int = kwargs.pop("steps", 512)
77
+ self.alg: str = kwargs.pop("alg", 'entropy')
78
+ self.alg_temp: Optional[float] = kwargs.pop("alg_temp", 0.0)
79
+ self.output_history: bool = kwargs.pop("output_history", False)
80
+ self.mask_token_id = kwargs.pop("mask_token_id", None)
81
+
82
+
83
+ class MDMGenerationMixin:
84
+ """
85
+ Mixin class for Masked Diffusion Model generation, adapted from the Dream model's generation utils.
86
+ """
87
+ @staticmethod
88
+ def _expand_inputs_for_generation(
89
+ expand_size: int = 1,
90
+ input_ids: Optional[torch.LongTensor] = None,
91
+ attention_mask: Optional[torch.LongTensor] = None
92
+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
93
+ if expand_size == 1:
94
+ return input_ids, attention_mask
95
+
96
+ if input_ids is not None:
97
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
98
+ if attention_mask is not None:
99
+ attention_mask = attention_mask.repeat_interleave(expand_size, dim=0)
100
+ return input_ids, attention_mask
101
+
102
+ def _prepare_generation_config(
103
+ self, generation_config: Optional[GenerationConfig], **kwargs
104
+ ) -> MDMGenerationConfig:
105
+ if generation_config is None:
106
+ generation_config = self.generation_config
107
+
108
+ # Use MDMGenerationConfig as the target class
109
+ if not isinstance(generation_config, MDMGenerationConfig):
110
+ generation_config = MDMGenerationConfig.from_dict(generation_config.to_dict())
111
+
112
+ # Update with kwargs
113
+ generation_config.update(**kwargs)
114
+ return generation_config
115
+
116
+ @torch.no_grad()
117
+ def diffusion_generate(
118
+ self,
119
+ inputs: Optional[torch.Tensor] = None,
120
+ generation_config: Optional[MDMGenerationConfig] = None,
121
+ **kwargs,
122
+ ) -> Union[MDMModelOutput, torch.LongTensor]:
123
+
124
+ # 1. Prepare generation config
125
+ generation_config = self._prepare_generation_config(generation_config, **kwargs)
126
+
127
+ # 2. Prepare inputs
128
+ input_ids = inputs
129
+ attention_mask = kwargs.get("attention_mask", None)
130
+
131
+ if input_ids is None:
132
+ raise ValueError("`inputs` must be provided for diffusion generation.")
133
+
134
+ if generation_config.max_new_tokens is not None:
135
+ generation_config.max_length = input_ids.shape[-1] + generation_config.max_new_tokens
136
+
137
+ # 3. Expand inputs for multi-sequence generation
138
+ input_ids, attention_mask = self._expand_inputs_for_generation(
139
+ expand_size=generation_config.num_return_sequences,
140
+ input_ids=input_ids,
141
+ attention_mask=attention_mask
142
+ )
143
+ # 4. Run the sampling loop
144
+ return self._sample(
145
+ input_ids,
146
+ attention_mask=attention_mask,
147
+ generation_config=generation_config
148
+ )
149
+
150
+ def _sample(
151
+ self,
152
+ input_ids: torch.LongTensor,
153
+ attention_mask: Optional[torch.LongTensor],
154
+ generation_config: MDMGenerationConfig
155
+ ) -> Union[MDMModelOutput, torch.LongTensor]:
156
+
157
+ # Extract params from config
158
+ max_length = generation_config.max_length
159
+ mask_token_id = generation_config.mask_token_id
160
+ if mask_token_id is None:
161
+ raise ValueError("`mask_token_id` must be set in the generation config.")
162
+
163
+ steps = generation_config.steps
164
+ eps = generation_config.eps
165
+ alg = generation_config.alg
166
+ alg_temp = generation_config.alg_temp
167
+ temperature = generation_config.temperature
168
+ top_p = generation_config.top_p
169
+ top_k = generation_config.top_k
170
+
171
+ histories = [] if generation_config.output_history else None
172
+
173
+ # Pad input_ids to max_length with mask tokens
174
+ x = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id)
175
+
176
+ # The model expects a bidirectional mask, so we just use the presence of pad_token_id
177
+ # for the attention mask during generation.
178
+ gen_attention_mask = (x != self.config.pad_token_id).long() if self.config.pad_token_id is not None else None
179
+
180
+ timesteps = torch.linspace(1, eps, steps + 1, device=x.device)
181
+
182
+ for i in range(steps):
183
+ mask_index = (x == mask_token_id)
184
+ if not mask_index.any(): # Stop if no tokens are masked
185
+ break
186
+ # is_causal=False is crucial for bidirectional attention
187
+ outputs = self(input_ids=x, attention_mask=gen_attention_mask, is_causal=False)
188
+ logits = outputs.logits
189
+
190
+ # CRITICAL: Shift logits to predict the next token, aligning with training
191
+ logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
192
+
193
+ mask_logits = logits[mask_index]
194
+ t = timesteps[i]
195
+ s = timesteps[i + 1]
196
+
197
+ if alg == 'origin':
198
+ p_transfer = 1 - s / t if i < steps - 1 else 1
199
+ x0 = torch.full_like(x[mask_index], fill_value=mask_token_id, device=self.device, dtype=torch.long)
200
+ transfer_index_t_s = torch.rand(*x0.shape, device=self.device) < p_transfer
201
+ _, sampled_tokens = sample_tokens(mask_logits[transfer_index_t_s], temperature=temperature, top_p=top_p, top_k=top_k)
202
+ x0[transfer_index_t_s] = sampled_tokens
203
+ x[mask_index] = x0
204
+ else:
205
+ # Confidence-based sampling (maskgit, entropy, etc.)
206
+ confidence_alg_map = {'maskgit_plus': False, 'topk_margin': True, 'entropy': True}
207
+ is_margin_conf = confidence_alg_map.get(alg, False)
208
+ is_neg_entropy = alg == 'entropy'
209
+
210
+ confidence, x0 = sample_tokens(mask_logits, temperature, top_p, top_k, margin_confidence=is_margin_conf, neg_entropy=is_neg_entropy)
211
+
212
+ num_masked = mask_index.sum(dim=-1, keepdim=True)
213
+ gamma = 1 - s / t
214
+ num_to_unmask = (num_masked * gamma).long()
215
+
216
+ # Place confidence scores back into a full tensor to find top-k across the sequence
217
+ full_confidence = torch.full_like(x, -torch.inf, device=self.device, dtype=confidence.dtype)
218
+ full_confidence[mask_index] = confidence
219
+
220
+ if (alg_temp is not None and alg_temp > 0):
221
+ # Temperature-based sampling of which tokens to unmask
222
+ unmask_probs = F.softmax(full_confidence / alg_temp, dim=-1)
223
+ unmask_indices = torch.multinomial(unmask_probs, num_samples=num_to_unmask.max(), replacement=False)
224
+ else:
225
+ # Top-k confidence sampling
226
+ _, unmask_indices = torch.topk(full_confidence, k=num_to_unmask.max(), dim=-1)
227
+
228
+ # Create a mask for the tokens we are going to unmask
229
+ rows = torch.arange(x.size(0), device=x.device).unsqueeze(1)
230
+ unmask_selection_mask = torch.zeros_like(x, dtype=torch.bool)
231
+ unmask_selection_mask[rows, unmask_indices] = True
232
+
233
+ # Filter indices based on per-row `num_to_unmask`
234
+ unmask_selection_mask = unmask_selection_mask & (torch.cumsum(unmask_selection_mask.long(), dim=-1) <= num_to_unmask)
235
+
236
+ # Place the newly generated tokens (x0) into a full tensor
237
+ x_unmasked_proposals = torch.full_like(x, fill_value=mask_token_id)
238
+ x_unmasked_proposals[mask_index] = x0
239
+
240
+ # Update the main tensor `x` with the unmasked tokens
241
+ x[unmask_selection_mask] = x_unmasked_proposals[unmask_selection_mask]
242
+
243
+ if histories is not None:
244
+ histories.append(x.clone())
245
+
246
+ if generation_config.return_dict_in_generate:
247
+ return MDMModelOutput(sequences=x, history=histories)
248
+ else:
249
+ return x
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d28ef84b77c6d180347b2de1fe48c92c4e487d807ae85cf217f30f3574fc9df2
3
+ size 1260367448
modeling_qwen2.py ADDED
@@ -0,0 +1,1084 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
2
+ # Copyright 2025 Bytedance Ltd. and/or its affiliates
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # adapted from https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2/modeling_qwen2.py
17
+ from typing import Callable, List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ from torch import nn
21
+ from transformers.activations import ACT2FN
22
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
23
+ from transformers.generation import GenerationMixin
24
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
25
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
26
+ from transformers.modeling_outputs import (
27
+ BaseModelOutputWithPast,
28
+ CausalLMOutputWithPast,
29
+ )
30
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
31
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
32
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
33
+ from transformers.processing_utils import Unpack
34
+ from transformers.utils import (
35
+ # LossKwargs,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ replace_return_docstrings,
39
+ )
40
+
41
+ from veomni.models.transformers.qwen2.generation_utils import MDMGenerationMixin
42
+
43
+ from ....data.constants import IGNORE_INDEX
44
+ from ....distributed.parallel_state import get_parallel_state
45
+ from ....distributed.sequence_parallel import (
46
+ gather_heads_scatter_seq,
47
+ gather_seq_scatter_heads,
48
+ reduce_sequence_parallel_loss,
49
+ )
50
+ from ....utils import logging
51
+ from ....utils.import_utils import is_liger_kernel_available
52
+
53
+
54
+ if is_liger_kernel_available():
55
+ from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss # type: ignore
56
+ from liger_kernel.transformers.rms_norm import LigerRMSNorm
57
+ from liger_kernel.transformers.rope import liger_rotary_pos_emb
58
+ from liger_kernel.transformers.swiglu import LigerSwiGLUMLP
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
63
+ _CONFIG_FOR_DOC = "Qwen2Config"
64
+
65
+
66
+ class Qwen2MLP(nn.Module):
67
+ def __init__(self, config):
68
+ super().__init__()
69
+ self.config = config
70
+ self.hidden_size = config.hidden_size
71
+ self.intermediate_size = config.intermediate_size
72
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
73
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
74
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
75
+ self.act_fn = ACT2FN[config.hidden_act]
76
+
77
+ def forward(self, x):
78
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
79
+ return down_proj
80
+
81
+
82
+ def rotate_half(x):
83
+ """Rotates half the hidden dims of the input."""
84
+ x1 = x[..., : x.shape[-1] // 2]
85
+ x2 = x[..., x.shape[-1] // 2 :]
86
+ return torch.cat((-x2, x1), dim=-1)
87
+
88
+
89
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
90
+ """Applies Rotary Position Embedding to the query and key tensors.
91
+
92
+ Args:
93
+ q (`torch.Tensor`): The query tensor.
94
+ k (`torch.Tensor`): The key tensor.
95
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
96
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
97
+ position_ids (`torch.Tensor`, *optional*):
98
+ Deprecated and unused.
99
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
100
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
101
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
102
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
103
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
104
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
105
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
106
+ Returns:
107
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
108
+ """
109
+ cos = cos.unsqueeze(unsqueeze_dim)
110
+ sin = sin.unsqueeze(unsqueeze_dim)
111
+ q_embed = (q * cos) + (rotate_half(q) * sin)
112
+ k_embed = (k * cos) + (rotate_half(k) * sin)
113
+ return q_embed, k_embed
114
+
115
+
116
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
117
+ """
118
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
119
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
120
+ """
121
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
122
+ if n_rep == 1:
123
+ return hidden_states
124
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
125
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
126
+
127
+
128
+ def eager_attention_forward(
129
+ module: nn.Module,
130
+ query: torch.Tensor,
131
+ key: torch.Tensor,
132
+ value: torch.Tensor,
133
+ attention_mask: Optional[torch.Tensor],
134
+ scaling: float,
135
+ dropout: float = 0.0,
136
+ **kwargs,
137
+ ):
138
+ key_states = repeat_kv(key, module.num_key_value_groups)
139
+ value_states = repeat_kv(value, module.num_key_value_groups)
140
+
141
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
142
+ if attention_mask is not None:
143
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
144
+ attn_weights = attn_weights + causal_mask
145
+
146
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
147
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
148
+ attn_output = torch.matmul(attn_weights, value_states)
149
+ attn_output = attn_output.transpose(1, 2).contiguous()
150
+
151
+ return attn_output, attn_weights
152
+
153
+
154
+ class Qwen2Attention(nn.Module):
155
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
156
+
157
+ def __init__(self, config: Qwen2Config, layer_idx: int):
158
+ super().__init__()
159
+ self.config = config
160
+ self.layer_idx = layer_idx
161
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
162
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
163
+ self.scaling = self.head_dim**-0.5
164
+ self.attention_dropout = config.attention_dropout
165
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
166
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
167
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
168
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
169
+
170
+ def forward(
171
+ self,
172
+ hidden_states: torch.Tensor,
173
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
174
+ attention_mask: Optional[torch.Tensor],
175
+ past_key_value: Optional[Cache] = None,
176
+ cache_position: Optional[torch.LongTensor] = None,
177
+ is_causal: bool = True,
178
+ **kwargs: Unpack[FlashAttentionKwargs],
179
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
180
+ bsz, q_len, _ = hidden_states.size() # q_len = seq_length / sp_size
181
+ hidden_shape = (bsz, q_len, -1, self.head_dim)
182
+
183
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
184
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
185
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
186
+ if get_parallel_state().ulysses_enabled:
187
+ query_states = gather_seq_scatter_heads(query_states, seq_dim=2, head_dim=1)
188
+ key_states = gather_seq_scatter_heads(key_states, seq_dim=2, head_dim=1)
189
+ value_states = gather_seq_scatter_heads(value_states, seq_dim=2, head_dim=1)
190
+ # (batch_size, num_head / sp_size, seq_length, head_size)
191
+
192
+ full_q_len = query_states.size(2) # full_q_len = seq_length
193
+ cos, sin = position_embeddings
194
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
195
+
196
+ if past_key_value is not None:
197
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
198
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
199
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
200
+
201
+ sliding_window = None
202
+ if (
203
+ self.config.use_sliding_window
204
+ and getattr(self.config, "sliding_window", None) is not None
205
+ and self.layer_idx >= self.config.max_window_layers
206
+ ):
207
+ sliding_window = self.config.sliding_window
208
+
209
+ attention_interface: Callable = eager_attention_forward
210
+ if self.config._attn_implementation != "eager":
211
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
212
+ logger.warning_once(
213
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
214
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
215
+ )
216
+ else:
217
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
218
+ self.is_causal = is_causal
219
+ attn_output, attn_weights = attention_interface(
220
+ self,
221
+ query_states,
222
+ key_states,
223
+ value_states,
224
+ attention_mask,
225
+ dropout=0.0 if not self.training else self.attention_dropout,
226
+ scaling=self.scaling,
227
+ sliding_window=sliding_window, # main diff with Llama
228
+ **kwargs,
229
+ )
230
+
231
+ attn_output = attn_output.reshape(bsz, full_q_len, -1, self.head_dim).contiguous()
232
+ if get_parallel_state().ulysses_enabled:
233
+ attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1)
234
+
235
+ attn_output = attn_output.reshape(bsz, q_len, self.config.hidden_size).contiguous()
236
+ attn_output = self.o_proj(attn_output)
237
+ return attn_output, attn_weights
238
+
239
+
240
+ class Qwen2RMSNorm(nn.Module):
241
+ def __init__(self, hidden_size, eps=1e-6):
242
+ """
243
+ Qwen2RMSNorm is equivalent to T5LayerNorm
244
+ """
245
+ super().__init__()
246
+ self.weight = nn.Parameter(torch.ones(hidden_size))
247
+ self.variance_epsilon = eps
248
+
249
+ def forward(self, hidden_states):
250
+ input_dtype = hidden_states.dtype
251
+ hidden_states = hidden_states.to(torch.float32)
252
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
253
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
254
+ return self.weight * hidden_states.to(input_dtype)
255
+
256
+ def extra_repr(self):
257
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
258
+
259
+
260
+ class Qwen2DecoderLayer(nn.Module):
261
+ def __init__(self, config: Qwen2Config, layer_idx: int):
262
+ super().__init__()
263
+ self.hidden_size = config.hidden_size
264
+ self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
265
+ self.mlp = Qwen2MLP(config)
266
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
267
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
268
+ if config.sliding_window and config._attn_implementation != "flash_attention_2":
269
+ logger.warning_once(
270
+ f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
271
+ "unexpected results may be encountered."
272
+ )
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states: torch.Tensor,
277
+ attention_mask: Optional[torch.Tensor] = None,
278
+ position_ids: Optional[torch.LongTensor] = None,
279
+ past_key_value: Optional[Cache] = None,
280
+ output_attentions: Optional[bool] = False,
281
+ use_cache: Optional[bool] = False,
282
+ cache_position: Optional[torch.LongTensor] = None,
283
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
284
+ is_causal: bool = True,
285
+ **kwargs: Unpack[FlashAttentionKwargs],
286
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
287
+ residual = hidden_states
288
+
289
+ hidden_states = self.input_layernorm(hidden_states)
290
+
291
+ # Self Attention
292
+ hidden_states, self_attn_weights = self.self_attn(
293
+ hidden_states=hidden_states,
294
+ attention_mask=attention_mask,
295
+ position_ids=position_ids,
296
+ past_key_value=past_key_value,
297
+ output_attentions=output_attentions,
298
+ use_cache=use_cache,
299
+ cache_position=cache_position,
300
+ position_embeddings=position_embeddings,
301
+ is_causal=is_causal,
302
+ **kwargs,
303
+ )
304
+ hidden_states = residual + hidden_states
305
+
306
+ # Fully Connected
307
+ residual = hidden_states
308
+ hidden_states = self.post_attention_layernorm(hidden_states)
309
+ hidden_states = self.mlp(hidden_states)
310
+ hidden_states = residual + hidden_states
311
+
312
+ outputs = (hidden_states,)
313
+ if output_attentions:
314
+ outputs += (self_attn_weights,)
315
+
316
+ return outputs
317
+
318
+
319
+ class Qwen2RotaryEmbedding(nn.Module):
320
+ def __init__(self, config: Qwen2Config, device=None):
321
+ super().__init__()
322
+ # BC: "rope_type" was originally "type"
323
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
324
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
325
+ else:
326
+ self.rope_type = "default"
327
+ self.max_seq_len_cached = config.max_position_embeddings
328
+ self.original_max_seq_len = config.max_position_embeddings
329
+
330
+ self.config = config
331
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
332
+
333
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
334
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
335
+ self.original_inv_freq = self.inv_freq
336
+
337
+ def _dynamic_frequency_update(self, position_ids, device):
338
+ """
339
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
340
+ 1 - growing beyond the cached sequence length (allow scaling)
341
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
342
+ """
343
+ seq_len = torch.max(position_ids) + 1
344
+ if seq_len > self.max_seq_len_cached: # growth
345
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
346
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
347
+ self.max_seq_len_cached = seq_len
348
+
349
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
350
+ # This .to() is needed if the model has been moved to a device after being initialized (because
351
+ # the buffer is automatically moved, but not the original copy)
352
+ self.original_inv_freq = self.original_inv_freq.to(device)
353
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
354
+ self.max_seq_len_cached = self.original_max_seq_len
355
+
356
+ @torch.no_grad()
357
+ def forward(self, x, position_ids):
358
+ if "dynamic" in self.rope_type:
359
+ self._dynamic_frequency_update(position_ids, device=x.device)
360
+
361
+ # Core RoPE block
362
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
363
+ position_ids_expanded = position_ids[:, None, :].float()
364
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
365
+ device_type = x.device.type
366
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
367
+ with torch.autocast(device_type=device_type, enabled=False):
368
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
369
+ emb = torch.cat((freqs, freqs), dim=-1)
370
+ cos = emb.cos()
371
+ sin = emb.sin()
372
+
373
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
374
+ cos = cos * self.attention_scaling
375
+ sin = sin * self.attention_scaling
376
+
377
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
378
+
379
+
380
+ QWEN2_START_DOCSTRING = r"""
381
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
382
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
383
+ etc.)
384
+
385
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
386
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
387
+ and behavior.
388
+
389
+ Parameters:
390
+ config ([`Qwen2Config`]):
391
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
392
+ load the weights associated with the model, only the configuration. Check out the
393
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
394
+ """
395
+
396
+
397
+ @add_start_docstrings(
398
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
399
+ QWEN2_START_DOCSTRING,
400
+ )
401
+ class Qwen2PreTrainedModel(PreTrainedModel):
402
+ config_class = Qwen2Config
403
+ base_model_prefix = "model"
404
+ supports_gradient_checkpointing = True
405
+ _no_split_modules = ["Qwen2DecoderLayer"]
406
+ _skip_keys_device_placement = ["past_key_values"]
407
+ _supports_flash_attn_2 = True
408
+ _supports_sdpa = True
409
+ _supports_flex_attn = True
410
+ _supports_cache_class = True
411
+ _supports_quantized_cache = True
412
+ _supports_static_cache = True
413
+ _supports_attention_backend = True
414
+
415
+ def _init_weights(self, module):
416
+ std = self.config.initializer_range
417
+ if isinstance(module, nn.Linear):
418
+ module.weight.data.normal_(mean=0.0, std=std)
419
+ if module.bias is not None:
420
+ module.bias.data.zero_()
421
+ elif isinstance(module, nn.Embedding):
422
+ module.weight.data.normal_(mean=0.0, std=std)
423
+ if module.padding_idx is not None:
424
+ module.weight.data[module.padding_idx].zero_()
425
+
426
+
427
+ QWEN2_INPUTS_DOCSTRING = r"""
428
+ Args:
429
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
430
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
431
+ it.
432
+
433
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
434
+ [`PreTrainedTokenizer.__call__`] for details.
435
+
436
+ [What are input IDs?](../glossary#input-ids)
437
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
438
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
439
+
440
+ - 1 for tokens that are **not masked**,
441
+ - 0 for tokens that are **masked**.
442
+
443
+ [What are attention masks?](../glossary#attention-mask)
444
+
445
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
446
+ [`PreTrainedTokenizer.__call__`] for details.
447
+
448
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
449
+ `past_key_values`).
450
+
451
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
452
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
453
+ information on the default strategy.
454
+
455
+ - 1 indicates the head is **not masked**,
456
+ - 0 indicates the head is **masked**.
457
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
458
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
459
+ config.n_positions - 1]`.
460
+
461
+ [What are position IDs?](../glossary#position-ids)
462
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
463
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
464
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
465
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
466
+
467
+ Two formats are allowed:
468
+ - a [`~cache_utils.Cache`] instance, see our
469
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
470
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
471
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
472
+ cache format.
473
+
474
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
475
+ legacy cache format will be returned.
476
+
477
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
478
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
479
+ of shape `(batch_size, sequence_length)`.
480
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
481
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
482
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
483
+ model's internal embedding lookup matrix.
484
+ use_cache (`bool`, *optional*):
485
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
486
+ `past_key_values`).
487
+ output_attentions (`bool`, *optional*):
488
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
489
+ tensors for more detail.
490
+ output_hidden_states (`bool`, *optional*):
491
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
492
+ more detail.
493
+ return_dict (`bool`, *optional*):
494
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
495
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
496
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
497
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
498
+ the complete sequence length.
499
+ """
500
+
501
+
502
+ @add_start_docstrings(
503
+ "The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
504
+ QWEN2_START_DOCSTRING,
505
+ )
506
+ class Qwen2Model(Qwen2PreTrainedModel):
507
+ """
508
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
509
+
510
+ Args:
511
+ config: Qwen2Config
512
+ """
513
+
514
+ def __init__(self, config: Qwen2Config):
515
+ super().__init__(config)
516
+ self.padding_idx = config.pad_token_id
517
+ self.vocab_size = config.vocab_size
518
+
519
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
520
+ self.layers = nn.ModuleList(
521
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
522
+ )
523
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
524
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
525
+ self.gradient_checkpointing = False
526
+
527
+ # Initialize weights and apply final processing
528
+ self.post_init()
529
+
530
+ def get_input_embeddings(self):
531
+ return self.embed_tokens
532
+
533
+ def set_input_embeddings(self, value):
534
+ self.embed_tokens = value
535
+
536
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
537
+ def forward(
538
+ self,
539
+ input_ids: torch.LongTensor = None,
540
+ attention_mask: Optional[torch.Tensor] = None,
541
+ position_ids: Optional[torch.LongTensor] = None,
542
+ past_key_values: Optional[Cache] = None,
543
+ inputs_embeds: Optional[torch.FloatTensor] = None,
544
+ use_cache: Optional[bool] = None,
545
+ output_attentions: Optional[bool] = None,
546
+ output_hidden_states: Optional[bool] = None,
547
+ return_dict: Optional[bool] = None,
548
+ cache_position: Optional[torch.LongTensor] = None,
549
+ is_causal: bool = True,
550
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
551
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
552
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
553
+ output_hidden_states = (
554
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
555
+ )
556
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
557
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
558
+
559
+ if (input_ids is None) ^ (inputs_embeds is not None):
560
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
561
+
562
+ if self.gradient_checkpointing and self.training and use_cache:
563
+ logger.warning_once(
564
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
565
+ )
566
+ use_cache = False
567
+
568
+ if inputs_embeds is None:
569
+ inputs_embeds = self.embed_tokens(input_ids)
570
+
571
+ if use_cache and past_key_values is None:
572
+ past_key_values = DynamicCache()
573
+
574
+ if cache_position is None:
575
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
576
+ cache_position = torch.arange(
577
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
578
+ )
579
+
580
+ if position_ids is None:
581
+ position_ids = cache_position.unsqueeze(0)
582
+
583
+ causal_mask = self._update_causal_mask(
584
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
585
+ )
586
+
587
+ hidden_states = inputs_embeds
588
+
589
+ # create position embeddings to be shared across the decoder layers
590
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
591
+
592
+ # decoder layers
593
+ all_hidden_states = () if output_hidden_states else None
594
+ all_self_attns = () if output_attentions else None
595
+
596
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
597
+ if output_hidden_states:
598
+ all_hidden_states += (hidden_states,)
599
+
600
+ if self.gradient_checkpointing and self.training:
601
+ layer_outputs = self._gradient_checkpointing_func(
602
+ decoder_layer.__call__,
603
+ hidden_states,
604
+ causal_mask,
605
+ position_ids,
606
+ past_key_values,
607
+ output_attentions,
608
+ use_cache,
609
+ cache_position,
610
+ position_embeddings,
611
+ is_causal,
612
+ )
613
+ else:
614
+ layer_outputs = decoder_layer(
615
+ hidden_states,
616
+ attention_mask=causal_mask,
617
+ position_ids=position_ids,
618
+ past_key_value=past_key_values,
619
+ output_attentions=output_attentions,
620
+ use_cache=use_cache,
621
+ cache_position=cache_position,
622
+ position_embeddings=position_embeddings,
623
+ is_causal=is_causal,
624
+ **flash_attn_kwargs,
625
+ )
626
+
627
+ hidden_states = layer_outputs[0]
628
+
629
+ if output_attentions:
630
+ all_self_attns += (layer_outputs[1],)
631
+
632
+ hidden_states = self.norm(hidden_states)
633
+
634
+ # add hidden states from the last decoder layer
635
+ if output_hidden_states:
636
+ all_hidden_states += (hidden_states,)
637
+
638
+ output = BaseModelOutputWithPast(
639
+ last_hidden_state=hidden_states,
640
+ past_key_values=past_key_values if use_cache else None,
641
+ hidden_states=all_hidden_states,
642
+ attentions=all_self_attns,
643
+ )
644
+ return output if return_dict else output.to_tuple()
645
+
646
+ def _update_causal_mask(
647
+ self,
648
+ attention_mask: torch.Tensor,
649
+ input_tensor: torch.Tensor,
650
+ cache_position: torch.Tensor,
651
+ past_key_values: Cache,
652
+ output_attentions: bool,
653
+ ):
654
+ if self.config._attn_implementation == "flash_attention_2":
655
+ if attention_mask is not None and past_key_values is not None:
656
+ is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0]
657
+ if is_padding_right:
658
+ raise ValueError(
659
+ "You are attempting to perform batched generation with padding_side='right'"
660
+ " this may lead to unexpected behaviour for Flash Attention version of Qwen2. Make sure to "
661
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
662
+ )
663
+ if attention_mask is not None and 0.0 in attention_mask:
664
+ return attention_mask
665
+ return None
666
+
667
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
668
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
669
+ # to infer the attention mask.
670
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
671
+ using_static_cache = isinstance(past_key_values, StaticCache)
672
+ using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
673
+
674
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
675
+ if (
676
+ self.config._attn_implementation == "sdpa"
677
+ and not (using_static_cache or using_sliding_window_cache)
678
+ and not output_attentions
679
+ ):
680
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
681
+ attention_mask,
682
+ inputs_embeds=input_tensor,
683
+ past_key_values_length=past_seen_tokens,
684
+ sliding_window=self.config.sliding_window,
685
+ is_training=self.training,
686
+ ):
687
+ return None
688
+
689
+ dtype, device = input_tensor.dtype, input_tensor.device
690
+ min_dtype = torch.finfo(dtype).min
691
+ sequence_length = input_tensor.shape[1]
692
+ # SlidingWindowCache or StaticCache
693
+ if using_sliding_window_cache or using_static_cache:
694
+ target_length = past_key_values.get_max_cache_shape()
695
+ # DynamicCache or no cache
696
+ else:
697
+ target_length = (
698
+ attention_mask.shape[-1]
699
+ if isinstance(attention_mask, torch.Tensor)
700
+ else past_seen_tokens + sequence_length + 1
701
+ )
702
+
703
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
704
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
705
+ attention_mask,
706
+ sequence_length=sequence_length,
707
+ target_length=target_length,
708
+ dtype=dtype,
709
+ device=device,
710
+ cache_position=cache_position,
711
+ batch_size=input_tensor.shape[0],
712
+ config=self.config,
713
+ past_key_values=past_key_values,
714
+ )
715
+
716
+ if (
717
+ self.config._attn_implementation == "sdpa"
718
+ and attention_mask is not None
719
+ and attention_mask.device.type in ["cuda", "xpu"]
720
+ and not output_attentions
721
+ ):
722
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
723
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
724
+ # Details: https://github.com/pytorch/pytorch/issues/110213
725
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
726
+
727
+ return causal_mask
728
+
729
+ @staticmethod
730
+ def _prepare_4d_causal_attention_mask_with_cache_position(
731
+ attention_mask: torch.Tensor,
732
+ sequence_length: int,
733
+ target_length: int,
734
+ dtype: torch.dtype,
735
+ device: torch.device,
736
+ cache_position: torch.Tensor,
737
+ batch_size: int,
738
+ config: Qwen2Config,
739
+ past_key_values: Cache,
740
+ ):
741
+ """
742
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
743
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
744
+
745
+ Args:
746
+ attention_mask (`torch.Tensor`):
747
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
748
+ sequence_length (`int`):
749
+ The sequence length being processed.
750
+ target_length (`int`):
751
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
752
+ dtype (`torch.dtype`):
753
+ The dtype to use for the 4D attention mask.
754
+ device (`torch.device`):
755
+ The device to plcae the 4D attention mask on.
756
+ cache_position (`torch.Tensor`):
757
+ Indices depicting the position of the input sequence tokens in the sequence.
758
+ batch_size (`torch.Tensor`):
759
+ Batch size.
760
+ config (`Qwen2Config`):
761
+ The model's configuration class
762
+ past_key_values (`Cache`):
763
+ The cache class that is being used currently to generate
764
+ """
765
+ if attention_mask is not None and attention_mask.dim() == 4:
766
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
767
+ causal_mask = attention_mask
768
+ else:
769
+ min_dtype = torch.finfo(dtype).min
770
+ causal_mask = torch.full(
771
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
772
+ )
773
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
774
+ if config.sliding_window is not None:
775
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
776
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
777
+ if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
778
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
779
+ cache_position.reshape(-1, 1) - config.sliding_window
780
+ )
781
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
782
+ causal_mask *= diagonal_attend_mask
783
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
784
+ if attention_mask is not None:
785
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
786
+ if attention_mask.shape[-1] > target_length:
787
+ attention_mask = attention_mask[:, :target_length]
788
+ mask_length = attention_mask.shape[-1]
789
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
790
+ causal_mask.device
791
+ )
792
+ padding_mask = padding_mask == 0
793
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
794
+ padding_mask, min_dtype
795
+ )
796
+ return causal_mask
797
+
798
+
799
+ class KwargsForCausalLM(FlashAttentionKwargs, ): ...
800
+
801
+
802
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel, MDMGenerationMixin):
803
+ _tied_weights_keys = ["lm_head.weight"]
804
+ _tp_plan = {"lm_head": "colwise_rep"}
805
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
806
+
807
+ def __init__(self, config):
808
+ super().__init__(config)
809
+ self.model = Qwen2Model(config)
810
+ self.vocab_size = config.vocab_size
811
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
812
+
813
+ # Initialize weights and apply final processing
814
+ self.post_init()
815
+
816
+ def get_input_embeddings(self):
817
+ return self.model.embed_tokens
818
+
819
+ def set_input_embeddings(self, value):
820
+ self.model.embed_tokens = value
821
+
822
+ def get_output_embeddings(self):
823
+ return self.lm_head
824
+
825
+ def set_output_embeddings(self, new_embeddings):
826
+ self.lm_head = new_embeddings
827
+
828
+ def set_decoder(self, decoder):
829
+ self.model = decoder
830
+
831
+ def get_decoder(self):
832
+ return self.model
833
+
834
+ @add_start_docstrings_to_model_forward(QWEN2_INPUTS_DOCSTRING)
835
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
836
+ def forward(
837
+ self,
838
+ input_ids: torch.LongTensor = None,
839
+ attention_mask: Optional[torch.Tensor] = None,
840
+ position_ids: Optional[torch.LongTensor] = None,
841
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
842
+ inputs_embeds: Optional[torch.FloatTensor] = None,
843
+ labels: Optional[torch.LongTensor] = None,
844
+ mask_ratio: Optional[torch.FloatTensor]=None,
845
+ use_cache: Optional[bool] = None,
846
+ output_attentions: Optional[bool] = None,
847
+ output_hidden_states: Optional[bool] = None,
848
+ return_dict: Optional[bool] = None,
849
+ cache_position: Optional[torch.LongTensor] = None,
850
+ logits_to_keep: Union[int, torch.Tensor] = 0,
851
+ is_causal: bool = True,
852
+ **kwargs: Unpack[KwargsForCausalLM],
853
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
854
+ r"""
855
+ Args:
856
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
857
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
858
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
859
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
860
+
861
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
862
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
863
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
864
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
865
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
866
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
867
+
868
+ Returns:
869
+
870
+ Example:
871
+
872
+ ```python
873
+ >>> from transformers import AutoTokenizer, Qwen2ForCausalLM
874
+
875
+ >>> model = Qwen2ForCausalLM.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
876
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-qwen2/Qwen2-2-7b-hf")
877
+
878
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
879
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
880
+
881
+ >>> # Generate
882
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
883
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
884
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
885
+ ```"""
886
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
887
+ output_hidden_states = (
888
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
889
+ )
890
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
891
+
892
+ if not get_parallel_state().sp_enabled and labels is not None:
893
+ # Shift so that tokens < n predict n
894
+ labels = labels[..., 1:].contiguous()
895
+ labels = labels.view(-1)
896
+ if (
897
+ position_ids is not None
898
+ and position_ids.size(0) == 1
899
+ and not (torch.diff(position_ids, dim=-1) >= 0).all()
900
+ ):
901
+ position_ids_ = position_ids.flatten()
902
+ indices_q = torch.arange(position_ids_.size(0), device=position_ids_.device, dtype=torch.int32)
903
+ cu_seq_lens = torch.cat(
904
+ (
905
+ indices_q[position_ids_ == 0],
906
+ torch.tensor(position_ids_.size(), device=position_ids_.device, dtype=torch.int32),
907
+ )
908
+ )
909
+ labels[cu_seq_lens[1:-1] - 1] = IGNORE_INDEX
910
+ if mask_ratio is not None:
911
+ is_causal = False
912
+ mask_ratio = mask_ratio[..., 1:].contiguous()
913
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
914
+ outputs = self.model(
915
+ input_ids=input_ids,
916
+ attention_mask=attention_mask,
917
+ position_ids=position_ids,
918
+ past_key_values=past_key_values,
919
+ inputs_embeds=inputs_embeds,
920
+ use_cache=use_cache,
921
+ output_attentions=output_attentions,
922
+ output_hidden_states=output_hidden_states,
923
+ return_dict=return_dict,
924
+ cache_position=cache_position,
925
+ is_causal=is_causal,
926
+ **kwargs,
927
+ )
928
+
929
+ hidden_states = outputs[0]
930
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
931
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
932
+ hidden_states = hidden_states[:, slice_indices, :]
933
+
934
+ loss = None
935
+ logits = None
936
+ if labels is not None:
937
+ labels = labels.view(-1) # flatten label
938
+ if is_liger_kernel_available():
939
+ if mask_ratio is not None:
940
+ loss_fct = LigerFusedLinearCrossEntropyLoss(reduction="none",ignore_index=IGNORE_INDEX)
941
+ if not get_parallel_state().sp_enabled:
942
+ # Shift so that tokens < n predict n
943
+ hidden_states = hidden_states[..., :-1, :].contiguous()
944
+ loss = loss_fct(
945
+ self.lm_head.weight,
946
+ hidden_states.view(-1, self.config.hidden_size),
947
+ labels
948
+ )
949
+ path_loss = (-loss).exp().detach() * loss
950
+ loss = loss + path_loss
951
+ loss_mask = labels != IGNORE_INDEX
952
+ loss = (loss * loss_mask * (1/mask_ratio)).sum() / (loss_mask.sum() + 1e-8)
953
+ else:
954
+ loss_fct = LigerFusedLinearCrossEntropyLoss(reduction="mean")
955
+ if not get_parallel_state().sp_enabled:
956
+ # Shift so that tokens < n predict n
957
+ hidden_states = hidden_states[..., :-1, :].contiguous()
958
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
959
+ loss = loss_fct(self.lm_head.weight, hidden_states, labels)
960
+ else:
961
+ if mask_ratio is not None:
962
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="none")
963
+ logits = self.lm_head(hidden_states)
964
+ logits = logits.view(-1, self.vocab_size)
965
+ loss = loss_fct(logits, labels.view(-1))
966
+ path_loss = (-loss).exp().detach() * loss
967
+ loss = loss + path_loss
968
+ loss_mask = labels != IGNORE_INDEX
969
+ loss = (loss * loss_mask * (1/mask_ratio)).sum() / (loss_mask.sum() + 1e-8)
970
+ else:
971
+ loss_fct = torch.nn.CrossEntropyLoss(reduction="mean")
972
+ logits = self.lm_head(hidden_states)
973
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
974
+ logits = logits.float()
975
+ if not get_parallel_state().sp_enabled:
976
+ # Shift so that tokens < n predict n
977
+ logits = logits[..., :-1, :].contiguous()
978
+
979
+ # Flatten the tokens
980
+ logits = logits.view(-1, self.vocab_size)
981
+ loss = loss_fct(logits, labels)
982
+
983
+ if get_parallel_state().sp_enabled:
984
+ num_valid_tokens = (labels != IGNORE_INDEX).sum()
985
+ loss = reduce_sequence_parallel_loss(loss, num_valid_tokens)
986
+ else:
987
+ logits = self.lm_head(hidden_states)
988
+
989
+ if not return_dict:
990
+ output = (logits,) + outputs[1:]
991
+ return (loss,) + output if loss is not None else output
992
+
993
+ return CausalLMOutputWithPast(
994
+ loss=loss,
995
+ logits=logits,
996
+ past_key_values=outputs.past_key_values,
997
+ hidden_states=outputs.hidden_states,
998
+ attentions=outputs.attentions,
999
+ )
1000
+
1001
+
1002
+
1003
+
1004
+ import torch
1005
+ from tqdm import tqdm
1006
+ from typing import Callable, Tuple, Any
1007
+
1008
+
1009
+ def topk_masking(scores: torch.Tensor, cutoff_len: torch.Tensor, mode: str = "lowest") -> torch.Tensor:
1010
+ """Generate a mask selecting the top-k lowest or highest elements per row."""
1011
+ sorted_scores = scores.sort(dim=-1, descending=(mode == "highest")).values
1012
+ cutoff = sorted_scores.gather(dim=-1, index=cutoff_len)
1013
+ return (scores >= cutoff) if mode == "highest" else (scores < cutoff)
1014
+
1015
+
1016
+ def sample_categorical(
1017
+ logits: torch.Tensor, temperature: float = 1.0, noise_scale: float = 1.0
1018
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1019
+ """
1020
+ Sample from a categorical distribution with optional Gumbel noise.
1021
+ Returns sampled tokens, their scores, and the noised logits.
1022
+ """
1023
+ logits = logits.to(torch.float64)
1024
+ if temperature > 0:
1025
+ gumbel_noise = -torch.log(-torch.log(torch.rand_like(logits) + 1e-8) + 1e-8)
1026
+ logits = logits / temperature + noise_scale * gumbel_noise
1027
+ log_probs = logits.log_softmax(dim=-1)
1028
+ scores, tokens = log_probs.max(dim=-1)
1029
+ return tokens, scores.to(logits.dtype), logits.to(logits.dtype)
1030
+
1031
+
1032
+ @torch.inference_mode()
1033
+ @torch.amp.autocast(device_type="cuda", dtype=torch.float16)
1034
+ def p2_sampling(
1035
+ xt: torch.Tensor,
1036
+ model: Any,
1037
+ mask_id: int,
1038
+ num_steps: int,
1039
+ tau: float = 1.0,
1040
+ kappa_fn: Callable[[float], float] = lambda t: t,
1041
+ eta: float = 1.0,
1042
+ **kwargs
1043
+ ) -> torch.Tensor:
1044
+ """
1045
+ P2 Sampling implementation for discrete diffusion models.
1046
+ Reference: https://arxiv.org/pdf/2502.03540
1047
+ """
1048
+ dt = 1 / num_steps
1049
+ fix_mask = (xt != mask_id)
1050
+
1051
+ for i in tqdm(range(1, num_steps + 1)):
1052
+ t = i * dt
1053
+ kappa_t = kappa_fn(t)
1054
+
1055
+ logits = model(xt).double()
1056
+ last_mask = (xt == mask_id)
1057
+ unmask_t = ~last_mask & ~fix_mask
1058
+
1059
+ x0, score, _ = sample_categorical(logits, temperature=tau)
1060
+ score = score.masked_fill(fix_mask, float("inf"))
1061
+ score[unmask_t] *= eta
1062
+
1063
+ num_to_mask = ((~fix_mask).sum(dim=1, keepdim=True).float() * (1 - kappa_t)).long()
1064
+ to_mask = topk_masking(score, num_to_mask, mode="lowest")
1065
+
1066
+ xt[to_mask] = mask_id
1067
+ mask_2_x0 = last_mask & ~to_mask
1068
+ xt[mask_2_x0] = x0[mask_2_x0]
1069
+
1070
+ xt[xt == mask_id] = x0[xt == mask_id]
1071
+ return xt
1072
+
1073
+
1074
+
1075
+ if is_liger_kernel_available():
1076
+ apply_rotary_pos_emb = liger_rotary_pos_emb
1077
+ Qwen2RMSNorm = LigerRMSNorm
1078
+ Qwen2MLP = LigerSwiGLUMLP
1079
+ logger.info_rank0("Apply liger kernel to Qwen2.")
1080
+
1081
+
1082
+ ModelClass = Qwen2ForCausalLM
1083
+
1084
+ __all__ = ["Qwen2ForCausalLM", "Qwen2Model", "Qwen2PreTrainedModel"]
special_tokens_map.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "mask_token": {
25
+ "content": "<M>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "pad_token": {
32
+ "content": "<|endoftext|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f3ead5ffbb2abfb9e51757b104af5174f59c994ff3b2ca715d344dc66ee1f4e
3
+ size 11422076
tokenizer_config.json ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<M>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": true
188
+ }
189
+ },
190
+ "additional_special_tokens": [
191
+ "<|im_start|>",
192
+ "<|im_end|>",
193
+ "<|object_ref_start|>",
194
+ "<|object_ref_end|>",
195
+ "<|box_start|>",
196
+ "<|box_end|>",
197
+ "<|quad_start|>",
198
+ "<|quad_end|>",
199
+ "<|vision_start|>",
200
+ "<|vision_end|>",
201
+ "<|vision_pad|>",
202
+ "<|image_pad|>",
203
+ "<|video_pad|>"
204
+ ],
205
+ "bos_token": null,
206
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n",
207
+ "clean_up_tokenization_spaces": false,
208
+ "eos_token": "<|endoftext|>",
209
+ "errors": "replace",
210
+ "extra_special_tokens": {},
211
+ "mask_token": "<M>",
212
+ "model_max_length": 32768,
213
+ "pad_token": "<|endoftext|>",
214
+ "padding_side": "right",
215
+ "split_special_tokens": false,
216
+ "tokenizer_class": "Qwen2Tokenizer",
217
+ "unk_token": null
218
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff