ynFeng commited on
Commit
9c0a4e6
·
verified ·
1 Parent(s): 8a90f14

ASD: Approximate Speculative Decoding custom generation method

Browse files
.gitignore ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.so
5
+ .Python
6
+ build/
7
+ develop-eggs/
8
+ dist/
9
+ downloads/
10
+ eggs/
11
+ .eggs/
12
+ lib/
13
+ lib64/
14
+ parts/
15
+ sdist/
16
+ var/
17
+ wheels/
18
+ *.egg-info/
19
+ .installed.cfg
20
+ *.egg
21
+ .pytest_cache/
22
+ .ipynb_checkpoints
23
+ *.log
24
+ *.pt
25
+ *.safetensors
26
+ checkpoints/
27
+ models/
README.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - custom_generate
4
+ library_name: transformers
5
+ ---
6
+
7
+ # ASD — Approximate Speculative Decoding
8
+
9
+ A training-free, verifier-side acceptance policy for **greedy assisted decoding** in Hugging Face Transformers.
10
+
11
+ Standard greedy speculative decoding discards the entire draft suffix at the first position where the draft token differs from the target argmax. ASD relaxes this strictly deterministic check with three explicit, bounded rules so that near-optimal draft tokens can still be accepted.
12
+
13
+ > Paper: [ASD: Approximate Speculative Decoding](https://arxiv.org/abs/2608.03447)
14
+ > Reference implementation: https://github.com/Kissmetothemoon/ASD
15
+
16
+ ## Usage
17
+
18
+ ```python
19
+ from transformers import AutoModelForCausalLM, AutoTokenizer
20
+
21
+ model_id = "Qwen/Qwen3-14B"
22
+ assistant_id = "your-draft-model"
23
+
24
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
25
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
26
+ assistant_model = AutoModelForCausalLM.from_pretrained(assistant_id, device_map="auto")
27
+
28
+ inputs = tokenizer("The quick brown", return_tensors="pt").to(model.device)
29
+
30
+ outputs = model.generate(
31
+ **inputs,
32
+ max_new_tokens=64,
33
+ assistant_model=assistant_model,
34
+ custom_generate="ynFeng/approximate-speculative-decoding",
35
+ trust_remote_code=True,
36
+ assistant_asd_budget=2.0,
37
+ assistant_asd_local_ratio=0.25,
38
+ assistant_asd_max_mismatches=2,
39
+ )
40
+ ```
41
+
42
+ ## Parameters
43
+
44
+ | Name | Type | Default | Description |
45
+ |------|------|---------|-------------|
46
+ | `assistant_asd_budget` | `float` | `None` | Request-level cumulative regret budget `B`. `None` = unlimited (only ratio / mismatch caps apply). `0.0` forces strict argmax verification. |
47
+ | `assistant_asd_local_ratio` | `float` | `None` | Max allowed `r_i / (K - i)` for a relaxed mismatch at draft position `i`, where `K` is the candidate length. `None` = unlimited. |
48
+ | `assistant_asd_max_mismatches` | `int` | `None` | Max number of relaxed mismatches accepted per block. `None` = unlimited. `0` forces strict verification. |
49
+
50
+ If any parameter is `0`, the policy **exactly reduces to strict greedy verification** — this is the built-in correctness baseline.
51
+
52
+ ## Rules
53
+
54
+ For each drafted token `x_i` with target logits `z_i`:
55
+
56
+ 1. `r_i = max_v z_i(v) - z_i(x_i)` (`r_i = 0` iff `x_i` is the target argmax).
57
+ 2. Accept the draft prefix while **all** hold:
58
+ - request-level cumulative regret `<= assistant_asd_budget`
59
+ - local regret `r_i / (K - i) <= assistant_asd_local_ratio`
60
+ - relaxed mismatches in the current block `<= assistant_asd_max_mismatches`
61
+ 3. On the first infeasible position, commit the target argmax as the bonus token.
62
+
63
+ ## Empirical results (paper)
64
+
65
+ Qwen3-14B + DSpark block-7 draft, 8×L20, greedy:
66
+
67
+ | Setting | Throughput | GSM8K |
68
+ |---------|-----------|-------|
69
+ | Strict verification | 66.21 tok/s | 79.682 % |
70
+ | ASD (`B=2.0625`) | 75.04 tok/s (+13.34 %) | 79.454 % (-0.227 pp) |
71
+ | ASD (`B=0`) | token-identical to strict on all 1319 requests | identical |
72
+
73
+ ## Requirements
74
+
75
+ ```text
76
+ transformers>=5.19.0,<5.20.0
77
+ torch>=2.0.0
78
+ ```
79
+
80
+ The acceptance loop mirrors `GenerationMixin._assisted_decoding` internals, so the
81
+ transformers minor version is pinned. Verified on `transformers==5.19.0`, `torch==2.6.0`.
82
+
83
+ ## Validation
84
+
85
+ Checked with Qwen2.5-1.5B-Instruct (target) + Qwen2.5-0.5B-Instruct (draft) on an
86
+ NVIDIA L20 (`scripts/example.py` reproduces):
87
+
88
+ - `assistant_asd_budget=0` and no-knob calls are **token-identical** to native
89
+ greedy assisted decoding on every tested prompt (also with `prompt_lookup_num_tokens`);
90
+ - relaxed runs are deterministic across repeated calls (no RNG anywhere in the policy);
91
+ - `do_sample=True`, combining with `assistant_ensemble_weight`, ASD knobs without a
92
+ draft source, and negative budgets all raise `ValueError`.
93
+
94
+ ASD also works with prompt-lookup drafting (`prompt_lookup_num_tokens`) — unlike
95
+ `assistant_ensemble_weight`, the regret rule needs target logits only.
96
+
97
+ ## License
98
+
99
+ Apache-2.0
custom_generate/generate.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Approximate Speculative Decoding (ASD) as a Transformers custom generation method.
2
+
3
+ ASD is a training-free, deterministic acceptance policy for *greedy* assisted
4
+ decoding. Instead of discarding the whole draft suffix at the first position
5
+ where the draft token differs from the target argmax, it accepts a draft prefix
6
+ while ALL of the following hold:
7
+
8
+ 1. request-level cumulative regret ``sum(r_j) <= assistant_asd_budget``;
9
+ 2. local regret ``r_i / (K - i) <= assistant_asd_local_ratio``
10
+ (suffix-value weighting: later draft positions get less slack);
11
+ 3. relaxed mismatches in the current block ``<= assistant_asd_max_mismatches``.
12
+
13
+ Here ``r_i = max_v z_i(v) - z_i(x_i)`` is the local regret of draft token
14
+ ``x_i`` under target logits ``z_i`` (``r_i = 0`` iff ``x_i`` is the target
15
+ argmax) and ``K`` is the candidate length. The policy uses *target logits only*
16
+ (no draft logits, no RNG) and exactly reduces to strict greedy verification
17
+ when the budget, the local ratio, or the mismatch cap is ``0``.
18
+
19
+ Paper: "ASD: Approximate Speculative Decoding", https://arxiv.org/abs/2608.03447
20
+
21
+ Implementation notes
22
+ --------------------
23
+ `generate` below mirrors the signature of `GenerationMixin.generate` (this is
24
+ the contract for Hub custom generation methods). It validates the ASD knobs and
25
+ then temporarily swaps `type(model)._assisted_decoding` for the ASD loop in
26
+ this file, so the standard `generate()` pipeline (logits processors, stopping
27
+ criteria, cache preparation, streamer, assistant handling, ...) runs unchanged.
28
+ The swap is reverted in a `finally` block.
29
+
30
+ `_asd_assisted_decoding` is a byte-faithful copy of
31
+ `transformers.generation.utils.GenerationMixin._assisted_decoding`
32
+ (transformers v5.19.0) with exactly three changes, marked `ASD-CHANGE`:
33
+ 1. request-level risk state is initialised before the decode loop;
34
+ 2. the strict greedy prefix match (upstream "Case 2") is replaced by the ASD
35
+ acceptance rule (the sampling path is rejected in `generate`, so upstream
36
+ "Case 1" is unreachable here);
37
+ 3. the risk account is charged after the EOS/length crop, only for draft
38
+ tokens that were actually committed.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import copy
44
+ import math
45
+ from typing import TYPE_CHECKING, Any, NamedTuple
46
+
47
+ import torch
48
+ from transformers import GenerationMixin
49
+ from transformers.cache_utils import StaticCache
50
+ from transformers.generation.candidate_generator import (
51
+ AssistedCandidateGenerator,
52
+ MTPCandidateGenerator,
53
+ _prepare_attention_mask,
54
+ _prepare_position_ids,
55
+ _prepare_token_type_ids,
56
+ )
57
+ from transformers.generation.utils import (
58
+ ALL_CACHE_NAMES,
59
+ GenerateDecoderOnlyOutput,
60
+ GenerateEncoderDecoderOutput,
61
+ _split_model_outputs,
62
+ )
63
+
64
+ if TYPE_CHECKING:
65
+ from transformers import (
66
+ GenerationConfig,
67
+ LogitsProcessorList,
68
+ PreTrainedModel,
69
+ PreTrainedTokenizerBase,
70
+ StoppingCriteriaList,
71
+ )
72
+ from transformers.generation import BaseStreamer
73
+ from transformers.generation.utils import GenerateNonBeamOutput
74
+
75
+
76
+ class _ASDVerification(NamedTuple):
77
+ """Resolved ASD acceptance parameters for one request."""
78
+
79
+ budget: float # request-level cumulative regret budget B (inf = uncapped)
80
+ local_ratio: float # per-token regret / suffix-value cap g (inf = uncapped)
81
+ max_mismatches: int # per-block relaxed mismatch cap m
82
+ strict_identity: bool # True => exactly upstream strict argmax verification
83
+
84
+
85
+ _ASD_CONFIG_ATTR = "_asd_verification"
86
+
87
+
88
+ def _resolve_asd_params(
89
+ budget: Any,
90
+ local_ratio: Any,
91
+ max_mismatches: Any,
92
+ ) -> _ASDVerification:
93
+ """Validate the user-facing knobs and return the resolved acceptance config.
94
+
95
+ All three knobs ``None`` means "ASD disabled": the policy is strict argmax
96
+ verification, i.e. token-identical to native assisted decoding. When any
97
+ knob is set, the unset ones default to their permissive limit. A value of
98
+ ``0`` for any knob forces strict verification (the paper's correctness
99
+ baseline).
100
+ """
101
+ all_none = budget is None and local_ratio is None and max_mismatches is None
102
+
103
+ if budget is not None:
104
+ budget = float(budget)
105
+ if not math.isfinite(budget) or budget < 0:
106
+ raise ValueError(f"`assistant_asd_budget` must be a finite float >= 0, got {budget}.")
107
+ else:
108
+ budget = math.inf
109
+
110
+ if local_ratio is not None:
111
+ local_ratio = float(local_ratio)
112
+ if not math.isfinite(local_ratio) or local_ratio < 0:
113
+ raise ValueError(
114
+ f"`assistant_asd_local_ratio` must be a finite float >= 0, got {local_ratio}."
115
+ )
116
+ else:
117
+ local_ratio = math.inf
118
+
119
+ if max_mismatches is not None:
120
+ max_mismatches = int(max_mismatches)
121
+ if max_mismatches < 0:
122
+ raise ValueError(f"`assistant_asd_max_mismatches` must be an int >= 0, got {max_mismatches}.")
123
+ else:
124
+ max_mismatches = 2**31 - 1
125
+
126
+ strict_identity = all_none or budget == 0.0 or local_ratio == 0.0 or max_mismatches == 0
127
+ return _ASDVerification(budget, local_ratio, max_mismatches, strict_identity)
128
+
129
+
130
+ def _effective_generation_value(name: str, kwargs: dict, generation_config, model):
131
+ """Resolve a generation flag the way `generate()` would: kwargs > config arg > model config."""
132
+ if name in kwargs:
133
+ return kwargs[name]
134
+ if generation_config is not None and getattr(generation_config, name, None) is not None:
135
+ return getattr(generation_config, name)
136
+ return getattr(model.generation_config, name, None)
137
+
138
+
139
+ def _choose_asd_prefix(
140
+ candidate_new_tokens: torch.LongTensor,
141
+ new_logits: torch.FloatTensor,
142
+ target_argmax: torch.LongTensor,
143
+ config: _ASDVerification,
144
+ ) -> tuple[int, list[float], list[bool]]:
145
+ """Return ``(accepted, regrets, mismatches)`` for one draft block.
146
+
147
+ ``candidate_new_tokens`` is ``(1, K)``, ``new_logits`` is ``(1, K, V)`` (the
148
+ processed target logits at each drafted position) and ``target_argmax`` is
149
+ ``(1, K)``: the target argmax token per position, computed with the exact
150
+ same ``argmax`` op upstream strict verification uses, so the strict path is
151
+ token-identical by construction. ``accepted`` is the longest prefix
152
+ satisfying all ASD constraints; ``regrets``/``mismatches`` are the
153
+ per-position values so the caller can charge the budget after the
154
+ EOS/length crop, only for tokens that were actually committed.
155
+ """
156
+ candidate_length = candidate_new_tokens.shape[1]
157
+ if candidate_length == 0:
158
+ return 0, [], []
159
+
160
+ # r_i = max_v z_i(v) - z_i(x_i); mismatch_i = (x_i != argmax_v z_i(v))
161
+ top_logits = new_logits[0].max(dim=-1).values
162
+ draft_logits = new_logits[0].gather(-1, candidate_new_tokens[0].unsqueeze(-1)).squeeze(-1)
163
+ regrets = (top_logits - draft_logits).clamp_min(0.0).tolist()
164
+ mismatches = (candidate_new_tokens[0] != target_argmax[0]).tolist()
165
+
166
+ # `config.budget` is the *remaining* request budget for this block: the caller
167
+ # (`_asd_assisted_decoding`) subtracts the running spend before calling.
168
+ remaining = max(0.0, config.budget)
169
+ cumulative_risk = 0.0
170
+ cumulative_relaxed = 0
171
+ accepted = 0
172
+ for index in range(candidate_length):
173
+ mismatch = mismatches[index]
174
+ regret = regrets[index]
175
+ value = float(candidate_length - index) # suffix-value weighting
176
+
177
+ if mismatch:
178
+ if config.strict_identity:
179
+ break
180
+ cumulative_risk += regret
181
+ cumulative_relaxed += 1
182
+
183
+ worthwhile = (not mismatch) or (regret / value <= config.local_ratio)
184
+ affordable = cumulative_risk <= remaining + 1e-9
185
+ within_cap = cumulative_relaxed <= config.max_mismatches
186
+
187
+ if not (worthwhile and affordable and within_cap):
188
+ break
189
+ accepted = index + 1
190
+
191
+ return accepted, regrets, mismatches
192
+
193
+
194
+ def _asd_assisted_decoding(
195
+ self: "PreTrainedModel",
196
+ input_ids: torch.LongTensor,
197
+ logits_processor: "LogitsProcessorList",
198
+ stopping_criteria: "StoppingCriteriaList",
199
+ generation_config: "GenerationConfig",
200
+ synced_gpus: bool = False,
201
+ streamer: "BaseStreamer | None" = None,
202
+ inputs_tensor: torch.FloatTensor | None = None,
203
+ assistant_model: "PreTrainedModel | None" = None,
204
+ assistant_tokenizer: "PreTrainedTokenizerBase | None" = None,
205
+ tokenizer: "PreTrainedTokenizerBase | None" = None,
206
+ **model_kwargs,
207
+ ) -> "GenerateNonBeamOutput | torch.LongTensor":
208
+ """Drop-in replacement for `GenerationMixin._assisted_decoding` (greedy only).
209
+
210
+ Identical to upstream except for the ASD changes marked `ASD-CHANGE`.
211
+ """
212
+ asd: _ASDVerification | None = getattr(self, _ASD_CONFIG_ATTR, None)
213
+ if asd is None: # defensive: behave exactly like upstream strict verification
214
+ asd = _ASDVerification(math.inf, math.inf, 2**31 - 1, True)
215
+
216
+ # The cache must be dynamic for assisted generation, and the check must happen AFTER preparing cache
217
+ if not model_kwargs["use_cache"]:
218
+ raise ValueError("assisted generate requires `use_cache=True`")
219
+ if (
220
+ generation_config.cache_implementation in ["static", "hybrid", "sliding_window"]
221
+ or type(model_kwargs.get("past_key_values")) is StaticCache
222
+ ):
223
+ raise ValueError("assisted generate is not supported with Static cache classes`")
224
+
225
+ # Same tensor the stopping criteria are built from
226
+ eos_token_id = getattr(generation_config, "_eos_token_tensor", None)
227
+
228
+ # Make sure we can record past on the cache
229
+ cache = model_kwargs.get("past_key_values")
230
+ if cache is None:
231
+ raise RuntimeError("assisted decoding requires a cache")
232
+ cache.activate_past_recording()
233
+
234
+ # Get the candidate generator, given the parameterization
235
+ candidate_generator = self._get_candidate_generator(
236
+ generation_config=generation_config,
237
+ input_ids=input_ids,
238
+ inputs_tensor=inputs_tensor,
239
+ assistant_model=assistant_model,
240
+ logits_processor=logits_processor,
241
+ target_tokenizer=tokenizer,
242
+ assistant_tokenizer=assistant_tokenizer,
243
+ model_kwargs=model_kwargs,
244
+ )
245
+ # init values
246
+ output_attentions = generation_config.output_attentions
247
+ output_hidden_states = generation_config.output_hidden_states
248
+ output_scores = generation_config.output_scores
249
+ output_logits = generation_config.output_logits
250
+ return_dict_in_generate = generation_config.return_dict_in_generate
251
+
252
+ # init attention / hidden states / scores tuples
253
+ scores = () if (return_dict_in_generate and output_scores) else None
254
+ raw_logits = () if (return_dict_in_generate and output_logits) else None
255
+ decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
256
+ cross_attentions = () if (return_dict_in_generate and output_attentions) else None
257
+ decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
258
+
259
+ # if model is an encoder-decoder, retrieve encoder attention weights and hidden states
260
+ if return_dict_in_generate and self.config.is_encoder_decoder:
261
+ encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
262
+ encoder_hidden_states = (
263
+ model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
264
+ )
265
+
266
+ # keep track of which sequences are already finished
267
+ batch_size, cur_len = input_ids.shape[:2]
268
+ if batch_size > 1:
269
+ raise ValueError("assisted generate is only supported for batch_size = 1")
270
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
271
+
272
+ this_peer_finished = False
273
+ is_first_iteration = True # to preserve the same API in the output as other generation methods
274
+ outputs = None
275
+ n_matches = 0
276
+ total_risk_spent = 0.0 # ASD-CHANGE (1): request-level cumulative regret account
277
+ while self._has_unfinished_sequences(this_peer_finished, synced_gpus, device=input_ids.device):
278
+ cur_len = input_ids.shape[1]
279
+
280
+ # 1. Fetch candidate sequences from a `CandidateGenerator` and move to the correct device
281
+ if candidate_generator.requires_model_outputs:
282
+ candidate_input_ids, candidate_logits = candidate_generator.get_candidates(
283
+ input_ids,
284
+ model_kwargs=model_kwargs,
285
+ model_outputs=outputs,
286
+ is_first_iteration=is_first_iteration,
287
+ n_last_matches=n_matches,
288
+ )
289
+ else:
290
+ candidate_input_ids, candidate_logits = candidate_generator.get_candidates(input_ids)
291
+ candidate_input_ids = candidate_input_ids.to(self.device)
292
+ if candidate_logits is not None:
293
+ candidate_logits = candidate_logits.to(self.device)
294
+
295
+ candidate_length = candidate_input_ids.shape[1] - input_ids.shape[1]
296
+
297
+ # 2. Use the original model to obtain the next token logits given the candidate sequence. We obtain
298
+ # `candidate_length + 1` relevant logits from this process: in the event that all candidates are correct,
299
+ # we use this forward pass to also pick the subsequent logits in the original model.
300
+
301
+ # 2.1. Prepare the model inputs
302
+ candidate_kwargs = copy.copy(model_kwargs)
303
+ candidate_kwargs = _prepare_attention_mask(
304
+ candidate_kwargs, candidate_input_ids.shape[1], self.config.is_encoder_decoder
305
+ )
306
+ candidate_kwargs = _prepare_token_type_ids(candidate_kwargs, candidate_input_ids.shape[1])
307
+ if (position_ids := candidate_kwargs.get("position_ids")) is not None and candidate_length > 0:
308
+ new_length = candidate_length + position_ids.shape[-1]
309
+ candidate_kwargs = _prepare_position_ids(candidate_kwargs, new_length, self.config.is_encoder_decoder)
310
+
311
+ next_sequence_length = candidate_length + 1 if not is_first_iteration else None
312
+ model_inputs = self.prepare_inputs_for_generation(
313
+ candidate_input_ids,
314
+ next_sequence_length=next_sequence_length,
315
+ is_first_iteration=is_first_iteration,
316
+ **candidate_kwargs,
317
+ )
318
+
319
+ if "logits_to_keep" in model_inputs:
320
+ model_inputs["logits_to_keep"] = candidate_length + 1
321
+
322
+ # We usually need to force returning hidden_states and some others if the candidate_generator requires the model's outputs
323
+ if candidate_generator.requires_model_outputs:
324
+ model_inputs |= candidate_generator.model_kwargs_overrides
325
+
326
+ # 2.2. Run a forward pass on the candidate sequence
327
+ outputs = self(**model_inputs)
328
+
329
+ # 2.3. Process the new logits
330
+ # .float() is needed to retain precision for later logits manipulations
331
+ new_logits = outputs.logits[:, -candidate_length - 1 :].to(
332
+ dtype=torch.float32, device=input_ids.device
333
+ ) # excludes the input prompt if present
334
+ next_token_logits = new_logits.clone()
335
+ if len(logits_processor) > 0:
336
+ for i in range(candidate_length + 1):
337
+ new_logits[:, i, :] = logits_processor(candidate_input_ids[:, : cur_len + i], new_logits[:, i, :])
338
+
339
+ # 3. Select the accepted tokens.
340
+ # ASD-CHANGE (2): the greedy verification below replaces upstream's strict argmax
341
+ # prefix match with the ASD acceptance rule. The sampling path ("Case 1") and the
342
+ # `assistant_ensemble_weight` variant are unreachable: `generate()` rejects
343
+ # `do_sample=True` and `assistant_ensemble_weight` before installing this method.
344
+ candidate_new_tokens = candidate_input_ids[:, cur_len:]
345
+ # Same op as upstream strict verification, so strict mode matches by construction.
346
+ target_argmax = new_logits.argmax(dim=-1) # (1, candidate_length + 1)
347
+ block_config = _ASDVerification(
348
+ budget=asd.budget - total_risk_spent, # remaining request budget for this block
349
+ local_ratio=asd.local_ratio,
350
+ max_mismatches=asd.max_mismatches,
351
+ strict_identity=asd.strict_identity,
352
+ )
353
+ accepted, regrets, mismatches = _choose_asd_prefix(
354
+ candidate_new_tokens, new_logits[:, :-1, :], target_argmax[:, :-1], block_config
355
+ )
356
+
357
+ # Commit the accepted draft prefix, then the target argmax at the first position
358
+ # after it as the bonus token (deterministic, exactly as upstream: upstream's
359
+ # `selected_tokens[:, :n_matches + 1]` is the argmax at position `n_matches`).
360
+ bonus_token = target_argmax[:, accepted : accepted + 1]
361
+ if accepted > 0:
362
+ valid_tokens = torch.cat([candidate_new_tokens[:, :accepted], bonus_token], dim=-1)
363
+ else:
364
+ valid_tokens = bonus_token
365
+ n_matches = accepted
366
+
367
+ # Whenever we are drafting several tokens at once with the candidate without capping its draft (e.g. MTP), we need to
368
+ # make sure that we did not just validate tokens outside the max length, or outside an eos token
369
+ # Note that we should technically crop based on other stopping criteria as well in all generality, not only EOS and Length
370
+ tokens_budget = generation_config.max_length - input_ids.shape[1]
371
+ # This is for the max length
372
+ if valid_tokens.shape[1] > tokens_budget:
373
+ valid_tokens = valid_tokens[:, :tokens_budget]
374
+ # This is for eos tokens
375
+ if eos_token_id is not None:
376
+ # We are restricted to batch_size == 1, so we can squeeze the batch dim to simplify
377
+ eos_positions = torch.isin(valid_tokens.squeeze(0), eos_token_id.to(valid_tokens.device)).nonzero()
378
+ if eos_positions.numel() > 0:
379
+ num_drafted = eos_positions[0].item() + 1
380
+ valid_tokens = valid_tokens[:, :num_drafted]
381
+ # Recompute how many matches we accepted if we just cropped above due to length/eos
382
+ n_matches = valid_tokens.shape[1] - 1
383
+
384
+ # ASD-CHANGE (3): charge the request-level regret account after the crop, only
385
+ # for relaxed (mismatched) draft tokens that were actually committed.
386
+ for index in range(max(0, min(n_matches, accepted))):
387
+ if mismatches[index]:
388
+ total_risk_spent += regrets[index]
389
+
390
+ # 4. Update variables according to the number of matching assistant tokens. Remember: the token generated
391
+ # by the model after the last candidate match is also valid, as it is generated from a correct sequence.
392
+ # Because of this last token, assisted generation search reduces to a normal greedy search/sample if there
393
+ # is no match.
394
+
395
+ # 4.1. Get the valid continuation, after the matching tokens
396
+ input_ids = torch.cat((input_ids, valid_tokens), dim=-1)
397
+ if streamer is not None:
398
+ streamer.put(valid_tokens.cpu())
399
+ new_cur_len = input_ids.shape[1]
400
+
401
+ # 4.2. Discard past key values relative to unused assistant tokens if any - if `number_of_tokens_to_crop == 0`, `crop` will
402
+ # still take care of shrinking back sliding window or linear attention cache layers back to their max size, so it's important
403
+ # to call it still
404
+ number_of_tokens_to_crop = candidate_length - n_matches
405
+ outputs.past_key_values.crop(-number_of_tokens_to_crop)
406
+
407
+ # 5. Update the candidate generation strategy if needed
408
+ candidate_generator.update_candidate_strategy(input_ids, new_logits, n_matches)
409
+
410
+ # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping
411
+ model_kwargs = self._update_model_kwargs_for_generation(
412
+ outputs,
413
+ model_kwargs,
414
+ is_encoder_decoder=self.config.is_encoder_decoder,
415
+ num_new_tokens=n_matches + 1,
416
+ )
417
+ if synced_gpus and this_peer_finished:
418
+ continue
419
+
420
+ # Store scores, attentions and hidden_states when required
421
+ # Assistant: modified to append one tuple element per token, as in the other generation methods.
422
+ if return_dict_in_generate:
423
+ newly_added_length = n_matches + 1
424
+ if output_scores:
425
+ scores += tuple(new_logits[:, i, :] for i in range(newly_added_length))
426
+ if output_logits:
427
+ raw_logits += tuple(next_token_logits[:, i, :] for i in range(newly_added_length))
428
+
429
+ newly_added_length = new_cur_len if is_first_iteration else newly_added_length
430
+ if output_attentions:
431
+ if self.config.is_encoder_decoder:
432
+ cross_attentions = _split_model_outputs(
433
+ cross_attentions, outputs.cross_attentions, cur_len, newly_added_length
434
+ )
435
+ decoder_attentions = _split_model_outputs(
436
+ decoder_attentions,
437
+ outputs.decoder_attentions,
438
+ cur_len,
439
+ newly_added_length,
440
+ is_decoder_attention=True,
441
+ )
442
+ # some (V)LLMs have hard requirement on SDPA and thus never return attn
443
+ elif outputs.attentions[0] is not None:
444
+ decoder_attentions = _split_model_outputs(
445
+ decoder_attentions,
446
+ outputs.attentions,
447
+ cur_len,
448
+ newly_added_length,
449
+ is_decoder_attention=True,
450
+ )
451
+ if output_hidden_states:
452
+ if self.config.is_encoder_decoder:
453
+ decoder_hidden_states = _split_model_outputs(
454
+ decoder_hidden_states, outputs.decoder_hidden_states, cur_len, newly_added_length
455
+ )
456
+ else:
457
+ decoder_hidden_states = _split_model_outputs(
458
+ decoder_hidden_states, outputs.hidden_states, cur_len, newly_added_length
459
+ )
460
+
461
+ unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids, scores)
462
+ this_peer_finished = unfinished_sequences.max() == 0
463
+ is_first_iteration = False
464
+
465
+ if streamer is not None:
466
+ streamer.end()
467
+
468
+ if (
469
+ isinstance(candidate_generator, AssistedCandidateGenerator)
470
+ and not isinstance(candidate_generator, MTPCandidateGenerator)
471
+ and candidate_generator.assistant_model.generation_config.num_assistant_tokens_schedule == "heuristic"
472
+ ):
473
+ candidate_generator.assistant_model.generation_config.num_assistant_tokens = (
474
+ candidate_generator.num_assistant_tokens
475
+ )
476
+ if return_dict_in_generate:
477
+ cache = None
478
+ if any(cache_key in model_kwargs for cache_key in ALL_CACHE_NAMES):
479
+ cache_key = next(cache_key for cache_key in ALL_CACHE_NAMES if cache_key in model_kwargs)
480
+ cache = model_kwargs[cache_key]
481
+ if self.config.is_encoder_decoder:
482
+ return GenerateEncoderDecoderOutput(
483
+ sequences=input_ids,
484
+ scores=scores,
485
+ logits=raw_logits,
486
+ encoder_attentions=encoder_attentions,
487
+ encoder_hidden_states=encoder_hidden_states,
488
+ decoder_attentions=decoder_attentions,
489
+ cross_attentions=cross_attentions,
490
+ decoder_hidden_states=decoder_hidden_states,
491
+ past_key_values=cache,
492
+ )
493
+ else:
494
+ return GenerateDecoderOnlyOutput(
495
+ sequences=input_ids,
496
+ scores=scores,
497
+ logits=raw_logits,
498
+ attentions=decoder_attentions,
499
+ hidden_states=decoder_hidden_states,
500
+ past_key_values=cache,
501
+ )
502
+ else:
503
+ return input_ids
504
+
505
+
506
+ def generate(
507
+ model: "PreTrainedModel",
508
+ inputs: torch.Tensor | None = None,
509
+ generation_config: "GenerationConfig | None" = None,
510
+ logits_processor: "LogitsProcessorList | None" = None,
511
+ stopping_criteria: "StoppingCriteriaList | None" = None,
512
+ prefix_allowed_tokens_fn=None,
513
+ synced_gpus: bool | None = None,
514
+ assistant_model: "PreTrainedModel | None" = None,
515
+ streamer: "BaseStreamer | None" = None,
516
+ negative_prompt_ids: torch.Tensor | None = None,
517
+ negative_prompt_attention_mask: torch.Tensor | None = None,
518
+ assistant_asd_budget: float | None = None,
519
+ assistant_asd_local_ratio: float | None = None,
520
+ assistant_asd_max_mismatches: int | None = None,
521
+ **kwargs,
522
+ ):
523
+ """Custom generation entry point loaded from the Hub.
524
+
525
+ Accepts every argument of `GenerationMixin.generate` plus the three ASD
526
+ knobs below, then runs the standard `generate()` pipeline with the ASD
527
+ assisted-decoding loop installed. With no ASD knob set (or any knob equal
528
+ to ``0``), the result is token-identical to native greedy assisted decoding.
529
+
530
+ Parameters
531
+ ----------
532
+ assistant_asd_budget:
533
+ Request-level cumulative regret budget ``B >= 0``. ``None`` (default)
534
+ leaves the budget uncapped; ``0.0`` forces strict verification.
535
+ assistant_asd_local_ratio:
536
+ Per-token cap ``g >= 0`` on ``r_i / (K - i)``. ``None`` leaves it
537
+ uncapped; ``0.0`` forces strict verification.
538
+ assistant_asd_max_mismatches:
539
+ Per-block cap ``m >= 0`` on relaxed mismatches. ``None`` leaves it
540
+ uncapped; ``0`` forces strict verification.
541
+ """
542
+ asd = _resolve_asd_params(assistant_asd_budget, assistant_asd_local_ratio, assistant_asd_max_mismatches)
543
+ any_asd_knob = any(
544
+ knob is not None
545
+ for knob in (assistant_asd_budget, assistant_asd_local_ratio, assistant_asd_max_mismatches)
546
+ )
547
+
548
+ if _effective_generation_value("do_sample", kwargs, generation_config, model) is True:
549
+ raise ValueError(
550
+ "ASD is a deterministic verifier for greedy decoding (`do_sample=False`). "
551
+ "For the sampling path, use native assisted decoding with `assistant_ensemble_weight` instead."
552
+ )
553
+ if _effective_generation_value("assistant_ensemble_weight", kwargs, generation_config, model) is not None:
554
+ raise ValueError(
555
+ "`assistant_ensemble_weight` and ASD are mutually exclusive verification relaxations. "
556
+ "Please use only one of them."
557
+ )
558
+ if (
559
+ any_asd_knob
560
+ and assistant_model is None
561
+ and _effective_generation_value("prompt_lookup_num_tokens", kwargs, generation_config, model) is None
562
+ ):
563
+ raise ValueError(
564
+ "ASD knobs require a draft source: pass `assistant_model` "
565
+ "(or set `prompt_lookup_num_tokens` for prompt-lookup drafting)."
566
+ )
567
+
568
+ # Install the ASD loop as the model class's assisted-decoding method for the
569
+ # duration of this call. `generate()` dispatches assisted generation through
570
+ # `getattr(type(self), "_assisted_decoding")`, so a class-level swap is the
571
+ # supported seam; it is reverted in `finally` below.
572
+ cls = type(model)
573
+ was_inherited = "_assisted_decoding" not in cls.__dict__
574
+ original = cls._assisted_decoding
575
+ cls._assisted_decoding = _asd_assisted_decoding
576
+ setattr(model, _ASD_CONFIG_ATTR, asd)
577
+ try:
578
+ return GenerationMixin.generate(
579
+ model,
580
+ inputs=inputs,
581
+ generation_config=generation_config,
582
+ logits_processor=logits_processor,
583
+ stopping_criteria=stopping_criteria,
584
+ prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
585
+ synced_gpus=synced_gpus,
586
+ assistant_model=assistant_model,
587
+ streamer=streamer,
588
+ negative_prompt_ids=negative_prompt_ids,
589
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
590
+ **kwargs,
591
+ )
592
+ finally:
593
+ if was_inherited:
594
+ del cls._assisted_decoding
595
+ else:
596
+ cls._assisted_decoding = original
597
+ try:
598
+ delattr(model, _ASD_CONFIG_ATTR)
599
+ except AttributeError:
600
+ pass
custom_generate/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # The acceptance loop mirrors `GenerationMixin._assisted_decoding` internals,
2
+ # so the minor version is pinned. Verified on transformers 5.19.0.
3
+ transformers>=5.19.0,<5.20.0
4
+ torch>=2.0.0
scripts/example.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sanity-check script for the ASD custom generation method.
2
+
3
+ Run from anywhere:
4
+ python scripts/example.py \
5
+ --model Qwen/Qwen2.5-1.5B-Instruct \
6
+ --assistant-model Qwen/Qwen2.5-0.5B-Instruct \
7
+ --budget 2.0 --local-ratio 0.25 --max-mismatches 2
8
+
9
+ Checks:
10
+ 1. ASD runs and produces text.
11
+ 2. `assistant_asd_budget=0` is token-identical to native strict assisted decoding
12
+ (the gold-standard correctness check).
13
+ 3. No ASD knob set is also token-identical to native (lossless default).
14
+ """
15
+
16
+ import argparse
17
+ import os
18
+
19
+ import torch
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+
22
+ REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
+
24
+
25
+ def main():
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--model", required=True)
28
+ parser.add_argument("--assistant-model", required=True)
29
+ parser.add_argument("--budget", type=float, default=2.0)
30
+ parser.add_argument("--local-ratio", type=float, default=0.25)
31
+ parser.add_argument("--max-mismatches", type=int, default=2)
32
+ parser.add_argument("--max-new-tokens", type=int, default=64)
33
+ parser.add_argument("--prompt", default="Give me a short introduction to large language models.")
34
+ parser.add_argument("--repo-path", default=REPO_ROOT,
35
+ help="Directory containing custom_generate/ (default: repo root)")
36
+ args = parser.parse_args()
37
+
38
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
39
+ model = AutoModelForCausalLM.from_pretrained(args.model, dtype="auto", device_map="auto")
40
+ assistant_model = AutoModelForCausalLM.from_pretrained(
41
+ args.assistant_model, dtype="auto", device_map="auto"
42
+ )
43
+
44
+ inputs = tokenizer(args.prompt, return_tensors="pt").to(model.device)
45
+ gen_kwargs = dict(max_new_tokens=args.max_new_tokens, do_sample=False)
46
+
47
+ # 1. Native strict assisted decoding baseline.
48
+ strict_out = model.generate(**inputs, assistant_model=assistant_model, **gen_kwargs)
49
+ print("Strict :", tokenizer.decode(strict_out[0], skip_special_tokens=True))
50
+
51
+ # 2. ASD relaxed.
52
+ asd_out = model.generate(
53
+ **inputs,
54
+ assistant_model=assistant_model,
55
+ custom_generate=args.repo_path,
56
+ trust_remote_code=True,
57
+ assistant_asd_budget=args.budget,
58
+ assistant_asd_local_ratio=args.local_ratio,
59
+ assistant_asd_max_mismatches=args.max_mismatches,
60
+ **gen_kwargs,
61
+ )
62
+ print("ASD :", tokenizer.decode(asd_out[0], skip_special_tokens=True))
63
+
64
+ # 3. Gold check: budget=0 must be token-identical to native strict decoding.
65
+ asd_b0_out = model.generate(
66
+ **inputs,
67
+ assistant_model=assistant_model,
68
+ custom_generate=args.repo_path,
69
+ trust_remote_code=True,
70
+ assistant_asd_budget=0.0,
71
+ **gen_kwargs,
72
+ )
73
+ assert torch.equal(strict_out, asd_b0_out), "ASD(budget=0) differs from strict decoding!"
74
+ print("OK: assistant_asd_budget=0 is token-identical to strict verification.")
75
+
76
+ # 4. Lossless default: no ASD knobs must also be token-identical.
77
+ asd_default_out = model.generate(
78
+ **inputs,
79
+ assistant_model=assistant_model,
80
+ custom_generate=args.repo_path,
81
+ trust_remote_code=True,
82
+ **gen_kwargs,
83
+ )
84
+ assert torch.equal(strict_out, asd_default_out), "ASD (no knobs) differs from strict decoding!"
85
+ print("OK: no ASD knobs is token-identical to strict verification.")
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
scripts/validate.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comprehensive GPU validation for the ASD custom generation method.
2
+
3
+ Covers:
4
+ 1. Native strict baseline vs ASD(B=0) -> must be token-identical (gold check)
5
+ 2. Native strict vs custom (no knobs) -> must be token-identical (lossless default)
6
+ 3. ASD(B=2.0) relaxed -> runs, deterministic, >= strict acceptance
7
+ 4. Determinism -> two identical relaxed runs, token-identical
8
+ 5. Error handling -> do_sample / ensemble_weight / no draft source
9
+ 6. Throughput + acceptance comparison -> strict vs relaxed
10
+ """
11
+
12
+ import os
13
+ import sys
14
+ import time
15
+
16
+ import torch
17
+ from transformers import AutoModelForCausalLM, AutoTokenizer
18
+
19
+ REPO = os.environ.get("ASD_REPO", os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
20
+ TARGET = os.environ.get("ASD_TARGET", "Qwen/Qwen2.5-1.5B-Instruct")
21
+ DRAFT = os.environ.get("ASD_DRAFT", "Qwen/Qwen2.5-0.5B-Instruct")
22
+ MAX_NEW = 128
23
+ PROMPTS = [
24
+ "Give me a short introduction to large language models.",
25
+ "What is the capital of France? Answer in one sentence.",
26
+ "Write a Python function that computes the nth Fibonacci number.",
27
+ "Explain the difference between TCP and UDP briefly.",
28
+ "List three prime numbers greater than 10 and justify one of them.",
29
+ ]
30
+
31
+ failures = []
32
+
33
+
34
+ def check(name, cond, detail=""):
35
+ status = "PASS" if cond else "FAIL"
36
+ print(f"[{status}] {name}" + (f" -- {detail}" if detail else ""))
37
+ if not cond:
38
+ failures.append(name)
39
+
40
+
41
+ def count_fwd(tok, out, prompt_len):
42
+ return out.shape[1] - prompt_len
43
+
44
+
45
+ def main():
46
+ tokenizer = AutoTokenizer.from_pretrained(TARGET)
47
+ model = AutoModelForCausalLM.from_pretrained(TARGET, dtype="auto", device_map="auto")
48
+ assistant = AutoModelForCausalLM.from_pretrained(DRAFT, dtype="auto", device_map="auto")
49
+ model.eval()
50
+ assistant.eval()
51
+
52
+ def run(prompt, **extra):
53
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
54
+ t0 = time.perf_counter()
55
+ out = model.generate(
56
+ **inputs, max_new_tokens=MAX_NEW, do_sample=False, **extra
57
+ )
58
+ dt = time.perf_counter() - t0
59
+ n = out.shape[1] - inputs["input_ids"].shape[1]
60
+ return out, n / dt
61
+
62
+ # ---------- 1&2. gold checks ----------
63
+ for prompt in PROMPTS:
64
+ strict, _ = run(prompt, assistant_model=assistant)
65
+ b0, _ = run(
66
+ prompt,
67
+ assistant_model=assistant,
68
+ custom_generate=REPO,
69
+ trust_remote_code=True,
70
+ assistant_asd_budget=0.0,
71
+ )
72
+ noknobs, _ = run(
73
+ prompt,
74
+ assistant_model=assistant,
75
+ custom_generate=REPO,
76
+ trust_remote_code=True,
77
+ )
78
+ check(f"gold B=0 identical ({prompt[:25]!r})", torch.equal(strict, b0))
79
+ check(f"gold no-knobs identical ({prompt[:25]!r})", torch.equal(strict, noknobs))
80
+
81
+ # ---------- 3&4. relaxed run + determinism ----------
82
+ for prompt in PROMPTS:
83
+ relaxed1, tps1 = run(
84
+ prompt,
85
+ assistant_model=assistant,
86
+ custom_generate=REPO,
87
+ trust_remote_code=True,
88
+ assistant_asd_budget=2.0,
89
+ assistant_asd_local_ratio=0.25,
90
+ assistant_asd_max_mismatches=2,
91
+ )
92
+ relaxed2, _ = run(
93
+ prompt,
94
+ assistant_model=assistant,
95
+ custom_generate=REPO,
96
+ trust_remote_code=True,
97
+ assistant_asd_budget=2.0,
98
+ assistant_asd_local_ratio=0.25,
99
+ assistant_asd_max_mismatches=2,
100
+ )
101
+ check(f"determinism ({prompt[:25]!r})", torch.equal(relaxed1, relaxed2))
102
+ check(f"relaxed non-empty ({prompt[:25]!r})", relaxed1.shape[1] > 0)
103
+
104
+ # ---------- 5. error handling ----------
105
+ inputs = tokenizer(PROMPTS[0], return_tensors="pt").to(model.device)
106
+
107
+ def expect_raise(name, **kw):
108
+ try:
109
+ model.generate(**inputs, max_new_tokens=8, **kw)
110
+ except ValueError:
111
+ check(f"raises {name}", True)
112
+ except Exception as e: # noqa: BLE001
113
+ check(f"raises {name}", False, f"wrong exception: {type(e).__name__}: {e}")
114
+ else:
115
+ check(f"raises {name}", False, "no exception")
116
+
117
+ expect_raise(
118
+ "do_sample=True",
119
+ assistant_model=assistant,
120
+ custom_generate=REPO,
121
+ trust_remote_code=True,
122
+ do_sample=True,
123
+ assistant_asd_budget=2.0,
124
+ )
125
+ expect_raise(
126
+ "ensemble_weight conflict",
127
+ assistant_model=assistant,
128
+ custom_generate=REPO,
129
+ trust_remote_code=True,
130
+ assistant_ensemble_weight=0.5,
131
+ assistant_asd_budget=2.0,
132
+ )
133
+ expect_raise(
134
+ "knobs without draft source",
135
+ custom_generate=REPO,
136
+ trust_remote_code=True,
137
+ assistant_asd_budget=2.0,
138
+ )
139
+ expect_raise(
140
+ "negative budget",
141
+ assistant_model=assistant,
142
+ custom_generate=REPO,
143
+ trust_remote_code=True,
144
+ assistant_asd_budget=-1.0,
145
+ )
146
+
147
+ # ---------- 6. throughput + acceptance ----------
148
+ print("\n=== throughput comparison ===")
149
+ tot_strict_tps = tot_relaxed_tps = 0.0
150
+ for prompt in PROMPTS:
151
+ strict, s_tps = run(prompt, assistant_model=assistant)
152
+ relaxed, r_tps = run(
153
+ prompt,
154
+ assistant_model=assistant,
155
+ custom_generate=REPO,
156
+ trust_remote_code=True,
157
+ assistant_asd_budget=2.0,
158
+ assistant_asd_local_ratio=0.25,
159
+ assistant_asd_max_mismatches=2,
160
+ )
161
+ tot_strict_tps += s_tps
162
+ tot_relaxed_tps += r_tps
163
+ overlap = sum(
164
+ 1 for a, b in zip(strict[0].tolist(), relaxed[0].tolist()) if a == b
165
+ ) / max(len(strict[0]), len(relaxed[0]))
166
+ print(
167
+ f" strict {s_tps:6.2f} tok/s | relaxed {r_tps:6.2f} tok/s "
168
+ f"({(r_tps / s_tps - 1) * 100:+5.1f}%) | prefix overlap {overlap:.2%}"
169
+ )
170
+ print(
171
+ f" MEAN strict {tot_strict_tps / len(PROMPTS):.2f} tok/s | "
172
+ f"relaxed {tot_relaxed_tps / len(PROMPTS):.2f} tok/s"
173
+ )
174
+
175
+ print("\n" + ("ALL PASS" if not failures else f"FAILURES: {failures}"))
176
+ sys.exit(1 if failures else 0)
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()