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

@@ -0,0 +1,317 @@
# SPDX-License-Identifier: Apache-2.0
"""CPU contracts for capability-driven AR-Diffusion sessions."""
from __future__ import annotations
from collections import OrderedDict
from contextlib import contextmanager
from types import SimpleNamespace
import pytest
import torch
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
from vllm_omni.experimental.ar_diffusion.capability import (
ARDiffusionCrossAttentionKVSpec,
ARDiffusionKVBranchSpec,
ARDiffusionKVCacheSpec,
)
from vllm_omni.experimental.ar_diffusion.kv_cache import ARDiffusionKVConfig
from vllm_omni.experimental.ar_diffusion.runner import ARDiffusionModelRunner
BLOCK = 16
POS = "positive"
NEG = "negative"
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def lingbot_like_spec(*, capacity: int = 2) -> ARDiffusionKVCacheSpec:
"""Single-kv_branch causal DMD: 3 latent frames/block + sink/window + text KV."""
return ARDiffusionKVCacheSpec(
num_layers=2,
num_kv_heads=4, # already TP-local
head_size=64,
tokens_per_frame=BLOCK,
frames_per_block=3,
window_frames=5,
sink_frames=1,
kv_branches=(ARDiffusionKVBranchSpec("main", 0),),
session_capacity=capacity,
cross_attention=(ARDiffusionCrossAttentionKVSpec("text", 8),),
)
def dreamzero_like_spec(*, capacity: int = 2) -> ARDiffusionKVCacheSpec:
return ARDiffusionKVCacheSpec(
num_layers=2,
num_kv_heads=4,
head_size=64,
tokens_per_frame=BLOCK,
frames_per_block=4,
window_frames=6,
kv_branches=(ARDiffusionKVBranchSpec(POS, 0), ARDiffusionKVBranchSpec(NEG, 1)),
session_capacity=capacity,
cross_attention=(ARDiffusionCrossAttentionKVSpec("text", 8),),
)
class CapablePipeline:
def __init__(self, spec: ARDiffusionKVCacheSpec) -> None:
self.spec = spec
self.bound_state = None
self.binds: list[str] = []
self.resets: list[str] = []
self.closes: list[str] = []
def ar_diffusion_kv_cache_spec(self) -> ARDiffusionKVCacheSpec:
return self.spec
@contextmanager
def bind_ar_diffusion_state(self, session_id: str, state):
assert self.bound_state is None
self.bound_state = state
self.binds.append(session_id)
try:
yield
finally:
self.bound_state = None
def reset_ar_diffusion_session(self, session_id: str) -> None:
self.resets.append(session_id)
def close_ar_diffusion_session(self, session_id: str) -> None:
self.closes.append(session_id)
class WarmupPipeline(CapablePipeline):
def __init__(self, spec: ARDiffusionKVCacheSpec, requests: list[object]) -> None:
super().__init__(spec)
self.requests = requests
def ar_diffusion_warmup_requests(self, session_id: str):
assert session_id == ARDiffusionModelRunner._WARMUP_SID
return iter(self.requests)
class BatchCapablePipeline(CapablePipeline):
supports_request_batch = True
def make_runner(
pipeline: object,
*,
available_bytes: int = 1 << 28,
step_execution: bool = False,
) -> ARDiffusionModelRunner:
runner = object.__new__(ARDiffusionModelRunner)
runner.od_config = SimpleNamespace(
max_num_seqs=1,
dtype=torch.float32,
enforce_eager=True,
step_execution=step_execution,
)
runner.device = torch.device("cpu")
runner.pipeline = pipeline
runner.ar_diffusion_kv_config = ARDiffusionKVConfig(enable=True)
runner.kv_cache = None
runner._ar_diffusion_capability = None
runner._ar_diffusion_kv_cache_spec = None
runner._sessions = OrderedDict()
runner._session_capacity = 0
runner._perf_e2e_times = []
runner._preallocate_kv_cache(available_bytes=available_bytes)
return runner
def commit_one_frame(runner: ARDiffusionModelRunner, session_id: str, kv_branch: str):
state = runner._get_or_create_session(session_id)
ctx = state.get_kv_caches(kv_branch, seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx.ensure_video_slots(torch.device("cpu"))
state.commit_paged_context(kv_branch)
return state
def test_ar_runner_rejects_pipeline_without_capability():
runner = object.__new__(ARDiffusionModelRunner)
runner.od_config = SimpleNamespace(max_num_seqs=1)
runner.pipeline = object()
with pytest.raises(TypeError, match="SupportsARDiffusionPipeline"):
runner._preallocate_kv_cache(available_bytes=1 << 20)
def test_lingbot_like_single_branch_session_reuse_reset_and_close():
pipeline = CapablePipeline(lingbot_like_spec())
runner = make_runner(pipeline)
kv = runner.kv_cache
assert kv is not None
assert kv.num_local_kv_branches == 1
assert kv.frames_per_block == 3
assert kv.spec.window_chunks == 5
assert kv.spec.sink_chunks == 1
assert kv.cross_attention_lengths == {"text": 8}
first = commit_one_frame(runner, "s1", "main")
assert runner._get_or_create_session("s1") is first
k = torch.randn(1, 8, 4, 64)
v = torch.randn(1, 8, 4, 64)
first.populate_cross_attention("main", "text", [(k, v)] * first.num_layers)
assert first.get_cross_attention_kv("main", "text")[0]["k"].shape == k.shape
runner.reset_session("s1")
assert "s1" not in runner._sessions
assert "s1" not in kv._cross_sessions
assert pipeline.resets == ["s1"]
second = runner._get_or_create_session("s1")
assert second is not first
runner.close_session("s1")
assert "s1" not in runner._sessions
assert pipeline.closes == ["s1"]
def test_lingbot_like_sink_survives_sliding_window_eviction():
runner = make_runner(CapablePipeline(lingbot_like_spec()))
kv = runner.kv_cache
assert kv is not None
for _ in range(8):
state = commit_one_frame(runner, "s1", "main")
table = kv.block_table(state.adapter("main"))
assert table[0] != kv.null_block_id
assert table[1] == kv.null_block_id
ctx = state.get_kv_caches("main", seq_len=BLOCK, commit_current=False)[0].forward_ctx
visible, _ = ctx.video_block_table(torch.device("cpu"))
assert visible[0] == table[0]
assert len(visible) == 6 # sink + recent window, including current scratch
def test_dreamzero_like_two_branches_are_independent():
runner = make_runner(CapablePipeline(dreamzero_like_spec()))
kv = runner.kv_cache
assert kv is not None and kv.num_local_kv_branches == 2
state = commit_one_frame(runner, "s1", POS)
assert len(kv.window_block_ids(state.adapter(POS))) == 1
assert kv.window_block_ids(state.adapter(NEG)) == []
def test_lru_eviction_releases_blocks_and_notifies_pipeline():
pipeline = CapablePipeline(lingbot_like_spec(capacity=8))
runner = make_runner(pipeline)
kv = runner.kv_cache
assert kv is not None
assert runner._session_capacity == 1
assert kv.session_capacity == 1
free_total = kv.manager.block_pool.get_num_free_blocks()
old = commit_one_frame(runner, "old", "main")
k = torch.randn(1, 8, 4, 64)
old.populate_cross_attention("main", "text", [(k, k)] * old.num_layers)
assert kv.manager.block_pool.get_num_free_blocks() < free_total
runner._get_or_create_session("new")
assert tuple(runner._sessions) == ("new",)
assert pipeline.closes == ["old"]
assert "old" not in kv._cross_sessions
assert kv.manager.block_pool.get_num_free_blocks() == free_total
def test_forward_exception_releases_pending_allocation_and_model_state(monkeypatch):
pipeline = CapablePipeline(lingbot_like_spec())
runner = make_runner(pipeline)
kv = runner.kv_cache
assert kv is not None
free_total = kv.manager.block_pool.get_num_free_blocks()
def boom(self, req, kv_prefetch_job=None):
state = pipeline.bound_state
ctx = state.get_kv_caches("main", seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx.ensure_video_slots(torch.device("cpu"))
raise RuntimeError("layer exploded")
monkeypatch.setattr(DiffusionModelRunner, "execute_model", boom)
request = SimpleNamespace(sampling_params=SimpleNamespace(extra_args={"session_id": "broken"}))
with pytest.raises(RuntimeError, match="layer exploded"):
runner.execute_model(request)
assert pipeline.bound_state is None
assert pipeline.closes == ["broken"]
assert not runner._sessions
assert not kv._adapters
assert kv.manager.block_pool.get_num_free_blocks() == free_total
def test_synchronize_exception_uses_forward_cleanup_path(monkeypatch):
pipeline = CapablePipeline(lingbot_like_spec())
runner = make_runner(pipeline)
kv = runner.kv_cache
assert kv is not None
free_total = kv.manager.block_pool.get_num_free_blocks()
def return_after_allocation(self, req, kv_prefetch_job=None):
state = pipeline.bound_state
ctx = state.get_kv_caches("main", seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx.ensure_video_slots(torch.device("cpu"))
return object()
def synchronize_boom(device):
raise RuntimeError("asynchronous kernel failed")
monkeypatch.setattr(DiffusionModelRunner, "execute_model", return_after_allocation)
monkeypatch.setattr(torch.accelerator, "synchronize", synchronize_boom)
runner.device = torch.device("cuda")
request = SimpleNamespace(sampling_params=SimpleNamespace(extra_args={"session_id": "broken"}))
with pytest.raises(RuntimeError, match="asynchronous kernel failed"):
runner.execute_model(request)
assert pipeline.bound_state is None
assert pipeline.closes == ["broken"]
assert not runner._sessions
assert not kv._adapters
assert not runner._perf_e2e_times
assert kv.manager.block_pool.get_num_free_blocks() == free_total
def test_ar_runner_rejects_step_and_request_batch_modes():
with pytest.raises(ValueError, match="step_execution=True"):
make_runner(CapablePipeline(lingbot_like_spec()), step_execution=True)
with pytest.raises(ValueError, match="request-batch execution"):
make_runner(BatchCapablePipeline(lingbot_like_spec()))
def test_ar_runner_defensively_rejects_inherited_batch_and_step_entrypoints():
runner = object.__new__(ARDiffusionModelRunner)
with pytest.raises(RuntimeError, match="request-batch execution"):
runner.execute_model_batch(None, None)
with pytest.raises(RuntimeError, match="step execution"):
runner.execute_stepwise(None)
def test_model_specific_warmup_provider_is_consumed(monkeypatch):
requests = [object(), object()]
pipeline = WarmupPipeline(lingbot_like_spec(), requests)
runner = make_runner(pipeline)
seen: list[object] = []
monkeypatch.setattr(runner, "execute_model", seen.append)
runner._warmup_ar_rollout()
assert seen == requests
assert pipeline.closes == [runner._WARMUP_SID]
def test_pipeline_without_warmup_provider_is_safely_skipped(monkeypatch):
pipeline = CapablePipeline(lingbot_like_spec())
runner = make_runner(pipeline)
execute = SimpleNamespace(called=False)
def fail_if_called(request):
execute.called = True
monkeypatch.setattr(runner, "execute_model", fail_if_called)
runner._warmup_ar_rollout()
assert execute.called is False
+66 -18
View File
@@ -12,6 +12,7 @@ from vllm.v1.kv_cache_interface import KVCacheSpecKind, get_kv_cache_spec_kind
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
from vllm.v1.request import RequestStatus
from vllm_omni.experimental.ar_diffusion.capability import ARDiffusionKVBranchSpec
from vllm_omni.experimental.ar_diffusion.kv_cache import (
ARDiffusionKVCache,
ARDiffusionKVConfig,
@@ -194,16 +195,29 @@ def test_cross_attn_pool_deducted_from_self_attn_budget():
block_size=BLOCK,
max_model_len=4096,
available_bytes=avail,
cross_attn_length=L,
kv_branches=(ARDiffusionKVBranchSpec("positive", 0), ARDiffusionKVBranchSpec("negative", 0)),
session_capacity=1,
cross_attention_lengths={"text": L},
device=torch.device("cpu"),
)
cross_bytes = 2 * 2 * L * 4 * 64 * torch.float16.itemsize * 2 # K+V, pos+neg, layers
expected = compute_num_blocks(avail - cross_bytes, 0.5, kv.spec.page_size_bytes * 2)
assert kv.num_blocks == expected
assert expected > 2 * (2 + 1) + 2 # above the min-blocks floor, so the deduction is what's tested
assert expected > 1 * (2 + 1) + 2 # above the local-slot floor, so the cross deduction is what's tested
def _make_kv(*, local_branches, num_frame_per_block=2, window_chunks=9):
def _make_kv(
*,
local_branches,
num_frame_per_block=2,
window_chunks=9,
max_scratch_tokens_per_branch=0,
):
kv_branches = (
(ARDiffusionKVBranchSpec("positive", 0), ARDiffusionKVBranchSpec("negative", 0))
if local_branches == 1
else (ARDiffusionKVBranchSpec("positive", 0), ARDiffusionKVBranchSpec("negative", 1))
)
return ARDiffusionKVCache(
ARDiffusionKVConfig(enable=True, chunk_size=BLOCK, window_chunks=window_chunks),
num_layers=1,
@@ -214,41 +228,75 @@ def _make_kv(*, local_branches, num_frame_per_block=2, window_chunks=9):
max_model_len=4096,
available_bytes=1 << 16, # tiny -> the floor binds
device=torch.device("cpu"),
local_branches=local_branches,
num_frame_per_block=num_frame_per_block,
kv_branches=kv_branches,
session_capacity=1,
frames_per_block=num_frame_per_block,
max_scratch_tokens_per_branch=max_scratch_tokens_per_branch,
)
def test_pool_floor_is_branch_aware():
"""CFG-parallel rank (one local branch) sizes for one window + in-flight chunk;
a single-process run (both branches) sizes for two. Scratch scales the same way."""
"""CFG-parallel rank (one local kv_branch) sizes for one window + in-flight chunk;
a single-process run (both kv_branches) sizes for two. Scratch scales the same way."""
one = _make_kv(local_branches=1)
two = _make_kv(local_branches=2)
assert one.managed_num_blocks == 1 * (9 + 2) + 2 # 13
assert two.managed_num_blocks == 2 * (9 + 2) + 2 # 24
assert one.scratch_num_blocks == one.scratch_blocks_per_branch
assert two.scratch_num_blocks == 2 * two.scratch_blocks_per_branch
assert one.num_blocks_total == 13 + one.scratch_blocks_per_branch
assert one.scratch_num_blocks == one.scratch_blocks_per_kv_branch
assert two.scratch_num_blocks == 2 * two.scratch_blocks_per_kv_branch
assert one.scratch_blocks_per_kv_branch == 2
assert one.num_blocks_total == 13 + one.scratch_blocks_per_kv_branch
def test_scratch_capacity_is_derived_from_declared_geometry(monkeypatch):
monkeypatch.delenv("AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH", raising=False)
kv = _make_kv(
local_branches=1,
num_frame_per_block=6,
max_scratch_tokens_per_branch=BLOCK + 1,
)
assert kv.scratch_blocks_per_kv_branch == 8 # six video blocks + two auxiliary blocks
def test_scratch_env_override_cannot_reduce_declared_minimum(monkeypatch):
monkeypatch.setenv("AR_DIFFUSION_KV_SCRATCH_BLOCKS_PER_BRANCH", "1")
kv = _make_kv(
local_branches=1,
num_frame_per_block=6,
max_scratch_tokens_per_branch=BLOCK + 1,
)
assert kv.scratch_blocks_per_kv_branch == 8
def test_scratch_maps_to_slot_zero_with_one_local_branch():
"""A CFG-parallel rank runs exactly one branch: whichever CFG side it is,
"""A CFG-parallel rank runs exactly one kv_branch: whichever CFG side it is,
its scratch lands in the rank's single slot (no dead second slot)."""
one = _make_kv(local_branches=1)
assert one.scratch_block_ids(True, 0, 2) == one.scratch_block_ids(False, 0, 2)
assert one.scratch_block_ids("positive", 0, 2) == one.scratch_block_ids("negative", 0, 2)
two = _make_kv(local_branches=2)
assert two.scratch_block_ids(True, 0, 2) != two.scratch_block_ids(False, 0, 2)
assert two.scratch_block_ids("positive", 0, 2) != two.scratch_block_ids("negative", 0, 2)
def test_scratch_exhaustion_still_raises():
one = _make_kv(local_branches=1)
cap = one.scratch_blocks_per_branch
cap = one.scratch_blocks_per_kv_branch
with pytest.raises(RuntimeError, match="scratch blocks exhausted"):
one.scratch_block_ids(False, 0, cap + 1)
one.scratch_block_ids("positive", 0, cap + 1)
def test_invalid_local_branches_rejected():
with pytest.raises(ValueError, match="local_branches"):
_make_kv(local_branches=3)
def test_non_contiguous_branch_indices_rejected():
with pytest.raises(ValueError, match="contiguous"):
ARDiffusionKVCache(
ARDiffusionKVConfig(enable=True, chunk_size=BLOCK, window_chunks=2),
num_layers=1,
num_kv_heads=4,
head_size=64,
dtype=torch.float32,
block_size=BLOCK,
max_model_len=4096,
available_bytes=1 << 16,
kv_branches=(ARDiffusionKVBranchSpec("main", 1),),
session_capacity=1,
)
+18 -4
View File
@@ -4,9 +4,18 @@
import pytest
import torch
from vllm_omni.experimental.ar_diffusion.capability import ARDiffusionKVBranchSpec
from vllm_omni.experimental.ar_diffusion.kv_cache import ARDiffusionKVCache, ARDiffusionKVConfig
DIMS = dict(num_layers=2, num_kv_heads=4, head_size=64, dtype=torch.float16, block_size=16)
DIMS = dict(
num_layers=2,
num_kv_heads=4,
head_size=64,
dtype=torch.float16,
block_size=16,
kv_branches=(ARDiffusionKVBranchSpec("positive", 0), ARDiffusionKVBranchSpec("negative", 1)),
session_capacity=2,
)
def make_cache(*, chunk_size=16, window_chunks=2, available_bytes=1 << 24):
@@ -67,7 +76,7 @@ def test_num_computed_advances_per_chunk():
def test_state_close_frees_both_branch_blocks():
"""ARDiffusionKVState.close() returns both CFG branches' pool blocks to the pool.
"""ARDiffusionKVState.close() returns both CFG kv_branches' pool blocks to the pool.
This is the primitive the runner's LRU eviction relies on: when a session is
evicted, close() must free the blocks both adapters hold, or session churn
@@ -80,12 +89,17 @@ def test_state_close_frees_both_branch_blocks():
pos = kv.begin_request("bde__s")
neg = kv.begin_request("bde__s__neg")
state = ARDiffusionKVState(kv, pos, neg, num_layers=kv.num_layers)
state = ARDiffusionKVState(
kv,
"s",
{"positive": pos, "negative": neg},
num_layers=kv.num_layers,
)
for _ in range(3):
for adapter in (pos, neg):
kv.allocate_chunk(adapter)
kv.commit_chunk(adapter)
# Both branches hold resident blocks now.
# Both kv_branches hold resident blocks now.
assert kv.manager.block_pool.get_num_free_blocks() < free_total
state.close()
+38 -31
View File
@@ -11,6 +11,7 @@ from unittest.mock import MagicMock
import pytest
import torch
from vllm_omni.experimental.ar_diffusion.capability import ARDiffusionKVBranchSpec
from vllm_omni.experimental.ar_diffusion.kv_cache import (
ARDiffusionKVCache,
ARDiffusionKVConfig,
@@ -24,6 +25,8 @@ from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVStat
BLOCK = 16
N_HEADS = 4
HEAD_DIM = 64
POS = "positive"
NEG = "negative"
def make_state(*, num_layers=1, window_chunks=2, dtype=torch.float32, device=torch.device("cpu")):
@@ -37,11 +40,15 @@ def make_state(*, num_layers=1, window_chunks=2, dtype=torch.float32, device=tor
block_size=BLOCK,
max_model_len=4096,
available_bytes=1 << 26,
kv_branches=(ARDiffusionKVBranchSpec(POS, 0), ARDiffusionKVBranchSpec(NEG, 1)),
session_capacity=2,
frames_per_block=2,
max_scratch_tokens_per_branch=BLOCK,
device=device,
)
pos = kv.begin_request("r-pos")
neg = kv.begin_request("r-neg")
return kv, ARDiffusionKVState(kv, pos, neg, num_layers=num_layers)
return kv, ARDiffusionKVState(kv, "s1", {POS: pos, NEG: neg}, num_layers=num_layers)
def _dense_attention(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
@@ -79,51 +86,51 @@ def _commit_video_span(
kv: ARDiffusionKVCache,
st: ARDiffusionKVState,
*,
is_negative: bool,
kv_branch: str,
n_chunks: int,
dtype: torch.dtype,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
ctx = st.get_kv_caches(is_negative, seq_len=n_chunks * BLOCK, commit_current=True)[0].forward_ctx
ctx = st.get_kv_caches(kv_branch, seq_len=n_chunks * BLOCK, commit_current=True)[0].forward_ctx
ctx.ensure_video_slots(device)
k = torch.randn(1, n_chunks * BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
v = torch.randn(1, n_chunks * BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
kv._k_pools[0][ctx.current_video_slot_mapping] = k[0]
kv._v_pools[0][ctx.current_video_slot_mapping] = v[0]
st.commit_paged_context(is_negative)
st.commit_paged_context(kv_branch)
return k, v
def test_paged_context_allocates_lazily_and_commits_after_forward():
_, st = make_state()
contexts = st.get_kv_caches(False, seq_len=BLOCK, commit_current=True)
contexts = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=True)
ctx = contexts[0].forward_ctx
assert isinstance(contexts[0], ARDiffusionPagedLayerContext)
assert st.pos.completed_chunks == 0
assert st.adapter(POS).completed_chunks == 0
assert ctx.current_video_slot_mapping is None
ctx.ensure_video_slots(torch.device("cpu"))
assert st.pos.completed_chunks == 0
assert st.adapter(POS).completed_chunks == 0
assert len(ctx.current_video_block_ids) == 1
st.commit_paged_context(False)
assert st.pos.completed_chunks == 1
assert st._committed[False] == BLOCK
st.commit_paged_context(POS)
assert st.adapter(POS).completed_chunks == 1
assert st._committed[POS] == BLOCK
def test_scratch_video_and_action_blocks_do_not_commit():
kv, st = make_state()
ctx = st.get_kv_caches(False, seq_len=2 * BLOCK, commit_current=False)[0].forward_ctx
ctx = st.get_kv_caches(POS, seq_len=2 * BLOCK, commit_current=False)[0].forward_ctx
ctx.ensure_video_slots(torch.device("cpu"))
ctx.ensure_action_slots(3, torch.device("cpu"))
assert ctx.current_video_block_ids == kv.scratch_block_ids(False, 0, 2)
assert ctx.action_scratch_block_ids == kv.scratch_block_ids(False, 2, 1)
st.commit_paged_context(False)
assert st.pos.completed_chunks == 0
assert st._committed[False] == 0
assert ctx.current_video_block_ids == kv.scratch_block_ids(POS, 0, 2)
assert ctx.action_scratch_block_ids == kv.scratch_block_ids(POS, 2, 1)
st.commit_paged_context(POS)
assert st.adapter(POS).completed_chunks == 0
assert st._committed[POS] == 0
def test_pipeline_kv_get_paged_path_has_no_gather_backend():
@@ -155,7 +162,7 @@ def test_paged_attention_matches_dense_reference_cpu(history_chunks, action_len,
k, v = _commit_video_span(
kv,
st,
is_negative=False,
kv_branch=POS,
n_chunks=history_chunks,
dtype=dtype,
device=device,
@@ -163,7 +170,7 @@ def test_paged_attention_matches_dense_reference_cpu(history_chunks, action_len,
history_k_parts.append(k)
history_v_parts.append(v)
ctx = st.get_kv_caches(False, seq_len=BLOCK, commit_current=commit_current)[0].forward_ctx
ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=commit_current)[0].forward_ctx
ctx.ensure_video_slots(device)
current_k = torch.randn(1, BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
current_v = torch.randn(1, BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
@@ -212,9 +219,9 @@ def test_paged_attention_matches_dense_reference_cpu(history_chunks, action_len,
torch.testing.assert_close(paged, ref, rtol=1e-5, atol=1e-5)
before = st.pos.completed_chunks
st.commit_paged_context(False)
assert st.pos.completed_chunks == before + (1 if commit_current else 0)
before = st.adapter(POS).completed_chunks
st.commit_paged_context(POS)
assert st.adapter(POS).completed_chunks == before + (1 if commit_current else 0)
@pytest.mark.skipif(not _cuda_flash_attn_usable(), reason="usable CUDA FlashAttention is required")
@@ -231,13 +238,13 @@ def test_paged_attention_matches_dense_reference_gpu(history_chunks, action_len,
history_k, history_v = _commit_video_span(
kv,
st,
is_negative=False,
kv_branch=POS,
n_chunks=history_chunks,
dtype=dtype,
device=device,
)
layer_ctx = st.get_kv_caches(False, seq_len=BLOCK, commit_current=commit_current)[0]
layer_ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=commit_current)[0]
ctx = layer_ctx.forward_ctx
current_k = torch.randn(1, BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
current_v = torch.randn(1, BLOCK, N_HEADS, HEAD_DIM, dtype=dtype, device=device)
@@ -294,13 +301,13 @@ def test_block_table_padded_to_fixed_width():
device = torch.device("cpu")
kv, st = make_state(window_chunks=2)
ctx1 = st.get_kv_caches(False, seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx1 = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx1.prepare(device=device, action_len=0, query_len=BLOCK)
st.commit_paged_context(False)
st.commit_paged_context(POS)
ctx2 = st.get_kv_caches(False, seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx2 = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=True)[0].forward_ctx
ctx2.prepare(device=device, action_len=0, query_len=BLOCK)
st.commit_paged_context(False)
st.commit_paged_context(POS)
# 1-block vs 2-block visible history: same table width, same max_seq_len.
assert ctx1.block_table.shape == ctx2.block_table.shape
@@ -315,7 +322,7 @@ def test_block_table_padded_to_fixed_width():
def test_prepare_is_idempotent_and_layers_share_metadata():
device = torch.device("cpu")
_, st = make_state(num_layers=2)
contexts = st.get_kv_caches(False, seq_len=BLOCK, commit_current=False)
contexts = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)
fctx = contexts[0].forward_ctx
fctx.prepare(device=device, action_len=0, query_len=BLOCK)
table = fctx.block_table
@@ -335,7 +342,7 @@ def test_prepare_is_idempotent_and_layers_share_metadata():
def test_layer_inputs_before_prepare_raises():
_, st = make_state()
layer_ctx = st.get_kv_caches(False, seq_len=BLOCK, commit_current=False)[0]
layer_ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)[0]
with pytest.raises(RuntimeError, match="before prepare"):
layer_ctx.to_layer_inputs()
@@ -363,7 +370,7 @@ def test_custom_op_compiles_fullgraph_without_recompile_on_value_change():
kv, st = make_state(num_layers=2, window_chunks=2)
def run_one_forward(commit):
contexts = st.get_kv_caches(False, seq_len=BLOCK, commit_current=commit)
contexts = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=commit)
fctx = contexts[0].forward_ctx
fctx.prepare(device=device, action_len=0, query_len=BLOCK)
q = torch.randn(BLOCK, N_HEADS, HEAD_DIM)
@@ -374,7 +381,7 @@ def test_custom_op_compiles_fullgraph_without_recompile_on_value_change():
# block-forward code object in production).
for layer_ctx in contexts:
out = compiled(layer_ctx.to_layer_inputs(), q, k, v)
st.commit_paged_context(False)
st.commit_paged_context(POS)
return out
torch._dynamo.reset()
+153 -98
View File
@@ -4,6 +4,7 @@
import pytest
import torch
from vllm_omni.experimental.ar_diffusion.capability import ARDiffusionKVBranchSpec
from vllm_omni.experimental.ar_diffusion.kv_cache import (
ARDiffusionKVCache,
ARDiffusionKVConfig,
@@ -14,9 +15,11 @@ from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVStat
BLOCK = 16
N_HEADS = 4
HEAD_DIM = 64
POS = "positive"
NEG = "negative"
def make_state(num_layers=1, window_chunks=4, cross_attn_length=0):
def make_state(num_layers=1, window_chunks=4, cross_attn_length=0, shared_local_index=False):
cfg = ARDiffusionKVConfig(enable=True, chunk_size=BLOCK, window_chunks=window_chunks)
kv = ARDiffusionKVCache(
cfg,
@@ -27,24 +30,29 @@ def make_state(num_layers=1, window_chunks=4, cross_attn_length=0):
block_size=BLOCK,
max_model_len=4096,
available_bytes=1 << 24,
cross_attn_length=cross_attn_length,
kv_branches=(
ARDiffusionKVBranchSpec(POS, 0),
ARDiffusionKVBranchSpec(NEG, 0 if shared_local_index else 1),
),
session_capacity=2,
cross_attention_lengths={"text": cross_attn_length} if cross_attn_length else None,
device=torch.device("cpu"),
)
pos = kv.begin_request("r-pos")
neg = kv.begin_request("r-neg")
return kv, ARDiffusionKVState(kv, pos, neg, num_layers=num_layers)
return kv, ARDiffusionKVState(kv, "s1", {POS: pos, NEG: neg}, num_layers=num_layers)
def _prepare_and_commit(st: ARDiffusionKVState, is_negative: bool, n_chunks: int) -> None:
ctx = st.get_kv_caches(is_negative, seq_len=n_chunks * BLOCK, commit_current=True)[0].forward_ctx
def _prepare_and_commit(st: ARDiffusionKVState, kv_branch: str, n_chunks: int) -> None:
ctx = st.get_kv_caches(kv_branch, seq_len=n_chunks * BLOCK, commit_current=True)[0].forward_ctx
ctx.ensure_video_slots(torch.device("cpu"))
st.commit_paged_context(is_negative)
st.commit_paged_context(kv_branch)
def test_get_returns_paged_layer_contexts_when_nothing_committed():
_, st = make_state(num_layers=2)
for neg in (False, True):
contexts = st.get_kv_caches(neg, seq_len=BLOCK, commit_current=False)
for kv_branch in (POS, NEG):
contexts = st.get_kv_caches(kv_branch, seq_len=BLOCK, commit_current=False)
assert len(contexts) == 2
assert all(isinstance(ctx, ARDiffusionPagedLayerContext) for ctx in contexts)
assert contexts[0].history_block_ids == []
@@ -52,43 +60,43 @@ def test_get_returns_paged_layer_contexts_when_nothing_committed():
def test_managed_paged_context_commits_only_after_forward():
kv, st = make_state(num_layers=1)
contexts = st.get_kv_caches(False, seq_len=2 * BLOCK, commit_current=True)
contexts = st.get_kv_caches(POS, seq_len=2 * BLOCK, commit_current=True)
ctx = contexts[0].forward_ctx
assert st.pos.completed_chunks == 0
assert kv.window_block_ids(st.pos) == []
assert st.adapter(POS).completed_chunks == 0
assert kv.window_block_ids(st.adapter(POS)) == []
ctx.ensure_video_slots(torch.device("cpu"))
assert st.pos.completed_chunks == 0
assert st.adapter(POS).completed_chunks == 0
assert len(ctx.current_video_block_ids) == 2
st.commit_paged_context(False)
st.commit_paged_context(POS)
assert st.pos.completed_chunks == 2
assert st._committed[False] == 2 * BLOCK
assert len(kv.window_block_ids(st.pos)) == 2
assert st.adapter(POS).completed_chunks == 2
assert st._committed[POS] == 2 * BLOCK
assert len(kv.window_block_ids(st.adapter(POS))) == 2
def test_scratch_paged_context_does_not_commit():
kv, st = make_state(num_layers=1)
contexts = st.get_kv_caches(False, seq_len=BLOCK, commit_current=False)
contexts = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)
ctx = contexts[0].forward_ctx
ctx.ensure_video_slots(torch.device("cpu"))
assert ctx.current_video_block_ids == kv.scratch_block_ids(False, 0, 1)
st.commit_paged_context(False)
assert ctx.current_video_block_ids == kv.scratch_block_ids(POS, 0, 1)
st.commit_paged_context(POS)
assert st.pos.completed_chunks == 0
assert st._committed[False] == 0
assert kv.window_block_ids(st.pos) == []
assert st.adapter(POS).completed_chunks == 0
assert st._committed[POS] == 0
assert kv.window_block_ids(st.adapter(POS)) == []
def test_eviction_bounds_resident_window():
kv, st = make_state(num_layers=1, window_chunks=3)
_prepare_and_commit(st, False, 3)
assert len(kv.window_block_ids(st.pos)) == 3
_prepare_and_commit(st, POS, 3)
assert len(kv.window_block_ids(st.adapter(POS))) == 3
_prepare_and_commit(st, False, 2)
ctx = st.get_kv_caches(False, seq_len=BLOCK, commit_current=False)[0].forward_ctx
_prepare_and_commit(st, POS, 2)
ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=False)[0].forward_ctx
visible_blocks, video_len = ctx.video_block_table(torch.device("cpu"))
assert len(visible_blocks) == 3
assert video_len == 3 * BLOCK
@@ -96,53 +104,47 @@ def test_eviction_bounds_resident_window():
def test_branches_are_independent():
kv, st = make_state()
_prepare_and_commit(st, False, 1)
assert len(kv.window_block_ids(st.pos)) == 1
assert kv.window_block_ids(st.neg) == []
_prepare_and_commit(st, POS, 1)
assert len(kv.window_block_ids(st.adapter(POS))) == 1
assert kv.window_block_ids(st.adapter(NEG)) == []
def test_reset_clears_session_window():
kv, st = make_state(num_layers=1, window_chunks=4)
_prepare_and_commit(st, False, 2)
_prepare_and_commit(st, True, 1)
assert st._committed[False] == 2 * BLOCK and st._committed[True] == BLOCK
_prepare_and_commit(st, POS, 2)
_prepare_and_commit(st, NEG, 1)
assert st._committed[POS] == 2 * BLOCK and st._committed[NEG] == BLOCK
free_before = kv.manager.block_pool.get_num_free_blocks()
st.reset()
assert st._committed == {False: 0, True: 0}
assert st._paged_pending == {False: None, True: None}
assert kv.window_block_ids(st.pos) == []
assert kv.window_block_ids(st.neg) == []
assert st._committed == {POS: 0, NEG: 0}
assert st._paged_pending == {POS: None, NEG: None}
assert kv.window_block_ids(st.adapter(POS)) == []
assert kv.window_block_ids(st.adapter(NEG)) == []
assert kv.manager.block_pool.get_num_free_blocks() > free_before
_prepare_and_commit(st, False, 1)
assert len(kv.window_block_ids(st.pos)) == 1
_prepare_and_commit(st, POS, 1)
assert len(kv.window_block_ids(st.adapter(POS))) == 1
def test_get_cross_kv_caches_raises_before_populate():
"""Engine ownership guard: a cross-attn read before _kv_populate_cross must fail loud."""
_, st = make_state() # cross_attn_length == 0, nothing populated
for neg in (False, True):
with pytest.raises(RuntimeError, match="cross-attn read before"):
st.get_cross_kv_caches(neg)
# Guards the full AND: the populated flag alone is not enough without a pool.
st._cross_text_populated[False] = True
with pytest.raises(RuntimeError, match="cross-attn read before"):
st.get_cross_kv_caches(False)
def test_get_cross_attention_kv_raises_before_populate():
_, st = make_state(cross_attn_length=8)
for kv_branch in (POS, NEG):
with pytest.raises(RuntimeError, match="before it was populated"):
st.get_cross_attention_kv(kv_branch, "text")
def test_get_cross_kv_caches_returns_pool_dicts_when_populated():
def test_get_cross_attention_kv_returns_session_pool_dicts_when_populated():
L = 8
kv, st = make_state(num_layers=2, cross_attn_length=L)
written = []
for i in range(2):
for _ in range(2):
k = torch.randn(1, L, N_HEADS, HEAD_DIM)
v = torch.randn(1, L, N_HEADS, HEAD_DIM)
kv.write_cross_kv(i, False, k, v)
written.append((k, v))
st._cross_text_populated[False] = True
st.populate_cross_attention(POS, "text", written)
out = st.get_cross_kv_caches(False)
out = st.get_cross_attention_kv(POS, "text")
assert len(out) == 2
for i, (k, v) in enumerate(written):
assert out[i]["is_init"] is True
@@ -151,6 +153,99 @@ def test_get_cross_kv_caches_returns_pool_dicts_when_populated():
assert torch.equal(out[i]["v"], v)
def test_window_reset_can_keep_named_cross_attention_cache():
kv, st = make_state(num_layers=1, cross_attn_length=8)
k = torch.randn(1, 8, N_HEADS, HEAD_DIM)
v = torch.randn(1, 8, N_HEADS, HEAD_DIM)
st.populate_cross_attention(POS, "text", [(k, v)])
old_adapter = st.adapter(POS)
st.reset(keep_cross_attention=("text",))
assert st.adapter(POS) is not old_adapter
assert torch.equal(st.get_cross_attention_kv(POS, "text")[0]["k"], k)
assert "s1" in kv._cross_sessions
st.reset()
assert "s1" not in kv._cross_sessions
assert not st.is_cross_attention_populated(POS, "text")
def test_cross_attention_uses_logical_branch_when_local_slot_is_shared():
_, st = make_state(num_layers=2, cross_attn_length=8, shared_local_index=True)
assert st.kv_cache.num_local_kv_branches == 1
pos_layers = [
(torch.full((1, 8, N_HEADS, HEAD_DIM), 1.0), torch.full((1, 8, N_HEADS, HEAD_DIM), 2.0)) for _ in range(2)
]
neg_layers = [
(torch.full((1, 8, N_HEADS, HEAD_DIM), 3.0), torch.full((1, 8, N_HEADS, HEAD_DIM), 4.0)) for _ in range(2)
]
st.populate_cross_attention(POS, "text", pos_layers)
st.populate_cross_attention(NEG, "text", neg_layers)
for layer in st.get_cross_attention_kv(POS, "text"):
assert torch.count_nonzero(layer["k"] != 1.0) == 0
assert torch.count_nonzero(layer["v"] != 2.0) == 0
for layer in st.get_cross_attention_kv(NEG, "text"):
assert torch.count_nonzero(layer["k"] != 3.0) == 0
assert torch.count_nonzero(layer["v"] != 4.0) == 0
def test_cross_attention_population_is_transactional():
kv, st = make_state(num_layers=2, cross_attn_length=8)
original = [
(torch.full((1, 8, N_HEADS, HEAD_DIM), value), torch.full((1, 8, N_HEADS, HEAD_DIM), -value))
for value in (1.0, 2.0)
]
replacement = (
torch.full((1, 8, N_HEADS, HEAD_DIM), 9.0),
torch.full((1, 8, N_HEADS, HEAD_DIM), -9.0),
)
def interrupted_population():
yield replacement
raise RuntimeError("projection failed")
with pytest.raises(RuntimeError, match="projection failed"):
st.populate_cross_attention(POS, "text", interrupted_population())
assert not st.is_cross_attention_populated(POS, "text")
assert "s1" not in kv._cross_sessions
st.populate_cross_attention(POS, "text", original)
with pytest.raises(RuntimeError, match="projection failed"):
st.populate_cross_attention(POS, "text", interrupted_population())
out = st.get_cross_attention_kv(POS, "text")
for layer_index, layer in enumerate(out):
assert torch.equal(layer["k"], original[layer_index][0])
assert torch.equal(layer["v"], original[layer_index][1])
for invalid_layers in (original[:1], [*original, replacement]):
with pytest.raises(ValueError, match="expected 2 layers"):
st.populate_cross_attention(POS, "text", invalid_layers)
out = st.get_cross_attention_kv(POS, "text")
for layer_index, layer in enumerate(out):
assert torch.equal(layer["k"], original[layer_index][0])
assert torch.equal(layer["v"], original[layer_index][1])
invalid_shape = (torch.empty(1, 7, N_HEADS, HEAD_DIM), original[0][1])
with pytest.raises(ValueError, match="expected k/v shape"):
st.populate_cross_attention(POS, "text", [invalid_shape, original[1]])
out = st.get_cross_attention_kv(POS, "text")
assert torch.equal(out[0]["k"], original[0][0])
def test_closed_state_cannot_repopulate_cross_attention():
kv, st = make_state(num_layers=1, cross_attn_length=8)
layer = (torch.ones(1, 8, N_HEADS, HEAD_DIM), torch.ones(1, 8, N_HEADS, HEAD_DIM))
st.close()
with pytest.raises(RuntimeError, match="is closed"):
st.populate_cross_attention(POS, "text", [layer])
assert "s1" not in kv._cross_sessions
def test_kv_create_is_noop_engine_owns_allocation():
from unittest.mock import MagicMock
@@ -166,57 +261,17 @@ def test_kv_create_is_noop_engine_owns_allocation():
def test_get_kv_cache_requires_frame_aligned_seqlen():
_, st = make_state()
with pytest.raises(AssertionError, match="frame-aligned"):
st.get_kv_caches(False, seq_len=BLOCK + 1, commit_current=True)
st.get_kv_caches(POS, seq_len=BLOCK + 1, commit_current=True)
def test_prepare_one_branch_allocates_nothing_for_the_other():
"""CFG-parallel laziness: a rank prepares only the branch it runs."""
"""CFG-parallel laziness: a rank prepares only the kv_branch it runs."""
kv, st = make_state(num_layers=1, window_chunks=4)
pos_ctx = st.get_kv_caches(False, seq_len=BLOCK, commit_current=True)[0].forward_ctx
neg_ctx = st.get_kv_caches(True, seq_len=BLOCK, commit_current=True)[0].forward_ctx
pos_ctx = st.get_kv_caches(POS, seq_len=BLOCK, commit_current=True)[0].forward_ctx
neg_ctx = st.get_kv_caches(NEG, seq_len=BLOCK, commit_current=True)[0].forward_ctx
pos_ctx.prepare(device=torch.device("cpu"), action_len=0, query_len=BLOCK)
assert pos_ctx._allocated_video
assert not neg_ctx._allocated_video
assert kv.window_block_ids(st.neg) == []
def test_failed_forward_tears_down_session(monkeypatch):
"""Review follow-up (hsliuustc0106): a forward that dies partway must not
leave allocated-but-uncommitted KV behind — the session is torn down (pool
blocks freed, model-local state dropped) and the error propagates."""
from types import SimpleNamespace
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
from vllm_omni.experimental.ar_diffusion.runner import ARDiffusionModelRunner
kv, st = make_state(num_layers=1, window_chunks=4)
_prepare_and_commit(st, False, 2) # session owns pool blocks
free_before_failure = kv.manager.block_pool.get_num_free_blocks()
runner = object.__new__(ARDiffusionModelRunner)
runner.kv_cache = kv
runner._ar_diffusion_states = __import__("collections").OrderedDict({"s1": st})
runner._max_ar_diffusion_states = 4
runner.pipeline = SimpleNamespace(_states={"s1": object()}, _ar_diffusion_kv_state=None)
runner.device = None
runner._perf_e2e_times = []
def boom(self, req, kv_prefetch_job=None):
raise RuntimeError("layer 17 exploded")
monkeypatch.setattr(DiffusionModelRunner, "execute_model", boom)
req = SimpleNamespace(
request_id="r0",
sampling_params=SimpleNamespace(extra_args={"session_id": "s1"}),
)
with pytest.raises(RuntimeError, match="layer 17 exploded"):
ARDiffusionModelRunner.execute_model(runner, req)
assert "s1" not in runner._ar_diffusion_states
assert "s1" not in runner.pipeline._states
assert runner.pipeline._ar_diffusion_kv_state is None
# close() freed the session's resident blocks.
assert kv.manager.block_pool.get_num_free_blocks() > free_before_failure
assert kv.window_block_ids(st.adapter(NEG)) == []