[LingBot World] Eleven bit-identical removals of repeated work in the realtime path (#7648)

Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Zhou TaichangandClaude Fable 5.1 authored and GitHub committed 2026-09-21 06:12:45 +00:00
1 parent a9e2117f5e
commit 86fcfe95f1
23 files changed
+1957 -200

No files matched your search

@@ -4,6 +4,7 @@
from __future__ import annotations
import functools
import math
import os
from collections import OrderedDict
@@ -54,6 +55,7 @@ from vllm_omni.diffusion.models.lingbot_world.camera import (
)
from vllm_omni.diffusion.models.lingbot_world.dmd_block import ARBlockContext, LingBotDMDBlockRunner
from vllm_omni.diffusion.models.lingbot_world.transformer import (
CameraModulationCache,
CausalLingBotWorldTransformer3DModel,
LingBotAttentionCache,
LingBotTransformerCache,
@@ -91,7 +93,6 @@ logger = init_logger(__name__)
_STREAMING_DECODE_BYTES_PER_PIXEL_FP32 = 37832 * 1024 / (64 * 64)
if TYPE_CHECKING:
from diffusers.video_processor import VideoProcessor
from tqdm.std import tqdm as TqdmProgressBar
from vllm_omni.diffusion.worker.input_batch import InputBatch
@@ -152,6 +153,9 @@ class _LingBotRequestInputs:
width: int
num_frames: int
num_latent_frames: int
# Request mode returns pixels through VideoProcessor in this type. Step execution (realtime sessions)
# returns every pixel type as ``(F, H, W, 3)`` uint8 frames, the layout the streaming endpoint muxes; only
# ``"latent"`` differs there. See ``_decode_chunk_to_pixels``.
output_type: str
max_sequence_length: int
flow_shift: float
@@ -163,10 +167,20 @@ class _LingBotARSessionState:
"""Model-owned state; attention tensors remain runner-owned."""
next_chunk_index: int = 0
prompt: str | None = None
# The umT5 embedding itself is reused by ``encode_prompt``'s own cache.
# ``text_cache_key`` does the same job for the runner-owned cross-attention
# K/V built from that embedding: it holds the (prompt, max_sequence_length,
# dtype) the K/V was built from and is only published after a successful
# build; ``text_cache_dirty`` is raised for the duration of a build, so a
# build that fails forces the next tick to invalidate whatever its prompt is.
text_cache_key: tuple[str, int, str] | None = None
text_cache_dirty: bool = False
generator_state: torch.Tensor | None = None
encoder_cache: list[torch.Tensor | None] | None = None
pending_encoder_cache: list[torch.Tensor | None] | None = None
# The condition the encoder settles on once its history has stopped
# changing; see ``_next_condition_chunk``.
condition_fixed_point: torch.Tensor | None = None
camera_tail: CameraTrajectory | None = None
camera_pitch: float = 0.0
@@ -284,7 +298,70 @@ def _decode_source_image(image: PIL.Image.Image) -> PIL.Image.Image:
raise ValueError(_SOURCE_IMAGE_ERROR) from None
def _source_image_fingerprint(path: str | os.PathLike[str]) -> tuple[str, int, int, int, int, int]:
"""Identify the bytes behind ``path``: the resolved path plus the stat fields that change when it is rewritten."""
resolved = os.path.realpath(os.fspath(path))
stat = os.stat(resolved)
return resolved, stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
def _encoder_caches_identical(
before: list[torch.Tensor | None] | None, after: list[torch.Tensor | None] | None
) -> bool:
"""Whether two encoder histories hold the same tensors bit for bit, slot by slot."""
if before is None or after is None or len(before) != len(after):
return False
for x, y in zip(before, after, strict=True):
if x is None or y is None:
if x is not y:
return False
elif x.shape != y.shape or x.dtype != y.dtype or not torch.equal(x, y):
return False
return True
def _uint8_frames(video: torch.Tensor) -> np.ndarray:
"""Turn one decoded block ``(1, 3, F, H, W)`` in ``[-1, 1]`` into ``(F, H, W, 3)`` uint8 on the host.
This is the arithmetic ``VideoProcessor.postprocess_video`` applies for
``"np"`` and ``"pil"`` -- denormalise, widen to float32, scale by 255 and
round -- done on the device before the copy instead of on the host after
it. The bytes are identical to the PIL path; what changes is that the
frames cross to the host once, already in the layout and dtype the
streaming endpoint muxes, instead of as a float32 copy that is then
converted per frame while the next block waits.
"""
# Same order of operations as VideoProcessor: denormalise and clamp in
# the decoder dtype, then widen, scale and round.
frames = (video[0] / 2 + 0.5).clamp(0, 1).permute(1, 2, 3, 0)
frames = frames.float().mul_(255).round_().to(torch.uint8)
return np.ascontiguousarray(frames.cpu().numpy())
@functools.lru_cache(maxsize=1)
def _decode_source_image_fingerprinted(fingerprint: tuple[str, int, int, int, int, int]) -> PIL.Image.Image:
"""The decoded image behind ``fingerprint`` (resolved path plus the stat fields that change on rewrite).
One entry: a request-mode caller that replays the same source path decodes it once. The realtime tick
carries its image inline and never comes through here.
"""
return _decode_source_image_file(fingerprint[0])
def _load_source_image(path: str | os.PathLike[str]) -> PIL.Image.Image:
"""Decode the source image at ``path``, reusing the last decode while the file is unchanged.
Every caller gets its own copy, so a request that mutates its image cannot reach the next one. A path
that cannot be stat'ed goes straight to the uncached decode, which owns the validation error contract.
"""
try:
fingerprint = _source_image_fingerprint(path)
except (OSError, TypeError, ValueError):
return _decode_source_image_file(path)
return _decode_source_image_fingerprinted(fingerprint).copy()
def _decode_source_image_file(path: str | os.PathLike[str]) -> PIL.Image.Image:
try:
source_image = PIL.Image.open(path)
except (OSError, SyntaxError, ValueError, PIL.Image.DecompressionBombError):
@@ -483,6 +560,9 @@ class LingBotWorldCausalDMDPipeline(
"""LingBot-World v2 I2V generation with a request-local causal cache."""
supports_step_execution: ClassVar[bool] = True
# A realtime block is four probes and a commit over one prepared chunk
# state; nothing between those steps needs the serving scheduler.
supports_chunk_step_grouping: ClassVar[bool] = True
_dit_modules: ClassVar[list[str]] = ["transformer"]
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae"]
@@ -637,12 +717,21 @@ class LingBotWorldCausalDMDPipeline(
raise ValueError("LingBot AR-Diffusion cache needs a positive recent window after reserving sink frames.")
condition_latent_frames = int(self.transformer.config.num_frames_per_block)
condition_channels = self.vae_scale_factor_temporal + int(self.transformer.config.out_channels)
element_size = torch.empty((), dtype=self.transformer.dtype).element_size()
condition_bytes_per_session = (
condition_channels
* condition_latent_frames
* latent_height
* latent_width
* torch.empty((), dtype=self.transformer.dtype).element_size()
condition_channels * condition_latent_frames * latent_height * latent_width * element_size
)
# Each layer retains scale and shift for the rank-local camera tokens
# across all forwards of a block, including between scheduler calls.
camera_tokens = tokens_per_frame * condition_latent_frames
sp_size = int(self.od_config.parallel_config.ulysses_degree)
camera_bytes_per_session = (
2
* int(self.transformer.config.num_layers)
* ((camera_tokens + sp_size - 1) // sp_size)
* int(self.transformer.config.num_attention_heads)
* int(self.transformer.config.attention_head_dim)
* element_size
)
return ARDiffusionKVCacheSpec(
num_layers=int(self.transformer.config.num_layers),
@@ -658,10 +747,14 @@ class LingBotWorldCausalDMDPipeline(
ARDiffusionCrossAttentionKVSpec(
self._AR_TEXT_CACHE,
_MAX_SEQUENCE_LENGTH,
# Cross-attention keeps every local head on every rank rather than sharding heads across
# the Ulysses group, so the text pool holds that many heads, not the self-attention share.
num_kv_heads=int(self.transformer.blocks[0].cross_attn.num_local_heads),
),
),
model_owned_state_bytes_per_session=(
condition_bytes_per_session
+ camera_bytes_per_session
+ 2 * self._condition_encoder_cache_bytes() # Committed and in-flight histories.
+ self._streaming_decode_bytes_per_session()
),
@@ -733,6 +826,7 @@ class LingBotWorldCausalDMDPipeline(
if state is not None:
state.encoder_cache = None
state.pending_encoder_cache = None
state.condition_fixed_point = None
def reset_ar_diffusion_session(self, session_id: str) -> None:
self._release_condition_encoder_state(session_id)
@@ -988,6 +1082,50 @@ class LingBotWorldCausalDMDPipeline(
)
return condition
def _next_condition_chunk(
self,
inputs: _LingBotRequestInputs,
*,
start_frame: int,
session_state: _LingBotARSessionState,
dtype: torch.dtype,
) -> tuple[torch.Tensor, list[torch.Tensor | None]]:
"""The session's condition for the block at ``start_frame``, encoding only while it still changes.
After a session's opening block the encoder is fed the same all-zero
pixel frames on every block, so the only thing that can make one
block's condition differ from the last is the encoder's own history.
The history is a causal cache with finite temporal reach, and once the
zero frames have flushed the source image out of it the encoder is at
a fixed point: identical input and identical state produce the same
output and the same state on every later block. That fixed point is
detected, not assumed after some number of blocks: a block whose
returned history is bit-identical to the history it was given is the
proof, and from then on the stored condition is returned and the
encoder is not run. Measured at 480x832 the encode is 178 ms of a
block and the fixed point arrives by the eleventh; the served
rollouts this was measured on (40 blocks) are then byte-identical.
The opening block resets the fixed point, so a session that restarts
from a new source image encodes again until it settles.
"""
if start_frame == 0:
session_state.condition_fixed_point = None
elif session_state.condition_fixed_point is not None:
assert session_state.encoder_cache is not None
# The history is unchanged by construction; the pending copy is
# what post_decode commits, exactly as an encoded block's would be.
return session_state.condition_fixed_point.clone(), list(session_state.encoder_cache)
condition, pending_cache = self._prepare_condition_chunk(
inputs,
start_frame=start_frame,
encoder_cache=session_state.encoder_cache,
dtype=dtype,
)
if start_frame > 0 and _encoder_caches_identical(session_state.encoder_cache, pending_cache):
session_state.condition_fixed_point = condition.clone()
return condition, pending_cache
@torch.no_grad()
def _prepare_condition_chunk(
self,
@@ -1160,10 +1298,8 @@ class LingBotWorldCausalDMDPipeline(
for block in self.transformer.blocks:
cross_attention = block.cross_attn
shape = (cross_attention.num_local_heads, cross_attention.head_dim)
key = cross_attention.shard_kv_heads(
cross_attention.norm_k(cross_attention.k(projected_text)).unflatten(2, shape)
)
value = cross_attention.shard_kv_heads(cross_attention.v(projected_text).unflatten(2, shape))
key = cross_attention.norm_k(cross_attention.k(projected_text)).unflatten(2, shape)
value = cross_attention.v(projected_text).unflatten(2, shape)
yield key, value
state.populate_cross_attention(
@@ -1243,6 +1379,34 @@ class LingBotWorldCausalDMDPipeline(
progress_bar=progress_bar,
)
def _session_text_caches(
self,
prompt_embeds: torch.Tensor,
*,
prompt: str,
max_sequence_length: int,
session_state: _LingBotARSessionState,
) -> list[LingBotAttentionCache]:
"""Runner-owned cross-attention K/V for this tick, rebuilt when its inputs change.
The K/V is keyed by everything that defines the prompt embedding
(text, sequence length, dtype). The first build of a session needs no
invalidation (the runner state is empty); a key change does. The dirty
flag is raised for the duration of the build and cleared only after
``_ar_text_caches`` returns, so a build that fails after invalidating
or partially writing the caches makes the next tick, whatever its
prompt, invalidate again instead of consuming partial K/V.
"""
text_key = (prompt, int(max_sequence_length), str(prompt_embeds.dtype))
previous = session_state.text_cache_key
invalidate = session_state.text_cache_dirty or (previous is not None and previous != text_key)
session_state.text_cache_dirty = True
session_state.text_cache_key = None
caches = self._ar_text_caches(prompt_embeds, invalidate=invalidate)
session_state.text_cache_key = text_key
session_state.text_cache_dirty = False
return caches
def encode_prompt(
self,
prompt: str,
@@ -1345,6 +1509,9 @@ class LingBotWorldCausalDMDPipeline(
)
dtype = self.transformer.dtype
# Phase 1: turn all three user inputs into DiT-ready conditions.
# ``encode_prompt`` reuses an already-encoded prompt itself; the
# runner-owned cross-attention K/V is keyed the same way in
# ``_session_text_caches`` below.
prompt_embeds = self.encode_prompt(
inputs.prompt,
max_sequence_length=inputs.max_sequence_length,
@@ -1354,10 +1521,10 @@ class LingBotWorldCausalDMDPipeline(
condition = self._prepare_condition(inputs, dtype=dtype)
else:
assert session_state is not None
condition, pending_encoder_cache = self._prepare_condition_chunk(
condition, pending_encoder_cache = self._next_condition_chunk(
inputs,
start_frame=tick.chunk_index * block_frames,
encoder_cache=session_state.encoder_cache,
session_state=session_state,
dtype=dtype,
)
camera_pitch: float | None = None
@@ -1396,12 +1563,13 @@ class LingBotWorldCausalDMDPipeline(
)
else:
assert session_state is not None
prompt_changed = session_state.prompt is not None and session_state.prompt != inputs.prompt
if session_state.generator_state is not None:
inputs.generator.set_state(session_state.generator_state)
ar_cross_attention = self._ar_text_caches(
ar_cross_attention = self._session_text_caches(
prompt_embeds,
invalidate=prompt_changed,
prompt=inputs.prompt,
max_sequence_length=inputs.max_sequence_length,
session_state=session_state,
)
generated_blocks: list[torch.Tensor] = []
total_steps = (inputs.num_latent_frames // block_frames) * len(LINGBOT_DMD_TIMESTEPS)
@@ -1437,7 +1605,6 @@ class LingBotWorldCausalDMDPipeline(
cache = None
if tick is not None:
assert session_state is not None
session_state.prompt = inputs.prompt
session_state.generator_state = inputs.generator.get_state()
session_state.encoder_cache = pending_encoder_cache
session_state.camera_tail = camera_tail
@@ -1536,11 +1703,15 @@ class LingBotWorldCausalDMDPipeline(
if state is not None:
state.release()
def _decode_chunk_to_pixels(
self, latents: torch.Tensor, *, output_type: str, session_id: str | None = None
) -> torch.Tensor | np.ndarray | list[list[PIL.Image.Image]]:
def _decode_chunk_to_pixels(self, latents: torch.Tensor, *, session_id: str | None = None) -> np.ndarray:
"""Decode one AR block so streaming consumers receive pixels, not latents.
The block comes back as ``(F, H, W, 3)`` uint8 whatever pixel output
type the request named: the realtime endpoint muxes uint8 frames, so
``"pil"`` and ``"np"`` only ever differed in how much work stood
between the decoder and those bytes. Only ``"latent"`` means
something else, and the caller keeps latents before reaching here.
With a ``session_id`` the block is decoded through that session's own
temporal cache, so chunk *N + 1* continues chunk *N*: the causal decoder
expands the session's opening latent frame to one raw frame and every
@@ -1566,7 +1737,7 @@ class LingBotWorldCausalDMDPipeline(
video = self.vae.decode(vae_latents, return_dict=False)[0]
else:
video = self._streaming_decode_chunk(decoder, vae_latents, cast(str, session_id))
return self._video_processor().postprocess_video(video, output_type=output_type)
return _uint8_frames(video)
def _streaming_decode_chunk(
self, decoder: WanStreamingDecoder, vae_latents: torch.Tensor, session_id: str
@@ -1587,15 +1758,6 @@ class LingBotWorldCausalDMDPipeline(
self._release_streaming_decode_state(session_id)
raise
def _video_processor(self) -> VideoProcessor:
processor = getattr(self, "_cached_video_processor", None)
if processor is None:
from diffusers.video_processor import VideoProcessor
processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
self._cached_video_processor = processor
return processor
def _require_bound_ar_state(self) -> None:
if self._ar_diffusion_kv_state is None:
raise RuntimeError("LingBot step execution requires AR-Diffusion session binding.")
@@ -1683,10 +1845,10 @@ class LingBotWorldCausalDMDPipeline(
session_state = self._ar_sessions[state.request_id]
if session_state.next_chunk_index != state.chunk_index:
raise ValueError("LingBot condition chunks must be contiguous within the session.")
condition, pending_encoder_cache = self._prepare_condition_chunk(
condition, pending_encoder_cache = self._next_condition_chunk(
inputs,
start_frame=start_frame,
encoder_cache=session_state.encoder_cache,
session_state=session_state,
dtype=extra["dtype"],
)
previous = extra.get("camera_tail")
@@ -1780,6 +1942,12 @@ class LingBotWorldCausalDMDPipeline(
raise ValueError("LingBot World requires the runner-provided torch.Generator.")
extra["condition"] = condition
extra["camera"] = camera
# One camera-modulation cache per block: the four probes and the
# commit below are separate scheduler steps, so the block runner
# cannot open the reuse window around them the way generate_block
# does around its own loop. Holding the cache here makes the window
# span exactly this block, per request.
extra["camera_cache"] = CameraModulationCache()
extra["camera_tail"] = camera_tail
extra["start_frame"] = start_frame
extra["ar_cross_attention"] = self._ar_text_caches(
@@ -1838,6 +2006,7 @@ class LingBotWorldCausalDMDPipeline(
start_frame=int(extra["start_frame"]),
timestep_value=float(schedule[step_in_chunk][0]),
step_index=step_in_chunk,
camera_cache=extra["camera_cache"],
)
def step_scheduler(self, state: StepRequestState, noise_pred: torch.Tensor, **kwargs: Any) -> None:
@@ -1880,6 +2049,7 @@ class LingBotWorldCausalDMDPipeline(
cache=None,
ar=self._ar_block_context(extra["ar_cross_attention"]),
start_frame=int(extra["start_frame"]),
camera_cache=extra.pop("camera_cache"),
)
completed_chunk_index = state.chunk_index
inputs: _LingBotRequestInputs = extra["inputs"]
@@ -1889,13 +2059,7 @@ class LingBotWorldCausalDMDPipeline(
if inputs.output_type == "latent":
payload: dict[str, Any] = {"latents": latents}
else:
payload = {
"video": self._decode_chunk_to_pixels(
latents,
output_type=inputs.output_type,
session_id=state.request_id,
)
}
payload = {"video": self._decode_chunk_to_pixels(latents, session_id=state.request_id)}
output = {
"payload": payload,
"metadata": {