quantuminfer 0.1.0 → 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 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
- Research-grade inference engine, not yet a serving replacement for vLLM or SGLang. It currently emphasizes single-user/low-batch decode innovation and kernel-level measurement; continuous batching, OpenAI-compatible serving, broad model coverage, and production hardening are future work.
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.
@@ -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 the quantumInfer Python/CUDA research engine
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,12 +1,37 @@
1
1
  {
2
2
  "name": "quantuminfer",
3
- "version": "0.1.0",
4
- "description": "Installer and CLI bootstrap for quantumInfer, a quantum-inspired exact speculative LLM inference research engine",
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
- "bin": { "quantuminfer": "./bin/quantuminfer.js" },
7
- "files": ["bin", "engine", "p27", "c27", "data", "results", "README.md", "LICENSE"],
8
- "keywords": ["llm", "inference", "speculative-decoding", "moe", "fp8", "cuda", "modal"],
9
- "repository": { "type": "git", "url": "https://github.com/Knihalani/quantumInfer.git" },
6
+ "bin": {
7
+ "quantuminfer": "./bin/quantuminfer.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "vllm_plugin",
12
+ "engine",
13
+ "p27",
14
+ "c27",
15
+ "data",
16
+ "results",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "keywords": [
21
+ "llm",
22
+ "inference",
23
+ "speculative-decoding",
24
+ "moe",
25
+ "fp8",
26
+ "cuda",
27
+ "modal"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/Knihalani/quantumInfer.git"
32
+ },
10
33
  "license": "MIT",
11
- "engines": { "node": ">=18" }
12
- }
34
+ "engines": {
35
+ "node": ">=18"
36
+ }
37
+ }
@@ -85,6 +85,10 @@ Shape-specialized quantumInfer ratios against direct vLLM: 0.28x on code and 0.3
85
85
 
86
86
  The decisive comparison is acceptance versus pass cost. quantumInfer matches or slightly exceeds vLLM's measured target-verified acceptance (5.20 versus 5.10 tokens/pass on code; 3.70 versus 3.47 on chat with the best chat shape), but vLLM executes a pass in roughly 9.7-10.1ms versus roughly 31.7-35.2ms for the research engine. In other words, acceptance is no longer the bottleneck; production kernel, collective, and runtime efficiency is. The highest-value follow-up is therefore to port the measurement-record tree proposers onto a vLLM-class optimized runtime rather than to widen the speculative tree blindly.
87
87
 
88
+ ### Full-scale Jacobi T=1 result
89
+
90
+ D3/C16/W1 exact T=1 chat on 8x B300: J8 measured 87.7 tok/s at 2.87 tokens/pass versus the same-shape no-Jacobi control at 77.7 tok/s and 2.50 tokens/pass. Speed ratio 1.13x. Artifacts: `res_glm_t1_j8_b300.json` and `res_glm_t1_e0_b300.json`.
91
+
88
92
  ## External competitor reference points
89
93
 
90
94
  These are published serving measurements, not controlled same-harness comparisons:
