ax-engine-vllm 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ """AX Engine for vLLM."""
@@ -0,0 +1,458 @@
1
+ """Acceptance-adaptive speculative length for vLLM, with a policy that reloads at runtime.
2
+
3
+ vLLM 0.34.0rc1.dev1105+g2f170a0fe can change the number of speculative tokens K every step, but
4
+ only from a static table indexed by batch size (`num_speculative_tokens_per_batch_size`). The
5
+ drafter captures CUDA graphs for every K that table contains. This hook keeps that machinery and
6
+ updates the scheduler's batch-size -> K table when the policy changes a slot's K. It uses
7
+ SGLang's `--speculative-adaptive` policy, with an EMA of accepted drafts per verify,
8
+ a step up when the EMA exceeds `K - 0.5 + up_hysteresis`, a step down when it falls to
9
+ `K_prev - 0.5 + down_hysteresis`, after `warmup_batches` and every `update_interval` verifies.
10
+
11
+ AX_VLLM_ADAPTIVE_K=<path> enables it. The JSON file has the SGLang adaptive format, keyed by
12
+ batch size: {"version": 3, "ema_alpha": 0.2, "1": {"candidate_steps": [3, 4, 5, 7]}, "4": {...}}.
13
+ Candidate steps must be K values of the boot schedule, so boot with a schedule that lists every K
14
+ to explore (e.g. [[1,1,7],[2,2,6],[3,3,5],[4,4,4],[5,5,3],[6,8,2]] with max_num_seqs=8). The file
15
+ is re-read when its file metadata changes (polled at most every AX_VLLM_ADAPTIVE_K_POLL_S,
16
+ default 0.5 s); write a temporary file and rename it over the path so a poll never sees a partial
17
+ policy. A rejected file is re-read on later polls until it parses, so a policy caught mid-write is
18
+ still applied once complete. After a reload every slot restarts its EMA and warmup. `<path>.ack`
19
+ records each reload and how many verify batches ran at each K under the previous policy. Without
20
+ the file the hook keeps the boot table, and removing the file restores it. File I/O and policy
21
+ validation run off the scheduler thread. Batch sizes the boot schedule runs without speculation
22
+ (K 0) stay at 0.
23
+
24
+ vLLM drafts at the end of a step for each request it scheduled, and a request verifies those drafts
25
+ the next time it is scheduled, which can be several steps later when the token budget skips it.
26
+ The hook records the slot, K, slot revision and policy generation that drafted for each request,
27
+ and feeds a verify batch back to that slot only when every request in it carries the same record
28
+ and the slot still runs that K. Mixed batches, batches that verify only part of the drafts, and
29
+ drafts padded onto new or resumed requests (which have no record) are left out. The worker's
30
+ drafted and verified counts must both match K for every request with scheduled drafts.
31
+ """
32
+
33
+ from bisect import bisect_right
34
+ from collections import deque
35
+ from concurrent.futures import ThreadPoolExecutor
36
+ from contextlib import suppress
37
+ from dataclasses import dataclass
38
+ import json
39
+ import logging
40
+ import math
41
+ import os
42
+ from pathlib import Path
43
+ import stat
44
+ import time
45
+ from uuid import uuid4
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+ def _real(cfg, key, default):
51
+ value = cfg.get(key, default)
52
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
53
+ raise ValueError(f"{key} must be a finite number, got {value!r}")
54
+ return float(value)
55
+
56
+
57
+ def _count(cfg, key, default, minimum):
58
+ value = cfg.get(key, default)
59
+ if type(value) is not int or value < minimum:
60
+ raise ValueError(f"{key} must be an integer >= {minimum}, got {value!r}")
61
+ return value
62
+
63
+
64
+ class Slot:
65
+ """SGLang's AdaptiveStepSlot policy (without the zero-step no-spec mode)."""
66
+
67
+ def __init__(self, initial_steps, cfg):
68
+ self.candidate_steps = sorted(set(cfg["candidate_steps"]))
69
+ self.ema_alpha = _real(cfg, "ema_alpha", 0.2)
70
+ if not 0 < self.ema_alpha <= 1:
71
+ raise ValueError(f"ema_alpha must be in (0, 1], got {self.ema_alpha!r}")
72
+ self.update_interval = _count(cfg, "update_interval", 5, 1)
73
+ self.warmup_batches = _count(cfg, "warmup_batches", 10, 0)
74
+ self.down_hysteresis = _real(cfg, "down_hysteresis", -0.25)
75
+ self.up_hysteresis = _real(cfg, "up_hysteresis", 0.0)
76
+ if initial_steps in self.candidate_steps:
77
+ self.current_steps = initial_steps
78
+ else:
79
+ self.current_steps = self.candidate_steps[len(self.candidate_steps) // 2]
80
+ self.ema = float(self.current_steps - 1)
81
+ self.batches = 0
82
+ self.revision = 0
83
+
84
+ def update(self, accepted):
85
+ self.ema = (1 - self.ema_alpha) * self.ema + self.ema_alpha * (sum(accepted) / len(accepted))
86
+ self.batches += 1
87
+ if self.batches <= self.warmup_batches or (self.batches - self.warmup_batches) % self.update_interval:
88
+ return
89
+ steps = self.candidate_steps
90
+ idx = old = steps.index(self.current_steps)
91
+ while idx > 0 and self.ema <= steps[idx - 1] - 0.5 + self.down_hysteresis:
92
+ idx -= 1
93
+ if idx == old:
94
+ while idx < len(steps) - 1 and self.ema > steps[idx] - 0.5 + self.up_hysteresis:
95
+ idx += 1
96
+ if idx != old:
97
+ self.current_steps = steps[idx]
98
+ self.revision += 1
99
+
100
+
101
+ @dataclass
102
+ class PolicyUpdate:
103
+ signature: tuple[int, ...] | None
104
+ version: object = None
105
+ slots: dict[int, Slot] | None = None
106
+ error: str | None = None
107
+
108
+
109
+ class Controller:
110
+ def __init__(self, path, boot_table, poll_s=0.5, clock=time.monotonic, *,
111
+ ack_path=None, benchmark=False):
112
+ self.path = path
113
+ self.ack_path = Path(ack_path) if ack_path is not None else Path(f"{path}.ack")
114
+ if os.path.abspath(self.ack_path) == os.path.abspath(self.path):
115
+ raise ValueError("Adaptive K acknowledgement must use a different path from the policy")
116
+ self.poll_s = poll_s
117
+ self.clock = clock
118
+ self.boot_table = list(boot_table)
119
+ self.allowed = sorted(set(boot_table[1:]) - {0})
120
+ self.slots = None # None: keep the boot table
121
+ self.routes = None
122
+ self.signature = None # stat signature of the applied file
123
+ self.rejected = None # signature of a file that failed to parse, re-read until it does
124
+ self.last_rejection = None # (version, error) of the last acknowledged rejection
125
+ self.next_check = 0.0
126
+ self.step_counts = {}
127
+ self.generation = 0 # bumped whenever the policy changes; drafts carry the one they ran under
128
+ self.table_dirty = False
129
+ self.pending = None
130
+ self.benchmark_steps = deque(maxlen=65536) if benchmark else None
131
+ self.benchmark_truncated = False
132
+ self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ax-adaptive-k")
133
+
134
+ def maybe_reload(self):
135
+ if self.pending is None:
136
+ now = self.clock()
137
+ if now < self.next_check:
138
+ return
139
+ self.next_check = now + self.poll_s
140
+ self.pending = self.executor.submit(self._read_policy, self.signature)
141
+ if self.pending.done():
142
+ future, self.pending = self.pending, None
143
+ update = future.result()
144
+ if update is not None:
145
+ self._apply_policy(update)
146
+
147
+ def close(self):
148
+ self.executor.shutdown(wait=False)
149
+
150
+ def _read_policy(self, applied_signature):
151
+ try:
152
+ st = os.stat(self.path)
153
+ except FileNotFoundError:
154
+ return PolicyUpdate(None)
155
+ except OSError as exc:
156
+ logger.warning("AX vLLM: could not stat adaptive K config: %s", exc)
157
+ return
158
+ signature = _signature(st)
159
+ if signature == applied_signature:
160
+ return
161
+ cfg = None
162
+ try:
163
+ if not stat.S_ISREG(st.st_mode):
164
+ raise ValueError("adaptive K config must be a regular file")
165
+ with open(self.path, "rb", opener=_open_policy) as f:
166
+ opened = os.fstat(f.fileno())
167
+ if not stat.S_ISREG(opened.st_mode):
168
+ raise ValueError("adaptive K config must be a regular file")
169
+ # An atomic replacement can land between stat and open. Bind
170
+ # the bytes to the opened file and discard a changing snapshot.
171
+ signature = _signature(opened)
172
+ if signature == applied_signature:
173
+ return
174
+ data = f.read()
175
+ if signature != _signature(os.fstat(f.fileno())) or signature != _signature(os.stat(self.path)):
176
+ return
177
+ cfg = json.loads(data)
178
+ if not isinstance(cfg, dict):
179
+ raise ValueError("adaptive K config must be a JSON object")
180
+ shared = {k: v for k, v in cfg.items() if not k.isdigit() and k != "version"}
181
+ slots = {}
182
+ allowed = set(self.allowed)
183
+ for key, entry in cfg.items():
184
+ if not key.isdigit():
185
+ continue
186
+ batch_size = int(key)
187
+ if batch_size in slots:
188
+ raise ValueError(f"batch size key {key!r} repeats batch size {batch_size}")
189
+ if not isinstance(entry, dict):
190
+ raise ValueError(f"BS {key}: policy must be a JSON object")
191
+ steps = entry.get("candidate_steps")
192
+ if (not isinstance(steps, list) or not steps
193
+ or any(type(step) is not int for step in steps)
194
+ or not set(steps) <= allowed):
195
+ raise ValueError(f"BS {key}: candidate_steps {steps!r} must be a non-empty subset of "
196
+ f"the boot schedule's K values {self.allowed}")
197
+ slots[batch_size] = Slot(self.boot_table[min(batch_size, len(self.boot_table) - 1)],
198
+ {**shared, **entry})
199
+ if not slots:
200
+ raise ValueError("live config has no batch-size entries")
201
+ except FileNotFoundError:
202
+ return PolicyUpdate(None)
203
+ except (OSError, ValueError, KeyError, TypeError, OverflowError, RecursionError) as exc:
204
+ version = cfg.get("version") if isinstance(cfg, dict) else None
205
+ return PolicyUpdate(signature, version, error=str(exc))
206
+ return PolicyUpdate(signature, cfg.get("version"), slots=slots)
207
+
208
+ def _apply_policy(self, update):
209
+ if update.signature is None:
210
+ self.signature = self.rejected = self.last_rejection = None
211
+ if self.slots is not None:
212
+ counts, self.step_counts = self.step_counts, {}
213
+ self.slots = self.routes = None
214
+ self.generation += 1
215
+ self.table_dirty = True
216
+ self._ack({"version": None, "applied": True, "boot_table": True, "step_counts": counts},
217
+ reset=True)
218
+ logger.info("AX vLLM: adaptive K config removed; boot schedule restored")
219
+ return
220
+ if update.error is not None:
221
+ retry = update.signature == self.rejected
222
+ self.rejected = update.signature
223
+ rejection = (update.version, update.error)
224
+ if retry and rejection == self.last_rejection:
225
+ return # already acknowledged; keep waiting for a complete file
226
+ self.last_rejection = rejection
227
+ # The previous policy keeps running, so its counts carry on into the next applied ack.
228
+ self._ack({"version": update.version, "applied": False, "error": update.error,
229
+ "step_counts": dict(self.step_counts)})
230
+ logger.warning("AX vLLM: adaptive K config rejected: %s", update.error)
231
+ return
232
+ self.signature, self.rejected, self.last_rejection = update.signature, None, None
233
+ counts, self.step_counts = self.step_counts, {}
234
+ self.slots = slots = update.slots
235
+ boundaries = sorted(slots)
236
+ self.routes = [
237
+ slots[boundaries[max(bisect_right(boundaries, size) - 1, 0)]] if boot else None
238
+ for size, boot in enumerate(self.boot_table)
239
+ ]
240
+ self.generation += 1
241
+ self.table_dirty = True
242
+ self._ack({"version": update.version, "applied": True, "step_counts": counts}, reset=True)
243
+ logger.info("AX vLLM: adaptive K config version %s applied (%s)", update.version,
244
+ ", ".join(f"{bs}:{slots[bs].candidate_steps}" for bs in boundaries))
245
+
246
+ def _ack(self, payload, *, reset=False):
247
+ if self.benchmark_steps is not None:
248
+ payload["benchmark_steps"] = list(self.benchmark_steps)
249
+ payload["benchmark_truncated"] = self.benchmark_truncated
250
+ if reset:
251
+ self.benchmark_steps.clear()
252
+ self.benchmark_truncated = False
253
+ self.executor.submit(self._write_ack, payload)
254
+
255
+ def _write_ack(self, payload):
256
+ tmp = self.ack_path.with_name(f".{self.ack_path.name}.{uuid4().hex}.tmp")
257
+ created = False
258
+ try:
259
+ with tmp.open("x") as f:
260
+ created = True
261
+ json.dump(payload, f)
262
+ os.replace(tmp, self.ack_path)
263
+ created = False
264
+ except (OSError, ValueError, RecursionError) as exc:
265
+ logger.warning("AX vLLM: could not write adaptive K acknowledgement: %s", exc)
266
+ finally:
267
+ if created:
268
+ with suppress(OSError):
269
+ tmp.unlink()
270
+
271
+ def record_step(self, k, graph, verifying):
272
+ self.benchmark_truncated |= len(self.benchmark_steps) == self.benchmark_steps.maxlen
273
+ mode = graph.runtime_mode if graph is not None else None
274
+ self.benchmark_steps.append((time.monotonic_ns(), k, mode, verifying))
275
+
276
+ def fill(self, table):
277
+ """Write the K each batch size should use into the scheduler's dense table."""
278
+ if not self.table_dirty:
279
+ return
280
+ if self.routes is None:
281
+ table[1:] = self.boot_table[1:]
282
+ else:
283
+ # Batch sizes the boot schedule runs without speculation stay without it.
284
+ table[1:] = [slot.current_steps if slot is not None else 0 for slot in self.routes[1:]]
285
+ self.table_dirty = False
286
+
287
+ def decide(self, batch_size, steps):
288
+ """Name the slot and K one scheduled step drafts with, for the batch that verifies them.
289
+
290
+ `batch_size` is every request the step scheduled (prefill chunks included), the index the
291
+ scheduler read `steps` from.
292
+ """
293
+ if steps <= 0:
294
+ return None
295
+ slot = self.routes[batch_size] if self.routes is not None else None
296
+ if slot is not None and slot.current_steps != steps:
297
+ slot = None
298
+ return slot, steps, self.generation, slot.revision if slot is not None else None
299
+
300
+ def observe(self, accepted, drafted):
301
+ """Feed the accepted-draft counts of one verify batch and the `decide` result that drafted it."""
302
+ if not accepted or drafted is None:
303
+ return
304
+ slot, k, generation, revision = drafted
305
+ if generation != self.generation:
306
+ return # drafted under a policy since replaced or removed; its ack is already written
307
+ key = str(k)
308
+ self.step_counts[key] = self.step_counts.get(key, 0) + 1
309
+ # Skip drafts from a K the slot has since moved away from.
310
+ if slot is not None and slot.revision == revision:
311
+ slot.update(accepted)
312
+ if slot.revision != revision:
313
+ self.table_dirty = True
314
+ return k
315
+
316
+
317
+ def _signature(st):
318
+ return st.st_mtime_ns, st.st_ctime_ns, st.st_size, st.st_ino, st.st_dev
319
+
320
+
321
+ def _open_policy(path, flags):
322
+ return os.open(path, flags | os.O_NONBLOCK)
323
+
324
+
325
+ def _poll_interval(text, default=0.5):
326
+ if text is None:
327
+ return default
328
+ try:
329
+ value = float(text)
330
+ except ValueError:
331
+ value = math.nan
332
+ if not math.isfinite(value) or value < 0:
333
+ logger.warning("AX vLLM: AX_VLLM_ADAPTIVE_K_POLL_S=%r is not a non-negative number of seconds; "
334
+ "using %s", text, default)
335
+ return default
336
+ return value
337
+
338
+
339
+ def install(path: str) -> None:
340
+ from vllm.v1.core.sched.scheduler import Scheduler
341
+
342
+ if getattr(Scheduler.schedule, "_ax_adaptive_k", False):
343
+ return
344
+ init, schedule = Scheduler.__init__, Scheduler.schedule
345
+ update_from_output, make_stats = Scheduler.update_from_output, Scheduler.make_spec_decoding_stats
346
+ preempt_request, free_request = Scheduler._preempt_request, Scheduler._free_request
347
+ shutdown = Scheduler.shutdown
348
+ poll_s = _poll_interval(os.environ.get("AX_VLLM_ADAPTIVE_K_POLL_S"))
349
+ ack_override = os.environ.get("AX_VLLM_ADAPTIVE_K_ACK_PATH")
350
+ benchmark = os.environ.get("AX_VLLM_ADAPTIVE_K_BENCHMARK") == "1"
351
+
352
+ def __init__(self, *args, **kwargs):
353
+ init(self, *args, **kwargs)
354
+ self._ax_k = None
355
+ self._ax_k_batch = None
356
+ if self.dynamic_sd_lookup is None:
357
+ logger.warning("AX vLLM: AX_VLLM_ADAPTIVE_K needs a num_speculative_tokens_per_batch_size "
358
+ "schedule listing every K to explore (vLLM captures drafter graphs only for "
359
+ "those); keeping vLLM's fixed speculative length")
360
+ return
361
+ parallel = self.parallel_config
362
+ ack_path = ack_override or f"{path}.ack"
363
+ if parallel.data_parallel_size > 1:
364
+ ack_path = f"{ack_path}.{parallel.data_parallel_rank}"
365
+ self._ax_k = Controller(path, self.dynamic_sd_lookup, poll_s, ack_path=ack_path, benchmark=benchmark)
366
+ self._ax_k_req = {} # request id -> decide() record of the step that drafts for it
367
+ # decide() record each scheduled output's verify batch was drafted with, keyed by the
368
+ # output's id. Kept on the scheduler so SchedulerOutput, pickled to workers, stays unchanged.
369
+ self._ax_k_drafted = {}
370
+ self._ax_k.maybe_reload()
371
+ logger.info("AX vLLM: adaptive K from %s over K %s", path, self._ax_k.allowed)
372
+
373
+ def ax_schedule(self, *args, **kwargs):
374
+ if self._ax_k is None:
375
+ return schedule(self, *args, **kwargs)
376
+ self._ax_k.maybe_reload()
377
+ self._ax_k.fill(self.dynamic_sd_lookup)
378
+ output = schedule(self, *args, **kwargs)
379
+ if not output.num_scheduled_tokens:
380
+ return output
381
+ # This step verifies each request's pending drafts and drafts again for every request it runs.
382
+ spec = output.scheduled_spec_decode_tokens
383
+ if spec:
384
+ records = {self._ax_k_req.get(req_id) for req_id in spec}
385
+ record = records.pop() if len(records) == 1 else None
386
+ # A token budget or grammar that verifies only part of the drafts would read as low
387
+ # acceptance at the full K, so such batches stay out of the policy.
388
+ if record is not None and any(len(tokens) != record[1] for tokens in spec.values()):
389
+ record = None
390
+ if record is not None:
391
+ self._ax_k_drafted[id(output)] = record
392
+ steps = 0 if output.skip_drafts else output.num_spec_tokens_to_schedule
393
+ drafting = self._ax_k.decide(len(output.num_scheduled_tokens), steps)
394
+ for req_id in output.num_scheduled_tokens:
395
+ self._ax_k_req[req_id] = drafting
396
+ return output
397
+
398
+ def ax_update_from_output(self, scheduler_output, model_runner_output):
399
+ controller = self._ax_k
400
+ if controller is None:
401
+ return update_from_output(self, scheduler_output, model_runner_output)
402
+ drafted = self._ax_k_drafted.pop(id(scheduler_output), None)
403
+ spec = scheduler_output.scheduled_spec_decode_tokens
404
+ if drafted is not None and not any(
405
+ (request := self.requests.get(req_id)) is None
406
+ or request.is_finished()
407
+ or request.num_stale_output_tokens
408
+ for req_id in spec
409
+ ):
410
+ batch = self._ax_k_batch = []
411
+ try:
412
+ result = update_from_output(self, scheduler_output, model_runner_output)
413
+ finally:
414
+ self._ax_k_batch = None
415
+ k = drafted[1]
416
+ full_k = None
417
+ if len(batch) == len(spec) and all(
418
+ num_draft == num_verified == k and 0 <= accepted <= k
419
+ for num_draft, num_verified, accepted in batch
420
+ ):
421
+ full_k = controller.observe([accepted for _, _, accepted in batch], drafted)
422
+ else:
423
+ result = update_from_output(self, scheduler_output, model_runner_output)
424
+ full_k = None
425
+ if controller.benchmark_steps is not None and scheduler_output.num_scheduled_tokens:
426
+ controller.record_step(full_k, model_runner_output.cudagraph_stats, bool(spec))
427
+ return result
428
+
429
+ def ax_make_spec_decoding_stats(self, spec_decoding_stats, num_draft_tokens, num_accepted_tokens,
430
+ num_verified_tokens):
431
+ if self._ax_k_batch is not None:
432
+ self._ax_k_batch.append((num_draft_tokens, num_verified_tokens, num_accepted_tokens))
433
+ return make_stats(self, spec_decoding_stats, num_draft_tokens=num_draft_tokens,
434
+ num_accepted_tokens=num_accepted_tokens, num_verified_tokens=num_verified_tokens)
435
+
436
+ def ax_preempt_request(self, request, *args, **kwargs):
437
+ if self._ax_k is not None:
438
+ self._ax_k_req.pop(request.request_id, None) # its drafts are dropped with it
439
+ return preempt_request(self, request, *args, **kwargs)
440
+
441
+ def ax_free_request(self, request, *args, **kwargs):
442
+ if self._ax_k is not None:
443
+ self._ax_k_req.pop(request.request_id, None)
444
+ return free_request(self, request, *args, **kwargs)
445
+
446
+ def ax_shutdown(self, *args, **kwargs):
447
+ if self._ax_k is not None:
448
+ self._ax_k.close()
449
+ return shutdown(self, *args, **kwargs)
450
+
451
+ ax_schedule._ax_adaptive_k = True
452
+ Scheduler._preempt_request = ax_preempt_request
453
+ Scheduler._free_request = ax_free_request
454
+ Scheduler.__init__ = __init__
455
+ Scheduler.schedule = ax_schedule
456
+ Scheduler.update_from_output = ax_update_from_output
457
+ Scheduler.make_spec_decoding_stats = ax_make_spec_decoding_stats
458
+ Scheduler.shutdown = ax_shutdown
@@ -0,0 +1,68 @@
1
+ """Keep DFlash2 projection views strided through native FlashInfer KV writes."""
2
+
3
+ from functools import wraps
4
+ import logging
5
+
6
+
7
+ logger = logging.getLogger("vllm.ax_engine_vllm")
8
+ _installed = False
9
+
10
+
11
+ def _can_use_views(model, context_states, torch, flashinfer_impl):
12
+ if (not context_states.is_cuda or context_states.dtype != torch.bfloat16
13
+ or not getattr(model, "_attn_layers", None)
14
+ or model._fused_kv_weight is None
15
+ or model.layers[0].self_attn.v_scale is not None):
16
+ return False
17
+ return all(
18
+ type(layer.impl) is flashinfer_impl
19
+ and layer.impl.cache_dtype in ("auto", "bfloat16", "fp8", "fp8_e4m3")
20
+ and layer.impl.kv_sharing_target_layer_name is None
21
+ and isinstance(layer.kv_cache, torch.Tensor)
22
+ and layer.kv_cache.ndim == 4
23
+ and layer.kv_cache.numel() > 0
24
+ and layer.kv_cache.device == context_states.device
25
+ for layer in model._attn_layers
26
+ )
27
+
28
+
29
+ def install() -> None:
30
+ global _installed
31
+ if _installed:
32
+ return
33
+
34
+ import torch
35
+ from vllm import _custom_ops as ops
36
+ from vllm.model_executor.models.qwen3_dflash2 import DFlash2Qwen3Model
37
+ from vllm.v1.attention.backends.flashinfer import FlashInferImpl
38
+
39
+ cls = DFlash2Qwen3Model
40
+ original_project = cls._project_context_kv
41
+ original_norm = cls._normalize_context_k
42
+
43
+ @wraps(original_project)
44
+ def project(self, context_states, num_ctx, num_layers, num_kv_heads, head_dim):
45
+ if not _can_use_views(self, context_states, torch, FlashInferImpl):
46
+ return original_project(self, context_states, num_ctx, num_layers, num_kv_heads, head_dim)
47
+ kv = self._project_context_kv_token_major(
48
+ context_states, num_ctx, num_layers, num_kv_heads, head_dim,
49
+ )
50
+ if not getattr(self, "_ax_context_kv_views_logged", False):
51
+ logger.info("AX vLLM DFlash2 context KV views active")
52
+ self._ax_context_kv_views_logged = True
53
+ # The native RMSNorm reads the K strides. Cache insertion reads V's
54
+ # token stride and the contiguous head/channel dimensions.
55
+ return kv[:, :, 0].transpose(0, 1), kv[:, :, 1].transpose(0, 1)
56
+
57
+ @wraps(original_norm)
58
+ def normalize(self, all_k):
59
+ if all_k.is_contiguous():
60
+ return original_norm(self, all_k)
61
+ # RoPE views the output as one dense batch across layers and tokens.
62
+ out = torch.empty_like(all_k, memory_format=torch.contiguous_format)
63
+ ops.rms_norm(out, all_k, self._k_norm_weights, self._rms_norm_eps)
64
+ return out
65
+
66
+ cls._project_context_kv = project
67
+ cls._normalize_context_k = normalize
68
+ _installed = True