[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
@@ -13,12 +13,32 @@ from vllm_omni.experimental.ar_diffusion.capability import (
|
||||
SupportsARDiffusionPipeline,
|
||||
SupportsARDiffusionWarmup,
|
||||
)
|
||||
from vllm_omni.experimental.ar_diffusion.consumer import ARDiffusionOmniTickConsumer
|
||||
from vllm_omni.experimental.ar_diffusion.engine import ARDiffusionEngine
|
||||
from vllm_omni.experimental.ar_diffusion.session import (
|
||||
ARDiffusionSession,
|
||||
ARDiffusionSessionManager,
|
||||
ARDiffusionWorkerLifecycle,
|
||||
)
|
||||
from vllm_omni.experimental.ar_diffusion.tick_protocol import (
|
||||
AR_DIFFUSION_TICK_KEY,
|
||||
ARDiffusionChunkMetadata,
|
||||
ARDiffusionControlInput,
|
||||
ARDiffusionTickRequest,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ARDiffusionKVBranchSpec",
|
||||
"ARDiffusionCrossAttentionKVSpec",
|
||||
"ARDiffusionEngine",
|
||||
"ARDiffusionOmniTickConsumer",
|
||||
"ARDiffusionSession",
|
||||
"ARDiffusionSessionManager",
|
||||
"ARDiffusionWorkerLifecycle",
|
||||
"AR_DIFFUSION_TICK_KEY",
|
||||
"ARDiffusionChunkMetadata",
|
||||
"ARDiffusionControlInput",
|
||||
"ARDiffusionTickRequest",
|
||||
"ARDiffusionKVCacheSpec",
|
||||
"SupportsARDiffusionPipeline",
|
||||
"SupportsARDiffusionWarmup",
|
||||
|
||||
@@ -58,6 +58,9 @@ class ARDiffusionKVCacheSpec:
|
||||
|
||||
``max_scratch_tokens_per_branch`` is the maximum non-video KV (for example,
|
||||
action/state registers) that must coexist with an uncommitted video block.
|
||||
``model_owned_state_bytes_per_session`` is a conservative upper bound for
|
||||
persistent per-session CUDA state outside runner-owned self/cross-attention
|
||||
KV and scratch pools.
|
||||
``session_capacity`` is the pipeline's upper bound; a runner may retain
|
||||
fewer sessions when its current memory and execution policy is stricter.
|
||||
|
||||
@@ -79,6 +82,7 @@ class ARDiffusionKVCacheSpec:
|
||||
cross_attention: tuple[ARDiffusionCrossAttentionKVSpec, ...] = ()
|
||||
max_model_len: int = 1 << 20
|
||||
max_scratch_tokens_per_branch: int = 0
|
||||
model_owned_state_bytes_per_session: int = 0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
positive_fields = {
|
||||
@@ -101,6 +105,11 @@ class ARDiffusionKVCacheSpec:
|
||||
"AR-Diffusion max_scratch_tokens_per_branch must be non-negative, "
|
||||
f"got {self.max_scratch_tokens_per_branch}"
|
||||
)
|
||||
if self.model_owned_state_bytes_per_session < 0:
|
||||
raise ValueError(
|
||||
"AR-Diffusion model_owned_state_bytes_per_session must be non-negative, "
|
||||
f"got {self.model_owned_state_bytes_per_session}"
|
||||
)
|
||||
if not self.kv_branches:
|
||||
raise ValueError("AR-Diffusion requires at least one KV branch")
|
||||
kv_branch_names = [kv_branch.name for kv_branch in self.kv_branches]
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""AsyncOmni consumer for typed realtime AR-Diffusion ticks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from collections.abc import AsyncIterator, Callable, Mapping, Sequence
|
||||
from typing import Any, Protocol
|
||||
|
||||
from vllm_omni.experimental.ar_diffusion.tick_protocol import (
|
||||
ARDiffusionChunkMetadata,
|
||||
ARDiffusionTickRequest,
|
||||
)
|
||||
from vllm_omni.inputs.data import (
|
||||
OmniDiffusionSamplingParams,
|
||||
OmniPromptType,
|
||||
OmniSamplingParams,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
AR_DIFFUSION_OUTPUT_METADATA_KEY = "ar_diffusion"
|
||||
|
||||
|
||||
class ARDiffusionGenerateClient(Protocol):
|
||||
"""Internal subset of AsyncOmni used to execute one tick."""
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: OmniPromptType,
|
||||
*,
|
||||
request_id: str,
|
||||
sampling_params_list: Sequence[OmniSamplingParams],
|
||||
output_modalities: list[str] | None = None,
|
||||
) -> AsyncIterator[OmniRequestOutput]: ...
|
||||
|
||||
|
||||
def _metadata_mapping(output: OmniRequestOutput) -> Mapping[str, Any]:
|
||||
multimodal_output = output.multimodal_output
|
||||
if not isinstance(multimodal_output, Mapping):
|
||||
raise ValueError("AR-Diffusion output must contain a multimodal output mapping.")
|
||||
metadata = multimodal_output.get("metadata")
|
||||
if not isinstance(metadata, Mapping):
|
||||
raise ValueError("AR-Diffusion output must contain multimodal_output.metadata.")
|
||||
value = metadata.get(AR_DIFFUSION_OUTPUT_METADATA_KEY)
|
||||
if not isinstance(value, Mapping):
|
||||
raise ValueError(f"AR-Diffusion output metadata must contain {AR_DIFFUSION_OUTPUT_METADATA_KEY!r}.")
|
||||
return value
|
||||
|
||||
|
||||
def _parse_chunk_metadata(output: OmniRequestOutput) -> ARDiffusionChunkMetadata:
|
||||
value = _metadata_mapping(output)
|
||||
session_id = value.get("session_id")
|
||||
request_id = value.get("request_id")
|
||||
chunk_index = value.get("chunk_index")
|
||||
applied_event_ids = value.get("applied_event_ids", ())
|
||||
if not isinstance(session_id, str) or not session_id.strip():
|
||||
raise ValueError("AR-Diffusion output metadata session_id must be a non-empty string.")
|
||||
if not isinstance(request_id, str) or not request_id.strip():
|
||||
raise ValueError("AR-Diffusion output metadata request_id must be a non-empty string.")
|
||||
if isinstance(chunk_index, bool) or not isinstance(chunk_index, int) or chunk_index < 0:
|
||||
raise ValueError("AR-Diffusion output metadata chunk_index must be a non-negative integer.")
|
||||
if not isinstance(applied_event_ids, Sequence) or isinstance(applied_event_ids, (str, bytes, bytearray)):
|
||||
raise ValueError("AR-Diffusion output metadata applied_event_ids must be a sequence.")
|
||||
event_ids = tuple(applied_event_ids)
|
||||
if any(isinstance(event_id, bool) or not isinstance(event_id, int) or event_id < 0 for event_id in event_ids):
|
||||
raise ValueError("AR-Diffusion output metadata applied_event_ids must contain non-negative integers.")
|
||||
if event_ids != tuple(sorted(set(event_ids))):
|
||||
raise ValueError("AR-Diffusion output metadata applied_event_ids must be unique and strictly increasing.")
|
||||
return ARDiffusionChunkMetadata(
|
||||
session_id=session_id,
|
||||
request_id=request_id,
|
||||
chunk_index=chunk_index,
|
||||
applied_event_ids=event_ids,
|
||||
)
|
||||
|
||||
|
||||
class ARDiffusionOmniTickConsumer:
|
||||
"""Converts a typed tick into one AsyncOmni diffusion request.
|
||||
|
||||
``prompt_provider`` packages session initialization data such as an initial
|
||||
image into the normal Omni prompt. Control ``track/schema/data`` remains in
|
||||
the typed tick and is not interpreted by this class.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
engine_client: ARDiffusionGenerateClient,
|
||||
*,
|
||||
prompt_provider: Callable[[ARDiffusionTickRequest], OmniPromptType],
|
||||
sampling_params_list: Sequence[OmniSamplingParams],
|
||||
diffusion_stage_id: int,
|
||||
output_modalities: Sequence[str] | None = None,
|
||||
) -> None:
|
||||
templates = tuple(sampling_params_list)
|
||||
if not templates:
|
||||
raise ValueError("sampling_params_list must not be empty.")
|
||||
if (
|
||||
isinstance(diffusion_stage_id, bool)
|
||||
or not isinstance(diffusion_stage_id, int)
|
||||
or not 0 <= diffusion_stage_id < len(templates)
|
||||
):
|
||||
raise ValueError("diffusion_stage_id must index sampling_params_list.")
|
||||
if not isinstance(templates[diffusion_stage_id], OmniDiffusionSamplingParams):
|
||||
raise TypeError("The selected diffusion stage must use OmniDiffusionSamplingParams.")
|
||||
stage_pools = getattr(getattr(engine_client, "engine", None), "stage_pools", None)
|
||||
if stage_pools is None or not 0 <= diffusion_stage_id < len(stage_pools):
|
||||
raise ValueError(
|
||||
"AR-Diffusion realtime execution requires an initialized AsyncOmni "
|
||||
"engine with a matching diffusion stage pool."
|
||||
)
|
||||
replica_count = getattr(stage_pools[diffusion_stage_id], "num_replicas", None)
|
||||
if isinstance(replica_count, bool) or not isinstance(replica_count, int) or replica_count < 1:
|
||||
raise ValueError("The selected AR-Diffusion stage must expose a positive num_replicas.")
|
||||
if replica_count != 1:
|
||||
raise ValueError(
|
||||
"AR-Diffusion realtime sessions currently require exactly one "
|
||||
"replica for the selected diffusion stage; session-affine "
|
||||
f"routing is not implemented (got num_replicas={replica_count})."
|
||||
)
|
||||
self._engine_client = engine_client
|
||||
self._prompt_provider = prompt_provider
|
||||
self._sampling_params_templates = templates
|
||||
self._diffusion_stage_id = diffusion_stage_id
|
||||
self._output_modalities = list(output_modalities) if output_modalities is not None else None
|
||||
|
||||
def _sampling_params_for_tick(
|
||||
self,
|
||||
tick: ARDiffusionTickRequest,
|
||||
) -> list[OmniSamplingParams]:
|
||||
params = [copy.copy(template) for template in self._sampling_params_templates]
|
||||
diffusion_params = params[self._diffusion_stage_id]
|
||||
assert isinstance(diffusion_params, OmniDiffusionSamplingParams)
|
||||
diffusion_params.extra_args = {
|
||||
**(diffusion_params.extra_args or {}),
|
||||
**tick.to_extra_args(),
|
||||
}
|
||||
return params
|
||||
|
||||
async def execute_tick(self, tick: ARDiffusionTickRequest) -> OmniRequestOutput:
|
||||
prompt = self._prompt_provider(tick)
|
||||
final_output: OmniRequestOutput | None = None
|
||||
async for output in self._engine_client.generate(
|
||||
prompt,
|
||||
request_id=tick.request_id,
|
||||
sampling_params_list=self._sampling_params_for_tick(tick),
|
||||
output_modalities=self._output_modalities,
|
||||
):
|
||||
if output.stage_id != self._diffusion_stage_id:
|
||||
continue
|
||||
if output.finished:
|
||||
final_output = output
|
||||
|
||||
if final_output is None:
|
||||
raise RuntimeError(
|
||||
f"AR-Diffusion tick {tick.request_id!r} completed without a final "
|
||||
f"output from stage {self._diffusion_stage_id}."
|
||||
)
|
||||
if final_output.error:
|
||||
raise RuntimeError(f"AR-Diffusion tick {tick.request_id!r} failed: {final_output.error}")
|
||||
if final_output.request_id != tick.request_id:
|
||||
raise ValueError("AR-Diffusion output request_id does not match the submitted tick request_id.")
|
||||
# Parse here so malformed/missing standard metadata fails at the engine
|
||||
# boundary, before the session attempts to commit accepted events.
|
||||
self.chunk_metadata(final_output)
|
||||
return final_output
|
||||
|
||||
def chunk_metadata(self, output: OmniRequestOutput) -> ARDiffusionChunkMetadata:
|
||||
return _parse_chunk_metadata(output)
|
||||
@@ -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:
|
||||
|
||||
@@ -21,6 +21,7 @@ from vllm_omni.experimental.ar_diffusion.capability import (
|
||||
from vllm_omni.experimental.ar_diffusion.kv_cache.config import ARDiffusionKVConfig
|
||||
from vllm_omni.experimental.ar_diffusion.kv_cache.manager import ARDiffusionKVCache
|
||||
from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVState
|
||||
from vllm_omni.experimental.ar_diffusion.tick_protocol import ARDiffusionTickRequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -51,7 +52,6 @@ class ARDiffusionModelRunner(DiffusionModelRunner):
|
||||
"""
|
||||
|
||||
_WARMUP_SID = "__ardiffusion_warmup__"
|
||||
_MAX_RESIDENT_SESSIONS = 1
|
||||
|
||||
def __init__(self, vllm_config: object, od_config: OmniDiffusionConfig, device: torch.device) -> None:
|
||||
super().__init__(vllm_config, od_config, device)
|
||||
@@ -123,7 +123,6 @@ class ARDiffusionModelRunner(DiffusionModelRunner):
|
||||
self.ar_diffusion_kv_config = config
|
||||
self._ar_diffusion_capability = capability
|
||||
self._ar_diffusion_kv_cache_spec = spec
|
||||
self._session_capacity = min(spec.session_capacity, self._MAX_RESIDENT_SESSIONS)
|
||||
self.kv_cache = ARDiffusionKVCache(
|
||||
config,
|
||||
num_layers=spec.num_layers,
|
||||
@@ -134,12 +133,14 @@ class ARDiffusionModelRunner(DiffusionModelRunner):
|
||||
max_model_len=spec.max_model_len,
|
||||
available_bytes=self._available_memory_bytes() if available_bytes is None else available_bytes,
|
||||
kv_branches=spec.kv_branches,
|
||||
session_capacity=self._session_capacity,
|
||||
session_capacity=spec.session_capacity,
|
||||
cross_attention_lengths=spec.cross_attention_lengths,
|
||||
frames_per_block=spec.frames_per_block,
|
||||
max_scratch_tokens_per_branch=spec.max_scratch_tokens_per_branch,
|
||||
model_owned_state_bytes_per_session=spec.model_owned_state_bytes_per_session,
|
||||
device=self.device,
|
||||
)
|
||||
self._session_capacity = self.kv_cache.session_capacity
|
||||
logger.info(
|
||||
"AR-Diffusion KV cache: blocks=%d layers=%d local_kv_heads=%d head_size=%d "
|
||||
"tokens/frame=%d frames/block=%d window=%d sink=%d kv_branches=%s cross=%s "
|
||||
@@ -230,9 +231,14 @@ class ARDiffusionModelRunner(DiffusionModelRunner):
|
||||
return state
|
||||
|
||||
@staticmethod
|
||||
def _request_session(req: OmniDiffusionRequest) -> tuple[str, dict]:
|
||||
def _request_session(
|
||||
req: OmniDiffusionRequest,
|
||||
) -> tuple[str, dict, ARDiffusionTickRequest | None]:
|
||||
extra_args = req.sampling_params.extra_args or {}
|
||||
return str(extra_args.get("session_id") or "default"), extra_args
|
||||
tick = ARDiffusionTickRequest.from_extra_args(extra_args)
|
||||
if tick is not None:
|
||||
return tick.session_id, extra_args, tick
|
||||
return str(extra_args.get("session_id") or "default"), extra_args, None
|
||||
|
||||
def execute_model(
|
||||
self,
|
||||
@@ -245,8 +251,10 @@ class ARDiffusionModelRunner(DiffusionModelRunner):
|
||||
if capability is None:
|
||||
raise RuntimeError("AR-Diffusion capability missing after KV cache initialization")
|
||||
|
||||
session_id, extra_args = self._request_session(req)
|
||||
if extra_args.get("reset", False):
|
||||
session_id, extra_args, tick = self._request_session(req)
|
||||
reset = tick.reset if tick is not None else bool(extra_args.get("reset", False))
|
||||
close_session = tick.close_session if tick is not None else bool(extra_args.get("close_session", False))
|
||||
if reset:
|
||||
self.reset_session(session_id)
|
||||
state = self._get_or_create_session(session_id)
|
||||
started = time.perf_counter()
|
||||
@@ -268,7 +276,7 @@ class ARDiffusionModelRunner(DiffusionModelRunner):
|
||||
)
|
||||
raise
|
||||
self._perf_e2e_times.append(time.perf_counter() - started)
|
||||
if extra_args.get("close_session", False):
|
||||
if close_session:
|
||||
self.close_session(session_id)
|
||||
return output
|
||||
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Internal realtime session control plane for AR-Diffusion.
|
||||
|
||||
This module owns transport-level identity, event ordering, backpressure, and
|
||||
chunk-boundary snapshots. Model-defined control payloads remain opaque here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Generic, Protocol, TypeVar
|
||||
|
||||
from vllm_omni.experimental.ar_diffusion.tick_protocol import (
|
||||
ARDiffusionChunkMetadata,
|
||||
ARDiffusionControlInput,
|
||||
ARDiffusionTickRequest,
|
||||
)
|
||||
|
||||
|
||||
class ARDiffusionSessionError(RuntimeError):
|
||||
"""Base error for realtime AR-Diffusion session operations."""
|
||||
|
||||
|
||||
class ARDiffusionSessionStateError(ARDiffusionSessionError):
|
||||
"""Raised when an operation is invalid for the current session state."""
|
||||
|
||||
|
||||
class ARDiffusionEventQueueFullError(ARDiffusionSessionError):
|
||||
"""Raised when accepting an event would exceed the bounded queue."""
|
||||
|
||||
|
||||
class ARDiffusionStaleEventError(ARDiffusionSessionError):
|
||||
"""Raised when an event is older than the current monotonic boundary."""
|
||||
|
||||
|
||||
class ARDiffusionChunkMetadataError(ARDiffusionSessionError):
|
||||
"""Raised when a tick consumer returns metadata for a different chunk."""
|
||||
|
||||
|
||||
class ARDiffusionEventAcceptanceStatus(str, Enum):
|
||||
ACCEPTED = "accepted"
|
||||
DUPLICATE = "duplicate"
|
||||
|
||||
|
||||
class ARDiffusionSessionStatus(str, Enum):
|
||||
ACTIVE = "active"
|
||||
RESETTING = "resetting"
|
||||
FAILED = "failed"
|
||||
CLOSING = "closing"
|
||||
CLEANUP_FAILED = "cleanup_failed"
|
||||
CLOSED = "closed"
|
||||
|
||||
|
||||
def _copy_control(control: ARDiffusionControlInput) -> ARDiffusionControlInput:
|
||||
return ARDiffusionControlInput(
|
||||
track=control.track,
|
||||
schema=control.schema,
|
||||
data=control.data,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARDiffusionSessionEvent:
|
||||
"""One atomically accepted prompt/control update.
|
||||
|
||||
``prompt=None`` means that this event does not update the prompt. Controls
|
||||
are keyed by ``track`` when the chunk snapshot is assembled; their schema
|
||||
and data are otherwise opaque to this layer.
|
||||
"""
|
||||
|
||||
event_id: int
|
||||
prompt: str | None = None
|
||||
controls: tuple[ARDiffusionControlInput, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if isinstance(self.event_id, bool) or not isinstance(self.event_id, int) or self.event_id < 0:
|
||||
raise ValueError("event_id must be a non-negative integer.")
|
||||
if self.prompt is not None and not isinstance(self.prompt, str):
|
||||
raise ValueError("prompt must be a string or None.")
|
||||
controls = tuple(self.controls)
|
||||
if any(not isinstance(control, ARDiffusionControlInput) for control in controls):
|
||||
raise ValueError("controls must contain ARDiffusionControlInput values.")
|
||||
tracks = [control.track for control in controls]
|
||||
if len(tracks) != len(set(tracks)):
|
||||
raise ValueError("A composite event may update each control track at most once.")
|
||||
if self.prompt is None and not controls:
|
||||
raise ValueError("An event must update the prompt, one or more controls, or both.")
|
||||
object.__setattr__(self, "controls", controls)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARDiffusionEventAcceptance:
|
||||
"""Immediate queue acceptance result; this does not mean applied."""
|
||||
|
||||
session_id: str
|
||||
event_id: int
|
||||
status: ARDiffusionEventAcceptanceStatus
|
||||
pending_event_count: int
|
||||
|
||||
|
||||
TickOutputT = TypeVar("TickOutputT")
|
||||
|
||||
|
||||
class ARDiffusionTickConsumer(Protocol[TickOutputT]):
|
||||
"""Consumes one immutable chunk-boundary tick."""
|
||||
|
||||
async def execute_tick(self, tick: ARDiffusionTickRequest) -> TickOutputT: ...
|
||||
|
||||
def chunk_metadata(self, output: TickOutputT) -> ARDiffusionChunkMetadata: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARDiffusionPreparedControls:
|
||||
"""One reducer-owned, transactional control snapshot.
|
||||
|
||||
``private_state`` is opaque to the session layer and becomes durable only
|
||||
after the corresponding model tick succeeds.
|
||||
"""
|
||||
|
||||
controls: tuple[ARDiffusionControlInput, ...]
|
||||
private_state: Any = None
|
||||
|
||||
|
||||
class ARDiffusionControlReducer(Protocol):
|
||||
"""Optional model adapter for stateful controls sampled per AR block."""
|
||||
|
||||
def prepare(
|
||||
self,
|
||||
*,
|
||||
current_controls: Mapping[str, ARDiffusionControlInput],
|
||||
events: Sequence[ARDiffusionSessionEvent],
|
||||
chunk_index: int,
|
||||
) -> ARDiffusionPreparedControls: ...
|
||||
|
||||
def commit(self, prepared: ARDiffusionPreparedControls) -> None: ...
|
||||
|
||||
def reset(self) -> None: ...
|
||||
|
||||
|
||||
class ARDiffusionSessionLifecycle(Protocol):
|
||||
"""Worker-facing session lifecycle operations."""
|
||||
|
||||
async def reset_session(self, session_id: str) -> None: ...
|
||||
|
||||
async def close_session(self, session_id: str) -> None: ...
|
||||
|
||||
|
||||
class ARDiffusionCollectiveRPCClient(Protocol):
|
||||
"""Subset of the engine control RPC surface used by session lifecycle."""
|
||||
|
||||
async def collective_rpc(
|
||||
self,
|
||||
method: str,
|
||||
timeout: float | None = None,
|
||||
args: tuple[Any, ...] = (),
|
||||
kwargs: dict[str, Any] | None = None,
|
||||
stage_ids: list[int] | None = None,
|
||||
) -> list[Any]: ...
|
||||
|
||||
|
||||
def _collect_rpc_support_results(value: Any, *, errors: list[str], supported: list[bool]) -> None:
|
||||
if isinstance(value, bool):
|
||||
supported.append(value)
|
||||
return
|
||||
if isinstance(value, (list, tuple)):
|
||||
for item in value:
|
||||
_collect_rpc_support_results(item, errors=errors, supported=supported)
|
||||
return
|
||||
if isinstance(value, Mapping):
|
||||
if value.get("supported") is False:
|
||||
errors.append(str(value.get("error") or "target stage does not support this lifecycle RPC"))
|
||||
return
|
||||
if "result" in value:
|
||||
_collect_rpc_support_results(value["result"], errors=errors, supported=supported)
|
||||
|
||||
|
||||
class ARDiffusionWorkerLifecycle:
|
||||
"""Routes reset/close through the existing orchestrator collective RPC."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rpc_client: ARDiffusionCollectiveRPCClient,
|
||||
*,
|
||||
stage_ids: Sequence[int],
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
normalized_stage_ids = tuple(stage_ids)
|
||||
if not normalized_stage_ids:
|
||||
raise ValueError("stage_ids must select at least one AR-Diffusion stage.")
|
||||
if any(isinstance(stage_id, bool) or not isinstance(stage_id, int) or stage_id < 0 for stage_id in stage_ids):
|
||||
raise ValueError("stage_ids must contain non-negative integers.")
|
||||
self._rpc_client = rpc_client
|
||||
self._stage_ids = normalized_stage_ids
|
||||
self._timeout = timeout
|
||||
|
||||
async def _invoke(self, method: str, session_id: str) -> None:
|
||||
results = await self._rpc_client.collective_rpc(
|
||||
method=method,
|
||||
timeout=self._timeout,
|
||||
args=(session_id,),
|
||||
stage_ids=list(self._stage_ids),
|
||||
)
|
||||
errors: list[str] = []
|
||||
supported: list[bool] = []
|
||||
_collect_rpc_support_results(results, errors=errors, supported=supported)
|
||||
if errors:
|
||||
raise ARDiffusionSessionError(f"{method} failed: {'; '.join(errors)}")
|
||||
if not supported or not all(supported):
|
||||
raise ARDiffusionSessionError(f"{method} is not supported by every selected worker.")
|
||||
|
||||
async def reset_session(self, session_id: str) -> None:
|
||||
await self._invoke("reset_ar_diffusion_session", session_id)
|
||||
|
||||
async def close_session(self, session_id: str) -> None:
|
||||
await self._invoke("close_ar_diffusion_session", session_id)
|
||||
|
||||
|
||||
def _default_request_id(session_id: str, chunk_index: int) -> str:
|
||||
return f"ar-{session_id}-{chunk_index}-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
class ARDiffusionSession(Generic[TickOutputT]):
|
||||
"""Transactional event queue and chunk snapshot for one realtime world."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: str,
|
||||
*,
|
||||
tick_consumer: ARDiffusionTickConsumer[TickOutputT],
|
||||
lifecycle: ARDiffusionSessionLifecycle,
|
||||
max_pending_events: int,
|
||||
request_id_factory: Callable[[str, int], str] | None = None,
|
||||
control_reducer: ARDiffusionControlReducer | None = None,
|
||||
) -> None:
|
||||
if not isinstance(session_id, str) or not session_id.strip():
|
||||
raise ValueError("session_id must be a non-empty string.")
|
||||
if isinstance(max_pending_events, bool) or not isinstance(max_pending_events, int) or max_pending_events <= 0:
|
||||
raise ValueError("max_pending_events must be a positive integer.")
|
||||
self.session_id = session_id
|
||||
self._tick_consumer = tick_consumer
|
||||
self._lifecycle = lifecycle
|
||||
self._max_pending_events = max_pending_events
|
||||
self._request_id_factory = request_id_factory or _default_request_id
|
||||
self._control_reducer = control_reducer
|
||||
|
||||
self._status = ARDiffusionSessionStatus.ACTIVE
|
||||
self._pending_events: dict[int, ARDiffusionSessionEvent] = {}
|
||||
self._recent_event_ids: OrderedDict[int, None] = OrderedDict()
|
||||
self._event_floor = -1
|
||||
self._inflight_event_floor: int | None = None
|
||||
self._chunk_index = 0
|
||||
self._prompt: str | None = None
|
||||
self._controls: dict[str, ARDiffusionControlInput] = {}
|
||||
|
||||
self._state_lock = asyncio.Lock()
|
||||
self._tick_lock = asyncio.Lock()
|
||||
|
||||
@property
|
||||
def status(self) -> ARDiffusionSessionStatus:
|
||||
return self._status
|
||||
|
||||
@property
|
||||
def chunk_index(self) -> int:
|
||||
return self._chunk_index
|
||||
|
||||
@property
|
||||
def pending_event_count(self) -> int:
|
||||
return len(self._pending_events)
|
||||
|
||||
def _require_active(self) -> None:
|
||||
if self._status is not ARDiffusionSessionStatus.ACTIVE:
|
||||
raise ARDiffusionSessionStateError(f"AR-Diffusion session {self.session_id!r} is {self._status.value}.")
|
||||
|
||||
def _require_resettable(self) -> None:
|
||||
if self._status not in {
|
||||
ARDiffusionSessionStatus.ACTIVE,
|
||||
ARDiffusionSessionStatus.FAILED,
|
||||
}:
|
||||
raise ARDiffusionSessionStateError(f"AR-Diffusion session {self.session_id!r} is {self._status.value}.")
|
||||
|
||||
async def accept_event(self, event: ARDiffusionSessionEvent) -> ARDiffusionEventAcceptance:
|
||||
"""Atomically enqueue an event or return an idempotent duplicate result."""
|
||||
if not isinstance(event, ARDiffusionSessionEvent):
|
||||
raise TypeError("event must be an ARDiffusionSessionEvent.")
|
||||
async with self._state_lock:
|
||||
self._require_active()
|
||||
if event.event_id in self._pending_events:
|
||||
return ARDiffusionEventAcceptance(
|
||||
session_id=self.session_id,
|
||||
event_id=event.event_id,
|
||||
status=ARDiffusionEventAcceptanceStatus.DUPLICATE,
|
||||
pending_event_count=len(self._pending_events),
|
||||
)
|
||||
if event.event_id in self._recent_event_ids:
|
||||
return ARDiffusionEventAcceptance(
|
||||
session_id=self.session_id,
|
||||
event_id=event.event_id,
|
||||
status=ARDiffusionEventAcceptanceStatus.DUPLICATE,
|
||||
pending_event_count=len(self._pending_events),
|
||||
)
|
||||
|
||||
event_floor = self._event_floor
|
||||
if self._inflight_event_floor is not None:
|
||||
event_floor = max(event_floor, self._inflight_event_floor)
|
||||
if event.event_id <= event_floor:
|
||||
raise ARDiffusionStaleEventError(
|
||||
f"event_id {event.event_id} is stale; the session event floor is {event_floor}."
|
||||
)
|
||||
if len(self._pending_events) >= self._max_pending_events:
|
||||
raise ARDiffusionEventQueueFullError(
|
||||
f"AR-Diffusion session {self.session_id!r} event queue is full "
|
||||
f"({self._max_pending_events} pending)."
|
||||
)
|
||||
|
||||
stored_event = ARDiffusionSessionEvent(
|
||||
event_id=event.event_id,
|
||||
prompt=event.prompt,
|
||||
controls=tuple(_copy_control(control) for control in event.controls),
|
||||
)
|
||||
self._pending_events[event.event_id] = stored_event
|
||||
self._recent_event_ids[event.event_id] = None
|
||||
while len(self._recent_event_ids) > self._max_pending_events:
|
||||
self._recent_event_ids.popitem(last=False)
|
||||
return ARDiffusionEventAcceptance(
|
||||
session_id=self.session_id,
|
||||
event_id=event.event_id,
|
||||
status=ARDiffusionEventAcceptanceStatus.ACCEPTED,
|
||||
pending_event_count=len(self._pending_events),
|
||||
)
|
||||
|
||||
def _build_tick_locked(
|
||||
self,
|
||||
) -> tuple[
|
||||
ARDiffusionTickRequest,
|
||||
str | None,
|
||||
dict[str, ARDiffusionControlInput],
|
||||
ARDiffusionPreparedControls | None,
|
||||
]:
|
||||
event_ids = tuple(sorted(self._pending_events))
|
||||
events = tuple(self._pending_events[event_id] for event_id in event_ids)
|
||||
prompt = self._prompt
|
||||
for event in events:
|
||||
if event.prompt is not None:
|
||||
prompt = event.prompt
|
||||
|
||||
prepared_controls: ARDiffusionPreparedControls | None = None
|
||||
if self._control_reducer is None:
|
||||
controls = {track: _copy_control(control) for track, control in self._controls.items()}
|
||||
for event in events:
|
||||
for control in event.controls:
|
||||
controls[control.track] = _copy_control(control)
|
||||
else:
|
||||
prepared_controls = self._control_reducer.prepare(
|
||||
current_controls={track: _copy_control(control) for track, control in self._controls.items()},
|
||||
events=events,
|
||||
chunk_index=self._chunk_index,
|
||||
)
|
||||
if not isinstance(prepared_controls, ARDiffusionPreparedControls):
|
||||
raise TypeError("control reducer prepare() must return ARDiffusionPreparedControls.")
|
||||
controls = {}
|
||||
for control in prepared_controls.controls:
|
||||
if not isinstance(control, ARDiffusionControlInput):
|
||||
raise TypeError("prepared controls must contain ARDiffusionControlInput values.")
|
||||
if control.track in controls:
|
||||
raise ValueError("prepared controls must contain at most one value per track.")
|
||||
controls[control.track] = _copy_control(control)
|
||||
|
||||
chunk_index = self._chunk_index
|
||||
request_id = self._request_id_factory(self.session_id, chunk_index)
|
||||
tick = ARDiffusionTickRequest(
|
||||
session_id=self.session_id,
|
||||
request_id=request_id,
|
||||
chunk_index=chunk_index,
|
||||
applied_event_ids=event_ids,
|
||||
prompt=prompt,
|
||||
controls=tuple(_copy_control(controls[track]) for track in sorted(controls)),
|
||||
)
|
||||
self._inflight_event_floor = event_ids[-1] if event_ids else None
|
||||
return tick, prompt, controls, prepared_controls
|
||||
|
||||
async def _commit_tick(
|
||||
self,
|
||||
tick: ARDiffusionTickRequest,
|
||||
prompt: str | None,
|
||||
controls: dict[str, ARDiffusionControlInput],
|
||||
prepared_controls: ARDiffusionPreparedControls | None,
|
||||
) -> None:
|
||||
async with self._state_lock:
|
||||
# Reducer state and the session snapshot form one logical commit.
|
||||
# Run the only fallible operation before mutating session fields so
|
||||
# a reducer failure cannot acknowledge events or advance the chunk.
|
||||
if prepared_controls is not None:
|
||||
assert self._control_reducer is not None
|
||||
self._control_reducer.commit(prepared_controls)
|
||||
for event_id in tick.applied_event_ids:
|
||||
self._pending_events.pop(event_id, None)
|
||||
if tick.applied_event_ids:
|
||||
self._event_floor = tick.applied_event_ids[-1]
|
||||
self._prompt = prompt
|
||||
self._controls = controls
|
||||
self._chunk_index += 1
|
||||
self._inflight_event_floor = None
|
||||
|
||||
async def _fail_tick(self, tick_error: BaseException) -> None:
|
||||
async with self._state_lock:
|
||||
self._inflight_event_floor = None
|
||||
self._status = ARDiffusionSessionStatus.FAILED
|
||||
try:
|
||||
# A model forward may already have released its state. This
|
||||
# idempotent close also covers successful forwards whose metadata
|
||||
# or local reducer commit could not be accepted.
|
||||
await self._lifecycle.close_session(self.session_id)
|
||||
except Exception as cleanup_error:
|
||||
raise ARDiffusionSessionError(
|
||||
"AR-Diffusion tick failed "
|
||||
f"({type(tick_error).__name__}: {tick_error}) and worker "
|
||||
f"session cleanup also failed: {cleanup_error}"
|
||||
) from tick_error
|
||||
|
||||
async def next_chunk(self) -> TickOutputT:
|
||||
"""Execute and atomically commit one chunk-boundary snapshot."""
|
||||
async with self._tick_lock:
|
||||
async with self._state_lock:
|
||||
self._require_active()
|
||||
tick, prompt, controls, prepared_controls = self._build_tick_locked()
|
||||
|
||||
expected_metadata = ARDiffusionChunkMetadata.from_tick(tick)
|
||||
try:
|
||||
output = await self._tick_consumer.execute_tick(tick)
|
||||
metadata = self._tick_consumer.chunk_metadata(output)
|
||||
if not isinstance(metadata, ARDiffusionChunkMetadata) or metadata != expected_metadata:
|
||||
raise ARDiffusionChunkMetadataError(
|
||||
"Tick consumer metadata does not match the submitted AR-Diffusion tick."
|
||||
)
|
||||
except BaseException as tick_error:
|
||||
await self._fail_tick(tick_error)
|
||||
raise
|
||||
|
||||
commit_task = asyncio.create_task(
|
||||
self._commit_tick(
|
||||
tick,
|
||||
prompt,
|
||||
controls,
|
||||
prepared_controls,
|
||||
)
|
||||
)
|
||||
try:
|
||||
await asyncio.shield(commit_task)
|
||||
except asyncio.CancelledError:
|
||||
# Once a consumer reports success, the local chunk/event state
|
||||
# must commit even if the transport task is being cancelled.
|
||||
try:
|
||||
await commit_task
|
||||
except BaseException as commit_error:
|
||||
await self._fail_tick(commit_error)
|
||||
raise
|
||||
raise
|
||||
except BaseException as commit_error:
|
||||
await self._fail_tick(commit_error)
|
||||
raise
|
||||
return output
|
||||
|
||||
async def reset(self) -> None:
|
||||
"""Reset worker state and discard queued/current transport state."""
|
||||
async with self._tick_lock:
|
||||
async with self._state_lock:
|
||||
self._require_resettable()
|
||||
self._status = ARDiffusionSessionStatus.RESETTING
|
||||
try:
|
||||
await self._lifecycle.reset_session(self.session_id)
|
||||
except BaseException:
|
||||
async with self._state_lock:
|
||||
self._status = ARDiffusionSessionStatus.FAILED
|
||||
raise
|
||||
async with self._state_lock:
|
||||
if self._pending_events:
|
||||
self._event_floor = max(self._event_floor, max(self._pending_events))
|
||||
self._pending_events.clear()
|
||||
self._prompt = None
|
||||
self._controls.clear()
|
||||
if self._control_reducer is not None:
|
||||
self._control_reducer.reset()
|
||||
self._inflight_event_floor = None
|
||||
self._chunk_index = 0
|
||||
self._status = ARDiffusionSessionStatus.ACTIVE
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close worker state, retaining a tombstone until cleanup succeeds."""
|
||||
async with self._tick_lock:
|
||||
async with self._state_lock:
|
||||
if self._status is ARDiffusionSessionStatus.CLOSED:
|
||||
return
|
||||
self._status = ARDiffusionSessionStatus.CLOSING
|
||||
try:
|
||||
await self._lifecycle.close_session(self.session_id)
|
||||
except BaseException:
|
||||
async with self._state_lock:
|
||||
self._status = ARDiffusionSessionStatus.CLEANUP_FAILED
|
||||
raise
|
||||
else:
|
||||
async with self._state_lock:
|
||||
self._pending_events.clear()
|
||||
self._prompt = None
|
||||
self._controls.clear()
|
||||
self._inflight_event_floor = None
|
||||
self._status = ARDiffusionSessionStatus.CLOSED
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""Disconnect uses the same owning-worker cleanup as explicit close."""
|
||||
await self.close()
|
||||
|
||||
|
||||
class ARDiffusionSessionManager(Generic[TickOutputT]):
|
||||
"""Creates and owns transport sessions sharing one tick/lifecycle backend."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
tick_consumer: ARDiffusionTickConsumer[TickOutputT],
|
||||
lifecycle: ARDiffusionSessionLifecycle,
|
||||
max_pending_events: int,
|
||||
request_id_factory: Callable[[str, int], str] | None = None,
|
||||
session_id_factory: Callable[[], str] | None = None,
|
||||
control_reducer_factory: Callable[[], ARDiffusionControlReducer] | None = None,
|
||||
) -> None:
|
||||
self._tick_consumer = tick_consumer
|
||||
self._lifecycle = lifecycle
|
||||
self._max_pending_events = max_pending_events
|
||||
self._request_id_factory = request_id_factory
|
||||
self._session_id_factory = session_id_factory or (lambda: uuid.uuid4().hex)
|
||||
self._control_reducer_factory = control_reducer_factory
|
||||
self._sessions: dict[str, ARDiffusionSession[TickOutputT]] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def create_session(self, session_id: str | None = None) -> ARDiffusionSession[TickOutputT]:
|
||||
resolved_session_id = session_id or self._session_id_factory()
|
||||
async with self._lock:
|
||||
if resolved_session_id in self._sessions:
|
||||
raise ARDiffusionSessionStateError(f"AR-Diffusion session {resolved_session_id!r} already exists.")
|
||||
session = ARDiffusionSession(
|
||||
resolved_session_id,
|
||||
tick_consumer=self._tick_consumer,
|
||||
lifecycle=self._lifecycle,
|
||||
max_pending_events=self._max_pending_events,
|
||||
request_id_factory=self._request_id_factory,
|
||||
control_reducer=(
|
||||
self._control_reducer_factory() if self._control_reducer_factory is not None else None
|
||||
),
|
||||
)
|
||||
self._sessions[resolved_session_id] = session
|
||||
return session
|
||||
|
||||
async def get_session(self, session_id: str) -> ARDiffusionSession[TickOutputT]:
|
||||
async with self._lock:
|
||||
try:
|
||||
return self._sessions[session_id]
|
||||
except KeyError as exc:
|
||||
raise ARDiffusionSessionStateError(f"AR-Diffusion session {session_id!r} does not exist.") from exc
|
||||
|
||||
async def reset_session(self, session_id: str) -> None:
|
||||
session = await self.get_session(session_id)
|
||||
await session.reset()
|
||||
|
||||
async def close_session(self, session_id: str) -> None:
|
||||
session = await self.get_session(session_id)
|
||||
await session.close()
|
||||
async with self._lock:
|
||||
if self._sessions.get(session_id) is session:
|
||||
self._sessions.pop(session_id)
|
||||
|
||||
async def disconnect(self, session_id: str) -> None:
|
||||
"""Release the owning worker route when its transport disconnects."""
|
||||
await self.close_session(session_id)
|
||||
@@ -0,0 +1,202 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Typed request boundary shared by AR-Diffusion models and serving APIs.
|
||||
|
||||
The transport layer owns event ordering and snapshots. Model adapters consume
|
||||
the resulting immutable tick without learning about WebSocket messages.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from types import MappingProxyType
|
||||
from typing import Any
|
||||
|
||||
AR_DIFFUSION_TICK_KEY = "ar_diffusion_tick"
|
||||
|
||||
|
||||
def _non_empty_string(value: object, *, field: str) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError(f"{field} must be a non-empty string.")
|
||||
return value
|
||||
|
||||
|
||||
def _non_negative_int(value: object, *, field: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
||||
raise ValueError(f"{field} must be a non-negative integer.")
|
||||
return value
|
||||
|
||||
|
||||
def _freeze_transport_value(value: Any, *, path: str) -> Any:
|
||||
"""Copy JSON-like transport data into recursively immutable containers."""
|
||||
if value is None or isinstance(value, (str, bool, int, float)):
|
||||
return value
|
||||
if isinstance(value, Mapping):
|
||||
frozen: dict[str, Any] = {}
|
||||
for key, item in value.items():
|
||||
if not isinstance(key, str):
|
||||
raise ValueError(f"{path} mapping keys must be strings.")
|
||||
frozen[key] = _freeze_transport_value(item, path=f"{path}.{key}")
|
||||
return MappingProxyType(frozen)
|
||||
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
||||
return tuple(_freeze_transport_value(item, path=f"{path}[]") for item in value)
|
||||
raise ValueError(
|
||||
f"{path} must contain only transport-safe mappings, sequences, and scalar values; got {type(value).__name__}."
|
||||
)
|
||||
|
||||
|
||||
def _thaw_transport_value(value: Any) -> Any:
|
||||
"""Return a detached JSON-serializable copy of an immutable snapshot."""
|
||||
if isinstance(value, Mapping):
|
||||
return {key: _thaw_transport_value(item) for key, item in value.items()}
|
||||
if isinstance(value, tuple):
|
||||
return [_thaw_transport_value(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARDiffusionControlInput:
|
||||
"""One model-defined control track in a chunk-boundary snapshot."""
|
||||
|
||||
track: str
|
||||
schema: str
|
||||
data: Mapping[str, Any]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_non_empty_string(self.track, field="control.track")
|
||||
_non_empty_string(self.schema, field="control.schema")
|
||||
if not isinstance(self.data, Mapping):
|
||||
raise ValueError("control.data must be a mapping.")
|
||||
object.__setattr__(
|
||||
self,
|
||||
"data",
|
||||
_freeze_transport_value(self.data, path=f"control[{self.track!r}].data"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"track": self.track,
|
||||
"schema": self.schema,
|
||||
"data": _thaw_transport_value(self.data),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value: object) -> ARDiffusionControlInput:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ValueError("Each control must be a mapping.")
|
||||
return cls(
|
||||
track=value.get("track"), # type: ignore[arg-type]
|
||||
schema=value.get("schema"), # type: ignore[arg-type]
|
||||
data=value.get("data"), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARDiffusionTickRequest:
|
||||
"""A single atomic AR-block computation.
|
||||
|
||||
``request_id`` identifies this computation, ``session_id`` identifies the
|
||||
persistent rollout, and ``applied_event_ids`` records which accepted
|
||||
interaction events are represented by this immutable snapshot.
|
||||
"""
|
||||
|
||||
session_id: str
|
||||
request_id: str
|
||||
chunk_index: int
|
||||
applied_event_ids: tuple[int, ...] = ()
|
||||
prompt: str | None = None
|
||||
controls: tuple[ARDiffusionControlInput, ...] = ()
|
||||
reset: bool = False
|
||||
close_session: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_non_empty_string(self.session_id, field="session_id")
|
||||
_non_empty_string(self.request_id, field="request_id")
|
||||
_non_negative_int(self.chunk_index, field="chunk_index")
|
||||
if self.prompt is not None and not isinstance(self.prompt, str):
|
||||
raise ValueError("prompt must be a string or None.")
|
||||
if not isinstance(self.reset, bool):
|
||||
raise ValueError("reset must be a boolean.")
|
||||
if not isinstance(self.close_session, bool):
|
||||
raise ValueError("close_session must be a boolean.")
|
||||
|
||||
event_ids = tuple(
|
||||
_non_negative_int(event_id, field="applied_event_ids item") for event_id in self.applied_event_ids
|
||||
)
|
||||
if event_ids != tuple(sorted(set(event_ids))):
|
||||
raise ValueError("applied_event_ids must be unique and strictly increasing.")
|
||||
controls = tuple(self.controls)
|
||||
if any(not isinstance(control, ARDiffusionControlInput) for control in controls):
|
||||
raise ValueError("controls must contain ARDiffusionControlInput values.")
|
||||
object.__setattr__(self, "applied_event_ids", event_ids)
|
||||
object.__setattr__(self, "controls", controls)
|
||||
|
||||
def to_extra_args(self) -> dict[str, Any]:
|
||||
"""Serialize the tick under one namespaced ``extra_args`` key."""
|
||||
return {
|
||||
AR_DIFFUSION_TICK_KEY: {
|
||||
"session_id": self.session_id,
|
||||
"request_id": self.request_id,
|
||||
"chunk_index": self.chunk_index,
|
||||
"applied_event_ids": list(self.applied_event_ids),
|
||||
"prompt": self.prompt,
|
||||
"controls": [control.to_dict() for control in self.controls],
|
||||
"reset": self.reset,
|
||||
"close_session": self.close_session,
|
||||
}
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_extra_args(
|
||||
cls,
|
||||
extra_args: Mapping[str, Any] | None,
|
||||
) -> ARDiffusionTickRequest | None:
|
||||
"""Parse a typed tick, returning ``None`` for legacy AR requests."""
|
||||
if extra_args is None or AR_DIFFUSION_TICK_KEY not in extra_args:
|
||||
return None
|
||||
value = extra_args[AR_DIFFUSION_TICK_KEY]
|
||||
if not isinstance(value, Mapping):
|
||||
raise ValueError(f"{AR_DIFFUSION_TICK_KEY} must be a mapping.")
|
||||
raw_event_ids = value.get("applied_event_ids", ())
|
||||
raw_controls = value.get("controls", ())
|
||||
if not isinstance(raw_event_ids, Sequence) or isinstance(raw_event_ids, (str, bytes)):
|
||||
raise ValueError("applied_event_ids must be a sequence.")
|
||||
if not isinstance(raw_controls, Sequence) or isinstance(raw_controls, (str, bytes)):
|
||||
raise ValueError("controls must be a sequence.")
|
||||
return cls(
|
||||
session_id=value.get("session_id"), # type: ignore[arg-type]
|
||||
request_id=value.get("request_id"), # type: ignore[arg-type]
|
||||
chunk_index=value.get("chunk_index"), # type: ignore[arg-type]
|
||||
applied_event_ids=tuple(raw_event_ids),
|
||||
prompt=value.get("prompt"), # type: ignore[arg-type]
|
||||
controls=tuple(ARDiffusionControlInput.from_dict(control) for control in raw_controls),
|
||||
reset=value.get("reset", False), # type: ignore[arg-type]
|
||||
close_session=value.get("close_session", False), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARDiffusionChunkMetadata:
|
||||
"""Identity metadata returned with one generated AR block."""
|
||||
|
||||
session_id: str
|
||||
request_id: str
|
||||
chunk_index: int
|
||||
applied_event_ids: tuple[int, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_tick(cls, tick: ARDiffusionTickRequest) -> ARDiffusionChunkMetadata:
|
||||
return cls(
|
||||
session_id=tick.session_id,
|
||||
request_id=tick.request_id,
|
||||
chunk_index=tick.chunk_index,
|
||||
applied_event_ids=tick.applied_event_ids,
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"session_id": self.session_id,
|
||||
"request_id": self.request_id,
|
||||
"chunk_index": self.chunk_index,
|
||||
"applied_event_ids": list(self.applied_event_ids),
|
||||
}
|
||||
Reference in new issue
Block a user