[QSA] Tag every raw-key ring row and validate it before pooling

The fused pre-indexer could read a stale or uncommitted raw-key ring row and
pass its int64 tail to RoPE as a position (illegal address). The writer now
tags each row with logical_position + 1; the reader checks the tag of every
source row and, on a mismatch, masks the pooled load, the RoPE-tail read and
the compressed-slot store. New guard site 11 (always fatal under warn). The
KV pool size is unchanged.

Co-Authored-By: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 20:01:26 +07:00
co-authored by Hinata
parent ad80cac06d
commit fba504d5bb
12 changed files with 463 additions and 16 deletions
+15
View File
@@ -867,6 +867,21 @@ class KVCacheManager:
ids.extend(mgr.take_new_block_ids())
return ids
def take_new_ring_block_ids(self) -> list[int]:
"""Drain ring blocks claimed since the last call (ring-row tag clear).
Independent of KV zeroing: every claim is returned."""
ids: list[int] = []
for mgr in self.coordinator.single_type_managers:
ids.extend(mgr.take_new_ring_block_ids())
return ids
def get_ring_block_ids(self, request_id: str) -> list[int]:
"""The request's ring (CircularBufferSpec) block ids, all groups."""
ids: list[int] = []
for mgr in self.coordinator.single_type_managers:
ids.extend(mgr.get_ring_block_ids(request_id))
return ids
def record_blocks_for_zeroing(self, request_id: str, start_token: int) -> None:
"""Re-record the request's blocks from start_token onwards for
zeroing, e.g. blocks a failed async KV load left unwritten.
+7
View File
@@ -301,6 +301,13 @@ class SchedulerOutput:
# preventing stale NaN/data from corrupting attention or SSM computation.
new_block_ids_to_zero: list[int] | None = None
# v2.2 ring-row tag fix: ring (CircularBufferSpec) blocks claimed during this
# scheduling step. Independent of new_block_ids_to_zero and of
# needs_kv_cache_zeroing: the worker clears only the rows' tag words, after
# the zeroer and before any copy or forward of this step, i.e. before the
# new owner's first read or write of the ring.
new_ring_block_ids_to_clear: list[int] | None = None
# CoW copies to apply after zeroing new blocks and before forward.
kv_cache_block_copies: list[KVCacheBlockCopy] | None = None
+24
View File
@@ -366,6 +366,11 @@ class Scheduler(SchedulerInterface):
# Bind after construction so connectors can access the cache manager.
if self.connector is not None:
self.connector.bind_kv_cache_manager(self.kv_cache_manager)
# Ring blocks an async KV load is about to fill. Their tag clear
# is skipped for the same reason as zeroing (it could land after the
# out-of-band write and wipe the producer's committed tags). Tracked
# whatever needs_kv_cache_zeroing says, like the clear itself.
self._skip_ring_clear_block_ids: set[int] = set()
self.use_pp = self.parallel_config.pipeline_parallel_size > 1
self.use_v2_model_runner = vllm_config.use_v2_model_runner
@@ -1333,6 +1338,12 @@ class Scheduler(SchedulerInterface):
request.num_computed_tokens = num_computed_tokens
self._inflight_prefills.add(request)
self._set_kv_fetch_stage(request, KV_FETCH_IN_PROGRESS)
# Same race for the ring's tag clear; the load
# brings the producer's rows and tags (or none, and the
# reader then fails closed on the missing history).
self._skip_ring_clear_block_ids.update(
self.kv_cache_manager.get_ring_block_ids(request.request_id)
)
skip_request(request_queue)
continue
@@ -1525,6 +1536,8 @@ class Scheduler(SchedulerInterface):
finished_req_ids=self.finished_req_ids,
free_encoder_mm_hashes=self.encoder_cache_manager.get_freed_mm_hashes(),
new_block_ids_to_zero=self._get_new_block_ids_to_zero(),
# Drained every step, never gated on KV zeroing.
new_ring_block_ids_to_clear=self._get_new_ring_block_ids_to_clear(),
has_sync_kv_loads=has_sync_kv_loads,
kv_cache_block_copies=pending_kv_cache_block_copies,
kv_connector_block_state=kv_connector_block_state,
@@ -1572,6 +1585,17 @@ class Scheduler(SchedulerInterface):
) -> KVConnectorMetadata:
return connector.build_connector_meta(scheduler_output)
def _get_new_ring_block_ids_to_clear(self) -> list[int] | None:
"""Ring claims of this step whose tag words the worker clears.
Unconditional (not under needs_kv_cache_zeroing); only blocks an async
KV load is about to write are left out."""
ids = self.kv_cache_manager.take_new_ring_block_ids()
if self._skip_ring_clear_block_ids:
skip = self._skip_ring_clear_block_ids
ids = [b for b in ids if b not in skip]
skip.clear()
return ids or None
def _get_new_block_ids_to_zero(self) -> list[int] | None:
# Drain new attention block ids every step so the manager-side list
# does not grow unbounded; only kv-cache zeroing consumes them.
@@ -121,6 +121,12 @@ class SingleTypeKVCacheManager(ABC):
and not isinstance(kv_cache_spec, CircularBufferSpec)
)
self.new_block_ids: list[int] = []
# v2.2 ring-row tag fix: ring blocks claimed since the last drain. The ring stays
# OUT of whole-block zeroing above; instead every claim is recorded
# UNCONDITIONALLY (never under needs_kv_cache_zeroing) so the worker
# clears the rows' tag words before the new owner's first step. Only
# CircularBufferManager appends here.
self.new_ring_block_ids: list[int] = []
# Mapping from request ID to blocks to track the blocks allocated
# for each request, so that we can free the blocks when the request
@@ -422,6 +428,17 @@ class SingleTypeKVCacheManager(ABC):
self.new_block_ids = []
return ids
def take_new_ring_block_ids(self) -> list[int]:
"""Drain ring blocks claimed since the last call; empty for
every manager but CircularBufferManager."""
ids = self.new_ring_block_ids
self.new_ring_block_ids = []
return ids
def get_ring_block_ids(self, request_id: str) -> list[int]:
"""The request's ring block ids; empty for non-ring managers."""
return []
def take_pending_cow_copies(
self,
) -> list[tuple[KVCacheBlock, KVCacheBlock]]:
@@ -1214,8 +1231,37 @@ class CircularBufferManager(FullAttentionManager):
req_blocks.extend(new_blocks)
if self._record_new_block_ids and record_for_zeroing:
self.new_block_ids.extend(block.block_id for block in new_blocks)
# Unconditional -- not gated on needs_kv_cache_zeroing.
self.new_ring_block_ids.extend(block.block_id for block in new_blocks)
return new_blocks
def take_new_ring_block_ids(self) -> list[int]:
"""Drain the ring blocks claimed since the last call, keeping only
blocks a request of this manager still holds, in claim order, once.
A block claimed and then freed within the same scheduling pass (the
request was preempted after its allocation) may already belong to
another group by the time the worker acts; clearing its tag words
there would write into that group's page, so it is dropped here.
"""
claimed = self.new_ring_block_ids
self.new_ring_block_ids = []
if not claimed:
return []
held = {
block.block_id for blocks in self.req_to_blocks.values() for block in blocks
}
out: list[int] = []
seen: set[int] = set()
for block_id in claimed:
if block_id in held and block_id not in seen:
seen.add(block_id)
out.append(block_id)
return out
def get_ring_block_ids(self, request_id: str) -> list[int]:
return [block.block_id for block in self.req_to_blocks.get(request_id, ())]
def get_num_blocks_to_allocate(
self,
request_id: str,
+10
View File
@@ -180,6 +180,7 @@ from vllm.v1.worker.gpu.ubatch_utils import (
maybe_build_ubatch_runner,
)
from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin
from vllm.v1.worker.ring_tags import clear_ring_row_tags, ring_tag_layers
from vllm.v1.worker.utils import (
KVBlockZeroer,
clear_layer_kv_caches,
@@ -1326,6 +1327,15 @@ class GPUModelRunner(LoRAModelRunnerMixin):
assert self.kv_block_zeroer is not None
self.kv_block_zeroer.zero_block_ids(scheduler_output.new_block_ids_to_zero)
# v2.2 ring-row tag fix: clear the tag words of newly claimed ring blocks. Not
# under the zeroing gate; after the zeroer, before copies and forward.
if scheduler_output.new_ring_block_ids_to_clear:
clear_ring_row_tags(
ring_tag_layers(self.compilation_config.static_forward_context),
scheduler_output.new_ring_block_ids_to_clear,
self.device,
)
# Apply copy-on-write block copies for partial prefix-cache hits, after
# zeroing new blocks and before the forward pass reads them.
if scheduler_output.kv_cache_block_copies:
+9
View File
@@ -214,6 +214,7 @@ from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
from vllm.v1.worker.gpu_ubatch_wrapper import UBatchWrapper
from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin
from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin
from vllm.v1.worker.ring_tags import clear_ring_row_tags, ring_tag_layers
from vllm.v1.worker.ubatch_utils import (
UBatchSlices,
check_ubatch_thresholds,
@@ -1218,6 +1219,14 @@ class GPUModelRunner(
# stale NaN/data from corrupting attention or SSM computation.
if scheduler_output.new_block_ids_to_zero:
self._zero_block_ids(scheduler_output.new_block_ids_to_zero)
# v2.2 ring-row tag fix: clear the tag words of newly claimed ring blocks. Not
# under the zeroing gate; after the zeroer, before copies and forward.
if scheduler_output.new_ring_block_ids_to_clear:
clear_ring_row_tags(
ring_tag_layers(self.compilation_config.static_forward_context),
scheduler_output.new_ring_block_ids_to_clear,
self.device,
)
if scheduler_output.kv_cache_block_copies:
copy_kv_cache_blocks_inplace(
self.kv_caches,
+72 -1
View File
@@ -146,7 +146,53 @@ SITE_QSA_ROPE_POS = 9
# The skip itself is the earlier behaviour; the count is the instrument
# for the v2.2 ring-row reconciliation. Telemetry only: warn.
SITE_QSA_RING_SKIP = 10
NUM_SITES = 11
# The pre-indexer found a historical raw-key ring row whose tag is
# not `logical_position + 1` -- a row this request never committed for that
# position (claim residue, a skipped suffix commit, a stale mapping). The
# group's pooled load, its RoPE-tail read and its compressed-slot store are all
# MASKED, so the compressed slot is left unwritten: durable damage, fatal.
# Unlike the other sites the three slots form ONE coherent record, claimed
# first-offender-wins with atomic_cas: slot 0 = rows flagged (all offenders),
# slot 1 = packed (layer + 1, batch request row, source logical position) of
# the first offender, slot 2 = the tag that offender's row actually held.
# Decode slot 1 with decode_ring_record().
SITE_QSA_RING_UNCOMMITTED = 11
NUM_SITES = 12
# Bit layout of the SITE_QSA_RING_UNCOMMITTED record (before GUARD_BIAS).
RING_RECORD_POS_BITS = 32
RING_RECORD_REQ_BITS = 16
RING_RECORD_LAYER_BITS = 14
def encode_ring_record(layer_id: int, request_row: int, position: int) -> int:
"""Python twin of the kernel's packing (tests; the kernel inlines it)."""
layer = (int(layer_id) + 1) & ((1 << RING_RECORD_LAYER_BITS) - 1)
row = int(request_row) & ((1 << RING_RECORD_REQ_BITS) - 1)
pos = int(position) & ((1 << RING_RECORD_POS_BITS) - 1)
return (
(layer << (RING_RECORD_REQ_BITS + RING_RECORD_POS_BITS))
| (row << RING_RECORD_POS_BITS)
| pos
)
def decode_ring_record(biased: int) -> dict[str, int] | None:
"""Unpack slot 1 of SITE_QSA_RING_UNCOMMITTED. ``layer`` is -1 when the
launcher was not given one. None = nothing recorded (or not yet visible)."""
value = decode_slot(biased)
if value is None:
return None
pos_mask = (1 << RING_RECORD_POS_BITS) - 1
req_mask = (1 << RING_RECORD_REQ_BITS) - 1
layer_mask = (1 << RING_RECORD_LAYER_BITS) - 1
return {
"layer": ((value >> (RING_RECORD_REQ_BITS + RING_RECORD_POS_BITS)) & layer_mask)
- 1,
"request_row": (value >> RING_RECORD_POS_BITS) & req_mask,
"source_position": value & pos_mask,
}
SITE_NAMES = {
SITE_MAMBA_COPY: "_copy_mamba_state_block (block-table row/column)",
@@ -165,6 +211,10 @@ SITE_NAMES = {
SITE_QSA_RING_SKIP: "_qsa_pre_indexer_kernel suffix commit SKIPPED "
"(state slot < 0 or >= ring capacity; slot 1 = token index, "
"slot 2 = state slot value)",
SITE_QSA_RING_UNCOMMITTED: "_qsa_pre_indexer_kernel historical ring row "
"UNCOMMITTED (tag != logical_position + 1; group load, RoPE tail and "
"compressed-slot store masked; slot 1 = packed first-offender record, "
"slot 2 = the tag its row held)",
}
@@ -373,6 +423,14 @@ _ALWAYS_FATAL_SITES: set[int] = set()
# whatever VLLM_E2_GUARD_MODE says. (bounds-guard instrumentation, rope site)
_ALWAYS_FATAL_SITES.add(SITE_QSA_ROPE_POS)
# An uncommitted ring row leaves the group's compressed slot
# UNWRITTEN (the store is masked, there is no correct value to store), and the
# selection kernels will read that slot on every later step. That is durable
# damage by the same argument as the rope site, so it stops the rank under
# warn too. The failure boundary is the rank, not the request: per-request
# containment (discard + quarantine + TP/PP coordination) is not implemented.
_ALWAYS_FATAL_SITES.add(SITE_QSA_RING_UNCOMMITTED)
def _normalize(device: torch.device) -> torch.device:
"""torch.device("cuda") and torch.device("cuda:0") are different dict keys.
@@ -479,6 +537,19 @@ def _report_rows(device: torch.device, rows: list[list[int]]) -> None:
_seen[(device, site)] = n_masked
row = decode_slot(biased_row)
val = decode_slot(biased_val)
if site == SITE_QSA_RING_UNCOMMITTED:
# One coherent first-offender record, not independent maxima.
record = decode_ring_record(biased_row)
msg = (
f"ring-row tag guard masked {n_masked} uncommitted historical "
f"ring row(s) in {SITE_NAMES[site]} on {device}; first "
f"offender {record}, its row held tag {val} (expected "
f"source_position + 1). The group was not pooled and its "
f"compressed slot was NOT written."
)
logger.warning("%s", msg)
_arm(msg)
continue
msg = (
f"bounds guard masked {n_masked} out-of-range access(es) "
f"in {SITE_NAMES.get(site, site)} on {device} "
+63
View File
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""v2.2 ring-row tag fix: worker side of the ring-row tag clear.
The scheduler reports every newly claimed ring (``CircularBufferSpec``) block
in ``SchedulerOutput.new_ring_block_ids_to_clear``, whether or not KV zeroing
is on. Before the step's forward, the runner hands them to every layer that
keeps a tagged ring (``clear_ring_row_tags``; today ``QSAKeyStateCache``),
which zeroes only the tag word of each row. A zero tag never validates, so the
new owner cannot pool a row it did not commit itself, whatever the previous
occupant (or another group that held the block) left there.
ORDER. The runners call this right after the KV zeroer and before the CoW
copies and the forward, on the same stream, inside the same execute_model as
the claim's first step. So: previous owner's work done (deferred free) ->
claim -> tag clear -> new owner's first read/write.
"""
from collections.abc import Iterable, Mapping
import torch
def ring_tag_layers(static_forward_context: Mapping[str, object]) -> list:
"""Layers of this worker that keep a tagged ring."""
return [
layer
for layer in static_forward_context.values()
if callable(getattr(layer, "clear_ring_row_tags", None))
]
def clear_ring_row_tags(
layers: Iterable,
block_ids: list[int],
device: torch.device,
) -> int:
"""Zero the tag word of every row of ``block_ids`` in every layer.
Returns the number of layers cleared. Raises (fail loud) on a block id
outside a layer's pool: an index_fill_ with a bad index is a device-side
assert, far from its cause."""
if not block_ids:
return 0
layers = list(layers)
if not layers:
return 0
lo, hi = min(block_ids), max(block_ids)
index = torch.tensor(block_ids, dtype=torch.long, device=device)
for layer in layers:
tags = getattr(layer, "ring_tag_cache", None)
if tags is None:
raise RuntimeError(
f"ring tag clear: layer {getattr(layer, 'prefix', layer)!r} has "
"no bound ring_tag_cache"
)
if lo < 0 or hi >= tags.shape[0]:
raise ValueError(
f"ring tag clear: block ids [{lo}, {hi}] outside the pool of "
f"{tags.shape[0]} blocks ({getattr(layer, 'prefix', layer)!r})"
)
layer.clear_ring_row_tags(index)
return len(layers)