@@ -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,340 @@
1
+ {
2
+ "model": "/vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c19c8738e2c57c71798c601d477a7bf844",
3
+ "gpu": "NVIDIA B300 SXM6 AC",
4
+ "world": 8,
5
+ "load_s": 110.39359712600708,
6
+ "weight_bytes_rank0": 93614947776,
7
+ "state_bytes_rank0": 24379392,
8
+ "expert_shard": "ep_tp",
9
+ "mem_alloc_gb_rank0": 100.370640384,
10
+ "Bmax": 1,
11
+ "smax": 2048,
12
+ "mtp": true,
13
+ "single": [
14
+ {
15
+ "name": "t1/chat",
16
+ "ctx": 23,
17
+ "sampling": "T=1 exact",
18
+ "tok_s": 87.7262526107552,
19
+ "tok_s_min": 87.7262526107552,
20
+ "tok_s_max": 87.7262526107552,
21
+ "tokens_per_pass": 2.865168539325843,
22
+ "mode": "spec D=3 (MTP) + suffix C=16 + echo E=0/W1",
23
+ "runs": [
24
+ {
25
+ "t1": 0.17357720700002233,
26
+ "t256": 3.08034675899998,
27
+ "tok_s": 87.7262526107552,
28
+ "tok_per_pass": 2.865168539325843,
29
+ "engine_decode_tok_s": 87.5900453488911
30
+ }
31
+ ]
32
+ }
33
+ ],
34
+ "batched": [],
35
+ "shared": [],
36
+ "ttft": [],
37
+ "errors": [],
38
+ "fusion": {
39
+ "x_fp8": 78,
40
+ "x_bf16": 0,
41
+ "q_fp8": 21
42
+ },
43
+ "streams": [
44
+ {
45
+ "id": "single/t1/chat",
46
+ "prompt": [
47
+ 154822,
48
+ 154824,
49
+ 154826,
50
+ 25062,
51
+ 287,
52
+ 29905,
53
+ 371,
54
+ 25,
55
+ 7487,
56
+ 154827,
57
+ 840,
58
+ 20726,
59
+ 304,
60
+ 2326,
61
+ 22809,
62
+ 3170,
63
+ 279,
64
+ 12877,
65
+ 374,
66
+ 6303,
67
+ 13,
68
+ 154828,
69
+ 154841
70
+ ],
71
+ "out": [
72
+ 785,
73
+ 1196,
74
+ 6801,
75
+ 264,
76
+ 2326,
77
+ 1331,
78
+ 18351,
79
+ 16134,
80
+ 315,
81
+ 3170,
82
+ 279,
83
+ 12877,
84
+ 374,
85
+ 6303,
86
+ 13,
87
+ 1096,
88
+ 374,
89
+ 13247,
90
+ 62524,
91
+ 71268,
92
+ 13,
93
+ 6771,
94
+ 752,
95
+ 10765,
96
+ 6896,
97
+ 2326,
98
+ 2797,
99
+ 22809,
100
+ 382,
101
+ 83869,
102
+ 220,
103
+ 16,
104
+ 25,
105
+ 8058,
106
+ 4145,
107
+ 5610,
108
+ 678,
109
+ 7986,
110
+ 315,
111
+ 9430,
112
+ 3100,
113
+ 624,
114
+ 83869,
115
+ 220,
116
+ 17,
117
+ 25,
118
+ 1634,
119
+ 38810,
120
+ 16197,
121
+ 1526,
122
+ 279,
123
+ 16550,
124
+ 11,
125
+ 23263,
126
+ 92080,
127
+ 320,
128
+ 12197,
129
+ 8,
130
+ 44219,
131
+ 803,
132
+ 1091,
133
+ 5021,
134
+ 92080,
135
+ 320,
136
+ 1151,
137
+ 8,
138
+ 979,
139
+ 807,
140
+ 13161,
141
+ 6819,
142
+ 34445,
143
+ 1959,
144
+ 419,
145
+ 374,
146
+ 13247,
147
+ 62524,
148
+ 71268,
149
+ 624,
150
+ 83869,
151
+ 220,
152
+ 18,
153
+ 25,
154
+ 1096,
155
+ 36775,
156
+ 6303,
157
+ 3100,
158
+ 4041,
159
+ 518,
160
+ 601,
161
+ 504,
162
+ 678,
163
+ 17934,
164
+ 315,
165
+ 279,
166
+ 12877,
167
+ 11,
168
+ 3259,
169
+ 432,
170
+ 4994,
171
+ 6303,
172
+ 382,
173
+ 4792,
174
+ 594,
175
+ 2326,
176
+ 22809,
177
+ 13,
178
+ 13646,
179
+ 432,
180
+ 63141,
181
+ 13,
182
+ 2308,
183
+ 1184,
184
+ 369,
185
+ 7102,
186
+ 476,
187
+ 11464,
188
+ 369,
189
+ 419,
190
+ 1959,
191
+ 1101,
192
+ 2326,
193
+ 22809,
194
+ 315,
195
+ 60276,
196
+ 13,
197
+ 154842,
198
+ 29975,
199
+ 4145,
200
+ 5610,
201
+ 678,
202
+ 7986,
203
+ 315,
204
+ 9430,
205
+ 3100,
206
+ 11,
207
+ 1817,
208
+ 20924,
209
+ 518,
210
+ 264,
211
+ 2155,
212
+ 45038,
213
+ 13,
214
+ 3197,
215
+ 38810,
216
+ 28730,
217
+ 9234,
218
+ 594,
219
+ 16550,
220
+ 11,
221
+ 279,
222
+ 23263,
223
+ 6303,
224
+ 92080,
225
+ 44219,
226
+ 1007,
227
+ 6819,
228
+ 34445,
229
+ 1753,
230
+ 803,
231
+ 1091,
232
+ 5021,
233
+ 92080,
234
+ 1075,
235
+ 2518,
236
+ 27901,
237
+ 24768,
238
+ 2598,
239
+ 13247,
240
+ 62524,
241
+ 71268,
242
+ 13,
243
+ 1096,
244
+ 36775,
245
+ 6303,
246
+ 3100,
247
+ 24417,
248
+ 1039,
249
+ 6414,
250
+ 504,
251
+ 1449,
252
+ 5106,
253
+ 304,
254
+ 279,
255
+ 12877,
256
+ 11,
257
+ 3259,
258
+ 279,
259
+ 12877,
260
+ 4994,
261
+ 6303,
262
+ 13,
263
+ 154827,
264
+ 15973,
265
+ 4238,
266
+ 4829,
267
+ 311,
268
+ 1414,
269
+ 279,
270
+ 16134,
271
+ 323,
272
+ 9494,
273
+ 429,
274
+ 279,
275
+ 12877,
276
+ 374,
277
+ 6303,
278
+ 1576,
279
+ 508,
280
+ 78832,
281
+ 1718,
282
+ 62,
283
+ 15,
284
+ 60,
285
+ 1576,
286
+ 508,
287
+ 78832,
288
+ 1718,
289
+ 62,
290
+ 16,
291
+ 60,
292
+ 1576,
293
+ 508,
294
+ 78832,
295
+ 1718,
296
+ 62,
297
+ 17,
298
+ 29450,
299
+ 785,
300
+ 11646,
301
+ 5944,
302
+ 374,
303
+ 25,
304
+ 330,
305
+ 15973,
306
+ 4238,
307
+ 4829,
308
+ 311,
309
+ 1414,
310
+ 279,
311
+ 16134,
312
+ 323,
313
+ 9494,
314
+ 429,
315
+ 279,
316
+ 12877,
317
+ 374,
318
+ 6303,
319
+ 1576,
320
+ 508,
321
+ 78832,
322
+ 1718,
323
+ 62,
324
+ 15,
325
+ 60,
326
+ 1576,
327
+ 508
328
+ ],
329
+ "T": 1.0,
330
+ "tail_periodicity": 0.27586206896551724,
331
+ "tail_period": 41,
332
+ "seq": 5001
333
+ }
334
+ ],
335
+ "wall_s": 162.25822377204895,
336
+ "mem_peak_gb_rank0": 103.3275008,
337
+ "symm_buffers": 4,
338
+ "symm_ok": true,
339
+ "job_s": 187.17249584197998
340
+ }
@@ -0,0 +1,6 @@
1
+ """quantumInfer vLLM speculative-decoding plugin."""
2
+
3
+
4
+ def quantum_infer_plugin():
5
+ from .spec import register
6
+ register()
@@ -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,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*"]
@@ -0,0 +1,6 @@
1
+ """quantumInfer vLLM speculative-decoding plugin."""
2
+
3
+
4
+ def quantum_infer_plugin():
5
+ from .spec import register
6
+ register()
@@ -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,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantum-infer-vllm
3
+ Version: 0.3.0
4
+ Summary: quantumInfer hybrid MTP/suffix/Jacobi speculative proposer plugin for vLLM
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: vllm<0.35.0,>=0.34.0
@@ -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,2 @@
1
+ [vllm.general_plugins]
2
+ quantum_infer = quantum_infer_vllm:quantum_infer_plugin
@@ -0,0 +1 @@
1
+ vllm<0.35.0,>=0.34.0
@@ -0,0 +1 @@
1
+ quantum_infer_vllm