[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:
1 parent
a9e2117f5e
commit
86fcfe95f1
23 files changed
+1957
-200
No files matched your search
@@ -24,7 +24,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.utils import set_weight_attrs
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.distributed.comm import SeqAllToAll4D
|
||||
from vllm_omni.diffusion.distributed.comm import SeqAllToAll4D, all_to_all_5D
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelInput, SequenceParallelOutput
|
||||
from vllm_omni.diffusion.layers.norm import LayerNorm
|
||||
@@ -329,9 +329,18 @@ class LingBotSelfAttention(nn.Module):
|
||||
key = self.rotary_embedding(key, cos, sin)
|
||||
|
||||
if self.ulysses_world_size > 1:
|
||||
query = SeqAllToAll4D.apply(self.ulysses_group, query, 2, 1, False)
|
||||
key = SeqAllToAll4D.apply(self.ulysses_group, key, 2, 1, False)
|
||||
value = SeqAllToAll4D.apply(self.ulysses_group, value, 2, 1, False)
|
||||
# One fused sequence->head all-to-all for q/k/v instead of three:
|
||||
# (B, S/N, 3, H, D) -> (B, S, 3, H/N, D). Same head-group assignment
|
||||
# as the per-tensor 4D exchange (rank r receives head group r), so
|
||||
# the result is a pure permutation of the three-call version, with a
|
||||
# 3x larger message and one third of the latency-bound collectives.
|
||||
qkv = all_to_all_5D(
|
||||
torch.stack((query, key, value), dim=2),
|
||||
scatter_idx=3,
|
||||
gather_idx=1,
|
||||
group=self.ulysses_group,
|
||||
)
|
||||
query, key, value = qkv.unbind(2)
|
||||
|
||||
if isinstance(cache, ARDiffusionPagedLayerInputs):
|
||||
if query.shape[0] != 1:
|
||||
@@ -421,13 +430,11 @@ class LingBotCrossAttention(nn.Module):
|
||||
self.num_heads = num_heads
|
||||
self.head_dim = dim // num_heads
|
||||
self.num_local_heads = num_heads // tp_size
|
||||
self.ulysses_world_size, self.ulysses_rank, self.ulysses_group = _ulysses_state()
|
||||
if self.num_local_heads % self.ulysses_world_size:
|
||||
raise ValueError(
|
||||
"LingBot local cross-attention heads must be divisible by the Ulysses degree: "
|
||||
f"heads={self.num_local_heads}, ulysses={self.ulysses_world_size}."
|
||||
)
|
||||
self.num_sp_heads = self.num_local_heads // self.ulysses_world_size
|
||||
# Cross-attention keeps every local head on every Ulysses rank and attends the rank's own sequence
|
||||
# shard. Each query token attends the whole text sequence independently of the others, so there is
|
||||
# nothing to exchange: the sequence split Ulysses already gives us is the only split needed, and both
|
||||
# all-to-all collectives -- one for the query, one for the output -- disappear. The cost is that the text K/V is
|
||||
# replicated per rank instead of head-sharded; ar_diffusion_kv_cache_spec sizes the pool for it.
|
||||
self.tp_inner_dim = self.num_local_heads * self.head_dim
|
||||
|
||||
self.q = ColumnParallelLinear(
|
||||
@@ -465,9 +472,9 @@ class LingBotCrossAttention(nn.Module):
|
||||
self.norm_q = _LingBotRMSNorm(self.tp_inner_dim, eps)
|
||||
self.norm_k = _LingBotRMSNorm(self.tp_inner_dim, eps)
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_sp_heads,
|
||||
num_heads=self.num_local_heads,
|
||||
head_size=self.head_dim,
|
||||
num_kv_heads=self.num_sp_heads,
|
||||
num_kv_heads=self.num_local_heads,
|
||||
softmax_scale=self.head_dim**-0.5,
|
||||
causal=False,
|
||||
role="cross",
|
||||
@@ -477,14 +484,6 @@ class LingBotCrossAttention(nn.Module):
|
||||
disable_kv_quant=True,
|
||||
)
|
||||
|
||||
def shard_kv_heads(self, value: torch.Tensor) -> torch.Tensor:
|
||||
"""Select this Ulysses rank's projected K/V heads."""
|
||||
|
||||
if self.ulysses_world_size == 1:
|
||||
return value
|
||||
start = self.ulysses_rank * self.num_sp_heads
|
||||
return value[:, :, start : start + self.num_sp_heads].clone(memory_format=torch.contiguous_format)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -494,8 +493,6 @@ class LingBotCrossAttention(nn.Module):
|
||||
) -> tuple[torch.Tensor, LingBotAttentionCache]:
|
||||
query = self.norm_q(self.q(hidden_states))
|
||||
query = query.unflatten(2, (self.num_local_heads, self.head_dim))
|
||||
if self.ulysses_world_size > 1:
|
||||
query = SeqAllToAll4D.apply(self.ulysses_group, query, 2, 1, False)
|
||||
|
||||
# Text K/V is constant within a request and is projected once per layer.
|
||||
if cache is None:
|
||||
@@ -503,8 +500,8 @@ class LingBotCrossAttention(nn.Module):
|
||||
raise ValueError("encoder_hidden_states are required when the cross-attention cache is empty.")
|
||||
key = self.norm_k(self.k(encoder_hidden_states))
|
||||
value = self.v(encoder_hidden_states)
|
||||
key = self.shard_kv_heads(key.unflatten(2, (self.num_local_heads, self.head_dim)))
|
||||
value = self.shard_kv_heads(value.unflatten(2, (self.num_local_heads, self.head_dim)))
|
||||
key = key.unflatten(2, (self.num_local_heads, self.head_dim))
|
||||
value = value.unflatten(2, (self.num_local_heads, self.head_dim))
|
||||
cache = LingBotAttentionCache(
|
||||
key=key,
|
||||
value=value,
|
||||
@@ -517,8 +514,6 @@ class LingBotCrossAttention(nn.Module):
|
||||
value = cache.value[:, : cache.end]
|
||||
|
||||
output = self.attn(query, key, value)
|
||||
if self.ulysses_world_size > 1:
|
||||
output = SeqAllToAll4D.apply(self.ulysses_group, output, 1, 2, False)
|
||||
return self.o(output.flatten(2, 3)), cache
|
||||
|
||||
|
||||
@@ -592,6 +587,16 @@ class LingBotAttentionBlock(nn.Module):
|
||||
self.cam_scale_layer = nn.Linear(dim, dim)
|
||||
self.cam_shift_layer = nn.Linear(dim, dim)
|
||||
|
||||
def camera_modulation(self, camera_hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Build this block's camera scale and shift from the patchified camera tokens.
|
||||
|
||||
Depends only on ``camera_hidden_states``, so a caller holding the camera trajectory fixed -- every
|
||||
denoise forward of one AR chunk does -- can build this once and pass it back through ``forward``.
|
||||
"""
|
||||
camera_features = self.cam_injector_layer2(F.silu(self.cam_injector_layer1(camera_hidden_states)))
|
||||
camera_features = camera_features + camera_hidden_states
|
||||
return self.cam_scale_layer(camera_features), self.cam_shift_layer(camera_features)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -605,6 +610,7 @@ class LingBotAttentionBlock(nn.Module):
|
||||
sink_tokens: int,
|
||||
update_cache: bool,
|
||||
rotary_emb: tuple[torch.Tensor, torch.Tensor],
|
||||
camera_modulation: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> tuple[torch.Tensor, LingBotAttentionCache]:
|
||||
batch_size, token_count, dim = hidden_states.shape
|
||||
if (
|
||||
@@ -638,10 +644,9 @@ class LingBotAttentionBlock(nn.Module):
|
||||
hidden_grid = hidden_grid + attention_output.unflatten(1, (num_frames, tokens_per_frame)) * gate_msa
|
||||
hidden_states = hidden_grid.flatten(1, 2).to(hidden_states.dtype)
|
||||
|
||||
camera_features = self.cam_injector_layer2(F.silu(self.cam_injector_layer1(camera_hidden_states)))
|
||||
camera_features = camera_features + camera_hidden_states
|
||||
camera_scale = self.cam_scale_layer(camera_features)
|
||||
camera_shift = self.cam_shift_layer(camera_features)
|
||||
camera_scale, camera_shift = (
|
||||
self.camera_modulation(camera_hidden_states) if camera_modulation is None else camera_modulation
|
||||
)
|
||||
hidden_states = ((1 + camera_scale) * hidden_states + camera_shift).to(hidden_states.dtype)
|
||||
|
||||
attention_output, cross_cache = self.cross_attn(
|
||||
@@ -763,6 +768,22 @@ def _rope_axis(max_seq_len: int, dim: int, *, start: int = 0) -> tuple[torch.Ten
|
||||
return phase.cos().float(), phase.sin().float()
|
||||
|
||||
|
||||
class CameraModulationCache:
|
||||
"""Per-block camera scale and shift, held by the caller across the forwards of one AR block.
|
||||
|
||||
The camera injector is four projections and a SiLU per block and reads only the camera tokens, which do
|
||||
not change between the denoise steps and the clean commit of one block. The caller that owns that
|
||||
invariant creates one of these per block and passes it to every forward of the block; ``forward`` fills a
|
||||
block's entry on first use and reads it after. Its lifetime is the caller's: the AR runner keeps one per
|
||||
block, ``generate_block`` one per loop, and nothing here checks the camera tensor for change.
|
||||
"""
|
||||
|
||||
__slots__ = ("entries",)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.entries: dict[int, tuple[torch.Tensor, torch.Tensor]] = {}
|
||||
|
||||
|
||||
class CausalLingBotWorldTransformer3DModel(nn.Module):
|
||||
"""Checkpoint-compatible causal LingBot World video transformer."""
|
||||
|
||||
@@ -922,6 +943,27 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
|
||||
cosine, sine = _rope_axis(rope_max_seq_len, axis_dim)
|
||||
self.register_buffer(f"_rope_{axis}_cosine", cosine, persistent=False)
|
||||
self.register_buffer(f"_rope_{axis}_sine", sine, persistent=False)
|
||||
# One static-address buffer per shape for the per-token timestep
|
||||
# projection; see _stage_timestep_projection.
|
||||
self._timestep_projection_buffers: dict[tuple[tuple[int, ...], torch.dtype, torch.device], torch.Tensor] = {}
|
||||
|
||||
def _stage_timestep_projection(self, projection: torch.Tensor) -> torch.Tensor:
|
||||
"""Hand the blocks the timestep projection from a buffer whose address never changes.
|
||||
|
||||
Every regional block graph takes the projection as an input. Under CUDA-graph replay an input that
|
||||
arrives in a fresh tensor each forward is copied into the graph's placeholder on every replay: at
|
||||
480x832 with four Ulysses ranks that is a 72 MB copy per block, forty times per forward, two hundred
|
||||
times per AR chunk. Copying the projection once per forward into a buffer marked static lets every
|
||||
replay read it in place. The values the blocks see are the same; only where they live changes.
|
||||
"""
|
||||
key = (tuple(projection.shape), projection.dtype, projection.device)
|
||||
buffer = self._timestep_projection_buffers.get(key)
|
||||
if buffer is None:
|
||||
buffer = torch.empty(projection.shape, dtype=projection.dtype, device=projection.device)
|
||||
torch._dynamo.mark_static_address(buffer)
|
||||
self._timestep_projection_buffers[key] = buffer
|
||||
buffer.copy_(projection)
|
||||
return buffer
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
@@ -1178,6 +1220,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
|
||||
cache: LingBotTransformerCache,
|
||||
start_frame: int,
|
||||
update_cache: bool,
|
||||
camera_modulation_cache: CameraModulationCache | None = None,
|
||||
) -> torch.Tensor:
|
||||
if not isinstance(update_cache, bool):
|
||||
raise ValueError("update_cache must be a boolean.")
|
||||
@@ -1272,16 +1315,25 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
|
||||
"LingBot SP input hooks did not shard all conditioning tensors consistently; "
|
||||
f"expected {local_tokens} tokens per rank. Check SP hook registration and input dimensions."
|
||||
)
|
||||
timestep_projection = self._stage_timestep_projection(timestep_projection)
|
||||
rotary_emb = (cosine, sine)
|
||||
# Phase 3: each layer receives its own cache entry. Text K/V is passed
|
||||
# only when absent; the returned cache is stored for subsequent DMD
|
||||
# steps and causal blocks in this request.
|
||||
# steps and causal blocks in this request. A caller-held camera cache
|
||||
# gives every block its modulation once per AR block.
|
||||
for index, block in enumerate(self.blocks):
|
||||
camera_modulation = None
|
||||
if camera_modulation_cache is not None:
|
||||
camera_modulation = camera_modulation_cache.entries.get(index)
|
||||
if camera_modulation is None:
|
||||
camera_modulation = block.camera_modulation(camera_hidden_states)
|
||||
camera_modulation_cache.entries[index] = camera_modulation
|
||||
hidden_states, cross_cache = block(
|
||||
hidden_states,
|
||||
projected_text if cache.cross_attention[index] is None else None,
|
||||
timestep_projection,
|
||||
camera_hidden_states,
|
||||
camera_modulation=camera_modulation,
|
||||
self_cache=cache.self_attention[index],
|
||||
cross_cache=cache.cross_attention[index],
|
||||
current_start=current_start,
|
||||
|
||||
Reference in new issue
Block a user