[Feature][LingBot World]stepwise execution (#6844)

Signed-off-by: BruceLoveDecimal <liuqihao970610@gmail.com>
Signed-off-by: liuqihao <liuqihao970610@gmail.com>
This commit is contained in:
BruceLoveDecimal authored and GitHub committed 2026-09-07 13:38:23 +08:00
1 parent 7f32c326c6
commit 5cd925631c
24 files changed
+2087 -217

No files matched your search

@@ -1,13 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Realtime keyboard controls for LingBot World 2.0."""
from __future__ import annotations
import math
from collections.abc import Mapping, Sequence
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from typing import Any, TypeAlias
import numpy as np
import torch
@@ -42,7 +42,31 @@ def _normalize_actions(value: object, *, field: str) -> tuple[str, ...]:
return tuple(action for action in _ACTION_ORDER if action in actions)
def _normalize_frames(value: object, *, field: str) -> tuple[tuple[str, ...], ...]:
#: Key states for one latent frame each, e.g. ``(("w",), ("w", "j"), ())`` for
#: the three latent frames of one AR block.
LingBotCameraActionFrames: TypeAlias = tuple[tuple[str, ...], ...]
#: One :data:`LingBotCameraActionFrames` per generated chunk, carried on the
#: request for the whole rollout.
LingBotCameraActionScript: TypeAlias = tuple[LingBotCameraActionFrames, ...]
def as_camera_action_frames(value: Iterable[Iterable[str]]) -> LingBotCameraActionFrames:
"""Restore the tuple form of one chunk's per-latent-frame key states."""
return tuple(tuple(frame) for frame in value)
def as_camera_action_script(value: Iterable[Iterable[Iterable[str]]]) -> LingBotCameraActionScript:
"""Restore the tuple form of a whole request's script.
``sampling_params.extra_args`` round-trips through JSON, so an already
validated script comes back as lists; this rebuilds the hashable tuple form
without re-running validation.
"""
return tuple(as_camera_action_frames(chunk) for chunk in value)
def _normalize_frames(value: object, *, field: str) -> LingBotCameraActionFrames:
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
raise ValueError(f"{field} must be a sequence of per-frame action lists.")
return tuple(_normalize_actions(actions, field=f"{field}[{index}]") for index, actions in enumerate(value))
@@ -52,7 +76,7 @@ def parse_lingbot_camera_action_frames(
data: Mapping[str, Any],
*,
expected_frames: int,
) -> tuple[tuple[str, ...], ...]:
) -> LingBotCameraActionFrames:
"""Validate the chunk-sized payload emitted by the session reducer."""
if data.get("mode") != "frames":
@@ -66,6 +90,30 @@ def parse_lingbot_camera_action_frames(
return frames
def parse_lingbot_camera_action_script(
script: object,
*,
frames_per_chunk: int,
) -> LingBotCameraActionScript:
"""Validate a request-scoped list of per-chunk camera action frames."""
if not isinstance(script, Sequence) or isinstance(script, (str, bytes)):
raise ValueError("camera_action_script must be a sequence of per-chunk action lists.")
if not script:
raise ValueError("camera_action_script must contain at least one chunk.")
chunks: list[LingBotCameraActionFrames] = []
for index, chunk in enumerate(script):
frames = _normalize_frames(chunk, field=f"camera_action_script[{index}]")
if len(frames) != frames_per_chunk:
raise ValueError(
"camera_action_script chunks must contain exactly "
f"{frames_per_chunk} per-latent-frame action lists; "
f"chunk {index} has {len(frames)}."
)
chunks.append(frames)
return tuple(chunks)
@dataclass(frozen=True)
class _LingBotCameraReducerState:
mode: str | None = None
@@ -0,0 +1,239 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""One AR block of LingBot World's causal DMD sampler.
The pipeline drives this in two ways -- request mode loops ``generate_block``
over every block, stepwise execution calls ``probe_step`` / ``apply_transition``
one denoise step at a time and ``commit_block_kv`` from ``post_decode`` -- so the
math lives here once and cannot drift between the two modes.
A block is four probes that must not touch KV, then one clean-x0 commit that
does. Whether a call sees paged (session-bound) or request-local KV is decided
by the ``ar`` argument, so this class never reaches back into the pipeline.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast
import torch
from diffusers.utils.torch_utils import randn_tensor
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.models.lingbot_world.transformer import (
LingBotAttentionCache,
LingBotTransformerCache,
)
if TYPE_CHECKING:
from vllm_omni.diffusion.models.lingbot_world.transformer import CausalLingBotWorldTransformer3DModel
from vllm_omni.diffusion.models.progress_bar import TqdmProgressBar
from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVState
@dataclass(frozen=True)
class ARBlockContext:
"""The bound AR-Diffusion session one block runs against.
Built by the pipeline from the state the runner bound for this invocation;
``None`` in place of a context means request-local contiguous KV.
"""
state: ARDiffusionKVState
cross_attention: list[LingBotAttentionCache]
branch: str
class LingBotDMDBlockRunner:
"""Runs the DMD probes and the KV commit for one latent-frame block."""
def __init__(
self,
transformer: CausalLingBotWorldTransformer3DModel,
*,
device: torch.device,
enforce_eager: bool,
) -> None:
self.transformer = transformer
self.device = device
self.enforce_eager = enforce_eager
# ── cache selection ──────────────────────────────────────────────────
def _paged_cache(
self,
*,
condition: torch.Tensor,
ar: ARBlockContext,
commit_current: bool,
) -> LingBotTransformerCache:
patch_frames, patch_height, patch_width = self.transformer.config.patch_size
frames = condition.shape[2] // patch_frames
height = condition.shape[3] // patch_height
width = condition.shape[4] // patch_width
return LingBotTransformerCache(
self_attention=ar.state.get_kv_caches(
ar.branch,
seq_len=frames * height * width,
commit_current=commit_current,
),
cross_attention=ar.cross_attention,
)
def _block_cache(
self,
*,
condition: torch.Tensor,
cache: LingBotTransformerCache | None,
ar: ARBlockContext | None,
commit_current: bool,
) -> LingBotTransformerCache:
"""Pick the cache one transformer call sees: paged when a session is
bound, else the caller's request-local cache."""
if ar is not None:
return self._paged_cache(condition=condition, ar=ar, commit_current=commit_current)
return cast(LingBotTransformerCache, cache)
# ── one block ────────────────────────────────────────────────────────
def probe_step(
self,
*,
current_latents: torch.Tensor,
condition: torch.Tensor,
camera: torch.Tensor,
prompt_embeds: torch.Tensor,
cache: LingBotTransformerCache | None,
ar: ARBlockContext | None,
start_frame: int,
timestep_value: float,
step_index: int,
) -> torch.Tensor:
"""Predict flow for one denoise step.
A probe never writes KV: only the clean x0 of a finished block may
enter the cache, which is ``commit_block_kv``'s job.
"""
if not self.enforce_eager:
torch.compiler.cudagraph_mark_step_begin()
set_forward_context_denoise_step_idx(step_index)
timestep = torch.full((1,), float(timestep_value), device=self.device, dtype=torch.float32)
# Checkpoint channel contract:
# [noise/x_t(16), temporal_mask(4), image_latent(16)] -> 36.
model_input = torch.cat((current_latents.to(dtype=condition.dtype), condition), dim=1)
flow_prediction = self.transformer(
hidden_states=model_input,
timestep=timestep,
encoder_hidden_states=prompt_embeds,
camera_hidden_states=camera,
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=False),
start_frame=start_frame,
update_cache=False,
)
if flow_prediction.shape != current_latents.shape:
raise RuntimeError(
"transformer flow prediction shape must match the 16-channel noise latent, "
f"got {tuple(flow_prediction.shape)} and {tuple(current_latents.shape)}."
)
return flow_prediction
def apply_transition(
self,
current_latents: torch.Tensor,
flow_prediction: torch.Tensor,
sigma: float,
*,
next_sigma: float | None,
generator: torch.Generator,
) -> torch.Tensor:
"""Invert the flow to x0, then re-noise at ``next_sigma``.
``next_sigma=None`` marks the final step, so where the caller sits in
its own loop stays out of this function.
"""
# The checkpoint's flow parameterization is inverted by
# x0 = x_t - sigma * flow. Intermediate steps re-noise that x0
# estimate at the next sigma; the final step keeps x0 as this
# block's generated latent.
x0 = current_latents - sigma * flow_prediction.float()
if next_sigma is None:
return x0
noise = randn_tensor(current_latents.shape, generator=generator, device=self.device, dtype=torch.float32)
return (1.0 - next_sigma) * x0 + next_sigma * noise
def commit_block_kv(
self,
*,
latents: torch.Tensor,
condition: torch.Tensor,
camera: torch.Tensor,
prompt_embeds: torch.Tensor,
cache: LingBotTransformerCache | None,
ar: ARBlockContext | None,
start_frame: int,
) -> None:
"""Write the finished block's clean x0 into KV and commit its pages.
The fifth transformer call of a block, deliberately not a denoise step:
on the stepwise path it belongs to ``post_decode()``.
"""
# Commit K/V only for the final clean block, never for noisy probes.
cache_input = torch.cat((latents.to(dtype=condition.dtype), condition), dim=1)
if not self.enforce_eager:
torch.compiler.cudagraph_mark_step_begin()
self.transformer(
hidden_states=cache_input,
timestep=torch.zeros(1, device=self.device, dtype=torch.float32),
encoder_hidden_states=prompt_embeds,
camera_hidden_states=camera,
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=True),
start_frame=start_frame,
update_cache=True,
)
if ar is not None:
ar.state.commit_paged_context(ar.branch)
def generate_block(
self,
*,
condition: torch.Tensor,
camera: torch.Tensor,
prompt_embeds: torch.Tensor,
cache: LingBotTransformerCache | None,
ar: ARBlockContext | None,
start_frame: int,
schedule: tuple[tuple[float, float], ...],
generator: torch.Generator,
progress_bar: TqdmProgressBar[Any],
) -> torch.Tensor:
"""Request mode: all probes of one block, then its commit."""
block_shape = (1, self.transformer.config.out_channels, *condition.shape[2:5])
current_latents = randn_tensor(block_shape, generator=generator, device=self.device, dtype=torch.float32)
for step_index, (timestep_value, sigma) in enumerate(schedule):
flow_prediction = self.probe_step(
current_latents=current_latents,
condition=condition,
camera=camera,
prompt_embeds=prompt_embeds,
cache=cache,
ar=ar,
start_frame=start_frame,
timestep_value=timestep_value,
step_index=step_index,
)
next_sigma = schedule[step_index + 1][1] if step_index + 1 < len(schedule) else None
current_latents = self.apply_transition(
current_latents, flow_prediction, sigma, next_sigma=next_sigma, generator=generator
)
progress_bar.update()
self.commit_block_kv(
latents=current_latents,
condition=condition,
camera=camera,
prompt_embeds=prompt_embeds,
cache=cache,
ar=ar,
start_frame=start_frame,
)
return current_latents
@@ -1,12 +1,12 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Request-scoped LingBot-World v2 causal DMD pipeline."""
from __future__ import annotations
import math
import os
from collections.abc import Callable, Iterable, Iterator
from collections.abc import Callable, Iterable, Iterator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, Any, ClassVar, cast
@@ -24,15 +24,19 @@ from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery, SupportsStepExecution
from vllm_omni.diffusion.models.lingbot_world.actions import (
LINGBOT_CAMERA_ACTION_SCHEMA,
LINGBOT_CAMERA_TRAJECTORY_SCHEMA,
LingBotCameraActionFrames,
LingBotCameraActionScript,
as_camera_action_frames,
as_camera_action_script,
integrate_lingbot_camera_actions,
parse_lingbot_camera_action_frames,
parse_lingbot_camera_action_script,
)
from vllm_omni.diffusion.models.lingbot_world.camera import (
CameraTrajectory,
@@ -41,6 +45,7 @@ from vllm_omni.diffusion.models.lingbot_world.camera import (
load_camera_trajectory,
resolve_trusted_action_directory,
)
from vllm_omni.diffusion.models.lingbot_world.dmd_block import ARBlockContext, LingBotDMDBlockRunner
from vllm_omni.diffusion.models.lingbot_world.transformer import (
CausalLingBotWorldTransformer3DModel,
LingBotAttentionCache,
@@ -64,8 +69,11 @@ from vllm_omni.experimental.ar_diffusion.tick_protocol import (
)
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
from vllm_omni.diffusion.worker.utils import StepRequestState
from vllm_omni.experimental.ar_diffusion.kv_cache.state import (
ARDiffusionKVState,
)
@@ -79,6 +87,7 @@ _MAX_SEQUENCE_LENGTH = 512
_ACTION_ROOT_ENV = "VLLM_OMNI_LINGBOT_ACTION_ROOT"
_PREPROCESSED_CAMERA_KEY = "_lingbot_camera_trajectory"
_PREPROCESSED_CAMERA_ACTIONS_KEY = "_lingbot_camera_actions"
_PREPROCESSED_CAMERA_ACTION_SCRIPT_KEY = "_lingbot_camera_action_script"
_SOURCE_IMAGE_ERROR = (
"Unable to load multi_modal_data.image; expected a decodable image within 4096 * 4096 source pixels."
)
@@ -86,12 +95,34 @@ _SOURCE_IMAGE_ERROR = (
@dataclass(frozen=True)
class _LingBotRequestInputs:
"""Validated model-specific request boundary."""
"""Validated model-specific request boundary.
Pre-processing materializes exactly one of the three camera fields, chosen
from the shape of the incoming control. They are not alternative spellings
of one input: ``camera_action_script`` is a *container* whose element is a
``camera_actions``, and the two are live at once during step execution.
- ``camera_trajectory`` is explicit per-frame poses and intrinsics. Offline
replay loads it from ``extra_args["action_path"]``; the tick entry point
receives the same content as a ``lingbot.camera_trajectory.v1`` control.
Integrating WASD actions also produces one, written back onto this field.
- ``camera_actions`` is WASD key state for *one* three-latent-frame block:
the unit every path reduces to before the camera is embedded. The tick
entry point fills it directly, because one of its requests is one block;
step execution derives it per block by slicing ``camera_action_script``.
``_prepare_camera`` also reads it as the signal that the trajectory it
was handed is already latent-aligned.
- ``camera_action_script`` holds one such action list *per generated chunk*
for the whole rollout, which only step execution needs, because only it
runs every block inside a single ``generate()``. The tick entry point has
no use for it and ``forward()`` rejects a request that carries it.
"""
prompt: str
image: PIL.Image.Image | torch.Tensor
camera_trajectory: CameraTrajectory | None
camera_actions: tuple[tuple[str, ...], ...] | None
camera_actions: LingBotCameraActionFrames | None
camera_action_script: LingBotCameraActionScript | None
height: int
width: int
num_frames: int
@@ -303,6 +334,16 @@ def get_lingbot_world_pre_process_func(
"LingBot realtime camera controls require schema "
"'lingbot.camera_trajectory.v1' or 'lingbot.camera_actions.v1'."
)
camera_action_script = None
elif extra_args.get("camera_action_script") is not None:
if extra_args.get("action_path"):
raise ValueError("camera_action_script cannot be combined with action_path.")
camera_action_script = parse_lingbot_camera_action_script(
extra_args.get("camera_action_script"),
frames_per_chunk=3,
)
trajectory = None
camera_actions = None
else:
action_path = extra_args.get("action_path")
if not isinstance(action_path, (str, os.PathLike)) or not str(action_path):
@@ -323,6 +364,7 @@ def get_lingbot_world_pre_process_func(
"Unable to load camera trajectory from action_path; expected poses.npy and intrinsics.npy."
) from None
camera_actions = None
camera_action_script = None
updated_prompt = dict(prompt)
updated_multi_modal_data = dict(multi_modal_data)
@@ -333,6 +375,7 @@ def get_lingbot_world_pre_process_func(
**extra_args,
_PREPROCESSED_CAMERA_KEY: trajectory,
_PREPROCESSED_CAMERA_ACTIONS_KEY: camera_actions,
_PREPROCESSED_CAMERA_ACTION_SCRIPT_KEY: camera_action_script,
}
return request
@@ -377,11 +420,13 @@ class LingBotWorldCausalDMDPipeline(
nn.Module,
SupportImageInput,
SupportsComponentDiscovery,
SupportsStepExecution,
ProgressBarMixin,
DiffusionPipelineProfilerMixin,
):
"""LingBot-World v2 I2V generation with a request-local causal cache."""
supports_step_execution: ClassVar[bool] = True
_dit_modules: ClassVar[list[str]] = ["transformer"]
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae"]
@@ -617,11 +662,17 @@ class LingBotWorldCausalDMDPipeline(
raise ValueError("sampling_params.extra_args must be a mapping.")
camera_trajectory = extra_args.get(_PREPROCESSED_CAMERA_KEY)
camera_actions = extra_args.get(_PREPROCESSED_CAMERA_ACTIONS_KEY)
camera_action_script = extra_args.get(_PREPROCESSED_CAMERA_ACTION_SCRIPT_KEY)
if camera_trajectory is not None and not isinstance(camera_trajectory, CameraTrajectory):
raise ValueError("LingBot camera trajectory must be materialized by the pre-process function.")
if camera_actions is not None:
camera_actions = tuple(tuple(actions) for actions in camera_actions)
if (camera_trajectory is None) == (camera_actions is None):
camera_actions = as_camera_action_frames(camera_actions)
if camera_action_script is not None:
camera_action_script = as_camera_action_script(camera_action_script)
camera_sources = (
int(camera_trajectory is not None) + int(camera_actions is not None) + int(camera_action_script is not None)
)
if camera_sources != 1:
raise ValueError("LingBot pre-processing must materialize exactly one camera input.")
request_flow_shift = (
@@ -720,6 +771,7 @@ class LingBotWorldCausalDMDPipeline(
image=image,
camera_trajectory=camera_trajectory,
camera_actions=camera_actions,
camera_action_script=camera_action_script,
height=height,
width=width,
num_frames=num_frames,
@@ -818,6 +870,7 @@ class LingBotWorldCausalDMDPipeline(
*,
dtype: torch.dtype,
previous: CameraTrajectory | None = None,
latent_aligned: bool = False,
) -> tuple[torch.Tensor, CameraTrajectory]:
"""Convert raw camera frames to a latent-aligned ray tensor."""
@@ -825,7 +878,7 @@ class LingBotWorldCausalDMDPipeline(
if trajectory is None:
raise RuntimeError("LingBot camera trajectory was not prepared before camera embedding.")
available_frames = int(trajectory.poses.shape[0])
if inputs.camera_actions is not None:
if inputs.camera_actions is not None or latent_aligned:
if available_frames != inputs.num_latent_frames:
raise ValueError(
"camera actions must produce exactly one pose per latent frame; "
@@ -942,29 +995,38 @@ class LingBotWorldCausalDMDPipeline(
)
]
def _ar_transformer_cache(
# ── DMD block helpers ─────────────────────────────────────────────────
#
# The DMD math for one AR block lives in ``LingBotDMDBlockRunner`` so that
# request mode (``_generate_block`` in a loop) and stepwise execution
# (``denoise_step`` / ``step_scheduler`` / ``post_decode``) share one copy.
# The pipeline's only jobs here are building the runner and translating
# the bound AR session into an ``ARBlockContext``.
@property
def _dmd_blocks(self) -> LingBotDMDBlockRunner:
runner = getattr(self, "_dmd_block_runner", None)
if runner is None:
runner = LingBotDMDBlockRunner(
self.transformer,
device=self.device,
enforce_eager=bool(self.od_config.enforce_eager),
)
self._dmd_block_runner = runner
return runner
def _ar_block_context(
self,
*,
condition: torch.Tensor,
cross_attention: list[LingBotAttentionCache],
commit_current: bool,
) -> LingBotTransformerCache:
cross_attention: list[LingBotAttentionCache] | None,
) -> ARBlockContext | None:
"""Wrap the bound session for the block runner; ``None`` keeps
request-local KV."""
if cross_attention is None:
return None
state = self._ar_diffusion_kv_state
if state is None:
raise RuntimeError("LingBot AR cache requested without a bound state.")
patch_frames, patch_height, patch_width = self.transformer.config.patch_size
frames = condition.shape[2] // patch_frames
height = condition.shape[3] // patch_height
width = condition.shape[4] // patch_width
seq_len = frames * height * width
return LingBotTransformerCache(
self_attention=state.get_kv_caches(
self._AR_BRANCH,
seq_len=seq_len,
commit_current=commit_current,
),
cross_attention=cross_attention,
)
return ARBlockContext(state=state, cross_attention=cross_attention, branch=self._AR_BRANCH)
def _generate_block(
self,
@@ -979,102 +1041,17 @@ class LingBotWorldCausalDMDPipeline(
generator: torch.Generator,
progress_bar: TqdmProgressBar[Any],
) -> torch.Tensor:
block_shape = (
1,
self.transformer.config.out_channels,
condition.shape[2],
condition.shape[3],
condition.shape[4],
)
current_latents = randn_tensor(
block_shape,
generator=generator,
device=self.device,
dtype=torch.float32,
)
for step_index, (timestep_value, sigma) in enumerate(schedule):
if not self.od_config.enforce_eager:
torch.compiler.cudagraph_mark_step_begin()
set_forward_context_denoise_step_idx(step_index)
timestep = torch.full((1,), float(timestep_value), device=self.device, dtype=torch.float32)
# Checkpoint channel contract:
# [noise/x_t(16), temporal_mask(4), image_latent(16)] -> 36.
model_input = torch.cat((current_latents.to(dtype=condition.dtype), condition), dim=1)
current_cache = (
self._ar_transformer_cache(
condition=condition,
cross_attention=cast(
list[LingBotAttentionCache],
ar_cross_attention,
),
commit_current=False,
)
if ar_cross_attention is not None
else cast(LingBotTransformerCache, cache)
)
flow_prediction = self.transformer(
hidden_states=model_input,
timestep=timestep,
encoder_hidden_states=prompt_embeds,
camera_hidden_states=camera,
cache=current_cache,
start_frame=start_frame,
update_cache=False,
)
if flow_prediction.shape != current_latents.shape:
raise RuntimeError(
"transformer flow prediction shape must match the 16-channel noise latent, "
f"got {tuple(flow_prediction.shape)} and {tuple(current_latents.shape)}."
)
# The checkpoint's flow parameterization is inverted by
# x0 = x_t - sigma * flow. Intermediate steps re-noise that x0
# estimate at the next sigma; the final step keeps x0 as this
# block's generated latent.
x0 = current_latents - sigma * flow_prediction.float()
if step_index + 1 < len(schedule):
next_sigma = schedule[step_index + 1][1]
noise = randn_tensor(
current_latents.shape,
generator=generator,
device=self.device,
dtype=torch.float32,
)
current_latents = (1.0 - next_sigma) * x0 + next_sigma * noise
else:
current_latents = x0
progress_bar.update()
# Commit K/V only for the final clean block, never for noisy probes.
cache_input = torch.cat((current_latents.to(dtype=condition.dtype), condition), dim=1)
commit_cache = (
self._ar_transformer_cache(
condition=condition,
cross_attention=cast(
list[LingBotAttentionCache],
ar_cross_attention,
),
commit_current=True,
)
if ar_cross_attention is not None
else cast(LingBotTransformerCache, cache)
)
if not self.od_config.enforce_eager:
torch.compiler.cudagraph_mark_step_begin()
self.transformer(
hidden_states=cache_input,
timestep=torch.zeros(1, device=self.device, dtype=torch.float32),
encoder_hidden_states=prompt_embeds,
camera_hidden_states=camera,
cache=commit_cache,
return self._dmd_blocks.generate_block(
condition=condition,
camera=camera,
prompt_embeds=prompt_embeds,
cache=cache,
ar=self._ar_block_context(ar_cross_attention),
start_frame=start_frame,
update_cache=True,
schedule=schedule,
generator=generator,
progress_bar=progress_bar,
)
if ar_cross_attention is not None:
state = self._ar_diffusion_kv_state
if state is None:
raise RuntimeError("LingBot AR state disappeared before KV commit.")
state.commit_paged_context(self._AR_BRANCH)
return current_latents
def encode_prompt(
self,
@@ -1100,6 +1077,15 @@ class LingBotWorldCausalDMDPipeline(
def forward(self, req: DiffusionRequestBatch) -> DiffusionOutput:
inputs = self._parse_request(req)
if inputs.camera_action_script is not None:
# Only step execution walks a whole rollout inside one request, so
# a per-chunk script here would be silently dropped rather than
# steering the camera.
raise ValueError(
"camera_action_script is read only by LingBot step execution; "
"request mode takes one three-frame camera_actions control per "
"block, or a camera_trajectory for the request."
)
tick = ARDiffusionTickRequest.from_extra_args(req.sampling_params.extra_args)
if tick is not None and self._ar_diffusion_kv_state is None:
raise RuntimeError("LingBot typed ticks require ARDiffusionEngine session binding.")
@@ -1287,6 +1273,317 @@ class LingBotWorldCausalDMDPipeline(
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
)
def _decode_chunk_to_pixels(
self, latents: torch.Tensor, *, output_type: str
) -> torch.Tensor | np.ndarray | list[list[PIL.Image.Image]]:
"""Decode one AR block so streaming consumers receive pixels, not latents.
Blocks are decoded independently, which keeps the shared VAE stateless
and lets a rollout be served without a per-session temporal cache. That
is the same shape Helios streams today; cross-block ``feat_cache``
continuity is a separate decision and is not made here.
The registered post-process hook returns a ``{"payload", "metadata"}``
envelope untouched, so the pixel conversion it would do for a bare
tensor has to happen here instead.
"""
latent_mean, latent_std = self._vae_latent_stats(latents)
vae_latents = (latents * latent_std + latent_mean).to(dtype=self.vae.dtype)
video = self.vae.decode(vae_latents, return_dict=False)[0]
return self._video_processor().postprocess_video(video, output_type=output_type)
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 _horizon_latent_frames(self) -> int:
return (_MAX_RAW_FRAMES - 1) // self.vae_scale_factor_temporal + 1
def _max_realtime_chunks(self) -> int:
return self._horizon_latent_frames() // int(self.transformer.config.num_frames_per_block)
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.")
def prepare_encode(self, state: StepRequestState, **kwargs: Any) -> StepRequestState:
del kwargs
self._require_bound_ar_state()
req = DiffusionRequestBatch(
requests=[
OmniDiffusionRequest(
prompt=state.prompt,
sampling_params=state.sampling,
request_id=state.request_id,
)
]
)
inputs = self._parse_request(req)
if ARDiffusionTickRequest.from_extra_args(state.sampling.extra_args) is not None:
raise ValueError("LingBot step execution does not accept AR-Diffusion ticks.")
if (inputs.height, inputs.width) != (self._ar_height, self._ar_width):
raise ValueError(
"LingBot AR-Diffusion request resolution must match the "
f"fixed cache geometry {self._ar_height}x{self._ar_width}."
)
block_frames = int(self.transformer.config.num_frames_per_block)
total_chunks = inputs.num_latent_frames // block_frames
max_chunks = self._max_realtime_chunks()
if total_chunks > max_chunks:
raise ValueError(
"LingBot step execution currently supports at most "
f"{max_chunks} chunks because the image-condition horizon is "
f"{_MAX_RAW_FRAMES} pixel frames."
)
if inputs.camera_action_script is not None and len(inputs.camera_action_script) != total_chunks:
raise ValueError(
"camera_action_script must contain one action list per generated chunk; "
f"got {len(inputs.camera_action_script)} chunks for {total_chunks} requested chunks."
)
dtype = self.transformer.dtype
prompt_embeds = self.encode_prompt(
inputs.prompt,
max_sequence_length=inputs.max_sequence_length,
dtype=dtype,
)
image_condition = self._prepare_condition(
replace(
inputs,
num_frames=_MAX_RAW_FRAMES,
num_latent_frames=self._horizon_latent_frames(),
),
dtype=dtype,
)
camera_trajectory_cache = None
camera_embedding_cache = None
if inputs.camera_trajectory is not None:
available_frames = int(inputs.camera_trajectory.poses.shape[0])
if available_frames < inputs.num_frames:
raise ValueError(
"camera trajectory frames must be at least num_frames; "
f"got camera_frames={available_frames}, num_frames={inputs.num_frames}."
)
truncated = CameraTrajectory(
poses=inputs.camera_trajectory.poses[: inputs.num_frames],
intrinsics=inputs.camera_trajectory.intrinsics[: inputs.num_frames],
)
camera_trajectory_cache = interpolate_camera_trajectory(truncated, inputs.num_latent_frames)
# Embed the whole trajectory once, exactly as request mode does, and
# slice it per block in ``_prepare_next_chunk``. Embedding each chunk
# on its own would normalize that block's framewise translations by
# its own largest step, so a slow block would be conditioned as
# full-speed motion and drift from offline replay of the same path.
camera_embedding_cache, _ = self._prepare_camera(inputs, dtype=dtype)
state.prompt_embeds = prompt_embeds
state.chunk_index = 0
state.step_index = 0
state.step_in_chunk = 0
state.total_chunks = total_chunks
state.chunk_num_steps = len(LINGBOT_DMD_TIMESTEPS)
state.extra = {
"inputs": inputs,
"image_condition": image_condition,
"schedule": _build_shifted_flow_schedule(flow_shift=inputs.flow_shift),
"dtype": dtype,
"block_frames": block_frames,
"camera_pitch": 0.0,
"camera_tail": None,
"camera_action_script": inputs.camera_action_script,
"camera_trajectory_cache": camera_trajectory_cache,
"camera_embedding_cache": camera_embedding_cache,
}
self._ar_text_caches(prompt_embeds, invalidate=False)
self._prepare_next_chunk(state)
return state
def _prepare_next_chunk(self, state: StepRequestState) -> None:
extra = state.extra
inputs: _LingBotRequestInputs = extra["inputs"]
block_frames = int(extra["block_frames"])
start_frame = state.chunk_index * block_frames
stop_frame = start_frame + block_frames
image_condition = extra["image_condition"]
if stop_frame > image_condition.shape[2]:
raise ValueError("LingBot chunk_index exceeds the configured causal image condition horizon.")
condition = image_condition[:, :, start_frame:stop_frame]
previous = extra.get("camera_tail")
if extra.get("camera_action_script") is not None:
chunk_actions = extra["camera_action_script"][state.chunk_index]
action_trajectory, camera_pitch = integrate_lingbot_camera_actions(
chunk_actions,
width=inputs.width,
height=inputs.height,
initial_pose=(previous.poses[-1] if previous is not None else None),
initial_pitch=float(extra.get("camera_pitch", 0.0)),
)
extra["camera_pitch"] = camera_pitch
chunk_inputs = replace(
inputs,
camera_trajectory=action_trajectory,
camera_actions=chunk_actions,
num_frames=(block_frames - 1) * self.vae_scale_factor_temporal + 1,
num_latent_frames=block_frames,
)
camera, camera_tail = self._prepare_camera(
chunk_inputs,
dtype=extra["dtype"],
previous=previous,
)
elif extra.get("camera_embedding_cache") is not None:
# Same slice request mode takes from its one full-trajectory
# embedding, so both paths condition a block identically.
trajectory = extra["camera_trajectory_cache"]
camera = extra["camera_embedding_cache"][:, :, start_frame:stop_frame]
camera_tail = CameraTrajectory(
poses=trajectory.poses[stop_frame - 1 : stop_frame].clone(),
intrinsics=trajectory.intrinsics[stop_frame - 1 : stop_frame].clone(),
)
else:
raise RuntimeError("LingBot step execution is missing a camera trajectory or action script.")
if camera.shape[2:] != condition.shape[2:]:
raise RuntimeError(
"folded camera and image condition must share latent frame/height/width geometry; "
f"got camera={tuple(camera.shape)}, condition={tuple(condition.shape)}."
)
generator = getattr(state.sampling, "generator", None)
if not isinstance(generator, torch.Generator):
raise ValueError("LingBot World requires the runner-provided torch.Generator.")
extra["condition"] = condition
extra["camera"] = camera
extra["camera_tail"] = camera_tail
extra["start_frame"] = start_frame
extra["ar_cross_attention"] = self._ar_text_caches(
cast(torch.Tensor, state.prompt_embeds),
invalidate=False,
)
state.latents = randn_tensor(
(
1,
self.transformer.config.out_channels,
condition.shape[2],
condition.shape[3],
condition.shape[4],
),
generator=generator,
device=self.device,
dtype=torch.float32,
)
state.timesteps = torch.tensor(
[timestep for timestep, _ in extra["schedule"]],
device=self.device,
dtype=torch.float32,
)
state.step_in_chunk = 0
state.step_index = 0
def denoise_step(
self,
input_batch: InputBatch,
*,
states: Sequence[StepRequestState] | None = None,
**kwargs: Any,
) -> torch.Tensor | None:
del input_batch, kwargs
if states is None or len(states) != 1:
raise ValueError("LingBot step execution supports a single request, not a batched request.")
self._require_bound_ar_state()
state = states[0]
extra = state.extra
latents = state.latents
if latents is None:
raise RuntimeError("LingBot step execution requires latents before denoise_step.")
timestep = state.current_timestep
if timestep is None:
raise RuntimeError("LingBot step execution requires a current timestep before denoise_step.")
schedule = extra["schedule"]
step_in_chunk = state.step_in_chunk
return self._dmd_blocks.probe_step(
current_latents=latents,
condition=extra["condition"],
camera=extra["camera"],
prompt_embeds=cast(torch.Tensor, state.prompt_embeds),
cache=None,
ar=self._ar_block_context(extra["ar_cross_attention"]),
start_frame=int(extra["start_frame"]),
timestep_value=float(schedule[step_in_chunk][0]),
step_index=step_in_chunk,
)
def step_scheduler(self, state: StepRequestState, noise_pred: torch.Tensor, **kwargs: Any) -> None:
del kwargs
extra = state.extra
latents = state.latents
if latents is None:
raise RuntimeError("LingBot step execution requires latents before step_scheduler.")
generator = getattr(state.sampling, "generator", None)
if not isinstance(generator, torch.Generator):
raise ValueError("LingBot World requires the runner-provided torch.Generator.")
schedule = extra["schedule"]
step_in_chunk = state.step_in_chunk
next_sigma = schedule[step_in_chunk + 1][1] if step_in_chunk + 1 < len(schedule) else None
state.latents = self._dmd_blocks.apply_transition(
latents,
noise_pred,
schedule[step_in_chunk][1],
next_sigma=next_sigma,
generator=generator,
)
state.step_in_chunk += 1
state.step_index = state.step_in_chunk
def post_decode(self, state: StepRequestState, **kwargs: Any) -> DiffusionOutput:
del kwargs
self._require_bound_ar_state()
extra = state.extra
latents = state.latents
if latents is None:
raise RuntimeError("LingBot step execution requires latents before post_decode.")
self._dmd_blocks.commit_block_kv(
latents=latents,
condition=extra["condition"],
camera=extra["camera"],
prompt_embeds=cast(torch.Tensor, state.prompt_embeds),
cache=None,
ar=self._ar_block_context(extra["ar_cross_attention"]),
start_frame=int(extra["start_frame"]),
)
completed_chunk_index = state.chunk_index
inputs: _LingBotRequestInputs = extra["inputs"]
# "video" is the payload key the output formatter treats as primary, so
# a streaming client receives frames on ``images`` like any other video
# pipeline; latent mode keeps the tensor for offline consumers.
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)}
output = {
"payload": payload,
"metadata": {
"ar_diffusion": ARDiffusionChunkMetadata(
session_id=state.request_id,
request_id=state.request_id,
chunk_index=completed_chunk_index,
applied_event_ids=(),
).to_dict()
},
}
state.chunk_index += 1
finished = state.request_denoise_completed
if not finished:
self._prepare_next_chunk(state)
return DiffusionOutput(
output=output,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
chunk_index=completed_chunk_index,
total_chunks=state.total_chunks,
finished=finished,
)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
return cast(set[str], loader.load_weights(weights))