[Core] Add realtime AR-Diffusion tick sessions for LingBot World 2.0 (#5491)
Signed-off-by: zhangbin.327 <zhangbin.327@bytedance.com> Signed-off-by: Jack47 <scsvip@gmail.com> Co-authored-by: zhangbin.327 <zhangbin.327@bytedance.com> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
53 files changed
+10754
-129
No files matched your search
@@ -32,7 +32,6 @@ from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import (
|
||||
ARDiffusionPagedLayerInputs,
|
||||
ar_diffusion_paged_attention,
|
||||
paged_write_attn,
|
||||
set_current_paged_kv_cache,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -53,5 +52,4 @@ __all__ = [
|
||||
"paged_write_attn",
|
||||
"pool_write_chunk",
|
||||
"resident_block_ids",
|
||||
"set_current_paged_kv_cache",
|
||||
]
|
||||
@@ -23,7 +23,8 @@ class ARDiffusionKVConfig:
|
||||
sink_chunks: int = 0
|
||||
# Boundary reset vs. sliding replacement.
|
||||
reset_at_boundary: bool = False
|
||||
# Fraction of free device memory budgeted for the AR-Diffusion KV pool.
|
||||
# Fraction of free device memory used to admit additional resident
|
||||
# sessions. One session is admitted whenever it fits actual free memory.
|
||||
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,
|
||||
|
||||
@@ -174,6 +174,7 @@ class ARDiffusionKVCache:
|
||||
device: torch.device | None = None,
|
||||
frames_per_block: int = 1,
|
||||
max_scratch_tokens_per_branch: int = 0,
|
||||
model_owned_state_bytes_per_session: int = 0,
|
||||
) -> None:
|
||||
if not config.enable:
|
||||
raise ValueError("ARDiffusionKVCache built with a disabled ARDiffusionKVConfig")
|
||||
@@ -197,13 +198,17 @@ class ARDiffusionKVCache:
|
||||
|
||||
self.config = config
|
||||
self.kv_branches = kv_branches
|
||||
self.session_capacity = session_capacity
|
||||
self.requested_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}")
|
||||
if model_owned_state_bytes_per_session < 0:
|
||||
raise ValueError(
|
||||
f"model_owned_state_bytes_per_session must be non-negative, got {model_owned_state_bytes_per_session}"
|
||||
)
|
||||
self.frames_per_block = int(frames_per_block)
|
||||
self.block_size = block_size
|
||||
self.num_layers = num_layers
|
||||
@@ -217,28 +222,11 @@ class ARDiffusionKVCache:
|
||||
self.device = device or torch.device("cpu")
|
||||
self._allocate_tensors = device is not None
|
||||
self._adapters: dict[str, ARDiffusionRequestAdapter] = {}
|
||||
|
||||
# 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]]]],
|
||||
] = {}
|
||||
|
||||
def _cross_pool_bytes(length: int) -> int:
|
||||
return int(2 * len(self.kv_branches) * length * num_kv_heads * head_size * dtype.itemsize * num_layers)
|
||||
|
||||
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 reservation: %.1f MiB/session × %d sessions = %.1f MiB",
|
||||
cross_bytes_per_session / (1024 * 1024),
|
||||
session_capacity,
|
||||
cross_total_bytes / (1024 * 1024),
|
||||
)
|
||||
|
||||
self.spec = ChunkWindowSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=num_kv_heads,
|
||||
@@ -250,41 +238,7 @@ class ARDiffusionKVCache:
|
||||
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 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
|
||||
# (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.
|
||||
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 KV branch(es) x (sink_chunks=%d + window_chunks=%d "
|
||||
"+ frames_per_block=%d) + 2 headroom)",
|
||||
num_blocks,
|
||||
min_blocks,
|
||||
self.num_local_kv_branches,
|
||||
config.sink_chunks,
|
||||
config.window_chunks,
|
||||
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. A non-committing
|
||||
# forward needs one block per current frame plus space for any
|
||||
# model-declared action/state tokens that coexist with video KV.
|
||||
@@ -297,6 +251,101 @@ class ARDiffusionKVCache:
|
||||
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
|
||||
|
||||
# The self-attention pool, scratch pool, and lazily materialized
|
||||
# cross-attention caches share one hard memory budget. Select the largest
|
||||
# feasible resident-session count rather than raising a block-count floor
|
||||
# past that budget. All resident sessions need a complete sink + window;
|
||||
# only one request can be in flight, so frames_per_block is counted once.
|
||||
page_size_bytes = self.spec.page_size_bytes * num_layers
|
||||
self.available_memory_bytes = available_bytes
|
||||
self.configured_memory_budget_bytes = int(available_bytes * config.gpu_memory_fraction)
|
||||
# Reuse the public helper's validation for the memory fraction/page size.
|
||||
compute_num_blocks(available_bytes, config.gpu_memory_fraction, page_size_bytes)
|
||||
self.scratch_reserved_bytes = self.scratch_num_blocks * page_size_bytes
|
||||
self.model_owned_state_bytes_per_session = model_owned_state_bytes_per_session
|
||||
|
||||
def _cross_pool_bytes(length: int) -> int:
|
||||
return int(2 * len(self.kv_branches) * length * num_kv_heads * head_size * dtype.itemsize * num_layers)
|
||||
|
||||
self.cross_attention_bytes_per_session = sum(
|
||||
_cross_pool_bytes(length) for length in self.cross_attention_lengths.values()
|
||||
)
|
||||
|
||||
def _required_managed_blocks(capacity: int) -> int:
|
||||
resident_per_session = config.sink_chunks + config.window_chunks
|
||||
return self.num_local_kv_branches * (capacity * resident_per_session + self.frames_per_block) + 2
|
||||
|
||||
def _required_bytes(capacity: int) -> int:
|
||||
return (
|
||||
self.scratch_reserved_bytes
|
||||
+ capacity * self.cross_attention_bytes_per_session
|
||||
+ capacity * self.model_owned_state_bytes_per_session
|
||||
+ _required_managed_blocks(capacity) * page_size_bytes
|
||||
)
|
||||
|
||||
one_session_bytes = _required_bytes(1)
|
||||
if one_session_bytes > available_bytes:
|
||||
raise ValueError(
|
||||
"AR-Diffusion available device memory cannot fit one session: "
|
||||
f"available={available_bytes} bytes, required={one_session_bytes} bytes "
|
||||
"(managed self-attention + cross-attention + scratch + model-owned state)."
|
||||
)
|
||||
self.memory_budget_bytes = max(self.configured_memory_budget_bytes, one_session_bytes)
|
||||
if self.memory_budget_bytes > self.configured_memory_budget_bytes:
|
||||
_log.warning(
|
||||
"AR-Diffusion raised the configured memory budget from %d to %d bytes "
|
||||
"to admit one session that fits actual free device memory",
|
||||
self.configured_memory_budget_bytes,
|
||||
self.memory_budget_bytes,
|
||||
)
|
||||
|
||||
effective_capacity = 0
|
||||
required_managed_blocks = 0
|
||||
for candidate in range(session_capacity, 0, -1):
|
||||
candidate_managed_blocks = _required_managed_blocks(candidate)
|
||||
if _required_bytes(candidate) <= self.memory_budget_bytes:
|
||||
effective_capacity = candidate
|
||||
required_managed_blocks = candidate_managed_blocks
|
||||
break
|
||||
assert effective_capacity > 0
|
||||
|
||||
self.session_capacity = effective_capacity
|
||||
self.cross_attention_reserved_bytes = self.cross_attention_bytes_per_session * effective_capacity
|
||||
self.model_owned_state_reserved_bytes = self.model_owned_state_bytes_per_session * effective_capacity
|
||||
self_attn_budget_bytes = (
|
||||
self.memory_budget_bytes
|
||||
- self.scratch_reserved_bytes
|
||||
- self.cross_attention_reserved_bytes
|
||||
- self.model_owned_state_reserved_bytes
|
||||
)
|
||||
num_blocks = self_attn_budget_bytes // page_size_bytes
|
||||
assert num_blocks >= required_managed_blocks
|
||||
if effective_capacity < session_capacity:
|
||||
_log.warning(
|
||||
"AR-Diffusion resident session capacity reduced from %d to %d by the KV memory budget",
|
||||
session_capacity,
|
||||
effective_capacity,
|
||||
)
|
||||
if self.cross_attention_reserved_bytes:
|
||||
_log.info(
|
||||
"AR-Diffusion cross-attn reservation: %.1f MiB/session × %d sessions = %.1f MiB",
|
||||
self.cross_attention_bytes_per_session / (1024 * 1024),
|
||||
effective_capacity,
|
||||
self.cross_attention_reserved_bytes / (1024 * 1024),
|
||||
)
|
||||
if self.model_owned_state_reserved_bytes:
|
||||
_log.info(
|
||||
"AR-Diffusion model-owned state reservation: %.1f MiB/session × %d sessions = %.1f MiB",
|
||||
self.model_owned_state_bytes_per_session / (1024 * 1024),
|
||||
effective_capacity,
|
||||
self.model_owned_state_reserved_bytes / (1024 * 1024),
|
||||
)
|
||||
|
||||
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
|
||||
self.num_blocks_total = self.managed_num_blocks + self.scratch_num_blocks
|
||||
self.null_block_id = self.manager.block_pool.null_block.block_id
|
||||
|
||||
@@ -561,6 +610,11 @@ class ARDiffusionKVCache:
|
||||
"""
|
||||
_log.debug("AR-Diffusion commit: req=%s before=%d", adapter.request_id, adapter.completed_chunks)
|
||||
adapter.on_chunk_committed()
|
||||
self.manager.remove_skipped_blocks(
|
||||
adapter.request_id,
|
||||
adapter.num_computed_tokens,
|
||||
num_prompt_tokens=adapter.num_prompt_tokens,
|
||||
)
|
||||
_log.debug("AR-Diffusion commit: req=%s after=%d", adapter.request_id, adapter.completed_chunks)
|
||||
|
||||
# -- pool-backed K/V access --------------------------------------------
|
||||
|
||||
@@ -10,19 +10,6 @@ import torch
|
||||
|
||||
from vllm_omni.experimental.ar_diffusion.kv_cache.paged import compute_slot_mapping
|
||||
|
||||
# Set by ARDiffusionPagedForwardContext.prepare() before each KV 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] = {}
|
||||
|
||||
|
||||
@@ -50,6 +37,9 @@ class ARDiffusionPagedLayerInputs(NamedTuple):
|
||||
"""
|
||||
|
||||
layer_idx: torch.Tensor
|
||||
key_pool: torch.Tensor
|
||||
value_pool: torch.Tensor
|
||||
block_size: int
|
||||
seq_len: int
|
||||
video_slots: torch.Tensor
|
||||
action_slots: torch.Tensor
|
||||
@@ -228,7 +218,6 @@ class ARDiffusionPagedForwardContext:
|
||||
) = 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:
|
||||
@@ -236,6 +225,9 @@ class ARDiffusionPagedForwardContext:
|
||||
raise RuntimeError("ARDiffusionPagedForwardContext.layer_inputs() before prepare()")
|
||||
return ARDiffusionPagedLayerInputs(
|
||||
layer_idx=_layer_idx_tensor(layer_idx),
|
||||
key_pool=self.kv_cache._k_pools[layer_idx],
|
||||
value_pool=self.kv_cache._v_pools[layer_idx],
|
||||
block_size=int(self.kv_cache.block_size),
|
||||
seq_len=int(self.seq_len),
|
||||
video_slots=self.current_video_slot_mapping,
|
||||
action_slots=self.action_slot_mapping,
|
||||
@@ -476,17 +468,18 @@ def ar_diffusion_paged_attention(
|
||||
# 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.
|
||||
# is internal. The flat pools are explicit mutable inputs: Inductor/CUDA Graph
|
||||
# must track their storage lifetime instead of observing an undeclared mutation
|
||||
# through a process-global registry.
|
||||
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,
|
||||
key_pool: torch.Tensor,
|
||||
value_pool: torch.Tensor,
|
||||
block_size: int,
|
||||
video_slots: torch.Tensor,
|
||||
action_slots: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
@@ -496,21 +489,17 @@ def _paged_write_attn_impl(
|
||||
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)
|
||||
key_pool[video_slots] = k_curr.to(key_pool.dtype)
|
||||
value_pool[video_slots] = v_curr.to(value_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)
|
||||
key_pool[action_slots] = k_act.to(key_pool.dtype)
|
||||
value_pool[action_slots] = v_act.to(value_pool.dtype)
|
||||
key_cache = key_pool.unflatten(0, (-1, block_size))
|
||||
value_cache = value_pool.unflatten(0, (-1, block_size))
|
||||
return ar_diffusion_paged_attention(
|
||||
query,
|
||||
kv.key_cache(layer_idx),
|
||||
kv.value_cache(layer_idx),
|
||||
key_cache,
|
||||
value_cache,
|
||||
block_table=block_table,
|
||||
query_start_loc=query_start_loc,
|
||||
seq_lens=seq_lens,
|
||||
@@ -525,14 +514,19 @@ def _paged_write_attn_impl(
|
||||
# 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=())
|
||||
@torch.library.custom_op(
|
||||
"vllm_omni::ar_diffusion_paged_write_attn",
|
||||
mutates_args=("key_pool", "value_pool"),
|
||||
)
|
||||
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,
|
||||
key_pool: torch.Tensor,
|
||||
value_pool: torch.Tensor,
|
||||
block_size: int,
|
||||
video_slots: torch.Tensor,
|
||||
action_slots: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
@@ -548,7 +542,9 @@ if not hasattr(torch.ops.vllm_omni, "ar_diffusion_paged_write_attn"):
|
||||
v_curr,
|
||||
k_act,
|
||||
v_act,
|
||||
layer_idx,
|
||||
key_pool,
|
||||
value_pool,
|
||||
block_size,
|
||||
video_slots,
|
||||
action_slots,
|
||||
block_table,
|
||||
@@ -566,7 +562,9 @@ if not hasattr(torch.ops.vllm_omni, "ar_diffusion_paged_write_attn"):
|
||||
v_curr,
|
||||
k_act,
|
||||
v_act,
|
||||
layer_idx,
|
||||
key_pool,
|
||||
value_pool,
|
||||
block_size,
|
||||
video_slots,
|
||||
action_slots,
|
||||
block_table,
|
||||
@@ -589,7 +587,9 @@ def paged_write_attn(
|
||||
v_curr,
|
||||
k_act,
|
||||
v_act,
|
||||
inputs.layer_idx,
|
||||
inputs.key_pool,
|
||||
inputs.value_pool,
|
||||
inputs.block_size,
|
||||
inputs.video_slots,
|
||||
inputs.action_slots,
|
||||
inputs.block_table,
|
||||
|
||||
@@ -130,7 +130,7 @@ class ARDiffusionKVState:
|
||||
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.kv_cache.commit_chunk(ctx.adapter)
|
||||
self._committed[kv_branch] += ctx.seq_len
|
||||
_log.debug(
|
||||
"AR-Diffusion COMMIT [%s] new_tokens=%d chunks=%d resident=%d/%d",
|
||||
@@ -173,6 +173,17 @@ class ARDiffusionKVState:
|
||||
for i in range(self.num_layers)
|
||||
]
|
||||
|
||||
def clear_cross_attention(self) -> None:
|
||||
"""Invalidate all named cross-attention caches without dropping self-KV.
|
||||
|
||||
Prompt changes may preserve the autoregressive world history while
|
||||
requiring fresh text projections. This operation deliberately leaves
|
||||
branch adapters and their resident self-attention blocks untouched.
|
||||
"""
|
||||
if self._closed:
|
||||
raise RuntimeError(f"AR-Diffusion session {self.session_id!r} is closed")
|
||||
self.kv_cache.release_cross_attention(self.session_id)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Release all self- and cross-attention storage owned by this session."""
|
||||
if self._closed:
|
||||
|
||||
Reference in new issue
Block a user