[BDE] Phase 1: engine-level KV cache management for DreamZero (RFC #4366) (#4534)

This commit is contained in:
Zhou Taichang authored and GitHub committed 2026-07-05 07:17:58 +08:00
1 parent aa21412c01
commit 86bdcaf3d5
27 files changed
+3795 -172

No files matched your search

@@ -0,0 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
"""AR-Diffusion engine-level KV cache helpers.
Thin glue over vLLM's paged KV stack (``KVCacheManager`` / ``BlockPool`` /
``SlidingWindowManager``), used by the AR-Diffusion Engine to manage KV for
AR-diffusion models. See ``BDE_doc/dreamzero_kv_phase1_plan.md``.
Layout: ``config`` (public knob) · ``paged`` (engine-generic paging mechanics +
chunk-window eviction spec) · ``manager`` (the ARDiffusionKVCache orchestrator + its
request adapter / pool builders) · ``state`` (the model-facing ARDiffusionKVState bridge).
"""
from vllm_omni.experimental.ar_diffusion.kv_cache.config import ARDiffusionKVConfig
from vllm_omni.experimental.ar_diffusion.kv_cache.manager import (
ARDiffusionKVCache,
ARDiffusionRequestAdapter,
build_kv_manager,
compute_num_blocks,
)
from vllm_omni.experimental.ar_diffusion.kv_cache.paged import (
ChunkWindowManager,
ChunkWindowSpec,
allocate_kv_pool_with_views,
chunk_slot_mapping,
compute_slot_mapping,
pool_write_chunk,
resident_block_ids,
)
from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import (
ARDiffusionPagedForwardContext,
ARDiffusionPagedLayerContext,
ARDiffusionPagedLayerInputs,
ar_diffusion_paged_attention,
paged_write_attn,
set_current_paged_kv_cache,
)
__all__ = [
"ARDiffusionKVCache",
"ARDiffusionKVConfig",
"ARDiffusionPagedForwardContext",
"ARDiffusionPagedLayerContext",
"ARDiffusionPagedLayerInputs",
"ARDiffusionRequestAdapter",
"ChunkWindowManager",
"ChunkWindowSpec",
"allocate_kv_pool_with_views",
"ar_diffusion_paged_attention",
"build_kv_manager",
"chunk_slot_mapping",
"compute_num_blocks",
"compute_slot_mapping",
"paged_write_attn",
"pool_write_chunk",
"resident_block_ids",
"set_current_paged_kv_cache",
]
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
"""Configuration for AR-Diffusion engine-level KV cache management."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class ARDiffusionKVConfig:
"""Settings for the AR-Diffusion paged KV cache.
Disabled by default: when ``enable`` is False the AR-Diffusion engine behaves exactly
like the base ``DiffusionEngine`` (no pool, no paged KV).
"""
enable: bool = False
# Persistent KV tokens materialized per AR chunk. For DreamZero this is
# ``num_frame_per_block * frame_seqlen``.
chunk_size: int = 0
# Resident window in chunks. ``None`` means full attention (no eviction).
window_chunks: int | None = None
# Protected leading chunks (attention sink); never evicted.
sink_chunks: int = 0
# DreamZero-style window reset vs. VGGT-style sliding replace.
reset_at_boundary: bool = False
# Fraction of free device memory budgeted for the AR-Diffusion KV pool.
gpu_memory_fraction: float = 0.1
# When CUDA graph / torch.compile is on (not enforce_eager), pre-capture the
# DiT graphs for every window-fill shape at load time via a synthetic rollout,
# so the serving run is fast from the first chunk. No effect when eager.
warmup_cudagraph: bool = True
# Also capture the post-window-boundary (reset-cycle) forward during warm-up.
warmup_capture_reset: bool = False
@property
def sliding_window(self) -> int | None:
"""Window size in tokens, or ``None`` for full attention."""
if self.window_chunks is None:
return None
return self.window_chunks * self.chunk_size
@@ -0,0 +1,497 @@
# SPDX-License-Identifier: Apache-2.0
"""ARDiffusionKVCache — the engine-level KV cache orchestrator for one AR-Diffusion model.
This is the *body* of AR-Diffusion's KV management: it owns a vLLM ``KVCacheManager`` (a
single chunk-window group) and the per-request adapter lifecycle, and exposes the
per-chunk operations a rollout needs — allocate, slot mapping, commit, window
lookup, free. It lives in the model runner (worker / GPU side), co-located with
the model and the KV tensors; the DreamZero pipeline calls these methods during a
rollout. The main-process ``ARDiffusionEngine`` only selects the engine and is otherwise
thin.
"""
from __future__ import annotations
import inspect
import os
from collections.abc import Sequence
import torch
from vllm.logger import init_logger
from vllm.v1.core.kv_cache_manager import KVCacheManager
from vllm.v1.kv_cache_interface import (
KVCacheConfig,
KVCacheGroupSpec,
KVCacheSpec,
KVCacheTensor,
)
from vllm.v1.request import RequestStatus
from vllm_omni.experimental.ar_diffusion.kv_cache.config import ARDiffusionKVConfig
from vllm_omni.experimental.ar_diffusion.kv_cache.paged import (
ChunkWindowSpec,
allocate_kv_pool_with_views,
chunk_slot_mapping,
pool_write_chunk,
resident_block_ids,
)
_log = init_logger(__name__)
class ARDiffusionRequestAdapter:
"""Duck-types the subset of ``vllm.v1.request.Request`` that the
``KVCacheManager`` reads (``allocate_slots`` / ``get_computed_blocks`` /
``free`` and the coordinator they call into).
It is intentionally NOT a full ``Request``. The conformance test exercises a
real ``KVCacheManager`` against this adapter so the surface cannot silently
drift across vLLM versions.
A AR-Diffusion request advances one *chunk* at a time: ``allocate_slots`` is called
once per chunk and ``num_computed_tokens`` advances only when a chunk is
committed (:meth:`on_chunk_committed`), so the ``T`` denoise steps of a chunk
reuse the same slots.
"""
def __init__(
self,
request_id: str,
*,
chunk_size: int,
prefill_prefix_tokens: int = 0,
) -> None:
self.request_id = request_id
self._chunk_size = chunk_size
self._prefill = prefill_prefix_tokens
self._completed_chunks = 0
# Filled only when cross-request prefix reuse is enabled (Phase 3).
self.block_hashes: list = []
self.skip_reading_prefix_cache = True
self.num_preemptions = 0
# vLLM watermark gate reads this; map the request lifecycle onto it.
self.status = RequestStatus.WAITING
@property
def num_computed_tokens(self) -> int:
"""Persistent KV already materialized (committed chunks + prefill)."""
return self._prefill + self._completed_chunks * self._chunk_size
@property
def num_tokens(self) -> int:
"""Total tokens once the in-flight chunk is committed."""
return self._prefill + (self._completed_chunks + 1) * self._chunk_size
@property
def num_prompt_tokens(self) -> int:
"""The prefill prefix length (read by ``cache_blocks`` when caching)."""
return self._prefill
@property
def completed_chunks(self) -> int:
return self._completed_chunks
def on_chunk_committed(self) -> None:
"""Advance by one chunk. Call once per chunk, not per denoise step."""
self._completed_chunks += 1
def compute_num_blocks(
available_bytes: int,
gpu_memory_fraction: float,
page_size_bytes: int,
) -> int:
"""Number of KV blocks that fit in ``fraction`` of the memory budget."""
if page_size_bytes <= 0:
raise ValueError(f"page_size_bytes must be positive, got {page_size_bytes}")
if not 0.0 < gpu_memory_fraction <= 1.0:
raise ValueError(f"gpu_memory_fraction must be in (0, 1], got {gpu_memory_fraction}")
budget = int(available_bytes * gpu_memory_fraction)
return max(0, budget // page_size_bytes)
def build_kv_manager(
spec: KVCacheSpec,
layer_names: Sequence[str],
num_blocks: int,
max_model_len: int,
*,
enable_caching: bool = False,
) -> KVCacheManager:
"""Build a ``KVCacheManager`` with a single KV cache group for ``spec``.
Args:
spec: The KV cache spec for the group (e.g. a ``ChunkWindowSpec``).
layer_names: Attention layers sharing this group's block table.
num_blocks: Total physical blocks in the pool.
max_model_len: Upper bound on a request's sequence length.
enable_caching: Cross-request prefix caching (Phase 3); off in Phase 1.
"""
layer_names = list(layer_names)
group = KVCacheGroupSpec(layer_names=layer_names, kv_cache_spec=spec)
tensors = [KVCacheTensor(size=spec.page_size_bytes * num_blocks, shared_by=layer_names)]
config = KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=tensors,
kv_cache_groups=[group],
)
kwargs = dict(max_model_len=max_model_len, hash_block_size=spec.block_size, enable_caching=enable_caching)
params = inspect.signature(KVCacheManager).parameters
if "scheduler_block_size" in params:
kwargs["scheduler_block_size"] = spec.block_size
if "max_num_batched_tokens" in params:
kwargs["max_num_batched_tokens"] = max_model_len
return KVCacheManager(config, **kwargs)
class ARDiffusionKVCache:
"""Owns the paged KV pool + per-request lifecycle for a AR-Diffusion model.
Build once per loaded model (dimensions known); then per request:
``begin_request`` → per chunk (``allocate_chunk`` → ``chunk_write_slots`` →
[model writes K/V] → ``commit_chunk``) → ``end_request``.
"""
def __init__(
self,
config: ARDiffusionKVConfig,
*,
num_layers: int,
num_kv_heads: int,
head_size: int,
dtype: torch.dtype,
block_size: int,
max_model_len: int,
available_bytes: int,
cross_attn_length: int = 0,
cross_attn_img_length: int = 0,
device: torch.device | None = None,
local_branches: int = 2,
num_frame_per_block: int = 1,
) -> None:
if not config.enable:
raise ValueError("ARDiffusionKVCache built with a disabled ARDiffusionKVConfig")
if config.window_chunks is None:
raise ValueError("Phase 1 requires a bounded window (window_chunks)")
if config.chunk_size <= 0:
raise ValueError("ARDiffusionKVConfig.chunk_size must be set (> 0)")
if local_branches not in (1, 2):
raise ValueError(f"local_branches must be 1 or 2, got {local_branches}")
self.config = config
# How many CFG branches allocate from THIS rank's pool. Under
# CFG-parallel x2 each rank executes exactly one branch (rank0 pos,
# rank1 neg) and the other branch's lazy contexts never allocate, so
# sizing for both would leave ~half the pool as idle capacity. A
# single-process run (TP1 / offline) executes both branches -> 2.
self.local_branches = local_branches
self.num_frame_per_block = max(1, int(num_frame_per_block))
self.block_size = block_size
self.num_layers = num_layers
self.num_kv_heads = num_kv_heads
self.head_size = head_size
self.dtype = dtype
self.cross_attn_length = cross_attn_length
self.device = device or torch.device("cpu")
self._adapters: dict[str, ARDiffusionRequestAdapter] = {}
# -- cross-attention pool (static, one-time-fill) -----------------------
# Cross-attn KV is computed once from the text encoder and never changes.
# Allocate a per-layer contiguous tensor for each branch: (2, text_len,
# kv_heads, head_dim) where dim-0 = [pos, neg]. Allocated separately
# from the self-attn block pool (static, small — ~400 MiB for
# DreamZero I2V). Both pools draw from the same GPU free memory but
# the cross-attn pool is sized directly rather than via the block pool
# budget (no eviction/chunk lifecycle needed).
self.cross_attn_img_length = cross_attn_img_length
self._cross_k: list[torch.Tensor] = []
self._cross_v: list[torch.Tensor] = []
# I2V image-token cross-attn pool. Like the text k/v, the image-token
# k_img/v_img are session-invariant (the conditioning image doesn't change),
# so they are cached once and read every denoise step — see
# WanI2VCrossAttention (#4154 caches these model-side too). Empty for T2V.
self._cross_k_img: list[torch.Tensor] = []
self._cross_v_img: list[torch.Tensor] = []
# Bytes the cross-attn pools consume directly (K+V, pos+neg, all layers).
# Deducted from the self-attn paged-pool budget below so the two
# allocations together stay within the GPU free-memory budget.
def _cross_pool_bytes(length: int) -> int:
return 2 * 2 * length * num_kv_heads * head_size * dtype.itemsize * num_layers
cross_total_bytes = 0
if device is not None and cross_attn_length > 0:
cross_shape = (2, cross_attn_length, num_kv_heads, head_size)
cross_bytes = _cross_pool_bytes(cross_attn_length)
cross_total_bytes += cross_bytes
for _ in range(num_layers):
self._cross_k.append(torch.empty(cross_shape, dtype=dtype, device=device))
self._cross_v.append(torch.empty(cross_shape, dtype=dtype, device=device))
_log.info(
"AR-Diffusion cross-attn pool: %d layers × (%d tok × %d heads × %d) = %.1f MiB",
num_layers,
cross_attn_length,
num_kv_heads,
head_size,
cross_bytes / (1024 * 1024),
)
if cross_attn_img_length > 0:
img_shape = (2, cross_attn_img_length, num_kv_heads, head_size)
cross_total_bytes += _cross_pool_bytes(cross_attn_img_length)
for _ in range(num_layers):
self._cross_k_img.append(torch.empty(img_shape, dtype=dtype, device=device))
self._cross_v_img.append(torch.empty(img_shape, dtype=dtype, device=device))
_log.info(
"AR-Diffusion cross-attn IMG pool: %d layers × %d img-tok (I2V)",
num_layers,
cross_attn_img_length,
)
self.spec = ChunkWindowSpec(
block_size=block_size,
num_kv_heads=num_kv_heads,
head_size=head_size,
dtype=dtype,
sliding_window=config.window_chunks * config.chunk_size,
chunk_size=config.chunk_size,
window_chunks=config.window_chunks,
sink_chunks=config.sink_chunks,
reset_at_boundary=config.reset_at_boundary,
)
# Each pool block spans all layers' K/V, so size against the per-layer
# page size times the layer count.
# Size the self-attn pool against the memory left after the cross-attn
# pools (allocated above), so cross + self-attn stays within the budget.
num_blocks = compute_num_blocks(
max(0, available_bytes - cross_total_bytes),
config.gpu_memory_fraction,
self.spec.page_size_bytes * num_layers,
)
# Floor: one forward needs the resident window plus the in-flight chunk
# (num_frame_per_block frame-blocks) for every branch THIS rank runs,
# with a little eviction-transient headroom. The memory-fraction
# heuristic can under-size this once block_size grows — e.g. frame-granular
# paging at the true frame_seqlen makes each block larger and the pool
# fewer-blocks — so guarantee the minimum the rollout cannot run without,
# otherwise allocate_chunk hits an exhausted pool mid-forward.
min_blocks = self.local_branches * (config.window_chunks + self.num_frame_per_block) + 2
if num_blocks < min_blocks:
_log.warning(
"AR-Diffusion KV pool: memory-fraction sizing gave %d blocks; raising to the %d-block "
"floor (%d local CFG branch(es) x (window_chunks=%d + num_frame_per_block=%d) + 2 headroom)",
num_blocks,
min_blocks,
self.local_branches,
config.window_chunks,
self.num_frame_per_block,
)
num_blocks = min_blocks
layer_names = [f"ar_diffusion.layer.{i}" for i in range(num_layers)]
self.manager = build_kv_manager(self.spec, layer_names, num_blocks, max_model_len)
self.managed_num_blocks = num_blocks
self.num_blocks = num_blocks
# Scratch blocks are outside KVCacheManager ownership. They hold current
# denoise-step video KV when update_kv_cache=False and action/state KV in
# both modes; they are reused every forward and never committed.
# Default 4: measured high-water is num_frame_per_block video blocks (2)
# + 1 action block per branch per forward, +1 margin.
scratch_per_branch = int(os.environ.get("AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH", "4"))
if scratch_per_branch <= 0:
raise ValueError("AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH must be positive")
self.scratch_blocks_per_branch = scratch_per_branch
self.scratch_num_blocks = self.local_branches * scratch_per_branch
self.num_blocks_total = self.managed_num_blocks + self.scratch_num_blocks
self.null_block_id = self.manager.block_pool.null_block.block_id
# Allocate the per-layer paged K/V pools on the given device.
self._kv_pools: list[torch.Tensor] = []
self._k_pools: list[torch.Tensor] = []
self._v_pools: list[torch.Tensor] = []
if device is not None:
self._kv_pools, self._k_pools, self._v_pools = allocate_kv_pool_with_views(
self.num_blocks_total,
block_size,
num_layers,
num_kv_heads,
head_size,
dtype,
device,
)
# -- cross-attention pool access -------------------------------------------
# Cross-attn KV is static once populated — write once (from text encoder),
# read many (every denoising step). Not managed through the paged block pool.
def write_cross_kv(
self,
layer_idx: int,
is_negative: bool,
k: torch.Tensor | None,
v: torch.Tensor | None,
k_img: torch.Tensor | None = None,
v_img: torch.Tensor | None = None,
) -> None:
"""Write one layer's cross-attn K/V into the pool.
``k`` / ``v``: ``(B, text_len, tp_num_heads, head_dim)``; only batch-0
is copied (B=1 for inference). ``None`` skips the text half (window
restarts keep the still-valid text K/V and rewrite only the image half).
The ``is_negative`` flag selects the correct CFG branch slot. ``k_img`` /
``v_img`` (I2V image tokens, ``(B, 257, ...)``) are written when the
image pool is allocated.
"""
branch = 1 if is_negative else 0
if k is not None:
self._cross_k[layer_idx][branch].copy_(k[0])
self._cross_v[layer_idx][branch].copy_(v[0])
if k_img is not None and self._cross_k_img:
self._cross_k_img[layer_idx][branch].copy_(k_img[0])
self._cross_v_img[layer_idx][branch].copy_(v_img[0])
def read_cross_kv(self, layer_idx: int, is_negative: bool) -> dict:
"""Return a pool-backed cross-attn cache dict for one layer.
The dict matches the ``{"is_init": True, "k": Tensor, "v": Tensor}``
convention the cross-attention module expects — it reads from the pool
slice rather than from the lazy-initialised model-local dict. For I2V,
``k_img`` / ``v_img`` are added so the image-token cache (added by #4154)
reads from the pool too.
"""
branch = 1 if is_negative else 0
k = self._cross_k[layer_idx][branch].unsqueeze(0) # (1, L, heads, dim)
v = self._cross_v[layer_idx][branch].unsqueeze(0)
cache = {"is_init": True, "k": k, "v": v}
if self._cross_k_img:
cache["k_img"] = self._cross_k_img[layer_idx][branch].unsqueeze(0)
cache["v_img"] = self._cross_v_img[layer_idx][branch].unsqueeze(0)
return cache
# -- request lifecycle ---------------------------------------------------
def begin_request(self, request_id: str, *, prefill_prefix_tokens: int = 0) -> ARDiffusionRequestAdapter:
adapter = ARDiffusionRequestAdapter(
request_id,
chunk_size=self.spec.chunk_size,
prefill_prefix_tokens=prefill_prefix_tokens,
)
self._adapters[request_id] = adapter
_log.debug("AR-Diffusion begin_request: req=%s prefill=%d", request_id, prefill_prefix_tokens)
return adapter
def end_request(self, adapter: ARDiffusionRequestAdapter) -> None:
_log.debug(
"AR-Diffusion end_request: req=%s chunks=%d free=%d",
adapter.request_id,
adapter.completed_chunks,
self.manager.block_pool.get_num_free_blocks(),
)
self.manager.free(adapter)
self._adapters.pop(adapter.request_id, None)
# -- per-chunk operations ------------------------------------------------
def allocate_chunk(self, adapter: ARDiffusionRequestAdapter) -> list[int]:
"""Allocate a chunk's blocks (evicting out-of-window blocks first).
Returns the request's full block table (incl. null_block placeholders).
"""
blocks = self.manager.allocate_slots(adapter, num_new_tokens=self.spec.chunk_size)
if blocks is None:
raise RuntimeError("AR-Diffusion KV pool exhausted while allocating a chunk")
table = self.block_table(adapter)
resident = resident_block_ids(table, self.null_block_id)
_log.debug(
"AR-Diffusion allocate_chunk: req=%s chunk=%d table_len=%d resident=%d free=%d",
adapter.request_id,
adapter.completed_chunks,
len(table),
len(resident),
self.manager.block_pool.get_num_free_blocks(),
)
return table
def allocate_token_slots(self, adapter: ARDiffusionRequestAdapter, num_tokens: int) -> list[int]:
"""Allocate managed blocks for an in-flight video span without committing it."""
if num_tokens <= 0:
raise ValueError(f"num_tokens must be positive, got {num_tokens}")
blocks = self.manager.allocate_slots(adapter, num_new_tokens=num_tokens)
if blocks is None:
raise RuntimeError("AR-Diffusion KV pool exhausted while allocating paged attention slots")
return self.block_table(adapter)
def block_table(self, adapter: ARDiffusionRequestAdapter) -> list[int]:
return list(self.manager.get_block_ids(adapter.request_id)[0])
def chunk_write_slots(self, adapter: ARDiffusionRequestAdapter) -> torch.Tensor:
"""Slot mapping for the in-flight chunk — the K/V write target."""
return chunk_slot_mapping(
self.block_table(adapter),
adapter.num_computed_tokens,
self.spec.chunk_size,
self.block_size,
)
def scratch_block_ids(self, is_negative: bool, start: int, count: int) -> list[int]:
"""Return branch-local scratch block ids outside manager ownership."""
if count < 0 or start < 0:
raise ValueError(f"scratch start/count must be non-negative, got start={start}, count={count}")
if start + count > self.scratch_blocks_per_branch:
raise RuntimeError(
"AR-Diffusion paged attention scratch blocks exhausted: "
f"need [{start}, {start + count}) of {self.scratch_blocks_per_branch}. "
"Increase AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH."
)
# With one local branch (CFG-parallel x2) the rank's only branch maps to
# slot 0 whichever CFG side it is; the other branch never allocates here.
branch_offset = self.scratch_blocks_per_branch if (is_negative and self.local_branches == 2) else 0
base = self.managed_num_blocks + branch_offset + start
return list(range(base, base + count))
def key_cache(self, layer_idx: int) -> torch.Tensor:
return self._kv_pools[layer_idx][0]
def value_cache(self, layer_idx: int) -> torch.Tensor:
return self._kv_pools[layer_idx][1]
def window_block_ids(self, adapter: ARDiffusionRequestAdapter) -> list[int]:
"""Resident (non-null) managed blocks visible to paged attention."""
return resident_block_ids(self.block_table(adapter), self.null_block_id)
def commit_chunk(self, adapter: ARDiffusionRequestAdapter) -> None:
"""Advance the adapter by one chunk after its K/V is written.
This standalone primitive is used by low-level manager tests. In the
DreamZero paged-attention path, :meth:`ARDiffusionKVState.commit_paged_context`
advances the adapter only after the forward succeeds. Call once per
committed chunk, not per denoise step.
"""
_log.debug("AR-Diffusion commit: req=%s before=%d", adapter.request_id, adapter.completed_chunks)
adapter.on_chunk_committed()
_log.debug("AR-Diffusion commit: req=%s after=%d", adapter.request_id, adapter.completed_chunks)
# -- pool-backed K/V access --------------------------------------------
def write_chunk_kv(
self,
layer_index: int,
new_k: torch.Tensor,
new_v: torch.Tensor,
adapter: ARDiffusionRequestAdapter,
) -> None:
"""Write one layer's committed-chunk K/V into the pool."""
slots = self.chunk_write_slots(adapter)
_log.debug(
"AR-Diffusion write: req=%s layer=%d chunk=%d shapes=%s dev=%s",
adapter.request_id,
layer_index,
adapter.completed_chunks,
(tuple(new_k.shape), tuple(new_v.shape)),
slots.device,
)
pool_write_chunk(
self._k_pools[layer_index],
self._v_pools[layer_index],
new_k,
new_v,
slots,
)
@@ -0,0 +1,223 @@
# SPDX-License-Identifier: Apache-2.0
"""Generic paging mechanics + chunk-window eviction spec for the AR-Diffusion engine.
Engine-generic, model-agnostic primitives — the layer a second model (e.g. the
Cosmos port) reuses unchanged. Three concerns live here:
* **Slot mapping** — absolute token positions → physical KV-cache slots, the
standard PagedAttention layout ``slot(pos) = block_id(pos) * block_size +
(pos % block_size)``.
* **Pool I/O** — allocate per-layer FlashAttention-compatible paged K/V pools
plus flat compatibility views for direct slot writes.
* **Chunk-window eviction** — a ``SlidingWindowSpec`` subclass whose unit is a
*chunk* (``sliding_window = window_chunks * chunk_size``) plus a manager that
evicts at chunk boundaries. Memory policy / refcounting / ``null_block``
replacement stay in vLLM's ``BlockPool``; only the token-skip math is here.
"""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
import torch
from vllm.v1.core.single_type_kv_cache_manager import SlidingWindowManager
from vllm.v1.kv_cache_interface import SlidingWindowSpec
try:
from vllm.v1.kv_cache_spec_registry import register_kv_cache_spec
except ModuleNotFoundError:
def register_kv_cache_spec(*, manager_class, uniform_type_base_spec=None):
"""Compatibility shim for vLLM versions without kv_cache_spec_registry."""
def decorator(spec_class):
from vllm.v1.core.single_type_kv_cache_manager import spec_manager_map
spec_manager_map[spec_class] = manager_class
return spec_class
return decorator
# ── Slot mapping ────────────────────────────────────────────────────────────
def compute_slot_mapping(
block_ids: Sequence[int],
positions: torch.Tensor | Sequence[int],
block_size: int,
) -> torch.Tensor:
"""Map absolute token positions to physical KV-cache slots.
Args:
block_ids: physical block id per block index (the request's block table).
positions: absolute token positions to map (1-D).
block_size: tokens per block.
Returns:
``LongTensor`` of physical slots, one per position.
"""
if block_size <= 0:
raise ValueError(f"block_size must be positive, got {block_size}")
table = torch.as_tensor(block_ids, dtype=torch.long)
pos = torch.as_tensor(positions, dtype=torch.long)
block_index = torch.div(pos, block_size, rounding_mode="floor")
offset = pos % block_size
return table[block_index] * block_size + offset
def chunk_slot_mapping(
block_ids: Sequence[int],
num_computed_tokens: int,
chunk_size: int,
block_size: int,
) -> torch.Tensor:
"""Slot mapping for the in-flight chunk's tokens (the commit write target).
The chunk occupies absolute positions
``[num_computed_tokens, num_computed_tokens + chunk_size)``.
"""
positions = torch.arange(
num_computed_tokens,
num_computed_tokens + chunk_size,
dtype=torch.long,
)
return compute_slot_mapping(block_ids, positions, block_size)
def resident_block_ids(block_ids: Sequence[int], null_block_id: int) -> list[int]:
"""Real (non-null) blocks currently resident, in table order.
These are the blocks the read path gathers the attention window from;
out-of-window positions are the shared ``null_block`` and are excluded.
"""
return [int(b) for b in block_ids if int(b) != null_block_id]
# ── Pool I/O (allocate / write) ─────────────────────────────────────────────
def allocate_kv_pool_with_views(
num_blocks: int,
block_size: int,
num_layers: int,
num_kv_heads: int,
head_dim: int,
dtype: torch.dtype,
device: torch.device,
) -> tuple[list[torch.Tensor], list[torch.Tensor], list[torch.Tensor]]:
"""Allocate vLLM-style paged KV pools plus flat slot-write views.
The owning tensor follows FlashAttention's block-table cache layout:
``(2, num_blocks, block_size, num_kv_heads, head_dim)``, where dim-0 is
``[K, V]``. The flat K/V views keep ``slot = block_id * block_size +
offset`` writes simple without changing the kernel-facing cache layout.
"""
kv_pools: list[torch.Tensor] = []
k_pools: list[torch.Tensor] = []
v_pools: list[torch.Tensor] = []
for _ in range(num_layers):
kv = torch.empty(2, num_blocks, block_size, num_kv_heads, head_dim, dtype=dtype, device=device)
kv_pools.append(kv)
k_pools.append(kv[0].reshape(num_blocks * block_size, num_kv_heads, head_dim))
v_pools.append(kv[1].reshape(num_blocks * block_size, num_kv_heads, head_dim))
return kv_pools, k_pools, v_pools
def pool_write_chunk(
k_pool: torch.Tensor,
v_pool: torch.Tensor,
new_k: torch.Tensor,
new_v: torch.Tensor,
slot_mapping: torch.Tensor,
) -> None:
"""Write the committed chunk's K/V into pool slots (in place).
``new_k`` / ``new_v`` shape: ``(batch, chunk_size, num_kv_heads, head_dim)``.
``slot_mapping`` shape: ``(chunk_size,)`` — one physical slot per token position.
The batch dim is written to the same slots (multi-batch writes the same
positions; the caller is responsible for per-sequence bookkeeping).
This is the *commit* write — called once per chunk, after the last denoise step.
"""
k_pool[slot_mapping] = new_k[0] # batch index 0
v_pool[slot_mapping] = new_v[0]
def _drop_batch(t: torch.Tensor) -> torch.Tensor:
"""``(1, L, n_heads, head_dim)`` -> ``(L, n_heads, head_dim)``; pass 3-D through."""
if t.dim() == 4 and t.shape[0] == 1:
return t[0]
return t
# ── Chunk-window eviction (spec + manager) ──────────────────────────────────
def chunk_window_skipped_tokens(
num_computed_tokens: int,
*,
chunk_size: int,
sliding_window: int,
sink_chunks: int,
reset_at_boundary: bool,
) -> int:
"""Tokens outside the resident chunk window, snapped to a chunk boundary.
Pure function so the eviction policy is unit-testable without constructing a
manager. Two strategies:
- ``reset_at_boundary`` (DreamZero): at each chunk boundary everything past
the sink is dropped.
- otherwise (VGGT-style sliding replace): keep the last ``window`` tokens
(plus the sink); the skip count snaps down to a chunk boundary so a chunk
is never half-evicted.
"""
sink = sink_chunks * chunk_size
if reset_at_boundary:
completed = (num_computed_tokens // chunk_size) * chunk_size
return max(0, completed - sink)
skipped = max(0, num_computed_tokens - sliding_window - sink)
return (skipped // chunk_size) * chunk_size
class ChunkWindowManager(SlidingWindowManager):
"""``SlidingWindowManager`` that evicts at chunk boundaries.
``self.sliding_window`` is set by the base ``__init__``; the chunk fields are
read from ``self.kv_cache_spec`` (a :class:`ChunkWindowSpec`).
"""
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
spec = self.kv_cache_spec
return chunk_window_skipped_tokens(
num_computed_tokens,
chunk_size=spec.chunk_size,
sliding_window=self.sliding_window,
sink_chunks=spec.sink_chunks,
reset_at_boundary=spec.reset_at_boundary,
)
# Register so KVCacheManager resolves ChunkWindowSpec to ChunkWindowManager.
# Dispatch walks the spec's MRO, so without explicit registration the subclass
# would silently fall back to the parent SlidingWindowManager (override ignored).
# uniform_type_base_spec=None => its own KV cache group.
@register_kv_cache_spec(manager_class=ChunkWindowManager, uniform_type_base_spec=None)
@dataclass(frozen=True, kw_only=True)
class ChunkWindowSpec(SlidingWindowSpec):
# sliding_window (inherited) MUST equal window_chunks * chunk_size.
chunk_size: int
window_chunks: int
sink_chunks: int = 0
reset_at_boundary: bool = False
def __post_init__(self):
super().__post_init__()
if self.sliding_window != self.window_chunks * self.chunk_size:
raise ValueError(
"ChunkWindowSpec.sliding_window must equal "
f"window_chunks * chunk_size ({self.window_chunks} * "
f"{self.chunk_size}), got {self.sliding_window}"
)
@@ -0,0 +1,550 @@
# SPDX-License-Identifier: Apache-2.0
"""Paged self-attention helpers for AR-Diffusion DreamZero KV reuse."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, ClassVar, NamedTuple
import torch
from vllm_omni.experimental.ar_diffusion.kv_cache.paged import compute_slot_mapping
# Set by ARDiffusionPagedForwardContext.prepare() before each branch forward and
# read by the fused write+attend custom op below. The pools are process-lifetime
# allocations owned by one ARDiffusionKVCache per worker process (CFG-parallel /
# TP ranks are separate processes), mirroring vLLM's forward-context pattern for
# keeping multi-GiB cache tensors out of the compiled graph's inputs.
_CURRENT_PAGED_KV_CACHE: Any = None
def set_current_paged_kv_cache(kv_cache: Any) -> None:
global _CURRENT_PAGED_KV_CACHE
_CURRENT_PAGED_KV_CACHE = kv_cache
_LAYER_IDX_TENSORS: dict[int, torch.Tensor] = {}
def _layer_idx_tensor(layer_idx: int) -> torch.Tensor:
t = _LAYER_IDX_TENSORS.get(layer_idx)
if t is None:
t = torch.tensor(layer_idx, dtype=torch.int64)
_LAYER_IDX_TENSORS[layer_idx] = t
return t
class ARDiffusionPagedLayerInputs(NamedTuple):
"""Compiled-region payload for one layer's paged self-attention.
A NamedTuple of plain tensors + ints so ``torch.compile`` treats every field
as a pytree graph input (no object-attribute guards, no recompiles when only
tensor *values* change). All layers of one branch forward share the same
metadata tensor objects, built once by ``prepare()``.
``layer_idx`` is a 0-dim CPU tensor, NOT a python int: all 40 DiT blocks
share one compiled code object, and an int here becomes a per-layer dynamo
value guard (``layer_idx == k``) — 40 cache variants that blow the
recompile limit. A tensor input guards on shape/dtype only, so one graph
serves every layer.
"""
layer_idx: torch.Tensor
seq_len: int
video_slots: torch.Tensor
action_slots: torch.Tensor
block_table: torch.Tensor
query_start_loc: torch.Tensor
seq_lens: torch.Tensor
max_query_len: int
max_seq_len: int
@dataclass
class ARDiffusionPagedForwardContext:
"""Mutable branch-level state shared by all layer contexts in one forward."""
kv_cache: Any
adapter: Any
is_negative: bool
history_block_ids: list[int]
seq_len: int
commit_current: bool
max_video_tokens: int
current_video_block_ids: list[int] = field(default_factory=list)
current_video_slot_mapping: torch.Tensor | None = None
action_scratch_block_ids: list[int] = field(default_factory=list)
action_slot_mapping: torch.Tensor | None = None
query_len: int = 0
kv_len: int = 0
_allocated_video: bool = False
_committed: bool = False
_action_len: int = 0
# Set once by prepare(); shared by all layers of the branch forward.
block_table: torch.Tensor | None = None
query_start_loc: torch.Tensor | None = None
seq_lens: torch.Tensor | None = None
max_query_len: int = 0
max_seq_len: int = 0
_prepared: bool = False
@property
def block_size(self) -> int:
return int(self.kv_cache.block_size)
@property
def num_current_video_blocks(self) -> int:
if self.seq_len % self.block_size != 0:
raise AssertionError(
"AR-Diffusion paged attention expects frame-aligned seq_len "
f"(multiple of block_size={self.block_size}), got {self.seq_len}"
)
return self.seq_len // self.block_size
def ensure_video_slots(self, device: torch.device) -> None:
"""Allocate/write targets for the current video tokens, once per branch."""
if self._allocated_video:
return
n_blocks = self.num_current_video_blocks
if self.commit_current:
start = int(self.adapter.num_computed_tokens)
self.kv_cache.allocate_token_slots(self.adapter, self.seq_len)
table = self.kv_cache.block_table(self.adapter)
start_block = start // self.block_size
self.current_video_block_ids = [int(b) for b in table[start_block : start_block + n_blocks]]
positions = torch.arange(start, start + self.seq_len, dtype=torch.long)
self.current_video_slot_mapping = compute_slot_mapping(table, positions, self.block_size).to(device=device)
else:
self.current_video_block_ids = self.kv_cache.scratch_block_ids(self.is_negative, 0, n_blocks)
positions = torch.arange(self.seq_len, dtype=torch.long)
self.current_video_slot_mapping = compute_slot_mapping(
self.current_video_block_ids,
positions,
self.block_size,
).to(device=device)
self._allocated_video = True
def ensure_action_slots(self, action_len: int, device: torch.device) -> None:
"""Reserve scratch slots for action/state K/V, if present."""
if action_len <= 0:
self.action_scratch_block_ids = []
self.action_slot_mapping = torch.empty(0, dtype=torch.long, device=device)
self._action_len = 0
return
self.ensure_video_slots(device)
if self.action_slot_mapping is not None and self._action_len == action_len:
return
action_blocks = (action_len + self.block_size - 1) // self.block_size
scratch_offset = 0 if self.commit_current else len(self.current_video_block_ids)
self.action_scratch_block_ids = self.kv_cache.scratch_block_ids(
self.is_negative,
scratch_offset,
action_blocks,
)
positions = torch.arange(action_len, dtype=torch.long)
self.action_slot_mapping = compute_slot_mapping(
self.action_scratch_block_ids,
positions,
self.block_size,
).to(device=device)
self._action_len = action_len
def video_block_table(self, device: torch.device) -> tuple[list[int], int]:
self.ensure_video_slots(device)
if self.max_video_tokens % self.block_size != 0:
raise AssertionError(
"AR-Diffusion paged attention requires max_video_tokens to be block-aligned, "
f"got max_video_tokens={self.max_video_tokens}, block_size={self.block_size}"
)
all_video_blocks = self.history_block_ids + self.current_video_block_ids
max_video_blocks = self.max_video_tokens // self.block_size
visible_video_blocks = all_video_blocks[-max_video_blocks:] if max_video_blocks else []
video_len = min(len(all_video_blocks) * self.block_size, self.max_video_tokens)
return visible_video_blocks, video_len
def build_block_table(
self,
*,
action_len: int,
query_len: int,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, int]:
"""Build FlashAttention block-table metadata for one self-attn call.
The block table is tail-padded to a fixed width and ``max_seq_len`` is a
constant upper bound, so across window growth only tensor *values* change
— tensor shapes and the int consts stay stable for ``torch.compile``
(and, later, CUDA-graph capture). The kernel only dereferences the first
``ceil(seq_lens/block_size)`` entries, so padding is never read.
"""
video_blocks, video_len = self.video_block_table(device)
self.ensure_action_slots(action_len, device)
action_blocks = self.action_scratch_block_ids if action_len > 0 else []
block_ids = video_blocks + action_blocks
if not block_ids:
raise RuntimeError("AR-Diffusion paged attention needs at least current video KV blocks")
# Fixed capacity: full visible video window + one action-capacity block.
action_capacity_blocks = max(1, (action_len + self.block_size - 1) // self.block_size)
width = max(self.max_video_tokens // self.block_size + action_capacity_blocks, len(block_ids))
padded = block_ids + [0] * (width - len(block_ids))
self.query_len = int(query_len)
self.kv_len = int(video_len + action_len)
max_seq_len = int(self.max_video_tokens + action_capacity_blocks * self.block_size)
block_table = torch.tensor([padded], dtype=torch.int32, device=device)
query_start_loc = torch.tensor([0, self.query_len], dtype=torch.int32, device=device)
seq_lens = torch.tensor([self.kv_len], dtype=torch.int32, device=device)
return block_table, query_start_loc, seq_lens, self.query_len, max_seq_len
def prepare(self, device: torch.device, action_len: int, query_len: int) -> None:
"""Host-side, once-per-branch-forward setup (called OUTSIDE torch.compile).
Allocates the current video/action slots (still lazy: only the branch a
CFG-parallel rank actually runs reaches its ``_forward_blocks``), builds
the padded block-table metadata ONCE for all layers, and publishes the
pool registry for the fused custom op. The compiled per-layer code then
only consumes prebuilt tensors via ``ARDiffusionPagedLayerInputs``.
"""
if getattr(self, "_prepared", False):
return
self.ensure_video_slots(device)
(
self.block_table,
self.query_start_loc,
self.seq_lens,
self.max_query_len,
self.max_seq_len,
) = self.build_block_table(action_len=action_len, query_len=query_len, device=device)
if self.action_slot_mapping is None:
self.action_slot_mapping = torch.empty(0, dtype=torch.long, device=device)
set_current_paged_kv_cache(self.kv_cache)
self._prepared = True
def layer_inputs(self, layer_idx: int) -> ARDiffusionPagedLayerInputs:
if not getattr(self, "_prepared", False):
raise RuntimeError("ARDiffusionPagedForwardContext.layer_inputs() before prepare()")
return ARDiffusionPagedLayerInputs(
layer_idx=_layer_idx_tensor(layer_idx),
seq_len=int(self.seq_len),
video_slots=self.current_video_slot_mapping,
action_slots=self.action_slot_mapping,
block_table=self.block_table,
query_start_loc=self.query_start_loc,
seq_lens=self.seq_lens,
max_query_len=int(self.max_query_len),
max_seq_len=int(self.max_seq_len),
)
def mark_committed(self) -> None:
self._committed = True
@dataclass
class ARDiffusionPagedLayerContext:
"""Layer-specific handle passed through DreamZero's existing ``kv_cache`` slot."""
is_ar_diffusion_paged_context: ClassVar[bool] = True
layer_idx: int
forward_ctx: ARDiffusionPagedForwardContext
@property
def kv_cache(self):
return self.forward_ctx.kv_cache
@property
def adapter(self):
return self.forward_ctx.adapter
@property
def is_negative(self) -> bool:
return self.forward_ctx.is_negative
@property
def history_block_ids(self) -> list[int]:
return self.forward_ctx.history_block_ids
@property
def current_video_block_ids(self) -> list[int]:
return self.forward_ctx.current_video_block_ids
@property
def current_video_slot_mapping(self) -> torch.Tensor | None:
return self.forward_ctx.current_video_slot_mapping
@property
def action_scratch_block_ids(self) -> list[int]:
return self.forward_ctx.action_scratch_block_ids
@property
def action_slot_mapping(self) -> torch.Tensor | None:
return self.forward_ctx.action_slot_mapping
@property
def seq_len(self) -> int:
return self.forward_ctx.seq_len
@property
def query_len(self) -> int:
return self.forward_ctx.query_len
@property
def kv_len(self) -> int:
return self.forward_ctx.kv_len
@property
def commit_current(self) -> bool:
return self.forward_ctx.commit_current
def to_layer_inputs(self) -> ARDiffusionPagedLayerInputs:
"""Compiled-region payload; requires ``forward_ctx.prepare()`` first."""
return self.forward_ctx.layer_inputs(self.layer_idx)
def is_ar_diffusion_paged_context(value: object) -> bool:
return isinstance(value, ARDiffusionPagedLayerContext)
def _reference_paged_attention(
query: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
block_table: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
softmax_scale: float,
*,
causal: bool,
) -> torch.Tensor:
if causal:
raise NotImplementedError("AR-Diffusion paged self-attention uses causal=False")
outs: list[torch.Tensor] = []
block_size = key_cache.shape[1]
for i in range(seq_lens.shape[0]):
q_start = int(query_start_loc[i].item())
q_end = int(query_start_loc[i + 1].item())
kv_len = int(seq_lens[i].item())
q = query[q_start:q_end]
positions = torch.arange(kv_len, device=query.device)
logical_blocks = torch.div(positions, block_size, rounding_mode="floor")
offsets = positions % block_size
physical_blocks = block_table[i, logical_blocks].long()
k = key_cache[physical_blocks, offsets]
v = value_cache[physical_blocks, offsets]
scores = torch.einsum("qhd,khd->hqk", q.float(), k.float()) * float(softmax_scale)
probs = torch.softmax(scores, dim=-1).to(v.dtype)
outs.append(torch.einsum("hqk,khd->qhd", probs, v))
return torch.cat(outs, dim=0)
_FA_VERSION_BY_HEAD_SIZE: dict[int, int] = {}
def _resolve_fa_version(head_size: int) -> int:
# get_flash_attn_version -> current_platform.get_device_capability() is not
# dynamo-traceable, and the answer is fixed per head size for the process.
version = _FA_VERSION_BY_HEAD_SIZE.get(head_size)
if version is None:
try:
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
version = int(get_flash_attn_version(requires_alibi=False, head_size=head_size) or 2)
except Exception:
version = 2
_FA_VERSION_BY_HEAD_SIZE[head_size] = version
return version
def ar_diffusion_paged_attention(
query: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
*,
block_table: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
max_query_len: int,
max_seq_len: int,
softmax_scale: float,
causal: bool = False,
) -> torch.Tensor:
"""Run non-causal paged attention over a vLLM block table.
``query`` may be ``(B, L, H, D)`` or already flattened as ``(T, H, D)``.
``key_cache`` / ``value_cache`` are ``(num_blocks, block_size, H, D)``.
"""
batched = query.dim() == 4
if batched:
batch, q_len = query.shape[:2]
query_flat = query.reshape(batch * q_len, *query.shape[2:])
else:
query_flat = query
if not query_flat.is_cuda:
out = _reference_paged_attention(
query_flat,
key_cache,
value_cache,
block_table,
query_start_loc,
seq_lens,
softmax_scale,
causal=causal,
)
else:
from vllm.vllm_flash_attn import flash_attn_varlen_func
fa_version = _resolve_fa_version(query_flat.shape[-1])
out = torch.empty_like(query_flat)
flash_attn_varlen_func(
q=query_flat,
k=key_cache,
v=value_cache,
out=out,
cu_seqlens_q=query_start_loc,
max_seqlen_q=int(max_query_len),
seqused_k=seq_lens,
max_seqlen_k=int(max_seq_len),
softmax_scale=float(softmax_scale),
causal=causal,
block_table=block_table,
fa_version=fa_version,
)
if batched:
return out.reshape(query.shape)
return out
# ── Fused write+attend custom op (torch.compile-safe) ──────────────────────
#
# One opaque op per layer keeps the compiled DiT block fullgraph: dynamo treats
# it as a single graph node (no eager island, no graph breaks), and the K/V slot
# writes happen inside the op so write→read ordering with the block-table kernel
# is internal — no hidden-mutation ordering hazards against a separate reader op
# and no multi-GiB pool tensors as graph inputs (the flat and paged pool views
# alias the same storage, which AOTAutograd handles poorly as inputs). Pattern
# follows sage_attn3.py in-repo and vLLM's own unified attention ops.
def _paged_write_attn_impl(
query: torch.Tensor,
k_curr: torch.Tensor,
v_curr: torch.Tensor,
k_act: torch.Tensor | None,
v_act: torch.Tensor | None,
layer_idx: torch.Tensor,
video_slots: torch.Tensor,
action_slots: torch.Tensor,
block_table: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
max_query_len: int,
max_seq_len: int,
softmax_scale: float,
) -> torch.Tensor:
kv = _CURRENT_PAGED_KV_CACHE
if kv is None:
raise RuntimeError("ar_diffusion_paged_write_attn called before prepare() set the KV pool registry")
layer_idx = int(layer_idx)
k_pool = kv._k_pools[layer_idx]
v_pool = kv._v_pools[layer_idx]
k_pool[video_slots] = k_curr.to(k_pool.dtype)
v_pool[video_slots] = v_curr.to(v_pool.dtype)
if k_act is not None and v_act is not None and k_act.shape[0] > 0:
k_pool[action_slots] = k_act.to(k_pool.dtype)
v_pool[action_slots] = v_act.to(v_pool.dtype)
return ar_diffusion_paged_attention(
query,
kv.key_cache(layer_idx),
kv.value_cache(layer_idx),
block_table=block_table,
query_start_loc=query_start_loc,
seq_lens=seq_lens,
max_query_len=max_query_len,
max_seq_len=max_seq_len,
softmax_scale=softmax_scale,
causal=False,
)
# hasattr guard keeps registration idempotent across test re-imports that pop
# the module from sys.modules (same as sage_attn3.py).
if not hasattr(torch.ops.vllm_omni, "ar_diffusion_paged_write_attn"):
@torch.library.custom_op("vllm_omni::ar_diffusion_paged_write_attn", mutates_args=())
def _paged_write_attn_op(
query: torch.Tensor,
k_curr: torch.Tensor,
v_curr: torch.Tensor,
k_act: torch.Tensor | None,
v_act: torch.Tensor | None,
layer_idx: torch.Tensor,
video_slots: torch.Tensor,
action_slots: torch.Tensor,
block_table: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
max_query_len: int,
max_seq_len: int,
softmax_scale: float,
) -> torch.Tensor:
return _paged_write_attn_impl(
query,
k_curr,
v_curr,
k_act,
v_act,
layer_idx,
video_slots,
action_slots,
block_table,
query_start_loc,
seq_lens,
max_query_len,
max_seq_len,
softmax_scale,
)
@_paged_write_attn_op.register_fake
def _(
query,
k_curr,
v_curr,
k_act,
v_act,
layer_idx,
video_slots,
action_slots,
block_table,
query_start_loc,
seq_lens,
max_query_len,
max_seq_len,
softmax_scale,
):
return torch.empty_like(query)
def paged_write_attn(
inputs: ARDiffusionPagedLayerInputs, query, k_curr, v_curr, k_act, v_act, softmax_scale: float
) -> torch.Tensor:
"""Model-facing entry: routes through the custom op (traceable in fullgraph)."""
return torch.ops.vllm_omni.ar_diffusion_paged_write_attn(
query,
k_curr,
v_curr,
k_act,
v_act,
inputs.layer_idx,
inputs.video_slots,
inputs.action_slots,
inputs.block_table,
inputs.query_start_loc,
inputs.seq_lens,
inputs.max_query_len,
inputs.max_seq_len,
softmax_scale,
)
@@ -0,0 +1,183 @@
# SPDX-License-Identifier: Apache-2.0
"""DreamZero-facing AR-Diffusion KV bridge backed by paged self-attention."""
from __future__ import annotations
from vllm.logger import init_logger
from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import (
ARDiffusionPagedForwardContext,
ARDiffusionPagedLayerContext,
)
_log = init_logger(__name__)
class ARDiffusionKVState:
"""Per-request bridge between a DreamZero rollout and the AR-Diffusion KV pool.
The self-attention path is paged-only: ``get_kv_caches`` returns lightweight
per-layer contexts, and each attention layer writes current K/V into the
pool before calling the FlashAttention block-table kernel. No resident
window is gathered into a contiguous tensor.
"""
def __init__(self, kv_cache, pos_adapter, neg_adapter, num_layers: int) -> None:
"""One state per DreamZero session, holding BOTH CFG branches' adapters.
``pos``/``neg`` are the classifier-free-guidance branches: ``pos`` is
the conditional pass (real prompt), ``neg`` the unconditional pass
(negative prompt). Each owns an independent request adapter — and
therefore independent pool blocks — because the two branches produce
different K/V for the same frames. Every ``is_negative`` flag in this
module selects between them (``False`` -> ``pos``, ``True`` -> ``neg``).
"""
self.kv_cache = kv_cache
self.pos = pos_adapter
self.neg = neg_adapter
self.num_layers = num_layers
self._committed: dict[bool, int] = {False: 0, True: 0}
self._paged_pending: dict[bool, ARDiffusionPagedForwardContext | None] = {False: None, True: None}
# Cross-attn KV is populated once after text encoding (eager), then
# read every denoising step. Tracked per half: the text K/V depend only
# on the session prompt (survive window-boundary resets), while the I2V
# image-token K/V come from the current observation's CLIP features and
# must be re-projected on every window restart.
self._cross_text_populated: dict[bool, bool] = {False: False, True: False}
self._cross_img_populated: dict[bool, bool] = {False: False, True: False}
def _adapter(self, is_negative: bool):
return self.neg if is_negative else self.pos
def get_kv_caches(
self,
is_negative: bool,
seq_len: int | None = None,
commit_current: bool = False,
) -> list[ARDiffusionPagedLayerContext]:
if seq_len is None:
raise ValueError("AR-Diffusion paged self-attention requires seq_len in get_kv_caches()")
return self.prepare_paged_context(is_negative, seq_len, commit_current)
def prepare_paged_context(
self,
is_negative: bool,
seq_len: int,
commit_current: bool,
) -> list[ARDiffusionPagedLayerContext]:
"""Return per-layer paged attention contexts for one branch forward.
Allocation is lazy: constructing both CFG branches' kwargs must not
allocate manager blocks for a branch that a CFG-parallel rank will not run.
The first self-attn layer that consumes the context allocates the current
video slots, then all layers share that branch-level state.
"""
cs = self.kv_cache.spec.chunk_size
if int(seq_len) % cs != 0:
raise AssertionError(
f"AR-Diffusion expects frame-aligned seq_len (multiple of chunk_size={cs}), got {seq_len}"
)
pending = self._paged_pending.get(is_negative)
if pending is not None and pending.commit_current and pending._allocated_video and not pending._committed:
raise RuntimeError("AR-Diffusion paged context replaced before its managed current chunk was committed")
adapter = self._adapter(is_negative)
branch = "neg" if is_negative else "pos"
forward_ctx = ARDiffusionPagedForwardContext(
kv_cache=self.kv_cache,
adapter=adapter,
is_negative=is_negative,
history_block_ids=self.kv_cache.window_block_ids(adapter),
seq_len=int(seq_len),
commit_current=bool(commit_current),
max_video_tokens=int(self.kv_cache.spec.sliding_window),
)
self._paged_pending[is_negative] = forward_ctx
_log.debug(
"AR-Diffusion GET [%s] source=paged-attn layers=%d history_blocks=%d seq_len=%d commit_current=%s",
branch,
self.num_layers,
len(forward_ctx.history_block_ids),
int(seq_len),
bool(commit_current),
)
return [ARDiffusionPagedLayerContext(layer_idx=i, forward_ctx=forward_ctx) for i in range(self.num_layers)]
def commit_paged_context(self, is_negative: bool) -> None:
"""Commit the managed current video blocks after a successful forward."""
ctx = self._paged_pending.get(is_negative)
if ctx is None:
return
branch = "neg" if is_negative else "pos"
if ctx.commit_current and ctx._allocated_video:
n_chunks = ctx.seq_len // self.kv_cache.spec.chunk_size
for _ in range(n_chunks):
ctx.adapter.on_chunk_committed()
self._committed[is_negative] += ctx.seq_len
_log.debug(
"AR-Diffusion COMMIT [%s] paged-attn new_tokens=%d chunks=%d resident=%d/%d",
branch,
ctx.seq_len,
n_chunks,
len(self.kv_cache.window_block_ids(ctx.adapter)),
self.kv_cache.spec.window_chunks,
)
ctx.mark_committed()
self._paged_pending[is_negative] = None
def get_cross_kv_caches(self, is_negative: bool) -> list[dict]:
"""Return pool-backed cross-attn cache dicts.
Under AR-Diffusion the cross-attn pool is always populated by ``_kv_populate_cross``
before the first read, so this must never be reached unpopulated — if it
were, the model would lazily project and write cross KV itself, violating
engine ownership. Fail loud rather than fall back to the model.
"""
img_ok = not self.kv_cache._cross_k_img or self._cross_img_populated[is_negative]
if not (self._cross_text_populated[is_negative] and img_ok and self.kv_cache.cross_attn_length > 0):
raise RuntimeError(
f"AR-Diffusion cross-attn read before _kv_populate_cross (neg={is_negative}, "
f"cross_attn_length={self.kv_cache.cross_attn_length}, "
f"text={self._cross_text_populated[is_negative]} "
f"img={self._cross_img_populated[is_negative]}) — the engine must own all cross KV"
)
return [self.kv_cache.read_cross_kv(i, is_negative) for i in range(self.num_layers)]
def close(self) -> None:
"""Final teardown: free both branches' resident pool blocks."""
self.kv_cache.end_request(self.pos)
self.kv_cache.end_request(self.neg)
self._paged_pending = {False: None, True: None}
def reset(self, *, keep_cross_text: bool = False) -> None:
"""Drop this session's KV — mirrors the model-local ``state.reset()``.
DreamZero resets at the attention-window boundary (``should_reset``); the
model starts a fresh sliding window, so AR-Diffusion must free the resident pool
blocks and start a fresh adapter for each branch. The ``ARDiffusionKVState``
object (and thus ``pipeline._ar_diffusion_kv_state``) is preserved across the reset
so the runner's session mapping stays valid — only the pool-backed state
is recycled.
Args:
keep_cross_text: On window ("inference") resets the session prompt is
unchanged, so the text cross-attn K/V in the static pool buffers are
still valid — keep them and only force the image half to repopulate.
Session resets (prompt change / explicit reset) pass ``False``.
"""
pos_id, neg_id = self.pos.request_id, self.neg.request_id
self.close()
self.pos = self.kv_cache.begin_request(pos_id)
self.neg = self.kv_cache.begin_request(neg_id)
self._committed = {False: 0, True: 0}
self._paged_pending = {False: None, True: None}
if not keep_cross_text:
self._cross_text_populated = {False: False, True: False}
self._cross_img_populated = {False: False, True: False}
_log.info(
"AR-Diffusion RESET [%s/%s] session KV cleared (window boundary; cross text %s)",
pos_id,
neg_id,
"kept" if keep_cross_text else "cleared",
)