quantuminfer 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -1
- package/bin/quantuminfer.js +3 -3
- package/package.json +4 -3
- package/results/OVERNIGHT.md +37 -0
- package/vllm_plugin/build/lib/quantum_infer_vllm/__init__.py +6 -0
- package/vllm_plugin/build/lib/quantum_infer_vllm/spec.py +321 -0
- package/vllm_plugin/dist/quantum_infer_vllm-0.3.0-py3-none-any.whl +0 -0
- package/vllm_plugin/pyproject.toml +17 -0
- package/vllm_plugin/quantum_infer_vllm/__init__.py +6 -0
- package/vllm_plugin/quantum_infer_vllm/__pycache__/spec.cpython-310.pyc +0 -0
- package/vllm_plugin/quantum_infer_vllm/spec.py +321 -0
- package/vllm_plugin/quantum_infer_vllm.egg-info/PKG-INFO +6 -0
- package/vllm_plugin/quantum_infer_vllm.egg-info/SOURCES.txt +9 -0
- package/vllm_plugin/quantum_infer_vllm.egg-info/dependency_links.txt +1 -0
- package/vllm_plugin/quantum_infer_vllm.egg-info/entry_points.txt +2 -0
- package/vllm_plugin/quantum_infer_vllm.egg-info/requires.txt +1 -0
- package/vllm_plugin/quantum_infer_vllm.egg-info/top_level.txt +1 -0
package/README.md
CHANGED
|
@@ -38,6 +38,23 @@ npx quantuminfer install
|
|
|
38
38
|
cd quantumInfer/p27
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
## Production vLLM plugin (active frontier)
|
|
42
|
+
|
|
43
|
+
`vllm_plugin/` packages the quantumInfer hybrid proposer as a standard vLLM general plugin. It combines MTP, whole-history suffix memory, and Jacobi fixed-point reuse inside vLLM's production runtime (continuous batching, optimized FP8 MoE/MLA kernels, CUDA graphs, OpenAI-compatible serving). The target-side verifier remains exact speculative verification within vLLM's numerical configuration.
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install vllm==0.34.0
|
|
47
|
+
pip install "git+https://github.com/Knihalani/quantumInfer.git#subdirectory=vllm_plugin"
|
|
48
|
+
|
|
49
|
+
# Offline or serve use: method "quantum" is registered by the installed entry point.
|
|
50
|
+
vllm serve zai-org/GLM-5.3 \
|
|
51
|
+
--tensor-parallel-size 8 \
|
|
52
|
+
--kv-cache-dtype fp8 \
|
|
53
|
+
--speculative-config '{"method":"quantum","num_speculative_tokens":12,"enable_adaptive_verification":true,"speculator_options":{"mtp_len":2,"jacobi":1,"suffix":1,"mix":"tail"}}'
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Useful proposer knobs, accepted either as `speculator_options` keys or environment variables: `mtp_len`/`QUANTUM_MTP_LEN` (default 5), `jacobi`/`QUANTUM_JACOBI`, `suffix`/`QUANTUM_SUFFIX`, `measurements`/`QUANTUM_MEAS`, `amplitude`/`QUANTUM_AMPLITUDE` (logit-margin-aware Jacobi confidence), and `mix`/`QUANTUM_MIX` (`tail`, `confidence`, or `stitch`).
|
|
57
|
+
|
|
41
58
|
## Run on Modal
|
|
42
59
|
|
|
43
60
|
Store the Hugging Face cache in a Modal volume named `qllm-big-vol` mounted at `/vol`, with GLM-5.3 present under HF's standard cache layout. Then:
|
|
@@ -94,4 +111,4 @@ Speculative proposals only decide which tokens are tested. Every emitted token i
|
|
|
94
111
|
|
|
95
112
|
## Status
|
|
96
113
|
|
|
97
|
-
|
|
114
|
+
The standalone research engine is not yet a serving replacement for vLLM or SGLang. The active production path is the vLLM plugin above, which inherits vLLM serving, batching, kernel, and deployment infrastructure while adding quantumInfer proposers. The standalone engine remains the exactness/reference and kernel research implementation.
|
package/bin/quantuminfer.js
CHANGED
|
@@ -12,7 +12,7 @@ function sh(cmd, args, opts = {}) {
|
|
|
12
12
|
return r.status === 0;
|
|
13
13
|
}
|
|
14
14
|
function usage() {
|
|
15
|
-
console.log(`quantuminfer — bootstrap
|
|
15
|
+
console.log(`quantuminfer — bootstrap quantumInfer research engine and production vLLM plugin
|
|
16
16
|
|
|
17
17
|
Usage:
|
|
18
18
|
quantuminfer install [dir] copy the engine source tree (default: ./quantumInfer)
|
|
@@ -34,12 +34,12 @@ else if (cmd === 'quickstart') {
|
|
|
34
34
|
process.exit(1);
|
|
35
35
|
}
|
|
36
36
|
mkdirSync(dest, { recursive: true });
|
|
37
|
-
for (const x of ['engine', 'p27', 'c27', 'data', 'results', 'README.md', 'LICENSE']) {
|
|
37
|
+
for (const x of ['engine', 'p27', 'c27', 'data', 'results', 'vllm_plugin', 'README.md', 'LICENSE']) {
|
|
38
38
|
cpSync(join(root, x), join(dest, x), { recursive: true });
|
|
39
39
|
}
|
|
40
40
|
console.log(`Installed quantumInfer source to ${dest}`);
|
|
41
41
|
console.log('Next: python3 -m pip install modal torch --user && modal setup');
|
|
42
|
-
console.log(`Then: cd ${dest}/p27 && modal run modal_p27.py --job t_align --gpus dev`);
|
|
42
|
+
console.log(`Then: cd ${dest}/p27 && modal run modal_p27.py --job t_align --gpus dev\nProduction vLLM path: python3 -m pip install vllm==0.34.0 ${dest}/vllm_plugin`);
|
|
43
43
|
} else if (cmd === 'doctor') {
|
|
44
44
|
let ok = true;
|
|
45
45
|
for (const x of ['python3', 'modal', 'git']) ok = sh(x, ['--version'], { stdio: 'pipe' }) && ok;
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "quantuminfer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Installer and CLI bootstrap for quantumInfer
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Installer and CLI bootstrap for quantumInfer: quantum-inspired speculative inference plus a production vLLM plugin",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"quantuminfer": "./bin/quantuminfer.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"bin",
|
|
11
|
+
"vllm_plugin",
|
|
11
12
|
"engine",
|
|
12
13
|
"p27",
|
|
13
14
|
"c27",
|
|
@@ -33,4 +34,4 @@
|
|
|
33
34
|
"engines": {
|
|
34
35
|
"node": ">=18"
|
|
35
36
|
}
|
|
36
|
-
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# quantumInfer overnight production benchmark program
|
|
2
|
+
|
|
3
|
+
Status: in progress toward the 09:00 UTC deadline. This file is updated as validated results land.
|
|
4
|
+
|
|
5
|
+
## Reproduced fixed controls, GLM-5.3 on 8xB300, vLLM 0.34 runtime
|
|
6
|
+
|
|
7
|
+
| configuration | code tok/s | chat tok/s | code tokens/pass | chat tokens/pass | mean iteration time |
|
|
8
|
+
|---|---:|---:|---:|---:|---:|
|
|
9
|
+
| vLLM MTP5, fixed verification | 524.9 | 343.5 | 5.10 | 3.47 | 9.7-10.1 ms |
|
|
10
|
+
| vLLM MTP8, fixed verification | 504.3 | 345.4 | 6.17 | 4.10 | 11.9-12.2 ms |
|
|
11
|
+
|
|
12
|
+
Measurement method: cache reset before every run, greedy single-user decode, `(n-1)/(t(256 new)-t(1 new))`, first repetition discarded. MTP acceptance is already strong; making the chain longer without cost-aware verification is not a free win.
|
|
13
|
+
|
|
14
|
+
External production context: [InferenceX GLM-5.3 on B200](https://inferencex.semianalysis.com/run/glm-5-3-on-b200) reports high-concurrency serving frontiers rather than this single-user decode metric; SGLang FP8 sustains 13,575 tokens/s/GPU at 50 tokens/s/user, while Dynamo/SGLang FP4 leads several higher-interactivity points. quantumInfer's production program therefore tracks single-user speed, continuous batching, shared-prefix, long-context, TTFT/cold start, memory, and FP4/FP8 runtime variants separately.
|
|
15
|
+
|
|
16
|
+
## Active innovations under test
|
|
17
|
+
|
|
18
|
+
- Measurement-memory Jacobi fixed-point decoding: reuse target measurements already computed at speculative positions as the next fixed-point iterate.
|
|
19
|
+
- Online Jacobi bandit: per-position posterior acceptance confidence, updated only from causally observed positions.
|
|
20
|
+
- Empirical-Bayes suffix priors: exact match length gives a prior before online acceptance counts escape the cold-start trap.
|
|
21
|
+
- Coherent suffix overlap stitching: suffix memory may take over only at the first disagreement, so the stitch never splices tokens conditioned on two different futures.
|
|
22
|
+
- Amplitude-aware Jacobi confidence: target-logit margin modulates trust in fixed-point measurements.
|
|
23
|
+
- Production vLLM entry-point plugin with structured `speculator_options` and exact verifier semantics.
|
|
24
|
+
|
|
25
|
+
## First focused production results, 8xB300 GLM-5.3
|
|
26
|
+
|
|
27
|
+
| configuration | code tok/s | chat tok/s | code tokens/pass | chat tokens/pass |
|
|
28
|
+
|---|---:|---:|---:|---:|
|
|
29
|
+
| DSpark8 fixed | 499.9 | 374.8 | 5.35 | 3.86 |
|
|
30
|
+
| suffix8 adaptive | 376.2 | 318.3 | 3.19 | 2.83 |
|
|
31
|
+
| MTP5 adaptive | 486.5 | 318.6 | 5.08 | 3.47 |
|
|
32
|
+
| MTP8 adaptive | 563.2 | 307.0 | 6.40 | 3.67 |
|
|
33
|
+
| quantum2 K12 tail-memory | 448.7 | 379.8 | 6.00 | 4.98 |
|
|
34
|
+
| quantum2 confidence-switch | 226.2 | 195.6 | 2.92 | 2.53 |
|
|
35
|
+
| quantum2 unconditional stitch | 412.8 | 310.8 | 5.54 | 4.06 |
|
|
36
|
+
|
|
37
|
+
Key finding: quantum measurement memory is the first configuration tested that materially improves natural-chat acceptance, reaching 4.98 verified tokens/pass. Its current weakness is cost calibration, not acceptance quality. Per-position measurements show strong gains at positions 2-6 but positions 7-11 of a K12 chain are almost dead because a long accepted jump shifts them beyond the retrospective measurement horizon. The next optimization is truthful chain trimming/prior calibration rather than more blind depth.
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""quantumInfer hybrid speculative proposer plugin for vLLM.
|
|
2
|
+
|
|
3
|
+
Composes target-dependent MTP chain proposals with free retrospective fixed-point
|
|
4
|
+
(Jacobi) reuse and whole-history suffix proposals inside vLLM's exact verifier.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from vllm.v1.worker.gpu.spec_decode.mtp.config import MTPSpeculatorConfig
|
|
10
|
+
from vllm.v1.worker.gpu.spec_decode.mtp.speculator import MTPSpeculator
|
|
11
|
+
from vllm.v1.worker.gpu.spec_decode.speculator_config import register_speculative_method
|
|
12
|
+
from vllm.v1.worker.gpu.spec_decode.suffix.speculator import SuffixSpeculator
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_MEASUREMENTS = None
|
|
16
|
+
_MEASUREMENT_MARGINS = None
|
|
17
|
+
_ORIGINAL_REJECTION_SAMPLE = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _measurement_capture_patch():
|
|
21
|
+
"""Capture target-model measurements at every verified draft position."""
|
|
22
|
+
global _ORIGINAL_REJECTION_SAMPLE
|
|
23
|
+
if _ORIGINAL_REJECTION_SAMPLE is not None:
|
|
24
|
+
return
|
|
25
|
+
import vllm.v1.worker.gpu.spec_decode.rejection_sampler as rs
|
|
26
|
+
_ORIGINAL_REJECTION_SAMPLE = rs.rejection_sample
|
|
27
|
+
|
|
28
|
+
def capture_rejection_sample(target_logits, *args, **kwargs):
|
|
29
|
+
if _MEASUREMENTS is not None:
|
|
30
|
+
try:
|
|
31
|
+
expanded_idx_mapping = args[5] if len(args) > 5 else kwargs["expanded_idx_mapping"]
|
|
32
|
+
expanded_local_pos = args[6] if len(args) > 6 else kwargs["expanded_local_pos"]
|
|
33
|
+
num_steps = args[9] if len(args) > 9 else kwargs["num_speculative_steps"]
|
|
34
|
+
vals = target_logits.argmax(dim=-1)
|
|
35
|
+
flat = (expanded_idx_mapping.long() * (num_steps + 1)
|
|
36
|
+
+ expanded_local_pos.long())
|
|
37
|
+
_MEASUREMENTS.view(-1).index_copy_(0, flat, vals)
|
|
38
|
+
if _MEASUREMENT_MARGINS is not None:
|
|
39
|
+
top2 = torch.topk(target_logits, 2, dim=-1).values
|
|
40
|
+
margins = (top2[..., 0] - top2[..., 1]).clamp(0.0, 50.0)
|
|
41
|
+
_MEASUREMENT_MARGINS.view(-1).index_copy_(0, flat, margins)
|
|
42
|
+
except Exception:
|
|
43
|
+
pass
|
|
44
|
+
return _ORIGINAL_REJECTION_SAMPLE(target_logits, *args, **kwargs)
|
|
45
|
+
|
|
46
|
+
rs.rejection_sample = capture_rejection_sample
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class QuantumSpeculatorConfig(MTPSpeculatorConfig):
|
|
50
|
+
base_method = "quantum"
|
|
51
|
+
supported_options = MTPSpeculatorConfig.supported_options | {"speculator_options"}
|
|
52
|
+
speculator_class = "quantum_infer_vllm.spec.QuantumSpeculator"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class QuantumSpeculator(MTPSpeculator):
|
|
56
|
+
def __init__(self, vllm_config, device, req_states=None):
|
|
57
|
+
super().__init__(vllm_config, device)
|
|
58
|
+
assert req_states is not None
|
|
59
|
+
self.req_states = req_states
|
|
60
|
+
spec_opts = getattr(vllm_config.speculative_config, "speculator_options", None) or {}
|
|
61
|
+
|
|
62
|
+
def opt(name, env_name, default, cast):
|
|
63
|
+
return cast(spec_opts.get(name, os.environ.get(env_name, str(default))))
|
|
64
|
+
|
|
65
|
+
self.mtp_len = opt("mtp_len", "QUANTUM_MTP_LEN", 5, int)
|
|
66
|
+
self.use_suffix = opt("suffix", "QUANTUM_SUFFIX", 1, int) != 0
|
|
67
|
+
self.suffix_max_batch = opt("suffix_max_batch", "QUANTUM_SUFFIX_MAX_BATCH", 32, int)
|
|
68
|
+
self.mix_mode = str(spec_opts.get("mix", os.environ.get("QUANTUM_MIX", "tail")))
|
|
69
|
+
self.mix_margin = opt("mix_margin", "QUANTUM_MIX_MARGIN", 0.10, float)
|
|
70
|
+
self.stitch_min_overlap = opt("stitch_min_overlap", "QUANTUM_STITCH_MIN_OVERLAP", 2, int)
|
|
71
|
+
self.use_jacobi = opt("jacobi", "QUANTUM_JACOBI", 1, int) != 0
|
|
72
|
+
self.use_measurements = opt("measurements", "QUANTUM_MEAS", 1, int) != 0
|
|
73
|
+
self.use_amplitude = opt("amplitude", "QUANTUM_AMPLITUDE", 0, int) != 0
|
|
74
|
+
self.amplitude_weight = opt("amplitude_weight", "QUANTUM_AMPLITUDE_WEIGHT", 0.5, float)
|
|
75
|
+
self.memory_bypass = opt("memory_bypass", "QUANTUM_MEMORY_BYPASS", 0, int) != 0
|
|
76
|
+
self.bypass_min_survival = opt("bypass_min_survival", "QUANTUM_BYPASS_MIN_SURVIVAL", 0.25, float)
|
|
77
|
+
self.suffix = SuffixSpeculator(vllm_config, device, req_states) if self.use_suffix else None
|
|
78
|
+
K = self.num_speculative_steps
|
|
79
|
+
self.prev_drafts = torch.full((self.max_num_reqs, K), -1, dtype=torch.int64, device=device)
|
|
80
|
+
self.prev_len = torch.zeros(self.max_num_reqs, dtype=torch.int64, device=device)
|
|
81
|
+
self.pos_arange = torch.arange(K, device=device)
|
|
82
|
+
# Empirical-Bayes prior by exact suffix-match length bucket.
|
|
83
|
+
self.match_prior = torch.tensor([0.20, 0.30, 0.45, 0.55, 0.65, 0.72, 0.82, 0.90, 0.95],
|
|
84
|
+
device=device, dtype=torch.float32)
|
|
85
|
+
self.match_prior_alpha = float(os.environ.get("QUANTUM_MATCH_PRIOR_ALPHA", "8"))
|
|
86
|
+
self.match_prior_scale = float(os.environ.get("QUANTUM_MATCH_PRIOR_SCALE", "1"))
|
|
87
|
+
self.suffix_ucb = float(os.environ.get("QUANTUM_SUFFIX_UCB", "0"))
|
|
88
|
+
self.corpus_prior_scale = float(os.environ.get("QUANTUM_CORPUS_PRIOR_SCALE", "1"))
|
|
89
|
+
self.measurements = torch.full((self.max_num_reqs, K + 1), -1, dtype=torch.int64, device=device)
|
|
90
|
+
self.measurement_margins = torch.zeros((self.max_num_reqs, K + 1), dtype=torch.float32, device=device)
|
|
91
|
+
self.jacobi_mask = torch.zeros((self.max_num_reqs, K), dtype=torch.bool, device=device)
|
|
92
|
+
self.jacobi_stats = torch.zeros((K, 2), dtype=torch.float32, device=device)
|
|
93
|
+
self.jacobi_prior = float(os.environ.get("QUANTUM_JACOBI_PRIOR", "0.55"))
|
|
94
|
+
self.jacobi_prior_alpha = float(os.environ.get("QUANTUM_JACOBI_PRIOR_ALPHA", "8"))
|
|
95
|
+
self.jacobi_ucb = float(os.environ.get("QUANTUM_JACOBI_UCB", "0"))
|
|
96
|
+
if self.use_measurements:
|
|
97
|
+
global _MEASUREMENTS, _MEASUREMENT_MARGINS
|
|
98
|
+
_MEASUREMENTS = self.measurements
|
|
99
|
+
_MEASUREMENT_MARGINS = self.measurement_margins if self.use_amplitude else None
|
|
100
|
+
_measurement_capture_patch()
|
|
101
|
+
|
|
102
|
+
def add_request(self, req_index: int) -> None:
|
|
103
|
+
super().add_request(req_index)
|
|
104
|
+
self.prev_drafts[req_index].fill_(-1)
|
|
105
|
+
self.prev_len[req_index] = 0
|
|
106
|
+
if self.suffix is not None:
|
|
107
|
+
self.suffix.add_request(req_index)
|
|
108
|
+
|
|
109
|
+
def on_requests_finished(self, finished_req_ids):
|
|
110
|
+
super().on_requests_finished(finished_req_ids)
|
|
111
|
+
if self.suffix is not None:
|
|
112
|
+
self.suffix.on_requests_finished(finished_req_ids)
|
|
113
|
+
|
|
114
|
+
def reset_state(self) -> None:
|
|
115
|
+
super().reset_state()
|
|
116
|
+
self.prev_drafts.fill_(-1)
|
|
117
|
+
self.prev_len.zero_()
|
|
118
|
+
if self.suffix is not None:
|
|
119
|
+
self.suffix.reset_state()
|
|
120
|
+
|
|
121
|
+
def propose(self, input_batch, attn_metadata, slot_mappings, last_hidden_states,
|
|
122
|
+
aux_hidden_states, num_sampled, num_rejected, last_sampled,
|
|
123
|
+
next_prefill_tokens, temperature, seeds, dp_sync_state=None,
|
|
124
|
+
dummy_run=False, skip_attn_for_dummy_run=False, mm_inputs=None,
|
|
125
|
+
is_profile=False, num_speculative_tokens=None):
|
|
126
|
+
outer_k = self.num_speculative_steps if num_speculative_tokens is None else num_speculative_tokens
|
|
127
|
+
mtp_k = min(self.mtp_len, outer_k)
|
|
128
|
+
n = input_batch.num_reqs
|
|
129
|
+
idx = input_batch.idx_mapping
|
|
130
|
+
K = self.num_speculative_steps
|
|
131
|
+
pre_sd = None
|
|
132
|
+
if (self.memory_bypass and self.suffix is not None and not dummy_run
|
|
133
|
+
and not is_profile and n <= self.suffix_max_batch):
|
|
134
|
+
pre_sd = self.suffix.propose(
|
|
135
|
+
input_batch, attn_metadata, slot_mappings, last_hidden_states, aux_hidden_states,
|
|
136
|
+
num_sampled, num_rejected, last_sampled, next_prefill_tokens, temperature, seeds,
|
|
137
|
+
dp_sync_state=dp_sync_state, dummy_run=dummy_run,
|
|
138
|
+
skip_attn_for_dummy_run=skip_attn_for_dummy_run, mm_inputs=mm_inputs,
|
|
139
|
+
is_profile=is_profile, num_speculative_tokens=outer_k)
|
|
140
|
+
if self.suffix.enable_adaptive_verification:
|
|
141
|
+
bucket = self.suffix.last_bucket[idx].long().clamp_min(0)
|
|
142
|
+
stats = self.suffix.accept_stats[bucket, :outer_k].float()
|
|
143
|
+
acc = stats[:, :, 0]
|
|
144
|
+
obs = stats[:, :, 1]
|
|
145
|
+
prior = self.match_prior[(bucket % 9).clamp(max=8)].unsqueeze(1) * self.match_prior_scale
|
|
146
|
+
alpha = self.match_prior_alpha
|
|
147
|
+
conf = (acc + prior * alpha) / (obs + alpha)
|
|
148
|
+
valid = self.suffix.num_valid[:n].unsqueeze(1) > self.pos_arange[:outer_k].unsqueeze(0)
|
|
149
|
+
conf = torch.where(valid, conf, torch.zeros_like(conf))
|
|
150
|
+
self.suffix.draft_token_confidence_probs[:n, :outer_k] = conf
|
|
151
|
+
survival = conf.clamp_min(1e-3).log().sum(dim=1).exp()
|
|
152
|
+
full = self.suffix.num_valid[:n] >= outer_k
|
|
153
|
+
eligible = full & (survival >= self.bypass_min_survival)
|
|
154
|
+
# Batch rows share one draft-model launch, so bypassing is all-or-nothing.
|
|
155
|
+
# The host branch is intentionally experimental and only used when the
|
|
156
|
+
# zero-draft memory mode is explicitly enabled.
|
|
157
|
+
if bool(eligible.all().item()):
|
|
158
|
+
drafts = pre_sd[:, :outer_k].clone()
|
|
159
|
+
self.draft_token_confidence_probs[:n, :outer_k] = conf
|
|
160
|
+
if self.use_jacobi:
|
|
161
|
+
pos = self.pos_arange.unsqueeze(0)
|
|
162
|
+
accepted = (num_sampled.long() - 1).clamp_min(0)
|
|
163
|
+
verified = accepted + num_rejected.long()
|
|
164
|
+
observed = ((pos <= accepted.unsqueeze(1)) & (pos < verified.unsqueeze(1))
|
|
165
|
+
& self.jacobi_mask[idx])
|
|
166
|
+
hit = observed & (pos < accepted.unsqueeze(1))
|
|
167
|
+
self.jacobi_stats[:, 0] += hit.sum(dim=0).float()
|
|
168
|
+
self.jacobi_stats[:, 1] += observed.sum(dim=0).float()
|
|
169
|
+
self.jacobi_mask[idx, :] = False
|
|
170
|
+
self.prev_drafts[idx, :outer_k] = drafts
|
|
171
|
+
self.prev_len[idx] = self.req_states.total_len.gpu[idx].long()
|
|
172
|
+
if self.use_measurements:
|
|
173
|
+
self.measurements.fill_(-1)
|
|
174
|
+
if self.use_amplitude:
|
|
175
|
+
self.measurement_margins.zero_()
|
|
176
|
+
return drafts
|
|
177
|
+
drafts = super().propose(
|
|
178
|
+
input_batch, attn_metadata, slot_mappings, last_hidden_states, aux_hidden_states,
|
|
179
|
+
num_sampled, num_rejected, last_sampled, next_prefill_tokens, temperature, seeds,
|
|
180
|
+
dp_sync_state=dp_sync_state, dummy_run=dummy_run,
|
|
181
|
+
skip_attn_for_dummy_run=skip_attn_for_dummy_run, mm_inputs=mm_inputs,
|
|
182
|
+
is_profile=is_profile, num_speculative_tokens=mtp_k)
|
|
183
|
+
if dummy_run:
|
|
184
|
+
return drafts
|
|
185
|
+
if self.use_jacobi and not dummy_run:
|
|
186
|
+
pos = self.pos_arange.unsqueeze(0)
|
|
187
|
+
accepted = (num_sampled.long() - 1).clamp_min(0)
|
|
188
|
+
verified = accepted + num_rejected.long()
|
|
189
|
+
observed = ((pos <= accepted.unsqueeze(1)) & (pos < verified.unsqueeze(1))
|
|
190
|
+
& self.jacobi_mask[idx])
|
|
191
|
+
hit = observed & (pos < accepted.unsqueeze(1))
|
|
192
|
+
self.jacobi_stats[:, 0] += hit.sum(dim=0).float()
|
|
193
|
+
self.jacobi_stats[:, 1] += observed.sum(dim=0).float()
|
|
194
|
+
self.jacobi_mask[idx, :] = False
|
|
195
|
+
if mtp_k < outer_k:
|
|
196
|
+
drafts[:, mtp_k:outer_k] = -1
|
|
197
|
+
if self.suffix is not None and n <= self.suffix_max_batch:
|
|
198
|
+
sd = pre_sd if pre_sd is not None else self.suffix.propose(
|
|
199
|
+
input_batch, attn_metadata, slot_mappings, last_hidden_states, aux_hidden_states,
|
|
200
|
+
num_sampled, num_rejected, last_sampled, next_prefill_tokens, temperature, seeds,
|
|
201
|
+
dp_sync_state=dp_sync_state, dummy_run=dummy_run,
|
|
202
|
+
skip_attn_for_dummy_run=skip_attn_for_dummy_run, mm_inputs=mm_inputs,
|
|
203
|
+
is_profile=is_profile, num_speculative_tokens=outer_k)
|
|
204
|
+
if self.suffix.enable_adaptive_verification:
|
|
205
|
+
bucket = self.suffix.last_bucket[idx].long().clamp_min(0)
|
|
206
|
+
stats = self.suffix.accept_stats[bucket, :outer_k].float()
|
|
207
|
+
acc = stats[:, :, 0]
|
|
208
|
+
obs = stats[:, :, 1]
|
|
209
|
+
prior = self.match_prior[(bucket % 9).clamp(max=8)].unsqueeze(1) * self.match_prior_scale
|
|
210
|
+
if self.corpus_prior_scale != 1.0:
|
|
211
|
+
is_corpus = (bucket // 9 == 1).float().unsqueeze(1)
|
|
212
|
+
prior = prior * (1.0 + is_corpus * (self.corpus_prior_scale - 1.0))
|
|
213
|
+
alpha = self.match_prior_alpha
|
|
214
|
+
conf = (acc + prior * alpha) / (obs + alpha)
|
|
215
|
+
if self.suffix_ucb:
|
|
216
|
+
conf = (conf + self.suffix_ucb / torch.sqrt(obs + 1.0)).clamp(max=0.99)
|
|
217
|
+
valid = self.suffix.num_valid[:n].unsqueeze(1) > self.pos_arange[:outer_k].unsqueeze(0)
|
|
218
|
+
self.suffix.draft_token_confidence_probs[:n, :outer_k] = torch.where(
|
|
219
|
+
valid, conf, torch.zeros_like(conf))
|
|
220
|
+
if self.mix_mode == "confidence":
|
|
221
|
+
# Collapse each request to one coherent world: mixing individual positions
|
|
222
|
+
# would leave MTP suffixes conditioned on tokens they did not actually
|
|
223
|
+
# follow. Compare survival probability of the two complete chains.
|
|
224
|
+
mc = self.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
225
|
+
sc = self.suffix.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
226
|
+
# Compare in log space: K=12/16 chain survivals routinely underflow
|
|
227
|
+
# fp32 products to zero, which would disable the whole-chain switch.
|
|
228
|
+
ms = mc.log().sum(dim=1)
|
|
229
|
+
ss = sc.log().sum(dim=1)
|
|
230
|
+
# A long exact suffix match is strong evidence even before its online
|
|
231
|
+
# acceptance statistics warm up.
|
|
232
|
+
take = (ss > ms + torch.log1p(torch.tensor(self.mix_margin, device=ms.device)))[:, None]
|
|
233
|
+
drafts[:, :outer_k] = torch.where(take, sd[:n, :outer_k], drafts[:, :outer_k])
|
|
234
|
+
self.draft_token_confidence_probs[:n, :outer_k] = torch.where(
|
|
235
|
+
take, sc, self.draft_token_confidence_probs[:n, :outer_k])
|
|
236
|
+
elif self.mix_mode == "stitch":
|
|
237
|
+
# Coherent overlap stitching. A raw MTP-prefix/suffix-tail splice is
|
|
238
|
+
# usually conditioned on two different worlds. Here the chains may
|
|
239
|
+
# only diverge at their first disagreement, so every token before the
|
|
240
|
+
# suffix tail is exactly the prefix that suffix continuation followed.
|
|
241
|
+
matches = (sd[:n, :outer_k] == drafts[:, :outer_k]).long()
|
|
242
|
+
overlap = torch.cumprod(matches, dim=1).sum(dim=1)
|
|
243
|
+
tail_pos = self.pos_arange[:outer_k].unsqueeze(0) >= overlap.unsqueeze(1)
|
|
244
|
+
sc0 = self.suffix.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
245
|
+
mc0 = self.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
246
|
+
# Compare only the divergent tails; the shared overlap cancels exactly.
|
|
247
|
+
# Stitching is therefore cost-aware rather than an unconditional win for
|
|
248
|
+
# suffix memory on natural text where its continuation is weak.
|
|
249
|
+
sl = (sc0.log() * tail_pos).sum(dim=1)
|
|
250
|
+
ml = (mc0.log() * tail_pos).sum(dim=1)
|
|
251
|
+
can_stitch = ((overlap >= self.stitch_min_overlap)
|
|
252
|
+
& (sl > ml + torch.log1p(torch.tensor(self.mix_margin, device=sl.device))))[:, None]
|
|
253
|
+
use_suffix_tail = can_stitch & tail_pos
|
|
254
|
+
drafts[:, :outer_k] = torch.where(
|
|
255
|
+
use_suffix_tail, sd[:n, :outer_k], drafts[:, :outer_k])
|
|
256
|
+
sc = self.suffix.draft_token_confidence_probs[:n, :outer_k]
|
|
257
|
+
cur = self.draft_token_confidence_probs[:n, :outer_k]
|
|
258
|
+
self.draft_token_confidence_probs[:n, :outer_k] = torch.where(
|
|
259
|
+
use_suffix_tail, sc, cur)
|
|
260
|
+
else:
|
|
261
|
+
# MTP owns the high-confidence prefix; suffix memory extends the chain.
|
|
262
|
+
drafts[:, mtp_k:outer_k] = sd[:n, mtp_k:outer_k]
|
|
263
|
+
self.draft_token_confidence_probs[:n, mtp_k:outer_k] = (
|
|
264
|
+
self.suffix.draft_token_confidence_probs[:n, mtp_k:outer_k])
|
|
265
|
+
if self.use_jacobi and mtp_k < outer_k:
|
|
266
|
+
cur = self.req_states.total_len.gpu[idx].long()
|
|
267
|
+
oldlen = self.prev_len[idx]
|
|
268
|
+
shift = (cur - oldlen).clamp(0, K - 1)
|
|
269
|
+
src = self.pos_arange[:outer_k].unsqueeze(0) + shift.unsqueeze(1)
|
|
270
|
+
valid_draft = (src < K) & (shift.unsqueeze(1) > 0)
|
|
271
|
+
valid_meas = (src <= K) & (shift.unsqueeze(1) > 0)
|
|
272
|
+
old_draft = self.prev_drafts[idx]
|
|
273
|
+
jac = torch.gather(old_draft, 1, src.clamp(max=K - 1))
|
|
274
|
+
live = valid_draft
|
|
275
|
+
if self.use_measurements:
|
|
276
|
+
# Rejected-position target measurements are stronger than old draft
|
|
277
|
+
# tokens: they already include target-model corrections near the fixed point.
|
|
278
|
+
old_meas = self.measurements[idx]
|
|
279
|
+
jac_meas = torch.gather(old_meas, 1, src.clamp(max=K))
|
|
280
|
+
use_meas = valid_meas & (jac_meas >= 0)
|
|
281
|
+
jac = torch.where(use_meas, jac_meas, jac)
|
|
282
|
+
live = use_meas | (valid_draft & ~use_meas)
|
|
283
|
+
# Fixed-point history is most useful beyond the learned MTP prefix. It only
|
|
284
|
+
# overwrites suffix slots where it actually has a live retrospective guess.
|
|
285
|
+
tail = slice(max(mtp_k, 1), outer_k)
|
|
286
|
+
ok = live[:, tail] & (jac[:, tail] >= 0)
|
|
287
|
+
drafts[:, tail] = torch.where(ok, jac[:, tail], drafts[:, tail])
|
|
288
|
+
jstats = self.jacobi_stats[tail, :]
|
|
289
|
+
jconf = ((jstats[:, 0] + self.jacobi_prior * self.jacobi_prior_alpha)
|
|
290
|
+
/ (jstats[:, 1] + self.jacobi_prior_alpha))
|
|
291
|
+
if self.jacobi_ucb:
|
|
292
|
+
jconf = (jconf + self.jacobi_ucb / torch.sqrt(jstats[:, 1] + 1.0)).clamp(max=0.99)
|
|
293
|
+
jconf_grid = jconf.unsqueeze(0).expand_as(self.draft_token_confidence_probs[:n, tail])
|
|
294
|
+
if self.use_amplitude and self.use_measurements:
|
|
295
|
+
old_margins = self.measurement_margins[idx]
|
|
296
|
+
marg = torch.gather(old_margins, 1, src.clamp(max=K))[:, tail]
|
|
297
|
+
amp = torch.sigmoid((marg - 1.5) * 1.5).clamp(1e-3, 0.99)
|
|
298
|
+
w = self.amplitude_weight
|
|
299
|
+
jconf_grid = torch.exp((1.0 - w) * torch.log(jconf_grid.clamp_min(1e-3))
|
|
300
|
+
+ w * torch.log(amp))
|
|
301
|
+
self.draft_token_confidence_probs[:n, tail] = torch.where(
|
|
302
|
+
ok, jconf_grid,
|
|
303
|
+
self.draft_token_confidence_probs[:n, tail])
|
|
304
|
+
self.jacobi_mask[idx, tail] = self.jacobi_mask[idx, tail] | ok
|
|
305
|
+
self.prev_drafts[idx, :outer_k] = drafts[:, :outer_k]
|
|
306
|
+
self.prev_len[idx] = self.req_states.total_len.gpu[idx].long()
|
|
307
|
+
if self.use_measurements:
|
|
308
|
+
# Measurements belong to one verification epoch. Positions trimmed by
|
|
309
|
+
# adaptive verification must not reappear later as stale fixed-point guesses.
|
|
310
|
+
self.measurements.fill_(-1)
|
|
311
|
+
if self.use_amplitude:
|
|
312
|
+
self.measurement_margins.zero_()
|
|
313
|
+
return drafts
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def register():
|
|
317
|
+
try:
|
|
318
|
+
register_speculative_method("quantum", QuantumSpeculatorConfig)
|
|
319
|
+
except ValueError as e:
|
|
320
|
+
if "already registered" not in str(e):
|
|
321
|
+
raise
|
|
Binary file
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "quantum-infer-vllm"
|
|
7
|
+
version = "0.3.0"
|
|
8
|
+
description = "quantumInfer hybrid MTP/suffix/Jacobi speculative proposer plugin for vLLM"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = ["vllm>=0.34.0,<0.35.0"]
|
|
11
|
+
|
|
12
|
+
[project.entry-points."vllm.general_plugins"]
|
|
13
|
+
quantum_infer = "quantum_infer_vllm:quantum_infer_plugin"
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["."]
|
|
17
|
+
include = ["quantum_infer_vllm*"]
|
|
Binary file
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
"""quantumInfer hybrid speculative proposer plugin for vLLM.
|
|
2
|
+
|
|
3
|
+
Composes target-dependent MTP chain proposals with free retrospective fixed-point
|
|
4
|
+
(Jacobi) reuse and whole-history suffix proposals inside vLLM's exact verifier.
|
|
5
|
+
"""
|
|
6
|
+
import os
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from vllm.v1.worker.gpu.spec_decode.mtp.config import MTPSpeculatorConfig
|
|
10
|
+
from vllm.v1.worker.gpu.spec_decode.mtp.speculator import MTPSpeculator
|
|
11
|
+
from vllm.v1.worker.gpu.spec_decode.speculator_config import register_speculative_method
|
|
12
|
+
from vllm.v1.worker.gpu.spec_decode.suffix.speculator import SuffixSpeculator
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_MEASUREMENTS = None
|
|
16
|
+
_MEASUREMENT_MARGINS = None
|
|
17
|
+
_ORIGINAL_REJECTION_SAMPLE = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _measurement_capture_patch():
|
|
21
|
+
"""Capture target-model measurements at every verified draft position."""
|
|
22
|
+
global _ORIGINAL_REJECTION_SAMPLE
|
|
23
|
+
if _ORIGINAL_REJECTION_SAMPLE is not None:
|
|
24
|
+
return
|
|
25
|
+
import vllm.v1.worker.gpu.spec_decode.rejection_sampler as rs
|
|
26
|
+
_ORIGINAL_REJECTION_SAMPLE = rs.rejection_sample
|
|
27
|
+
|
|
28
|
+
def capture_rejection_sample(target_logits, *args, **kwargs):
|
|
29
|
+
if _MEASUREMENTS is not None:
|
|
30
|
+
try:
|
|
31
|
+
expanded_idx_mapping = args[5] if len(args) > 5 else kwargs["expanded_idx_mapping"]
|
|
32
|
+
expanded_local_pos = args[6] if len(args) > 6 else kwargs["expanded_local_pos"]
|
|
33
|
+
num_steps = args[9] if len(args) > 9 else kwargs["num_speculative_steps"]
|
|
34
|
+
vals = target_logits.argmax(dim=-1)
|
|
35
|
+
flat = (expanded_idx_mapping.long() * (num_steps + 1)
|
|
36
|
+
+ expanded_local_pos.long())
|
|
37
|
+
_MEASUREMENTS.view(-1).index_copy_(0, flat, vals)
|
|
38
|
+
if _MEASUREMENT_MARGINS is not None:
|
|
39
|
+
top2 = torch.topk(target_logits, 2, dim=-1).values
|
|
40
|
+
margins = (top2[..., 0] - top2[..., 1]).clamp(0.0, 50.0)
|
|
41
|
+
_MEASUREMENT_MARGINS.view(-1).index_copy_(0, flat, margins)
|
|
42
|
+
except Exception:
|
|
43
|
+
pass
|
|
44
|
+
return _ORIGINAL_REJECTION_SAMPLE(target_logits, *args, **kwargs)
|
|
45
|
+
|
|
46
|
+
rs.rejection_sample = capture_rejection_sample
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class QuantumSpeculatorConfig(MTPSpeculatorConfig):
|
|
50
|
+
base_method = "quantum"
|
|
51
|
+
supported_options = MTPSpeculatorConfig.supported_options | {"speculator_options"}
|
|
52
|
+
speculator_class = "quantum_infer_vllm.spec.QuantumSpeculator"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class QuantumSpeculator(MTPSpeculator):
|
|
56
|
+
def __init__(self, vllm_config, device, req_states=None):
|
|
57
|
+
super().__init__(vllm_config, device)
|
|
58
|
+
assert req_states is not None
|
|
59
|
+
self.req_states = req_states
|
|
60
|
+
spec_opts = getattr(vllm_config.speculative_config, "speculator_options", None) or {}
|
|
61
|
+
|
|
62
|
+
def opt(name, env_name, default, cast):
|
|
63
|
+
return cast(spec_opts.get(name, os.environ.get(env_name, str(default))))
|
|
64
|
+
|
|
65
|
+
self.mtp_len = opt("mtp_len", "QUANTUM_MTP_LEN", 5, int)
|
|
66
|
+
self.use_suffix = opt("suffix", "QUANTUM_SUFFIX", 1, int) != 0
|
|
67
|
+
self.suffix_max_batch = opt("suffix_max_batch", "QUANTUM_SUFFIX_MAX_BATCH", 32, int)
|
|
68
|
+
self.mix_mode = str(spec_opts.get("mix", os.environ.get("QUANTUM_MIX", "tail")))
|
|
69
|
+
self.mix_margin = opt("mix_margin", "QUANTUM_MIX_MARGIN", 0.10, float)
|
|
70
|
+
self.stitch_min_overlap = opt("stitch_min_overlap", "QUANTUM_STITCH_MIN_OVERLAP", 2, int)
|
|
71
|
+
self.use_jacobi = opt("jacobi", "QUANTUM_JACOBI", 1, int) != 0
|
|
72
|
+
self.use_measurements = opt("measurements", "QUANTUM_MEAS", 1, int) != 0
|
|
73
|
+
self.use_amplitude = opt("amplitude", "QUANTUM_AMPLITUDE", 0, int) != 0
|
|
74
|
+
self.amplitude_weight = opt("amplitude_weight", "QUANTUM_AMPLITUDE_WEIGHT", 0.5, float)
|
|
75
|
+
self.memory_bypass = opt("memory_bypass", "QUANTUM_MEMORY_BYPASS", 0, int) != 0
|
|
76
|
+
self.bypass_min_survival = opt("bypass_min_survival", "QUANTUM_BYPASS_MIN_SURVIVAL", 0.25, float)
|
|
77
|
+
self.suffix = SuffixSpeculator(vllm_config, device, req_states) if self.use_suffix else None
|
|
78
|
+
K = self.num_speculative_steps
|
|
79
|
+
self.prev_drafts = torch.full((self.max_num_reqs, K), -1, dtype=torch.int64, device=device)
|
|
80
|
+
self.prev_len = torch.zeros(self.max_num_reqs, dtype=torch.int64, device=device)
|
|
81
|
+
self.pos_arange = torch.arange(K, device=device)
|
|
82
|
+
# Empirical-Bayes prior by exact suffix-match length bucket.
|
|
83
|
+
self.match_prior = torch.tensor([0.20, 0.30, 0.45, 0.55, 0.65, 0.72, 0.82, 0.90, 0.95],
|
|
84
|
+
device=device, dtype=torch.float32)
|
|
85
|
+
self.match_prior_alpha = float(os.environ.get("QUANTUM_MATCH_PRIOR_ALPHA", "8"))
|
|
86
|
+
self.match_prior_scale = float(os.environ.get("QUANTUM_MATCH_PRIOR_SCALE", "1"))
|
|
87
|
+
self.suffix_ucb = float(os.environ.get("QUANTUM_SUFFIX_UCB", "0"))
|
|
88
|
+
self.corpus_prior_scale = float(os.environ.get("QUANTUM_CORPUS_PRIOR_SCALE", "1"))
|
|
89
|
+
self.measurements = torch.full((self.max_num_reqs, K + 1), -1, dtype=torch.int64, device=device)
|
|
90
|
+
self.measurement_margins = torch.zeros((self.max_num_reqs, K + 1), dtype=torch.float32, device=device)
|
|
91
|
+
self.jacobi_mask = torch.zeros((self.max_num_reqs, K), dtype=torch.bool, device=device)
|
|
92
|
+
self.jacobi_stats = torch.zeros((K, 2), dtype=torch.float32, device=device)
|
|
93
|
+
self.jacobi_prior = float(os.environ.get("QUANTUM_JACOBI_PRIOR", "0.55"))
|
|
94
|
+
self.jacobi_prior_alpha = float(os.environ.get("QUANTUM_JACOBI_PRIOR_ALPHA", "8"))
|
|
95
|
+
self.jacobi_ucb = float(os.environ.get("QUANTUM_JACOBI_UCB", "0"))
|
|
96
|
+
if self.use_measurements:
|
|
97
|
+
global _MEASUREMENTS, _MEASUREMENT_MARGINS
|
|
98
|
+
_MEASUREMENTS = self.measurements
|
|
99
|
+
_MEASUREMENT_MARGINS = self.measurement_margins if self.use_amplitude else None
|
|
100
|
+
_measurement_capture_patch()
|
|
101
|
+
|
|
102
|
+
def add_request(self, req_index: int) -> None:
|
|
103
|
+
super().add_request(req_index)
|
|
104
|
+
self.prev_drafts[req_index].fill_(-1)
|
|
105
|
+
self.prev_len[req_index] = 0
|
|
106
|
+
if self.suffix is not None:
|
|
107
|
+
self.suffix.add_request(req_index)
|
|
108
|
+
|
|
109
|
+
def on_requests_finished(self, finished_req_ids):
|
|
110
|
+
super().on_requests_finished(finished_req_ids)
|
|
111
|
+
if self.suffix is not None:
|
|
112
|
+
self.suffix.on_requests_finished(finished_req_ids)
|
|
113
|
+
|
|
114
|
+
def reset_state(self) -> None:
|
|
115
|
+
super().reset_state()
|
|
116
|
+
self.prev_drafts.fill_(-1)
|
|
117
|
+
self.prev_len.zero_()
|
|
118
|
+
if self.suffix is not None:
|
|
119
|
+
self.suffix.reset_state()
|
|
120
|
+
|
|
121
|
+
def propose(self, input_batch, attn_metadata, slot_mappings, last_hidden_states,
|
|
122
|
+
aux_hidden_states, num_sampled, num_rejected, last_sampled,
|
|
123
|
+
next_prefill_tokens, temperature, seeds, dp_sync_state=None,
|
|
124
|
+
dummy_run=False, skip_attn_for_dummy_run=False, mm_inputs=None,
|
|
125
|
+
is_profile=False, num_speculative_tokens=None):
|
|
126
|
+
outer_k = self.num_speculative_steps if num_speculative_tokens is None else num_speculative_tokens
|
|
127
|
+
mtp_k = min(self.mtp_len, outer_k)
|
|
128
|
+
n = input_batch.num_reqs
|
|
129
|
+
idx = input_batch.idx_mapping
|
|
130
|
+
K = self.num_speculative_steps
|
|
131
|
+
pre_sd = None
|
|
132
|
+
if (self.memory_bypass and self.suffix is not None and not dummy_run
|
|
133
|
+
and not is_profile and n <= self.suffix_max_batch):
|
|
134
|
+
pre_sd = self.suffix.propose(
|
|
135
|
+
input_batch, attn_metadata, slot_mappings, last_hidden_states, aux_hidden_states,
|
|
136
|
+
num_sampled, num_rejected, last_sampled, next_prefill_tokens, temperature, seeds,
|
|
137
|
+
dp_sync_state=dp_sync_state, dummy_run=dummy_run,
|
|
138
|
+
skip_attn_for_dummy_run=skip_attn_for_dummy_run, mm_inputs=mm_inputs,
|
|
139
|
+
is_profile=is_profile, num_speculative_tokens=outer_k)
|
|
140
|
+
if self.suffix.enable_adaptive_verification:
|
|
141
|
+
bucket = self.suffix.last_bucket[idx].long().clamp_min(0)
|
|
142
|
+
stats = self.suffix.accept_stats[bucket, :outer_k].float()
|
|
143
|
+
acc = stats[:, :, 0]
|
|
144
|
+
obs = stats[:, :, 1]
|
|
145
|
+
prior = self.match_prior[(bucket % 9).clamp(max=8)].unsqueeze(1) * self.match_prior_scale
|
|
146
|
+
alpha = self.match_prior_alpha
|
|
147
|
+
conf = (acc + prior * alpha) / (obs + alpha)
|
|
148
|
+
valid = self.suffix.num_valid[:n].unsqueeze(1) > self.pos_arange[:outer_k].unsqueeze(0)
|
|
149
|
+
conf = torch.where(valid, conf, torch.zeros_like(conf))
|
|
150
|
+
self.suffix.draft_token_confidence_probs[:n, :outer_k] = conf
|
|
151
|
+
survival = conf.clamp_min(1e-3).log().sum(dim=1).exp()
|
|
152
|
+
full = self.suffix.num_valid[:n] >= outer_k
|
|
153
|
+
eligible = full & (survival >= self.bypass_min_survival)
|
|
154
|
+
# Batch rows share one draft-model launch, so bypassing is all-or-nothing.
|
|
155
|
+
# The host branch is intentionally experimental and only used when the
|
|
156
|
+
# zero-draft memory mode is explicitly enabled.
|
|
157
|
+
if bool(eligible.all().item()):
|
|
158
|
+
drafts = pre_sd[:, :outer_k].clone()
|
|
159
|
+
self.draft_token_confidence_probs[:n, :outer_k] = conf
|
|
160
|
+
if self.use_jacobi:
|
|
161
|
+
pos = self.pos_arange.unsqueeze(0)
|
|
162
|
+
accepted = (num_sampled.long() - 1).clamp_min(0)
|
|
163
|
+
verified = accepted + num_rejected.long()
|
|
164
|
+
observed = ((pos <= accepted.unsqueeze(1)) & (pos < verified.unsqueeze(1))
|
|
165
|
+
& self.jacobi_mask[idx])
|
|
166
|
+
hit = observed & (pos < accepted.unsqueeze(1))
|
|
167
|
+
self.jacobi_stats[:, 0] += hit.sum(dim=0).float()
|
|
168
|
+
self.jacobi_stats[:, 1] += observed.sum(dim=0).float()
|
|
169
|
+
self.jacobi_mask[idx, :] = False
|
|
170
|
+
self.prev_drafts[idx, :outer_k] = drafts
|
|
171
|
+
self.prev_len[idx] = self.req_states.total_len.gpu[idx].long()
|
|
172
|
+
if self.use_measurements:
|
|
173
|
+
self.measurements.fill_(-1)
|
|
174
|
+
if self.use_amplitude:
|
|
175
|
+
self.measurement_margins.zero_()
|
|
176
|
+
return drafts
|
|
177
|
+
drafts = super().propose(
|
|
178
|
+
input_batch, attn_metadata, slot_mappings, last_hidden_states, aux_hidden_states,
|
|
179
|
+
num_sampled, num_rejected, last_sampled, next_prefill_tokens, temperature, seeds,
|
|
180
|
+
dp_sync_state=dp_sync_state, dummy_run=dummy_run,
|
|
181
|
+
skip_attn_for_dummy_run=skip_attn_for_dummy_run, mm_inputs=mm_inputs,
|
|
182
|
+
is_profile=is_profile, num_speculative_tokens=mtp_k)
|
|
183
|
+
if dummy_run:
|
|
184
|
+
return drafts
|
|
185
|
+
if self.use_jacobi and not dummy_run:
|
|
186
|
+
pos = self.pos_arange.unsqueeze(0)
|
|
187
|
+
accepted = (num_sampled.long() - 1).clamp_min(0)
|
|
188
|
+
verified = accepted + num_rejected.long()
|
|
189
|
+
observed = ((pos <= accepted.unsqueeze(1)) & (pos < verified.unsqueeze(1))
|
|
190
|
+
& self.jacobi_mask[idx])
|
|
191
|
+
hit = observed & (pos < accepted.unsqueeze(1))
|
|
192
|
+
self.jacobi_stats[:, 0] += hit.sum(dim=0).float()
|
|
193
|
+
self.jacobi_stats[:, 1] += observed.sum(dim=0).float()
|
|
194
|
+
self.jacobi_mask[idx, :] = False
|
|
195
|
+
if mtp_k < outer_k:
|
|
196
|
+
drafts[:, mtp_k:outer_k] = -1
|
|
197
|
+
if self.suffix is not None and n <= self.suffix_max_batch:
|
|
198
|
+
sd = pre_sd if pre_sd is not None else self.suffix.propose(
|
|
199
|
+
input_batch, attn_metadata, slot_mappings, last_hidden_states, aux_hidden_states,
|
|
200
|
+
num_sampled, num_rejected, last_sampled, next_prefill_tokens, temperature, seeds,
|
|
201
|
+
dp_sync_state=dp_sync_state, dummy_run=dummy_run,
|
|
202
|
+
skip_attn_for_dummy_run=skip_attn_for_dummy_run, mm_inputs=mm_inputs,
|
|
203
|
+
is_profile=is_profile, num_speculative_tokens=outer_k)
|
|
204
|
+
if self.suffix.enable_adaptive_verification:
|
|
205
|
+
bucket = self.suffix.last_bucket[idx].long().clamp_min(0)
|
|
206
|
+
stats = self.suffix.accept_stats[bucket, :outer_k].float()
|
|
207
|
+
acc = stats[:, :, 0]
|
|
208
|
+
obs = stats[:, :, 1]
|
|
209
|
+
prior = self.match_prior[(bucket % 9).clamp(max=8)].unsqueeze(1) * self.match_prior_scale
|
|
210
|
+
if self.corpus_prior_scale != 1.0:
|
|
211
|
+
is_corpus = (bucket // 9 == 1).float().unsqueeze(1)
|
|
212
|
+
prior = prior * (1.0 + is_corpus * (self.corpus_prior_scale - 1.0))
|
|
213
|
+
alpha = self.match_prior_alpha
|
|
214
|
+
conf = (acc + prior * alpha) / (obs + alpha)
|
|
215
|
+
if self.suffix_ucb:
|
|
216
|
+
conf = (conf + self.suffix_ucb / torch.sqrt(obs + 1.0)).clamp(max=0.99)
|
|
217
|
+
valid = self.suffix.num_valid[:n].unsqueeze(1) > self.pos_arange[:outer_k].unsqueeze(0)
|
|
218
|
+
self.suffix.draft_token_confidence_probs[:n, :outer_k] = torch.where(
|
|
219
|
+
valid, conf, torch.zeros_like(conf))
|
|
220
|
+
if self.mix_mode == "confidence":
|
|
221
|
+
# Collapse each request to one coherent world: mixing individual positions
|
|
222
|
+
# would leave MTP suffixes conditioned on tokens they did not actually
|
|
223
|
+
# follow. Compare survival probability of the two complete chains.
|
|
224
|
+
mc = self.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
225
|
+
sc = self.suffix.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
226
|
+
# Compare in log space: K=12/16 chain survivals routinely underflow
|
|
227
|
+
# fp32 products to zero, which would disable the whole-chain switch.
|
|
228
|
+
ms = mc.log().sum(dim=1)
|
|
229
|
+
ss = sc.log().sum(dim=1)
|
|
230
|
+
# A long exact suffix match is strong evidence even before its online
|
|
231
|
+
# acceptance statistics warm up.
|
|
232
|
+
take = (ss > ms + torch.log1p(torch.tensor(self.mix_margin, device=ms.device)))[:, None]
|
|
233
|
+
drafts[:, :outer_k] = torch.where(take, sd[:n, :outer_k], drafts[:, :outer_k])
|
|
234
|
+
self.draft_token_confidence_probs[:n, :outer_k] = torch.where(
|
|
235
|
+
take, sc, self.draft_token_confidence_probs[:n, :outer_k])
|
|
236
|
+
elif self.mix_mode == "stitch":
|
|
237
|
+
# Coherent overlap stitching. A raw MTP-prefix/suffix-tail splice is
|
|
238
|
+
# usually conditioned on two different worlds. Here the chains may
|
|
239
|
+
# only diverge at their first disagreement, so every token before the
|
|
240
|
+
# suffix tail is exactly the prefix that suffix continuation followed.
|
|
241
|
+
matches = (sd[:n, :outer_k] == drafts[:, :outer_k]).long()
|
|
242
|
+
overlap = torch.cumprod(matches, dim=1).sum(dim=1)
|
|
243
|
+
tail_pos = self.pos_arange[:outer_k].unsqueeze(0) >= overlap.unsqueeze(1)
|
|
244
|
+
sc0 = self.suffix.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
245
|
+
mc0 = self.draft_token_confidence_probs[:n, :outer_k].clamp_min(1e-3)
|
|
246
|
+
# Compare only the divergent tails; the shared overlap cancels exactly.
|
|
247
|
+
# Stitching is therefore cost-aware rather than an unconditional win for
|
|
248
|
+
# suffix memory on natural text where its continuation is weak.
|
|
249
|
+
sl = (sc0.log() * tail_pos).sum(dim=1)
|
|
250
|
+
ml = (mc0.log() * tail_pos).sum(dim=1)
|
|
251
|
+
can_stitch = ((overlap >= self.stitch_min_overlap)
|
|
252
|
+
& (sl > ml + torch.log1p(torch.tensor(self.mix_margin, device=sl.device))))[:, None]
|
|
253
|
+
use_suffix_tail = can_stitch & tail_pos
|
|
254
|
+
drafts[:, :outer_k] = torch.where(
|
|
255
|
+
use_suffix_tail, sd[:n, :outer_k], drafts[:, :outer_k])
|
|
256
|
+
sc = self.suffix.draft_token_confidence_probs[:n, :outer_k]
|
|
257
|
+
cur = self.draft_token_confidence_probs[:n, :outer_k]
|
|
258
|
+
self.draft_token_confidence_probs[:n, :outer_k] = torch.where(
|
|
259
|
+
use_suffix_tail, sc, cur)
|
|
260
|
+
else:
|
|
261
|
+
# MTP owns the high-confidence prefix; suffix memory extends the chain.
|
|
262
|
+
drafts[:, mtp_k:outer_k] = sd[:n, mtp_k:outer_k]
|
|
263
|
+
self.draft_token_confidence_probs[:n, mtp_k:outer_k] = (
|
|
264
|
+
self.suffix.draft_token_confidence_probs[:n, mtp_k:outer_k])
|
|
265
|
+
if self.use_jacobi and mtp_k < outer_k:
|
|
266
|
+
cur = self.req_states.total_len.gpu[idx].long()
|
|
267
|
+
oldlen = self.prev_len[idx]
|
|
268
|
+
shift = (cur - oldlen).clamp(0, K - 1)
|
|
269
|
+
src = self.pos_arange[:outer_k].unsqueeze(0) + shift.unsqueeze(1)
|
|
270
|
+
valid_draft = (src < K) & (shift.unsqueeze(1) > 0)
|
|
271
|
+
valid_meas = (src <= K) & (shift.unsqueeze(1) > 0)
|
|
272
|
+
old_draft = self.prev_drafts[idx]
|
|
273
|
+
jac = torch.gather(old_draft, 1, src.clamp(max=K - 1))
|
|
274
|
+
live = valid_draft
|
|
275
|
+
if self.use_measurements:
|
|
276
|
+
# Rejected-position target measurements are stronger than old draft
|
|
277
|
+
# tokens: they already include target-model corrections near the fixed point.
|
|
278
|
+
old_meas = self.measurements[idx]
|
|
279
|
+
jac_meas = torch.gather(old_meas, 1, src.clamp(max=K))
|
|
280
|
+
use_meas = valid_meas & (jac_meas >= 0)
|
|
281
|
+
jac = torch.where(use_meas, jac_meas, jac)
|
|
282
|
+
live = use_meas | (valid_draft & ~use_meas)
|
|
283
|
+
# Fixed-point history is most useful beyond the learned MTP prefix. It only
|
|
284
|
+
# overwrites suffix slots where it actually has a live retrospective guess.
|
|
285
|
+
tail = slice(max(mtp_k, 1), outer_k)
|
|
286
|
+
ok = live[:, tail] & (jac[:, tail] >= 0)
|
|
287
|
+
drafts[:, tail] = torch.where(ok, jac[:, tail], drafts[:, tail])
|
|
288
|
+
jstats = self.jacobi_stats[tail, :]
|
|
289
|
+
jconf = ((jstats[:, 0] + self.jacobi_prior * self.jacobi_prior_alpha)
|
|
290
|
+
/ (jstats[:, 1] + self.jacobi_prior_alpha))
|
|
291
|
+
if self.jacobi_ucb:
|
|
292
|
+
jconf = (jconf + self.jacobi_ucb / torch.sqrt(jstats[:, 1] + 1.0)).clamp(max=0.99)
|
|
293
|
+
jconf_grid = jconf.unsqueeze(0).expand_as(self.draft_token_confidence_probs[:n, tail])
|
|
294
|
+
if self.use_amplitude and self.use_measurements:
|
|
295
|
+
old_margins = self.measurement_margins[idx]
|
|
296
|
+
marg = torch.gather(old_margins, 1, src.clamp(max=K))[:, tail]
|
|
297
|
+
amp = torch.sigmoid((marg - 1.5) * 1.5).clamp(1e-3, 0.99)
|
|
298
|
+
w = self.amplitude_weight
|
|
299
|
+
jconf_grid = torch.exp((1.0 - w) * torch.log(jconf_grid.clamp_min(1e-3))
|
|
300
|
+
+ w * torch.log(amp))
|
|
301
|
+
self.draft_token_confidence_probs[:n, tail] = torch.where(
|
|
302
|
+
ok, jconf_grid,
|
|
303
|
+
self.draft_token_confidence_probs[:n, tail])
|
|
304
|
+
self.jacobi_mask[idx, tail] = self.jacobi_mask[idx, tail] | ok
|
|
305
|
+
self.prev_drafts[idx, :outer_k] = drafts[:, :outer_k]
|
|
306
|
+
self.prev_len[idx] = self.req_states.total_len.gpu[idx].long()
|
|
307
|
+
if self.use_measurements:
|
|
308
|
+
# Measurements belong to one verification epoch. Positions trimmed by
|
|
309
|
+
# adaptive verification must not reappear later as stale fixed-point guesses.
|
|
310
|
+
self.measurements.fill_(-1)
|
|
311
|
+
if self.use_amplitude:
|
|
312
|
+
self.measurement_margins.zero_()
|
|
313
|
+
return drafts
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def register():
|
|
317
|
+
try:
|
|
318
|
+
register_speculative_method("quantum", QuantumSpeculatorConfig)
|
|
319
|
+
except ValueError as e:
|
|
320
|
+
if "already registered" not in str(e):
|
|
321
|
+
raise
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
pyproject.toml
|
|
2
|
+
quantum_infer_vllm/__init__.py
|
|
3
|
+
quantum_infer_vllm/spec.py
|
|
4
|
+
quantum_infer_vllm.egg-info/PKG-INFO
|
|
5
|
+
quantum_infer_vllm.egg-info/SOURCES.txt
|
|
6
|
+
quantum_infer_vllm.egg-info/dependency_links.txt
|
|
7
|
+
quantum_infer_vllm.egg-info/entry_points.txt
|
|
8
|
+
quantum_infer_vllm.egg-info/requires.txt
|
|
9
|
+
quantum_infer_vllm.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
vllm<0.35.0,>=0.34.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quantum_infer_vllm
|