Generalize AR-Diffusion KV session capabilities (#5271)

Signed-off-by: Jack47 <scsvip@gmail.com>
This commit is contained in:
Jack Chen authored and GitHub committed 2026-07-23 12:37:32 +08:00
1 parent 00bdb5dcd7
commit 96235da468
18 files changed
+1808 -800

No files matched your search

@@ -1,20 +1,19 @@
# SPDX-License-Identifier: Apache-2.0
"""ARDiffusionKVCache — the engine-level KV cache orchestrator for one AR-Diffusion model.
"""Engine-level KV cache orchestration for AR-Diffusion models.
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.
the model and the KV tensors. 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
from collections.abc import Collection, Iterable, Sequence
import torch
from vllm.logger import init_logger
@@ -27,6 +26,7 @@ from vllm.v1.kv_cache_interface import (
)
from vllm.v1.request import RequestStatus
from vllm_omni.experimental.ar_diffusion.capability import ARDiffusionKVBranchSpec
from vllm_omni.experimental.ar_diffusion.kv_cache.config import ARDiffusionKVConfig
from vllm_omni.experimental.ar_diffusion.kv_cache.paged import (
ChunkWindowSpec,
@@ -48,7 +48,7 @@ class ARDiffusionRequestAdapter:
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
An 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.
@@ -145,7 +145,7 @@ def build_kv_manager(
class ARDiffusionKVCache:
"""Owns the paged KV pool + per-request lifecycle for a AR-Diffusion model.
"""Own the paged KV pool and KV-branch-local storage for one model.
Build once per loaded model (dimensions known); then per request:
``begin_request`` → per chunk (``allocate_chunk`` → ``chunk_write_slots`` →
@@ -163,11 +163,12 @@ class ARDiffusionKVCache:
block_size: int,
max_model_len: int,
available_bytes: int,
cross_attn_length: int = 0,
cross_attn_img_length: int = 0,
kv_branches: tuple[ARDiffusionKVBranchSpec, ...],
session_capacity: int,
cross_attention_lengths: dict[str, int] | None = None,
device: torch.device | None = None,
local_branches: int = 2,
num_frame_per_block: int = 1,
frames_per_block: int = 1,
max_scratch_tokens_per_branch: int = 0,
) -> None:
if not config.enable:
raise ValueError("ARDiffusionKVCache built with a disabled ARDiffusionKVConfig")
@@ -175,77 +176,63 @@ class ARDiffusionKVCache:
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}")
if not kv_branches:
raise ValueError("ARDiffusionKVCache requires at least one KV branch")
if session_capacity <= 0:
raise ValueError(f"session_capacity must be positive, got {session_capacity}")
kv_branch_names = [kv_branch.name for kv_branch in kv_branches]
if len(kv_branch_names) != len(set(kv_branch_names)):
raise ValueError(f"ARDiffusionKVCache KV branch names must be unique, got {kv_branch_names}")
local_indices = {kv_branch.local_index for kv_branch in kv_branches}
if local_indices != set(range(max(local_indices) + 1)):
raise ValueError(
"ARDiffusionKVCache KV branch local_index values must be contiguous from zero, "
f"got {sorted(local_indices)}"
)
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.kv_branches = kv_branches
self.session_capacity = session_capacity
self._kv_branch_local_indices = {kv_branch.name: kv_branch.local_index for kv_branch in kv_branches}
self.num_local_kv_branches = max(local_indices) + 1
if frames_per_block <= 0:
raise ValueError(f"frames_per_block must be positive, got {frames_per_block}")
if max_scratch_tokens_per_branch < 0:
raise ValueError(f"max_scratch_tokens_per_branch must be non-negative, got {max_scratch_tokens_per_branch}")
self.frames_per_block = int(frames_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.cross_attention_lengths = dict(cross_attention_lengths or {})
invalid_cross = {name: length for name, length in self.cross_attention_lengths.items() if length <= 0}
if invalid_cross:
raise ValueError(f"cross_attention_lengths must be positive, got {invalid_cross}")
self.device = device or torch.device("cpu")
self._allocate_tensors = device is not None
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] = []
# Named cross-attention K/V is allocated lazily per session and released
# with that session. Reserve its worst-case capacity when sizing the
# paged self-attention pool so the two stores share one memory budget.
self._cross_sessions: dict[
str,
dict[str, dict[str, tuple[list[torch.Tensor], 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
return int(2 * len(self.kv_branches) * 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))
cross_bytes_per_session = sum(_cross_pool_bytes(length) for length in self.cross_attention_lengths.values())
cross_total_bytes = cross_bytes_per_session * session_capacity
if cross_total_bytes:
_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),
"AR-Diffusion cross-attn reservation: %.1f MiB/session × %d sessions = %.1f MiB",
cross_bytes_per_session / (1024 * 1024),
session_capacity,
cross_total_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,
@@ -260,46 +247,51 @@ class ARDiffusionKVCache:
)
# 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.
# Size the self-attn pool against memory reserved for the maximum number
# of lazily allocated cross-attention sessions.
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,
# (frames_per_block frame-blocks) for every KV 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
resident_blocks = config.sink_chunks + config.window_chunks
min_blocks = self.num_local_kv_branches * (resident_blocks + self.frames_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)",
"floor (%d local KV branch(es) x (sink_chunks=%d + window_chunks=%d "
"+ frames_per_block=%d) + 2 headroom)",
num_blocks,
min_blocks,
self.local_branches,
self.num_local_kv_branches,
config.sink_chunks,
config.window_chunks,
self.num_frame_per_block,
self.frames_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
# Scratch blocks are outside KVCacheManager ownership. A non-committing
# forward needs one block per current frame plus space for any
# model-declared action/state tokens that coexist with video KV.
declared_scratch_blocks = (max_scratch_tokens_per_branch + block_size - 1) // block_size
minimum_scratch_blocks = self.frames_per_block + declared_scratch_blocks
override = os.environ.get("AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH")
override_blocks = int(override) if override is not None else 0
if override_blocks < 0:
raise ValueError("AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH must be non-negative")
scratch_per_kv_branch = max(minimum_scratch_blocks, override_blocks)
self.scratch_blocks_per_kv_branch = scratch_per_kv_branch
self.scratch_num_blocks = self.num_local_kv_branches * scratch_per_kv_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
@@ -322,49 +314,147 @@ class ARDiffusionKVCache:
# 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(
def _kv_branch_index(self, kv_branch: str) -> int:
try:
return self._kv_branch_local_indices[kv_branch]
except KeyError as exc:
expected = tuple(self._kv_branch_local_indices)
raise KeyError(f"Unknown AR-Diffusion KV branch {kv_branch!r}; expected {expected}") from exc
def _cross_attention_pool(
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,
session_id: str,
cache_name: str,
kv_branch: str,
) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
if cache_name not in self.cross_attention_lengths:
raise KeyError(
f"Unknown AR-Diffusion cross-attention cache {cache_name!r}; "
f"expected {tuple(self.cross_attention_lengths)}"
)
self._kv_branch_index(kv_branch)
session = self._cross_sessions.get(session_id)
if session is None:
raise RuntimeError(
f"AR-Diffusion cross-attention cache {cache_name!r} for session {session_id!r} "
"was read before it was populated"
)
pool = session.get(cache_name, {}).get(kv_branch)
if pool is None:
raise RuntimeError(
f"AR-Diffusion cross-attention cache {cache_name!r} for session {session_id!r} "
f"and KV branch {kv_branch!r} was read before it was populated"
)
return pool
def is_cross_attention_populated(self, session_id: str, cache_name: str, kv_branch: str) -> bool:
"""Whether a complete logical-branch cache has been published."""
if cache_name not in self.cross_attention_lengths:
raise KeyError(
f"Unknown AR-Diffusion cross-attention cache {cache_name!r}; "
f"expected {tuple(self.cross_attention_lengths)}"
)
self._kv_branch_index(kv_branch)
session = self._cross_sessions.get(session_id)
return session is not None and kv_branch in session.get(cache_name, {})
def populate_cross_attention(
self,
session_id: str,
cache_name: str,
kv_branch: str,
layer_kv: Iterable[tuple[torch.Tensor, torch.Tensor]],
) -> None:
"""Write one layer's cross-attn K/V into the pool.
"""Atomically populate one logical branch of a named cross-attention cache.
``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.
``layer_kv`` must yield exactly one ``(k, v)`` pair per model layer.
Inputs have shape ``(B, length, local_kv_heads, head_size)``; batch zero
is copied because AR-Diffusion currently supports one sequence per
forward. The new cache is published only after every layer is copied,
so failed projection/copy work cannot expose partially initialized KV.
"""
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])
try:
length = self.cross_attention_lengths[cache_name]
except KeyError as exc:
raise KeyError(
f"Unknown AR-Diffusion cross-attention cache {cache_name!r}; "
f"expected {tuple(self.cross_attention_lengths)}"
) from exc
self._kv_branch_index(kv_branch)
session = self._cross_sessions.get(session_id)
if session is None and len(self._cross_sessions) >= self.session_capacity:
raise RuntimeError(
"AR-Diffusion cross-attention session capacity exhausted; "
"the runner must evict a session before allocating another"
)
if not self._allocate_tensors:
raise RuntimeError("AR-Diffusion cross-attention tensors require a configured pool device")
def read_cross_kv(self, layer_idx: int, is_negative: bool) -> dict:
"""Return a pool-backed cross-attn cache dict for one layer.
shape = (length, self.num_kv_heads, self.head_size)
expected_input_shape = (1, *shape)
k_pool = [torch.empty(shape, dtype=self.dtype, device=self.device) for _ in range(self.num_layers)]
v_pool = [torch.empty(shape, dtype=self.dtype, device=self.device) for _ in range(self.num_layers)]
populated_layers = 0
for layer_idx, (k, v) in enumerate(layer_kv):
if layer_idx >= self.num_layers:
raise ValueError(
f"AR-Diffusion cross-attention cache {cache_name!r} expected {self.num_layers} layers, "
f"got more than {self.num_layers}"
)
if not isinstance(k, torch.Tensor) or not isinstance(v, torch.Tensor):
raise ValueError(
f"AR-Diffusion cross-attention cache {cache_name!r} layer {layer_idx} "
f"must yield torch.Tensor k/v, got {type(k).__name__} and {type(v).__name__}"
)
if tuple(k.shape) != expected_input_shape or tuple(v.shape) != expected_input_shape:
raise ValueError(
f"AR-Diffusion cross-attention cache {cache_name!r} layer {layer_idx} expected "
f"k/v shape {expected_input_shape}, got {tuple(k.shape)} and {tuple(v.shape)}"
)
k_pool[layer_idx].copy_(k[0])
v_pool[layer_idx].copy_(v[0])
populated_layers += 1
if populated_layers != self.num_layers:
raise ValueError(
f"AR-Diffusion cross-attention cache {cache_name!r} expected {self.num_layers} layers, "
f"got {populated_layers}"
)
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
if session is None:
session = {}
self._cross_sessions[session_id] = session
session.setdefault(cache_name, {})[kv_branch] = (k_pool, v_pool)
def read_cross_attention_kv(
self,
session_id: str,
cache_name: str,
layer_idx: int,
kv_branch: str,
) -> dict[str, torch.Tensor | bool]:
"""Return a model-facing K/V dict for one named cross-attention pool."""
k_pool, v_pool = self._cross_attention_pool(session_id, cache_name, kv_branch)
return {
"is_init": True,
"k": k_pool[layer_idx].unsqueeze(0),
"v": v_pool[layer_idx].unsqueeze(0),
}
def retain_cross_attention(self, session_id: str, cache_names: Collection[str]) -> None:
"""Release named cross-attention caches not retained by an internal reset."""
session = self._cross_sessions.get(session_id)
if session is None:
return
keep = set(cache_names)
for cache_name in tuple(session):
if cache_name not in keep:
del session[cache_name]
if not session:
self._cross_sessions.pop(session_id, None)
def release_cross_attention(self, session_id: str) -> None:
"""Release every named cross-attention allocation for one session."""
self._cross_sessions.pop(session_id, None)
# -- request lifecycle ---------------------------------------------------
@@ -431,20 +521,19 @@ class ARDiffusionKVCache:
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."""
def scratch_block_ids(self, kv_branch: str, start: int, count: int) -> list[int]:
"""Return KV-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:
if start + count > self.scratch_blocks_per_kv_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."
f"need [{start}, {start + count}) of {self.scratch_blocks_per_kv_branch}. "
"Declare max_scratch_tokens_per_branch in the pipeline capability "
"or 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
kv_branch_offset = self.scratch_blocks_per_kv_branch * self._kv_branch_index(kv_branch)
base = self.managed_num_blocks + kv_branch_offset + start
return list(range(base, base + count))
def key_cache(self, layer_idx: int) -> torch.Tensor:
@@ -455,13 +544,13 @@ class ARDiffusionKVCache:
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)
return [int(block_id) for block_id in 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`
This standalone primitive is used by low-level manager tests. The
paged-attention path uses :meth:`ARDiffusionKVState.commit_paged_context`,
advances the adapter only after the forward succeeds. Call once per
committed chunk, not per denoise step.
"""