tucian commited on
Commit
849a848
·
verified ·
1 Parent(s): 4fb6b3e

upload dlm-code0.6b-exp weights

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ 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
37
+ quick-sort-demo-with-music.mp4 filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## thunder-dlm-0.6b — Masked Diffusion Model for Code Generation
13
+
14
+ This repository contains the weights and custom code for the **staticlabs/thunder-dlm-0.6b** 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
+
26
+ You can then use the model for generation. Note: You must pass trust_remote_code=True to load the custom model architecture.
27
+ ```python
28
+ import torch
29
+ from transformers import AutoTokenizer, AutoModelForCausalLM
30
+
31
+ model_id = "staticlabs/thunder-dlm-0.6b"
32
+ device = "cuda" if torch.cuda.is_available() else "cpu"
33
+
34
+ # trust_remote_code=True is essential
35
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
36
+ model = AutoModelForCausalLM.from_pretrained(
37
+ model_id,
38
+ torch_dtype=torch.bfloat16,
39
+ trust_remote_code=True
40
+ ).to(device)
41
+
42
+ prompt = "def fibonacci(n):"
43
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
44
+
45
+ # The model will use the generation_config.json from the repo by default
46
+ # You can also override parameters here
47
+ outputs = model.diffusion_generate(
48
+ inputs=input_ids,
49
+ max_new_tokens=100,
50
+ steps=16,
51
+ temperature=0.8
52
+ )
53
+
54
+ # Decode the output
55
+ prompt_len = input_ids.shape[1]
56
+ generated_text = tokenizer.decode(outputs.sequences[0][prompt_len:], skip_special_tokens=True)
57
+
58
+ print("--- Generated Code ---")
59
+ print(generated_text)
60
+ ```
__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,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
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:59c1a005f4b672bdd3bbdab6258b283dff3b87bab5cc4bbc0d479e8388f77b6e
3
+ size 1260367448
modeling_qwen2.py ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
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.
14
+
15
+ # This is a fully self-contained version of the model script.
16
+ # It includes the MDMGenerationMixin and all necessary utilities for public release.
17
+
18
+ import logging
19
+ import warnings
20
+ import copy
21
+ from dataclasses import dataclass
22
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.distributions as dists
26
+ from torch import nn
27
+ from torch.nn import functional as F
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
31
+ from transformers.generation.configuration_utils import GenerationConfig
32
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
33
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ ModelOutput,
38
+ )
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
40
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
41
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
42
+ from transformers.processing_utils import Unpack
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ replace_return_docstrings,
47
+ )
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ # ==============================================================================
52
+ # Start of Generation Utilities (Integrated directly into this file)
53
+ # ==============================================================================
54
+
55
+ def top_p_logits(logits, top_p=None):
56
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
57
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
58
+ sorted_indices_to_remove = cumulative_probs > top_p
59
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
60
+ sorted_indices_to_remove[..., 0] = 0
61
+ mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
62
+ mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
63
+ logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
64
+ return logits
65
+
66
+ def top_k_logits(logits, top_k=None):
67
+ if top_k is None or top_k == 0:
68
+ return logits
69
+ top_k = min(top_k, logits.size(-1))
70
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
71
+ logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
72
+ return logits
73
+
74
+ def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
75
+ if temperature > 0:
76
+ logits = logits / temperature
77
+ if top_p is not None and top_p < 1:
78
+ logits = top_p_logits(logits, top_p)
79
+ if top_k is not None:
80
+ logits = top_k_logits(logits, top_k)
81
+ probs = torch.softmax(logits.float(), dim=-1)
82
+ if temperature > 0:
83
+ x0 = dists.Categorical(probs=probs).sample()
84
+ else:
85
+ _, x0 = probs.max(dim=-1)
86
+
87
+ confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
88
+
89
+ if margin_confidence:
90
+ sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
91
+ top1_probs = sorted_probs[..., 0]
92
+ top2_probs = sorted_probs[..., 1]
93
+ confidence = top1_probs - top2_probs
94
+ elif neg_entropy:
95
+ log_probs = torch.log(probs.clamp(min=1e-10))
96
+ confidence = (probs * log_probs).sum(dim=-1)
97
+
98
+ return confidence, x0
99
+
100
+
101
+ @dataclass
102
+ class MDMModelOutput(ModelOutput):
103
+ sequences: torch.LongTensor = None
104
+ history: Optional[Tuple[torch.FloatTensor]] = None
105
+
106
+ class MDMGenerationConfig(GenerationConfig):
107
+ def __init__(self, **kwargs):
108
+ super().__init__(**kwargs)
109
+ self.temperature: float = kwargs.pop("temperature", 0.0)
110
+ self.top_p: Optional[float] = kwargs.pop("top_p", None)
111
+ self.top_k: Optional[int] = kwargs.pop("top_k", None)
112
+ self.eps: float = kwargs.pop("eps", 1e-3)
113
+ self.steps: int = kwargs.pop("steps", 512)
114
+ self.alg: str = kwargs.pop("alg", 'entropy')
115
+ self.alg_temp: Optional[float] = kwargs.pop("alg_temp", 0.0)
116
+ self.output_history: bool = kwargs.pop("output_history", False)
117
+ self.mask_token_id = kwargs.pop("mask_token_id", None)
118
+
119
+
120
+ class MDMGenerationMixin:
121
+ """
122
+ Mixin class for Masked Diffusion Model generation.
123
+ """
124
+ @staticmethod
125
+ def _expand_inputs_for_generation(
126
+ expand_size: int = 1,
127
+ input_ids: Optional[torch.LongTensor] = None,
128
+ attention_mask: Optional[torch.LongTensor] = None
129
+ ) -> Tuple[torch.LongTensor, Dict[str, Any]]:
130
+ if expand_size == 1:
131
+ return input_ids, attention_mask
132
+
133
+ if input_ids is not None:
134
+ input_ids = input_ids.repeat_interleave(expand_size, dim=0)
135
+ if attention_mask is not None:
136
+ attention_mask = attention_mask.repeat_interleave(expand_size, dim=0)
137
+ return input_ids, attention_mask
138
+
139
+ def _prepare_generation_config(
140
+ self, generation_config: Optional[GenerationConfig], **kwargs
141
+ ) -> MDMGenerationConfig:
142
+ if generation_config is None:
143
+ generation_config = self.generation_config
144
+
145
+ if not isinstance(generation_config, MDMGenerationConfig):
146
+ generation_config = MDMGenerationConfig.from_dict(generation_config.to_dict())
147
+
148
+ generation_config.update(**kwargs)
149
+ return generation_config
150
+
151
+ @torch.no_grad()
152
+ def diffusion_generate(
153
+ self,
154
+ inputs: Optional[torch.Tensor] = None,
155
+ generation_config: Optional[MDMGenerationConfig] = None,
156
+ **kwargs,
157
+ ) -> Union[MDMModelOutput, torch.LongTensor]:
158
+
159
+ generation_config = self._prepare_generation_config(generation_config, **kwargs)
160
+ input_ids = inputs
161
+ attention_mask = kwargs.get("attention_mask", None)
162
+
163
+ if input_ids is None:
164
+ raise ValueError("`inputs` must be provided for diffusion generation.")
165
+
166
+ if generation_config.max_new_tokens is not None:
167
+ generation_config.max_length = input_ids.shape[-1] + generation_config.max_new_tokens
168
+
169
+ input_ids, attention_mask = self._expand_inputs_for_generation(
170
+ expand_size=generation_config.num_return_sequences,
171
+ input_ids=input_ids,
172
+ attention_mask=attention_mask
173
+ )
174
+ return self._sample(
175
+ input_ids,
176
+ attention_mask=attention_mask,
177
+ generation_config=generation_config
178
+ )
179
+
180
+ def _sample(
181
+ self,
182
+ input_ids: torch.LongTensor,
183
+ attention_mask: Optional[torch.LongTensor],
184
+ generation_config: MDMGenerationConfig
185
+ ) -> Union[MDMModelOutput, torch.LongTensor]:
186
+
187
+ max_length = generation_config.max_length
188
+ mask_token_id = generation_config.mask_token_id
189
+ if mask_token_id is None:
190
+ raise ValueError("`mask_token_id` must be set in the generation config.")
191
+
192
+ steps = generation_config.steps
193
+ eps = generation_config.eps
194
+ alg = generation_config.alg
195
+ alg_temp = generation_config.alg_temp
196
+ temperature = generation_config.temperature
197
+ top_p = generation_config.top_p
198
+ top_k = generation_config.top_k
199
+
200
+ histories = [] if generation_config.output_history else None
201
+ x = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id)
202
+ gen_attention_mask = (x != self.config.pad_token_id).long() if self.config.pad_token_id is not None else None
203
+ timesteps = torch.linspace(1, eps, steps + 1, device=x.device)
204
+
205
+ for i in range(steps):
206
+ mask_index = (x == mask_token_id)
207
+ if not mask_index.any():
208
+ break
209
+ outputs = self(input_ids=x, attention_mask=gen_attention_mask, is_causal=False)
210
+ logits = outputs.logits
211
+ logits = torch.cat([logits[:, :1], logits[:, :-1]], dim=1)
212
+ mask_logits = logits[mask_index]
213
+ t = timesteps[i]
214
+ s = timesteps[i + 1]
215
+
216
+ confidence_alg_map = {'maskgit_plus': False, 'topk_margin': True, 'entropy': True}
217
+ is_margin_conf = confidence_alg_map.get(alg, False)
218
+ is_neg_entropy = alg == 'entropy'
219
+
220
+ confidence, x0 = sample_tokens(mask_logits, temperature, top_p, top_k, margin_confidence=is_margin_conf, neg_entropy=is_neg_entropy)
221
+ num_masked = mask_index.sum(dim=-1, keepdim=True)
222
+ gamma = 1 - s / t
223
+ num_to_unmask = (num_masked * gamma).long()
224
+ full_confidence = torch.full_like(x, -torch.inf, device=self.device, dtype=confidence.dtype)
225
+ full_confidence[mask_index] = confidence
226
+
227
+ if (alg_temp is not None and alg_temp > 0):
228
+ unmask_probs = F.softmax(full_confidence / alg_temp, dim=-1)
229
+ unmask_indices = torch.multinomial(unmask_probs, num_samples=num_to_unmask.max(), replacement=False)
230
+ else:
231
+ _, unmask_indices = torch.topk(full_confidence, k=num_to_unmask.max(), dim=-1)
232
+
233
+ rows = torch.arange(x.size(0), device=x.device).unsqueeze(1)
234
+ unmask_selection_mask = torch.zeros_like(x, dtype=torch.bool)
235
+ unmask_selection_mask[rows, unmask_indices] = True
236
+ unmask_selection_mask = unmask_selection_mask & (torch.cumsum(unmask_selection_mask.long(), dim=-1) <= num_to_unmask)
237
+ x_unmasked_proposals = torch.full_like(x, fill_value=mask_token_id)
238
+ x_unmasked_proposals[mask_index] = x0
239
+ x[unmask_selection_mask] = x_unmasked_proposals[unmask_selection_mask]
240
+
241
+ if histories is not None:
242
+ histories.append(x.clone())
243
+
244
+ if generation_config.return_dict_in_generate:
245
+ return MDMModelOutput(sequences=x, history=histories)
246
+ else:
247
+ return x
248
+
249
+ # ==============================================================================
250
+ # End of Generation Utilities
251
+ # ==============================================================================
252
+
253
+
254
+ _CHECKPOINT_FOR_DOC = "meta-qwen2/Qwen2-2-7b-hf"
255
+ _CONFIG_FOR_DOC = "Qwen2Config"
256
+
257
+
258
+ class Qwen2MLP(nn.Module):
259
+ # ... (class unchanged)
260
+ def __init__(self, config):
261
+ super().__init__()
262
+ self.config = config
263
+ self.hidden_size = config.hidden_size
264
+ self.intermediate_size = config.intermediate_size
265
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
266
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
267
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
268
+ self.act_fn = ACT2FN[config.hidden_act]
269
+
270
+ def forward(self, x):
271
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
272
+ return down_proj
273
+
274
+ def rotate_half(x):
275
+ # ... (function unchanged)
276
+ x1 = x[..., : x.shape[-1] // 2]
277
+ x2 = x[..., x.shape[-1] // 2 :]
278
+ return torch.cat((-x2, x1), dim=-1)
279
+
280
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
281
+ # ... (function unchanged)
282
+ cos = cos.unsqueeze(unsqueeze_dim)
283
+ sin = sin.unsqueeze(unsqueeze_dim)
284
+ q_embed = (q * cos) + (rotate_half(q) * sin)
285
+ k_embed = (k * cos) + (rotate_half(k) * sin)
286
+ return q_embed, k_embed
287
+
288
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
289
+ # ... (function unchanged)
290
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
291
+ if n_rep == 1:
292
+ return hidden_states
293
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
294
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
295
+
296
+ class Qwen2Attention(nn.Module):
297
+ # ... (class unchanged)
298
+ def __init__(self, config: Qwen2Config, layer_idx: int):
299
+ super().__init__()
300
+ self.config = config
301
+ self.layer_idx = layer_idx
302
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
303
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
304
+ self.scaling = self.head_dim**-0.5
305
+ self.attention_dropout = config.attention_dropout
306
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
307
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
308
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
309
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
310
+
311
+ def forward(
312
+ self,
313
+ hidden_states: torch.Tensor,
314
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
315
+ attention_mask: Optional[torch.Tensor],
316
+ past_key_value: Optional[Cache] = None,
317
+ output_attentions: Optional[bool] = False,
318
+ cache_position: Optional[torch.LongTensor] = None,
319
+ is_causal: bool = True,
320
+ **kwargs: Unpack[FlashAttentionKwargs],
321
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
322
+ bsz, q_len, _ = hidden_states.size()
323
+ hidden_shape = (bsz, q_len, -1, self.head_dim)
324
+
325
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
326
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
327
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
328
+
329
+ full_q_len = query_states.size(2)
330
+ cos, sin = position_embeddings
331
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
332
+
333
+ if past_key_value is not None:
334
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
335
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
336
+
337
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get(self.config._attn_implementation, None)
338
+ if attention_interface is None:
339
+ raise ValueError(f"Attention implementation {self.config._attn_implementation} not found.")
340
+
341
+ if self.config._attn_implementation == "sdpa" and output_attentions:
342
+ logger.warning_once("Using SDPA with `output_attentions=True` requires eager attention.")
343
+ attention_interface = ALL_ATTENTION_FUNCTIONS["eager"]
344
+
345
+
346
+ attn_output, attn_weights = attention_interface(
347
+ query_states,
348
+ key_states,
349
+ value_states,
350
+ attention_mask=attention_mask,
351
+ dropout=self.attention_dropout if self.training else 0.0,
352
+ is_causal=is_causal,
353
+ **kwargs,
354
+ )
355
+ attn_output = attn_output.transpose(1, 2).contiguous()
356
+ attn_output = attn_output.reshape(bsz, q_len, self.config.hidden_size)
357
+ attn_output = self.o_proj(attn_output)
358
+
359
+ if not output_attentions:
360
+ attn_weights = None
361
+
362
+ return attn_output, attn_weights, past_key_value
363
+
364
+ class Qwen2RMSNorm(nn.Module):
365
+ # ... (class unchanged)
366
+ def __init__(self, hidden_size, eps=1e-6):
367
+ super().__init__()
368
+ self.weight = nn.Parameter(torch.ones(hidden_size))
369
+ self.variance_epsilon = eps
370
+
371
+ def forward(self, hidden_states):
372
+ input_dtype = hidden_states.dtype
373
+ hidden_states = hidden_states.to(torch.float32)
374
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
375
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
376
+ return self.weight * hidden_states.to(input_dtype)
377
+
378
+ class Qwen2DecoderLayer(nn.Module):
379
+ # ... (class unchanged)
380
+ def __init__(self, config: Qwen2Config, layer_idx: int):
381
+ super().__init__()
382
+ self.hidden_size = config.hidden_size
383
+ self.self_attn = Qwen2Attention(config=config, layer_idx=layer_idx)
384
+ self.mlp = Qwen2MLP(config)
385
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
386
+ self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.Tensor] = None,
392
+ position_ids: Optional[torch.LongTensor] = None,
393
+ past_key_value: Optional[Cache] = None,
394
+ output_attentions: Optional[bool] = False,
395
+ use_cache: Optional[bool] = False,
396
+ cache_position: Optional[torch.LongTensor] = None,
397
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
398
+ is_causal: bool = True,
399
+ **kwargs: Unpack[FlashAttentionKwargs],
400
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
401
+ residual = hidden_states
402
+ hidden_states = self.input_layernorm(hidden_states)
403
+
404
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
405
+ hidden_states=hidden_states,
406
+ attention_mask=attention_mask,
407
+ past_key_value=past_key_value,
408
+ output_attentions=output_attentions,
409
+ cache_position=cache_position,
410
+ position_embeddings=position_embeddings,
411
+ is_causal=is_causal,
412
+ **kwargs,
413
+ )
414
+ hidden_states = residual + hidden_states
415
+
416
+ residual = hidden_states
417
+ hidden_states = self.post_attention_layernorm(hidden_states)
418
+ hidden_states = self.mlp(hidden_states)
419
+ hidden_states = residual + hidden_states
420
+
421
+ outputs = (hidden_states,)
422
+ if output_attentions:
423
+ outputs += (self_attn_weights,)
424
+ if use_cache:
425
+ outputs += (present_key_value,)
426
+
427
+ return outputs
428
+
429
+ class Qwen2RotaryEmbedding(nn.Module):
430
+ # ... (class unchanged)
431
+ def __init__(self, config: Qwen2Config, device=None):
432
+ super().__init__()
433
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
434
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
435
+ else:
436
+ self.rope_type = "default"
437
+ self.max_seq_len_cached = config.max_position_embeddings
438
+ self.original_max_seq_len = config.max_position_embeddings
439
+ self.config = config
440
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
441
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
442
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
443
+ self.original_inv_freq = self.inv_freq
444
+
445
+ def _dynamic_frequency_update(self, position_ids, device):
446
+ seq_len = torch.max(position_ids) + 1
447
+ if seq_len > self.max_seq_len_cached:
448
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
449
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
450
+ self.max_seq_len_cached = seq_len
451
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len:
452
+ self.original_inv_freq = self.original_inv_freq.to(device)
453
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
454
+ self.max_seq_len_cached = self.original_max_seq_len
455
+
456
+ @torch.no_grad()
457
+ def forward(self, x, position_ids):
458
+ if "dynamic" in self.rope_type:
459
+ self._dynamic_frequency_update(position_ids, device=x.device)
460
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
461
+ position_ids_expanded = position_ids[:, None, :].float()
462
+ device_type = x.device.type
463
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
464
+ with torch.autocast(device_type=device_type, enabled=False):
465
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
466
+ emb = torch.cat((freqs, freqs), dim=-1)
467
+ cos = emb.cos()
468
+ sin = emb.sin()
469
+ cos = cos * self.attention_scaling
470
+ sin = sin * self.attention_scaling
471
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
472
+
473
+ class Qwen2PreTrainedModel(PreTrainedModel):
474
+ # ... (class unchanged)
475
+ config_class = Qwen2Config
476
+ base_model_prefix = "model"
477
+ supports_gradient_checkpointing = True
478
+ _no_split_modules = ["Qwen2DecoderLayer"]
479
+ _skip_keys_device_placement = ["past_key_values"]
480
+ _supports_flash_attn_2 = True
481
+ _supports_sdpa = True
482
+ _supports_cache_class = True
483
+
484
+ def _init_weights(self, module):
485
+ std = self.config.initializer_range
486
+ if isinstance(module, nn.Linear):
487
+ module.weight.data.normal_(mean=0.0, std=std)
488
+ if module.bias is not None:
489
+ module.bias.data.zero_()
490
+ elif isinstance(module, nn.Embedding):
491
+ module.weight.data.normal_(mean=0.0, std=std)
492
+ if module.padding_idx is not None:
493
+ module.weight.data[module.padding_idx].zero_()
494
+
495
+ class Qwen2Model(Qwen2PreTrainedModel):
496
+ # ... (class unchanged)
497
+ def __init__(self, config: Qwen2Config):
498
+ super().__init__(config)
499
+ self.padding_idx = config.pad_token_id
500
+ self.vocab_size = config.vocab_size
501
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
502
+ self.layers = nn.ModuleList(
503
+ [Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
504
+ )
505
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
506
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
507
+ self.gradient_checkpointing = False
508
+ self.post_init()
509
+
510
+ def get_input_embeddings(self):
511
+ return self.embed_tokens
512
+
513
+ def set_input_embeddings(self, value):
514
+ self.embed_tokens = value
515
+
516
+ def forward(
517
+ self,
518
+ input_ids: torch.LongTensor = None,
519
+ attention_mask: Optional[torch.Tensor] = None,
520
+ position_ids: Optional[torch.LongTensor] = None,
521
+ past_key_values: Optional[Cache] = None,
522
+ inputs_embeds: Optional[torch.FloatTensor] = None,
523
+ use_cache: Optional[bool] = None,
524
+ output_attentions: Optional[bool] = None,
525
+ output_hidden_states: Optional[bool] = None,
526
+ return_dict: Optional[bool] = None,
527
+ cache_position: Optional[torch.LongTensor] = None,
528
+ is_causal: bool = True,
529
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
530
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
531
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
532
+ output_hidden_states = (
533
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
534
+ )
535
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
536
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
537
+
538
+ if (input_ids is None) ^ (inputs_embeds is not None):
539
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
540
+ if self.gradient_checkpointing and self.training and use_cache:
541
+ logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.")
542
+ use_cache = False
543
+ if inputs_embeds is None:
544
+ inputs_embeds = self.embed_tokens(input_ids)
545
+
546
+ past_key_values_length = 0
547
+ if use_cache:
548
+ if past_key_values is None:
549
+ past_key_values = DynamicCache()
550
+ past_key_values_length = past_key_values.get_seq_length()
551
+
552
+ if cache_position is None:
553
+ cache_position = torch.arange(
554
+ past_key_values_length, past_key_values_length + inputs_embeds.shape[1], device=inputs_embeds.device
555
+ )
556
+ if position_ids is None:
557
+ position_ids = cache_position.unsqueeze(0)
558
+
559
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, is_causal)
560
+ hidden_states = inputs_embeds
561
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
562
+ all_hidden_states = () if output_hidden_states else None
563
+ all_self_attns = () if output_attentions else None
564
+ next_decoder_cache = () if use_cache else None
565
+
566
+ for decoder_layer in self.layers:
567
+ if output_hidden_states:
568
+ all_hidden_states += (hidden_states,)
569
+
570
+ layer_outputs = decoder_layer(
571
+ hidden_states,
572
+ attention_mask=causal_mask,
573
+ position_ids=position_ids,
574
+ past_key_value=past_key_values,
575
+ output_attentions=output_attentions,
576
+ use_cache=use_cache,
577
+ cache_position=cache_position,
578
+ position_embeddings=position_embeddings,
579
+ is_causal=is_causal,
580
+ **flash_attn_kwargs,
581
+ )
582
+ hidden_states = layer_outputs[0]
583
+ if use_cache:
584
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
585
+ if output_attentions:
586
+ all_self_attns += (layer_outputs[1],)
587
+
588
+ hidden_states = self.norm(hidden_states)
589
+ if output_hidden_states:
590
+ all_hidden_states += (hidden_states,)
591
+
592
+ next_cache = next_decoder_cache if use_cache else None
593
+
594
+ if not return_dict:
595
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
596
+ return BaseModelOutputWithPast(
597
+ last_hidden_state=hidden_states,
598
+ past_key_values=next_cache,
599
+ hidden_states=all_hidden_states,
600
+ attentions=all_self_attns,
601
+ )
602
+
603
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position, is_causal):
604
+ if not is_causal:
605
+ return attention_mask
606
+
607
+ seq_len = input_tensor.shape[1]
608
+ if self.config._attn_implementation == "flash_attention_2":
609
+ if attention_mask is not None and 0.0 in attention_mask:
610
+ return attention_mask
611
+ return None
612
+
613
+ dtype = input_tensor.dtype
614
+ device = input_tensor.device
615
+
616
+ causal_mask = torch.triu(torch.full((seq_len, seq_len), torch.finfo(dtype).min, device=device), 1)
617
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
618
+
619
+ if attention_mask is not None:
620
+ causal_mask = causal_mask.clone()
621
+ causal_mask = causal_mask + attention_mask[:, None, None, :]
622
+
623
+ return causal_mask
624
+
625
+ class Qwen2ForCausalLM(Qwen2PreTrainedModel, MDMGenerationMixin):
626
+ _tied_weights_keys = ["lm_head.weight"]
627
+
628
+ def __init__(self, config):
629
+ super().__init__(config)
630
+ self.model = Qwen2Model(config)
631
+ self.vocab_size = config.vocab_size
632
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
633
+ self.post_init()
634
+
635
+ def get_input_embeddings(self):
636
+ return self.model.embed_tokens
637
+
638
+ def set_input_embeddings(self, value):
639
+ self.model.embed_tokens = value
640
+
641
+ def get_output_embeddings(self):
642
+ return self.lm_head
643
+
644
+ def set_output_embeddings(self, new_embeddings):
645
+ self.lm_head = new_embeddings
646
+
647
+ def set_decoder(self, decoder):
648
+ self.model = decoder
649
+
650
+ def get_decoder(self):
651
+ return self.model
652
+
653
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
654
+ def forward(
655
+ self,
656
+ input_ids: torch.LongTensor = None,
657
+ attention_mask: Optional[torch.Tensor] = None,
658
+ position_ids: Optional[torch.LongTensor] = None,
659
+ past_key_values: Optional[Cache] = None,
660
+ inputs_embeds: Optional[torch.FloatTensor] = None,
661
+ labels: Optional[torch.LongTensor] = None,
662
+ use_cache: Optional[bool] = None,
663
+ output_attentions: Optional[bool] = None,
664
+ output_hidden_states: Optional[bool] = None,
665
+ return_dict: Optional[bool] = None,
666
+ cache_position: Optional[torch.LongTensor] = None,
667
+ is_causal: bool = True,
668
+ **kwargs: Unpack[FlashAttentionKwargs],
669
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
670
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
671
+ output_hidden_states = (
672
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
673
+ )
674
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
675
+
676
+ outputs = self.model(
677
+ input_ids=input_ids,
678
+ attention_mask=attention_mask,
679
+ position_ids=position_ids,
680
+ past_key_values=past_key_values,
681
+ inputs_embeds=inputs_embeds,
682
+ use_cache=use_cache,
683
+ output_attentions=output_attentions,
684
+ output_hidden_states=output_hidden_states,
685
+ return_dict=return_dict,
686
+ cache_position=cache_position,
687
+ is_causal=is_causal,
688
+ **kwargs,
689
+ )
690
+
691
+ hidden_states = outputs[0]
692
+ logits = self.lm_head(hidden_states)
693
+ logits = logits.float()
694
+ loss = None
695
+
696
+ if labels is not None:
697
+ shift_logits = logits[..., :-1, :].contiguous()
698
+ shift_labels = labels[..., 1:].contiguous()
699
+ loss_fct = torch.nn.CrossEntropyLoss()
700
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
701
+ shift_labels = shift_labels.view(-1)
702
+ shift_labels = shift_labels.to(shift_logits.device)
703
+ loss = loss_fct(shift_logits, shift_labels)
704
+
705
+ if not return_dict:
706
+ output = (logits,) + outputs[1:]
707
+ return (loss,) + output if loss is not None else output
708
+
709
+ return CausalLMOutputWithPast(
710
+ loss=loss,
711
+ logits=logits,
712
+ past_key_values=outputs.past_key_values,
713
+ hidden_states=outputs.hidden_states,
714
+ attentions=outputs.attentions,
715
+ )
716
+
717
+ ModelClass = Qwen2ForCausalLM
718
+
719
+ __all__ = ["Qwen2ForCausalLM", "Qwen2Model", "Qwen2PreTrainedModel", "MDMGenerationMixin"]
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