jianchen0311 commited on
Commit
38d1425
·
verified ·
1 Parent(s): 46c8477

Upload model

Browse files
Files changed (4) hide show
  1. README.md +199 -0
  2. config.json +42 -0
  3. model.safetensors +3 -0
  4. modeling_dflash.py +304 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DFlashDraftModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoModel": "modeling_dflash.DFlashDraftModel"
9
+ },
10
+ "block_size": 16,
11
+ "bos_token_id": 151643,
12
+ "dtype": "bfloat16",
13
+ "eos_token_id": 151645,
14
+ "head_dim": 128,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 4096,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 12288,
19
+ "layer_types": [
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention"
25
+ ],
26
+ "max_position_embeddings": 40960,
27
+ "max_window_layers": 5,
28
+ "model_type": "qwen3",
29
+ "num_attention_heads": 32,
30
+ "num_hidden_layers": 5,
31
+ "num_key_value_heads": 8,
32
+ "num_target_layers": 36,
33
+ "rms_norm_eps": 1e-06,
34
+ "rope_scaling": null,
35
+ "rope_theta": 1000000,
36
+ "sliding_window": null,
37
+ "tie_word_embeddings": false,
38
+ "transformers_version": "4.57.3",
39
+ "use_cache": true,
40
+ "use_sliding_window": false,
41
+ "vocab_size": 151936
42
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c702878094f38ad5843e6ac40b327720b3147ffbf669a5d9ca1974865ca6c080
3
+ size 2097259104
modeling_dflash.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
21
+ def sample(logits: torch.Tensor, temperature: float = 0.0) -> torch.Tensor:
22
+ if temperature < 1e-5:
23
+ return torch.argmax(logits, dim=-1)
24
+ logits = logits / temperature
25
+ probs = torch.softmax(logits, dim=-1)
26
+ return torch.multinomial(probs, num_samples=1).squeeze(-1)
27
+
28
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
29
+ cos = cos.unsqueeze(unsqueeze_dim)
30
+ sin = sin.unsqueeze(unsqueeze_dim)
31
+ q_len = q.size(-2)
32
+ q_embed = (q * cos[..., -q_len:, :]) + (rotate_half(q) * sin[..., -q_len:, :])
33
+ k_embed = (k * cos) + (rotate_half(k) * sin)
34
+ return q_embed, k_embed
35
+
36
+ class Qwen3DFlashAttention(nn.Module):
37
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
38
+
39
+ def __init__(self, config: Qwen3Config, layer_idx: int):
40
+ super().__init__()
41
+ self.config = config
42
+ self.layer_idx = layer_idx
43
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
44
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
45
+ self.scaling = self.head_dim**-0.5
46
+ self.attention_dropout = config.attention_dropout
47
+ self.is_causal = False
48
+ self.q_proj = nn.Linear(
49
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
50
+ )
51
+ self.k_proj = nn.Linear(
52
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
53
+ )
54
+ self.v_proj = nn.Linear(
55
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
56
+ )
57
+ self.o_proj = nn.Linear(
58
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
59
+ )
60
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
61
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
62
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
63
+
64
+ def forward(
65
+ self,
66
+ hidden_states: torch.Tensor,
67
+ target_hidden: torch.Tensor,
68
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
69
+ attention_mask: Optional[torch.Tensor],
70
+ past_key_values: Optional[Cache] = None,
71
+ cache_position: Optional[torch.LongTensor] = None,
72
+ **kwargs: Unpack[FlashAttentionKwargs],
73
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
74
+ bsz, q_len = hidden_states.shape[:-1]
75
+ ctx_len = target_hidden.shape[1]
76
+ q = self.q_proj(hidden_states)
77
+ q = q.view(bsz, q_len, -1, self.head_dim)
78
+ q = self.q_norm(q).transpose(1, 2)
79
+ k_ctx = self.k_proj(target_hidden)
80
+ k_noise = self.k_proj(hidden_states)
81
+ v_ctx = self.v_proj(target_hidden)
82
+ v_noise = self.v_proj(hidden_states)
83
+ k = torch.cat([k_ctx, k_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
84
+ v = torch.cat([v_ctx, v_noise], dim=1).view(bsz, ctx_len + q_len, -1, self.head_dim)
85
+ k = self.k_norm(k).transpose(1, 2)
86
+ v = v.transpose(1, 2)
87
+ cos, sin = position_embeddings
88
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
89
+ if past_key_values is not None:
90
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
91
+ k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs)
92
+ attn_fn: Callable = eager_attention_forward
93
+ if self.config._attn_implementation != "eager":
94
+ attn_fn = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
95
+ attn_output, attn_weights = attn_fn(
96
+ self,
97
+ q,
98
+ k,
99
+ v,
100
+ attention_mask,
101
+ dropout=0.0 if not self.training else self.attention_dropout,
102
+ scaling=self.scaling,
103
+ sliding_window=self.sliding_window,
104
+ **kwargs,
105
+ )
106
+ attn_output = attn_output.reshape(bsz, q_len, -1)
107
+ attn_output = self.o_proj(attn_output)
108
+ return attn_output, attn_weights
109
+
110
+ class Qwen3DFlashDecoderLayer(GradientCheckpointingLayer):
111
+ def __init__(self, config: Qwen3Config, layer_idx: int):
112
+ super().__init__()
113
+ self.hidden_size = config.hidden_size
114
+ self.self_attn = Qwen3DFlashAttention(config=config, layer_idx=layer_idx)
115
+ self.mlp = Qwen3MLP(config)
116
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
117
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
118
+
119
+ def forward(
120
+ self,
121
+ target_hidden: Optional[torch.Tensor] = None,
122
+ hidden_states: Optional[torch.Tensor] = None,
123
+ attention_mask: Optional[torch.Tensor] = None,
124
+ position_ids: Optional[torch.LongTensor] = None,
125
+ past_key_value: Optional[Cache] = None,
126
+ output_attentions: Optional[bool] = False,
127
+ use_cache: Optional[bool] = False,
128
+ cache_position: Optional[torch.LongTensor] = None,
129
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
130
+ **kwargs: Unpack[FlashAttentionKwargs],
131
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
132
+ residual = hidden_states
133
+ hidden_states = self.input_layernorm(hidden_states)
134
+ hidden_states = self.self_attn(
135
+ hidden_states=hidden_states,
136
+ target_hidden=target_hidden,
137
+ attention_mask=attention_mask,
138
+ position_ids=position_ids,
139
+ past_key_values=past_key_value,
140
+ output_attentions=output_attentions,
141
+ use_cache=use_cache,
142
+ cache_position=cache_position,
143
+ position_embeddings=position_embeddings,
144
+ **kwargs,
145
+ )[0]
146
+ hidden_states = residual + hidden_states
147
+ residual = hidden_states
148
+ hidden_states = self.post_attention_layernorm(hidden_states)
149
+ hidden_states = self.mlp(hidden_states)
150
+ hidden_states = residual + hidden_states
151
+ return hidden_states
152
+
153
+ def build_target_layer_ids(num_target_layers: int, num_draft_layers: int):
154
+ if num_draft_layers == 1:
155
+ return [(num_target_layers // 2)]
156
+ start = 1
157
+ end = num_target_layers - 3
158
+ span = end - start
159
+ aux_ids = [
160
+ int(round(start + (i * span) / (num_draft_layers - 1)))
161
+ for i in range(num_draft_layers)
162
+ ]
163
+ return aux_ids
164
+
165
+ def extract_context_feature(
166
+ hidden_states: list[torch.Tensor],
167
+ layer_ids: Optional[list[int]],
168
+ ) -> torch.Tensor:
169
+ offset = 1
170
+ selected_states = []
171
+ for layer_id in layer_ids:
172
+ selected_states.append(hidden_states[layer_id + offset])
173
+ target_hidden = torch.cat(selected_states, dim=-1)
174
+ return target_hidden
175
+
176
+ class DFlashDraftModel(Qwen3PreTrainedModel):
177
+ config_class = Qwen3Config
178
+ def __init__(self, config) -> None:
179
+ super().__init__(config)
180
+ self.config = config
181
+ self.layers = nn.ModuleList(
182
+ [Qwen3DFlashDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
183
+ )
184
+ self.target_layer_ids = build_target_layer_ids(config.num_target_layers, config.num_hidden_layers)
185
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
186
+ self.rotary_emb = Qwen3RotaryEmbedding(config)
187
+ self.fc = nn.Linear(len(self.target_layer_ids) * config.hidden_size, config.hidden_size, bias=False)
188
+ self.hidden_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
189
+ self.block_size = config.block_size
190
+ self.post_init()
191
+
192
+ def forward(
193
+ self,
194
+ position_ids: torch.LongTensor,
195
+ attention_mask: Optional[torch.Tensor] = None,
196
+ noise_embedding: Optional[torch.Tensor] = None,
197
+ target_hidden: Optional[torch.Tensor] = None,
198
+ past_key_values: Optional[Cache] = None,
199
+ use_cache: bool = False,
200
+ **kwargs,
201
+ ) -> CausalLMOutputWithPast:
202
+ hidden_states = noise_embedding
203
+ target_hidden = self.hidden_norm(self.fc(target_hidden))
204
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
205
+ for layer in self.layers:
206
+ hidden_states = layer(
207
+ hidden_states=hidden_states,
208
+ target_hidden=target_hidden,
209
+ attention_mask=attention_mask,
210
+ position_ids=position_ids,
211
+ past_key_value=past_key_values,
212
+ use_cache=use_cache,
213
+ position_embeddings=position_embeddings,
214
+ **kwargs,
215
+ )
216
+ return self.norm(hidden_states)
217
+
218
+ @torch.inference_mode()
219
+ def spec_generate(
220
+ self,
221
+ target: nn.Module,
222
+ input_ids: torch.LongTensor,
223
+ mask_token_id: int,
224
+ max_new_tokens: int,
225
+ stop_token_ids: list[int],
226
+ temperature: float,
227
+ ):
228
+ self.eval()
229
+ num_input_tokens = input_ids.shape[1]
230
+ max_length = num_input_tokens + max_new_tokens
231
+
232
+ block_size = self.block_size
233
+ output_ids = torch.full(
234
+ (1, max_length + block_size),
235
+ mask_token_id,
236
+ dtype=torch.long,
237
+ device=target.device,
238
+ )
239
+ position_ids = torch.arange(output_ids.shape[1], device=target.device).unsqueeze(0)
240
+
241
+ past_key_values_target = DynamicCache()
242
+ past_key_values_draft = DynamicCache()
243
+
244
+ # Prefill stage
245
+ output = target(
246
+ input_ids,
247
+ position_ids=position_ids[:, :num_input_tokens],
248
+ past_key_values=past_key_values_target,
249
+ use_cache=True,
250
+ logits_to_keep=1,
251
+ output_hidden_states=True,
252
+ )
253
+
254
+ output_ids[:, :num_input_tokens] = input_ids
255
+ output_ids[:, num_input_tokens:num_input_tokens+1] = sample(output.logits, temperature)
256
+ target_hidden = extract_context_feature(output.hidden_states, self.target_layer_ids)
257
+
258
+ # Decode stage
259
+ acceptance_lengths = []
260
+ start = input_ids.shape[1]
261
+ while start < max_length:
262
+ block_output_ids = output_ids[:, start : start + block_size].clone()
263
+ block_position_ids = position_ids[:, start : start + block_size]
264
+ noise_embedding = target.model.embed_tokens(block_output_ids)
265
+ draft_logits = target.lm_head(self(
266
+ target_hidden=target_hidden,
267
+ noise_embedding=noise_embedding,
268
+ position_ids=position_ids[:, past_key_values_draft.get_seq_length(): start + block_size],
269
+ past_key_values=past_key_values_draft,
270
+ use_cache=True,
271
+ is_causal=False,
272
+ )[:, -block_size+1:, :])
273
+ past_key_values_draft.crop(start)
274
+ block_output_ids[:, 1:] = sample(draft_logits)
275
+
276
+ output = target(
277
+ block_output_ids,
278
+ position_ids=block_position_ids,
279
+ past_key_values=past_key_values_target,
280
+ use_cache=True,
281
+ output_hidden_states=True,
282
+ )
283
+
284
+ posterior = sample(output.logits, temperature)
285
+ acceptance_length = (block_output_ids[:, 1:] == posterior[:, :-1]).cumprod(dim=1).sum(dim=1)[0].item()
286
+ output_ids[:, start : start + acceptance_length + 1] = block_output_ids[:, : acceptance_length + 1]
287
+ output_ids[:, start + acceptance_length + 1] = posterior[:, acceptance_length]
288
+ start += acceptance_length + 1
289
+ past_key_values_target.crop(start)
290
+ target_hidden = extract_context_feature(output.hidden_states, self.target_layer_ids)[:, :acceptance_length + 1, :]
291
+ acceptance_lengths.append(acceptance_length+1)
292
+ if stop_token_ids is not None and any(
293
+ stop_token_id in output_ids[:, num_input_tokens:] for stop_token_id in stop_token_ids
294
+ ):
295
+ break
296
+ output_ids = output_ids[:, :max_length]
297
+ output_ids = output_ids[:, output_ids[0] != mask_token_id]
298
+ if stop_token_ids is not None:
299
+ stop_token_ids = torch.tensor(stop_token_ids, device=output_ids.device)
300
+ stop_token_indices = torch.isin(output_ids[0][num_input_tokens:], stop_token_ids).nonzero(as_tuple=True)[0]
301
+ if stop_token_indices.numel() > 0:
302
+ output_ids = output_ids[:, : num_input_tokens + stop_token_indices[0] + 1]
303
+
304
+ return output_ids