bingyang-lei commited on
Commit
249cc9a
·
verified ·
1 Parent(s): aaecdf7

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. config.json +52 -0
  2. dflash.py +277 -0
  3. model.safetensors +3 -0
config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DFlashDraftModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoModel": "dflash.DFlashDraftModel"
9
+ },
10
+ "block_size": 16,
11
+ "bos_token_id": 151643,
12
+ "dflash_config": {
13
+ "mask_token_id": 151669,
14
+ "target_layer_ids": [
15
+ 1,
16
+ 9,
17
+ 17,
18
+ 25,
19
+ 33
20
+ ]
21
+ },
22
+ "dtype": "bfloat16",
23
+ "eos_token_id": 151645,
24
+ "head_dim": 128,
25
+ "hidden_act": "silu",
26
+ "hidden_size": 2560,
27
+ "initializer_range": 0.02,
28
+ "intermediate_size": 9728,
29
+ "layer_types": [
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention"
35
+ ],
36
+ "max_position_embeddings": 40960,
37
+ "max_window_layers": 5,
38
+ "model_type": "qwen3",
39
+ "num_attention_heads": 32,
40
+ "num_hidden_layers": 5,
41
+ "num_key_value_heads": 8,
42
+ "num_target_layers": 36,
43
+ "rms_norm_eps": 1e-06,
44
+ "rope_scaling": null,
45
+ "rope_theta": 1000000,
46
+ "sliding_window": null,
47
+ "tie_word_embeddings": true,
48
+ "transformers_version": "4.57.3",
49
+ "use_cache": true,
50
+ "use_sliding_window": false,
51
+ "vocab_size": 151936
52
+ }
dflash.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Callable
2
+ from typing_extensions import Unpack, Tuple
3
+ import torch
4
+ from torch import nn
5
+ from transformers.models.qwen3.modeling_qwen3 import (
6
+ Qwen3RMSNorm,
7
+ Qwen3RotaryEmbedding,
8
+ Qwen3Config,
9
+ Qwen3PreTrainedModel,
10
+ Qwen3MLP,
11
+ GradientCheckpointingLayer,
12
+ FlashAttentionKwargs,
13
+ rotate_half,
14
+ eager_attention_forward,
15
+ ALL_ATTENTION_FUNCTIONS,
16
+ )
17
+ from transformers import DynamicCache
18
+ from transformers.modeling_outputs import CausalLMOutputWithPast
19
+ from transformers.cache_utils import Cache
20
+ from .utils import build_target_layer_ids, extract_context_feature, sample
21
+
22
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
23
+ cos = cos.unsqueeze(unsqueeze_dim)
24
+ sin = sin.unsqueeze(unsqueeze_dim)
25
+ q_len = q.size(-2)
26
+ q_embed = (q * cos[..., -q_len:, :]) + (rotate_half(q) * sin[..., -q_len:, :])
27
+ k_embed = (k * cos) + (rotate_half(k) * sin)
28
+ return q_embed, k_embed
29
+
30
+ class Qwen3DFlashAttention(nn.Module):
31
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
32
+
33
+ def __init__(self, config: Qwen3Config, layer_idx: int):
34
+ super().__init__()
35
+ self.config = config
36
+ self.layer_idx = layer_idx
37
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
38
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
39
+ self.scaling = self.head_dim**-0.5
40
+ self.attention_dropout = config.attention_dropout
41
+ self.is_causal = False
42
+ self.q_proj = nn.Linear(
43
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
44
+ )
45
+ self.k_proj = nn.Linear(
46
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
47
+ )
48
+ self.v_proj = nn.Linear(
49
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
50
+ )
51
+ self.o_proj = nn.Linear(
52
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
53
+ )
54
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
55
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
56
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
57
+
58
+ def forward(
59
+ self,
60
+ hidden_states: torch.Tensor,
61
+ target_hidden: torch.Tensor,
62
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
63
+ attention_mask: Optional[torch.Tensor],
64
+ past_key_values: Optional[Cache] = None,
65
+ cache_position: Optional[torch.LongTensor] = None,
66
+ **kwargs: Unpack[FlashAttentionKwargs],
67
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
68
+ bsz, q_len = hidden_states.shape[:-1]
69
+ ctx_len = target_hidden.shape[1]
70
+ q = self.q_proj(hidden_states)
71
+ q = q.view(bsz, q_len, -1, self.head_dim)
72
+ q = self.q_norm(q).transpose(1, 2)
73
+ k_ctx = self.k_proj(target_hidden)
74
+ k_noise = self.k_proj(hidden_states)
75
+ v_ctx = self.v_proj(target_hidden)
76
+ v_noise = self.v_proj(hidden_states)
77
+ k = torch.cat([k_ctx, k_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
78
+ v = torch.cat([v_ctx, v_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
79
+ k = self.k_norm(k).transpose(1, 2)
80
+ v = v.transpose(1, 2)
81
+ cos, sin = position_embeddings
82
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
83
+ if past_key_values is not None:
84
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
85
+ k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs)
86
+ attn_fn: Callable = eager_attention_forward
87
+ if self.config._attn_implementation != "eager":
88
+ attn_fn = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
89
+ attn_output, attn_weights = attn_fn(
90
+ self,
91
+ q,
92
+ k,
93
+ v,
94
+ attention_mask,
95
+ dropout=0.0 if not self.training else self.attention_dropout,
96
+ scaling=self.scaling,
97
+ sliding_window=self.sliding_window,
98
+ **kwargs,
99
+ )
100
+ attn_output = attn_output.reshape(bsz, q_len, -1)
101
+ attn_output = self.o_proj(attn_output)
102
+ return attn_output, attn_weights
103
+
104
+ class Qwen3DFlashDecoderLayer(GradientCheckpointingLayer):
105
+ def __init__(self, config: Qwen3Config, layer_idx: int):
106
+ super().__init__()
107
+ self.hidden_size = config.hidden_size
108
+ self.self_attn = Qwen3DFlashAttention(config=config, layer_idx=layer_idx)
109
+ self.mlp = Qwen3MLP(config)
110
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
111
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
112
+
113
+ def forward(
114
+ self,
115
+ target_hidden: Optional[torch.Tensor] = None,
116
+ hidden_states: Optional[torch.Tensor] = None,
117
+ attention_mask: Optional[torch.Tensor] = None,
118
+ position_ids: Optional[torch.LongTensor] = None,
119
+ past_key_value: Optional[Cache] = None,
120
+ output_attentions: Optional[bool] = False,
121
+ use_cache: Optional[bool] = False,
122
+ cache_position: Optional[torch.LongTensor] = None,
123
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
124
+ **kwargs: Unpack[FlashAttentionKwargs],
125
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
126
+ residual = hidden_states
127
+ hidden_states = self.input_layernorm(hidden_states)
128
+ hidden_states = self.self_attn(
129
+ hidden_states=hidden_states,
130
+ target_hidden=target_hidden,
131
+ attention_mask=attention_mask,
132
+ position_ids=position_ids,
133
+ past_key_values=past_key_value,
134
+ output_attentions=output_attentions,
135
+ use_cache=use_cache,
136
+ cache_position=cache_position,
137
+ position_embeddings=position_embeddings,
138
+ **kwargs,
139
+ )[0]
140
+ hidden_states = residual + hidden_states
141
+ residual = hidden_states
142
+ hidden_states = self.post_attention_layernorm(hidden_states)
143
+ hidden_states = self.mlp(hidden_states)
144
+ hidden_states = residual + hidden_states
145
+ return hidden_states
146
+
147
+ class DFlashDraftModel(Qwen3PreTrainedModel):
148
+ config_class = Qwen3Config
149
+ _no_split_modules = ["Qwen3DFlashDecoderLayer"]
150
+
151
+ def __init__(self, config) -> None:
152
+ super().__init__(config)
153
+ self.config = config
154
+ self.layers = nn.ModuleList(
155
+ [Qwen3DFlashDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
156
+ )
157
+ self.target_layer_ids = self.config.dflash_config.get("target_layer_ids", build_target_layer_ids(config.num_target_layers, config.num_hidden_layers))
158
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
159
+ self.rotary_emb = Qwen3RotaryEmbedding(config)
160
+ self.fc = nn.Linear(len(self.target_layer_ids) * config.hidden_size, config.hidden_size, bias=False)
161
+ self.hidden_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
162
+ self.block_size = config.block_size
163
+ self.mask_token_id = self.config.dflash_config.get("mask_token_id", None)
164
+ self.post_init()
165
+
166
+ def forward(
167
+ self,
168
+ position_ids: torch.LongTensor,
169
+ attention_mask: Optional[torch.Tensor] = None,
170
+ noise_embedding: Optional[torch.Tensor] = None,
171
+ target_hidden: Optional[torch.Tensor] = None,
172
+ past_key_values: Optional[Cache] = None,
173
+ use_cache: bool = False,
174
+ **kwargs,
175
+ ) -> CausalLMOutputWithPast:
176
+ hidden_states = noise_embedding
177
+ target_hidden = self.hidden_norm(self.fc(target_hidden))
178
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
179
+ for layer in self.layers:
180
+ hidden_states = layer(
181
+ hidden_states=hidden_states,
182
+ target_hidden=target_hidden,
183
+ attention_mask=attention_mask,
184
+ position_ids=position_ids,
185
+ past_key_value=past_key_values,
186
+ use_cache=use_cache,
187
+ position_embeddings=position_embeddings,
188
+ **kwargs,
189
+ )
190
+ return self.norm(hidden_states)
191
+
192
+ @torch.inference_mode()
193
+ def spec_generate(
194
+ self,
195
+ target: nn.Module,
196
+ input_ids: torch.LongTensor,
197
+ max_new_tokens: int,
198
+ stop_token_ids: list[int],
199
+ temperature: float,
200
+ ):
201
+ self.eval()
202
+ num_input_tokens = input_ids.shape[1]
203
+ max_length = num_input_tokens + max_new_tokens
204
+
205
+ block_size = self.block_size
206
+ output_ids = torch.full(
207
+ (1, max_length + block_size),
208
+ self.mask_token_id,
209
+ dtype=torch.long,
210
+ device=target.device,
211
+ )
212
+ position_ids = torch.arange(output_ids.shape[1], device=target.device).unsqueeze(0)
213
+
214
+ past_key_values_target = DynamicCache()
215
+ past_key_values_draft = DynamicCache()
216
+
217
+ # Prefill stage
218
+ output = target(
219
+ input_ids,
220
+ position_ids=position_ids[:, :num_input_tokens],
221
+ past_key_values=past_key_values_target,
222
+ use_cache=True,
223
+ logits_to_keep=1,
224
+ output_hidden_states=True,
225
+ )
226
+
227
+ output_ids[:, :num_input_tokens] = input_ids
228
+ output_ids[:, num_input_tokens:num_input_tokens+1] = sample(output.logits, temperature)
229
+ target_hidden = extract_context_feature(output.hidden_states, self.target_layer_ids)
230
+
231
+ # Decode stage
232
+ acceptance_lengths = []
233
+ start = input_ids.shape[1]
234
+ while start < max_length:
235
+ block_output_ids = output_ids[:, start : start + block_size].clone()
236
+ block_position_ids = position_ids[:, start : start + block_size]
237
+ noise_embedding = target.model.embed_tokens(block_output_ids)
238
+ draft_logits = target.lm_head(self(
239
+ target_hidden=target_hidden,
240
+ noise_embedding=noise_embedding,
241
+ position_ids=position_ids[:, past_key_values_draft.get_seq_length(): start + block_size],
242
+ past_key_values=past_key_values_draft,
243
+ use_cache=True,
244
+ is_causal=False,
245
+ )[:, -block_size+1:, :])
246
+ past_key_values_draft.crop(start)
247
+ block_output_ids[:, 1:] = sample(draft_logits)
248
+
249
+ output = target(
250
+ block_output_ids,
251
+ position_ids=block_position_ids,
252
+ past_key_values=past_key_values_target,
253
+ use_cache=True,
254
+ output_hidden_states=True,
255
+ )
256
+
257
+ posterior = sample(output.logits, temperature)
258
+ acceptance_length = (block_output_ids[:, 1:] == posterior[:, :-1]).cumprod(dim=1).sum(dim=1)[0].item()
259
+ output_ids[:, start : start + acceptance_length + 1] = block_output_ids[:, : acceptance_length + 1]
260
+ output_ids[:, start + acceptance_length + 1] = posterior[:, acceptance_length]
261
+ start += acceptance_length + 1
262
+ past_key_values_target.crop(start)
263
+ target_hidden = extract_context_feature(output.hidden_states, self.target_layer_ids)[:, :acceptance_length + 1, :]
264
+ acceptance_lengths.append(acceptance_length+1)
265
+ if stop_token_ids is not None and any(
266
+ stop_token_id in output_ids[:, num_input_tokens:] for stop_token_id in stop_token_ids
267
+ ):
268
+ break
269
+ output_ids = output_ids[:, :max_length]
270
+ output_ids = output_ids[:, output_ids[0] != self.mask_token_id]
271
+ if stop_token_ids is not None:
272
+ stop_token_ids = torch.tensor(stop_token_ids, device=output_ids.device)
273
+ stop_token_indices = torch.isin(output_ids[0][num_input_tokens:], stop_token_ids).nonzero(as_tuple=True)[0]
274
+ if stop_token_indices.numel() > 0:
275
+ output_ids = output_ids[:, : num_input_tokens + stop_token_indices[0] + 1]
276
+
277
+ return output_ids
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:046523f587f941616ae9c81f349a54689833061a5d37591d952ffd28aaa0e043
3
+ size 1074860544