[Feature][Diffusion] Add BOOGU Image sequence parallel support (#5718)

Signed-off-by: Xenoryn <timberh2000@outlook.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-09-25 16:18:23 +08:00
1 parent e5613794ca
commit 0c7042d0d5
12 files changed
+1461 -68

No files matched your search

@@ -38,13 +38,22 @@ from vllm.triton_utils import HAS_TRITON
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelInput,
SequenceParallelOutput,
)
from vllm_omni.diffusion.layers.fused_qk_norm_rope import (
_fused_cuda_supported,
fused_qk_norm_rope,
fused_qk_norm_rope_min_tokens,
)
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.models.utils import make_attention_mask
from vllm_omni.diffusion.models.boogu_image.sp_layout import (
RotaryEmbedding,
ShardLayout,
pack_local_rotary,
rank_concat_mask_or_none,
)
from vllm_omni.platforms import current_omni_platform
if TYPE_CHECKING:
@@ -52,10 +61,6 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
# (cos, sin) — optionally (cos, sin, packed_table) where packed_table is the
# fp32 [tokens, head_dim] = [cos(theta) | sin(theta)] layout the fused
# qk-norm+RoPE op consumes; the eager path ignores the third element.
RotaryEmbedding = tuple[torch.Tensor, ...]
RotaryFrequencyTables = list[RotaryEmbedding]
@@ -540,12 +545,16 @@ def _concat_instruction_image_features(
assert len(img_tensors) == len(instruct_tensors)
batch_size = img_tensors[0].shape[0]
max_seq_len = max(seq_lengths)
joint_capacity = instruct_tensors[0].shape[1] + img_tensors[0].shape[1]
concatenated_list = []
for img_tensor, instruct_tensor in zip(img_tensors, instruct_tensors):
feature_dim = img_tensor.shape[-1]
concatenated = img_tensor.new_zeros(batch_size, max_seq_len, feature_dim)
concatenated = img_tensor.new_zeros(
batch_size,
joint_capacity,
feature_dim,
)
for i, (encoder_seq_len, seq_len) in enumerate(zip(encoder_seq_lengths, seq_lengths)):
concatenated[i, :encoder_seq_len] = instruct_tensor[i, :encoder_seq_len]
concatenated[i, encoder_seq_len:seq_len] = img_tensor[i, : seq_len - encoder_seq_len]
@@ -558,16 +567,24 @@ def _split_instruction_image_features(
hidden_states: torch.Tensor,
encoder_seq_lengths: list[int],
seq_lengths: list[int],
*,
instruct_capacity: int,
img_capacity: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Unpack a joint sequence back into (instruction, image) streams."""
batch_size = hidden_states.shape[0]
feature_dim = hidden_states.shape[-1]
max_instruct_len = max(encoder_seq_lengths)
max_img_len = max(seq_len - encoder_seq_len for seq_len, encoder_seq_len in zip(seq_lengths, encoder_seq_lengths))
instruct_hidden_states = hidden_states.new_zeros(batch_size, max_instruct_len, feature_dim)
img_hidden_states = hidden_states.new_zeros(batch_size, max_img_len, feature_dim)
instruct_hidden_states = hidden_states.new_zeros(
batch_size,
instruct_capacity,
feature_dim,
)
img_hidden_states = hidden_states.new_zeros(
batch_size,
img_capacity,
feature_dim,
)
for i, (encoder_seq_len, seq_len) in enumerate(zip(encoder_seq_lengths, seq_lengths)):
img_len = seq_len - encoder_seq_len
@@ -772,7 +789,11 @@ class BooguImageJointAttention(nn.Module):
attn_output = attn_output.flatten(2, 3).to(dtype)
instruct_attn_out, img_attn_out = _split_instruction_image_features(
attn_output, encoder_seq_lengths, seq_lengths
attn_output,
encoder_seq_lengths,
seq_lengths,
instruct_capacity=instruct_hidden_states.shape[1],
img_capacity=img_hidden_states.shape[1],
)
instruct_projected, _ = self.instruct_out(instruct_attn_out)
img_projected, _ = self.img_out(img_attn_out)
@@ -1139,6 +1160,20 @@ _BOOGU_STACKED_PARAMS_MAPPING = (
)
class _BooguImageSPBoundary(nn.Module):
"""Identity module used by framework SP split hooks."""
def forward(self, *tensors: torch.Tensor) -> tuple[torch.Tensor, ...]:
return tensors
class _BooguImageSPGather(nn.Module):
"""Identity module used by the framework SP gather hook."""
def forward(self, tensor: torch.Tensor) -> torch.Tensor:
return tensor
class BooguImageTransformer2DModel(nn.Module):
"""Boogu-Image transformer with mixed stream topology.
@@ -1156,6 +1191,46 @@ class BooguImageTransformer2DModel(nn.Module):
"BooguImageSingleStreamTransformerBlock",
]
_layerwise_offload_blocks_attrs = ["single_stream_layers", "double_stream_layers"]
# Boundary outputs are hidden states, masks, and RoPE; each triplet is in
# image/reference/context order so tensors sharing a sequence reuse metadata.
# Twelve entries: 3 hidden states (dim=3), 3 masks (dim=2), then the
# rotary cos/sin pairs for image/reference/context (dim=3 each). Real-valued
# RoPE returns tuples, so each rotary embedding contributes two tensors.
_sp_plan = {
"sp_shard_boundary": {
index: SequenceParallelInput(
split_dim=1,
expected_dims=dims,
split_output=True,
auto_pad=True,
shard_group=shard_group,
)
for index, (dims, shard_group) in enumerate(
zip(
(3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3),
(
"image",
"reference",
"context",
"image",
"reference",
"context",
"image",
"image",
"reference",
"reference",
"context",
"context",
),
)
)
},
"sp_gather_boundary": SequenceParallelOutput(
gather_dim=1,
expected_dims=3,
shard_group="image",
),
}
def __init__(
self,
@@ -1226,6 +1301,8 @@ class BooguImageTransformer2DModel(nn.Module):
axes_lens=axes_lens,
patch_size=patch_size,
)
self.sp_shard_boundary = _BooguImageSPBoundary()
self.sp_gather_boundary = _BooguImageSPGather()
self.x_embedder = nn.Linear(
in_features=patch_size * patch_size * in_channels,
@@ -1472,6 +1549,7 @@ class BooguImageTransformer2DModel(nn.Module):
l_effective_ref_img_len: list[list[int]],
l_effective_img_len: list[int],
temb: torch.Tensor,
per_rank_ref_lengths: list[list[list[int]]] | None = None,
):
"""Embed image patches and run the refiner blocks.
@@ -1481,9 +1559,7 @@ class BooguImageTransformer2DModel(nn.Module):
avoiding a degenerate zero-length attention.
"""
batch_size = len(hidden_states)
max_combined_img_len = max(
img_len + sum(ref_img_len) for img_len, ref_img_len in zip(l_effective_img_len, l_effective_ref_img_len)
)
max_combined_img_len = hidden_states.shape[1] + ref_image_hidden_states.shape[1]
hidden_states = self.x_embedder(hidden_states)
ref_image_hidden_states = self.ref_image_patch_embedder(ref_image_hidden_states)
@@ -1502,6 +1578,14 @@ class BooguImageTransformer2DModel(nn.Module):
flat_l_effective_ref_img_len = list(itertools.chain(*l_effective_ref_img_len))
num_ref_images = len(flat_l_effective_ref_img_len)
max_ref_img_len = max(flat_l_effective_ref_img_len)
sp_sharded = per_rank_ref_lengths is not None and len(per_rank_ref_lengths) > 1
if sp_sharded:
# Keep the packed reference batch at the padded local capacity so
# every SP rank retains the equal-length contract.
max_ref_img_len = max(
max_ref_img_len,
padded_ref_img_mask.shape[1],
)
if max_ref_img_len > 0:
batch_ref_img_mask = ref_image_hidden_states.new_zeros(num_ref_images, max_ref_img_len, dtype=torch.bool)
@@ -1544,9 +1628,27 @@ class BooguImageTransformer2DModel(nn.Module):
# table; the forward-level tuples do not flow into this batch.
batch_ref_img_rotary_emb = _with_packed_rope_table(batch_ref_img_rotary_emb)
if sp_sharded:
# Ulysses will concatenate each rank's packed reference batch,
# so the mask must cover all ranks' segments.
ref_attention_mask = rank_concat_mask_or_none(
[list(itertools.chain(*rank_lengths)) for rank_lengths in per_rank_ref_lengths],
max_ref_img_len,
like=batch_ref_img_mask,
)
else:
ref_attention_mask = (
batch_ref_img_mask
if any(length != max_ref_img_len for length in flat_l_effective_ref_img_len)
else None
)
for layer in self.ref_image_refiner:
batch_ref_image_hidden_states = layer(
batch_ref_image_hidden_states, batch_ref_img_mask, batch_ref_img_rotary_emb, batch_temb
batch_ref_image_hidden_states,
ref_attention_mask,
batch_ref_img_rotary_emb,
batch_temb,
)
# Restore reference-image sequence layout.
@@ -1614,11 +1716,11 @@ class BooguImageTransformer2DModel(nn.Module):
context_rotary_emb,
ref_img_rotary_emb,
noise_rotary_emb,
rotary_emb,
encoder_seq_lengths,
seq_lengths,
combined_img_rotary_emb,
combined_img_seq_lengths,
_,
global_encoder_seq_lengths,
_,
_,
_,
) = self.rope_embedder(
freqs_real,
instruction_attention_mask,
@@ -1629,10 +1731,91 @@ class BooguImageTransformer2DModel(nn.Module):
device,
)
# RoPE is real-valued (cos, sin) tuples; unpack them to shard cos and
# sin independently through the split hook, then re-pair below.
noise_cos, noise_sin = noise_rotary_emb
ref_cos, ref_sin = ref_img_rotary_emb
context_cos, context_sin = context_rotary_emb
(
hidden_states,
ref_image_hidden_states,
instruction_hidden_states,
img_mask,
ref_img_mask,
instruction_attention_mask,
noise_cos,
noise_sin,
ref_cos,
ref_sin,
context_cos,
context_sin,
) = self.sp_shard_boundary(
hidden_states,
ref_image_hidden_states,
instruction_hidden_states,
img_mask,
ref_img_mask,
instruction_attention_mask,
noise_cos,
noise_sin,
ref_cos,
ref_sin,
context_cos,
context_sin,
)
noise_rotary_emb = (noise_cos, noise_sin)
ref_img_rotary_emb = (ref_cos, ref_sin)
context_rotary_emb = (context_cos, context_sin)
image_layout = ShardLayout.resolve("image", local_seq_len=img_mask.shape[1])
reference_layout = ShardLayout.resolve("reference", local_seq_len=ref_img_mask.shape[1])
context_layout = ShardLayout.resolve("context", local_seq_len=instruction_attention_mask.shape[1])
sp_world_size = image_layout.world_size
sp_rank = image_layout.rank
context_mask_required = context_layout.padding_size > 0 or any(
length != context_layout.original_seq_len for length in global_encoder_seq_lengths
)
noise_mask_required = image_layout.padding_size > 0 or any(
length != image_layout.original_seq_len for length in l_effective_img_len
)
ref_mask_required = reference_layout.padding_size > 0 or any(
sum(lengths) != reference_layout.original_seq_len for lengths in l_effective_ref_img_len
)
global_img_lengths = list(l_effective_img_len)
# Ulysses concatenates the rank-local sequences after its all-to-all, so
# attention masks must describe that rank-concatenated layout. Every
# rank's shard bounds are pure arithmetic over the global lengths, so
# each rank derives all ranks' segments without any communication.
ranks = range(sp_world_size)
per_rank_img_lengths = [image_layout.valid_lengths(global_img_lengths, rank=r) for r in ranks]
per_rank_ref_lengths = [reference_layout.segment_lengths(l_effective_ref_img_len, rank=r) for r in ranks]
per_rank_encoder_lengths = [context_layout.valid_lengths(global_encoder_seq_lengths, rank=r) for r in ranks]
local_img_lengths = per_rank_img_lengths[sp_rank]
local_ref_lengths = per_rank_ref_lengths[sp_rank]
local_encoder_lengths = per_rank_encoder_lengths[sp_rank]
(
rotary_emb,
combined_img_rotary_emb,
seq_lengths,
combined_img_seq_lengths,
) = pack_local_rotary(
context_rotary_emb,
ref_img_rotary_emb,
noise_rotary_emb,
local_encoder_lengths,
local_ref_lengths,
local_img_lengths,
)
if _FUSED_QK_NORM_ROPE:
# One packed [cos|sin] table per rotary embedding that reaches an
# attention, built once per forward; the tuples grow a third
# element that the fused path consumes and the eager path ignores.
# Under SP, cos/sin are already the rank-local sharded tensors, so
# the packed table matches the fused kernel's local Q/K geometry.
# (ref_img_rotary_emb is packed inside img_patch_embed_and_refine,
# on the rebuilt per-reference-image batch tuple.)
context_rotary_emb = _with_packed_rope_table(context_rotary_emb)
@@ -1640,32 +1823,68 @@ class BooguImageTransformer2DModel(nn.Module):
rotary_emb = _with_packed_rope_table(rotary_emb)
combined_img_rotary_emb = _with_packed_rope_table(combined_img_rotary_emb)
context_attention_mask = rank_concat_mask_or_none(
per_rank_encoder_lengths,
context_layout.local_seq_len,
like=instruction_attention_mask,
required=context_mask_required,
)
noise_attention_mask = rank_concat_mask_or_none(
per_rank_img_lengths,
image_layout.local_seq_len,
like=img_mask,
required=noise_mask_required,
)
# Context refinement.
for layer in self.context_refiner:
instruction_hidden_states = layer(instruction_hidden_states, instruction_attention_mask, context_rotary_emb)
instruction_hidden_states = layer(
instruction_hidden_states,
context_attention_mask,
context_rotary_emb,
)
# Image patch embedding and refinement.
combined_img_hidden_states = self.img_patch_embed_and_refine(
hidden_states,
ref_image_hidden_states,
img_mask,
noise_attention_mask,
ref_img_mask,
noise_rotary_emb,
ref_img_rotary_emb,
l_effective_ref_img_len,
l_effective_img_len,
local_ref_lengths,
local_img_lengths,
temb,
per_rank_ref_lengths=per_rank_ref_lengths,
)
instruct_hidden_states = instruction_hidden_states
img_hidden_states = combined_img_hidden_states
# Joint mask for [instruct + image].
joint_attention_mask = make_attention_mask(hidden_states, seq_lengths)
# Joint mask for [instruct + image], over the rank-concatenated sequence.
per_rank_combined_img_lengths = [
[sum(ref_lengths) + img_length for ref_lengths, img_length in zip(ref_per_sample, img_per_sample)]
for ref_per_sample, img_per_sample in zip(per_rank_ref_lengths, per_rank_img_lengths)
]
per_rank_seq_lengths = [
[encoder_length + combined_length for encoder_length, combined_length in zip(enc_per_sample, comb)]
for enc_per_sample, comb in zip(per_rank_encoder_lengths, per_rank_combined_img_lengths)
]
joint_attention_mask = rank_concat_mask_or_none(
per_rank_seq_lengths,
rotary_emb[0].shape[1],
like=hidden_states,
required=(context_mask_required or noise_mask_required or ref_mask_required),
)
# Dual-stream (double-stream) stage.
if self.num_double_stream_layers > 0:
img_attention_mask = make_attention_mask(hidden_states, combined_img_seq_lengths)
img_attention_mask = rank_concat_mask_or_none(
per_rank_combined_img_lengths,
combined_img_rotary_emb[0].shape[1],
like=hidden_states,
required=noise_mask_required or ref_mask_required,
)
for layer in self.double_stream_layers:
img_hidden_states, instruct_hidden_states = layer(
@@ -1676,13 +1895,17 @@ class BooguImageTransformer2DModel(nn.Module):
combined_img_rotary_emb,
rotary_emb,
temb,
encoder_seq_lengths,
local_encoder_lengths,
seq_lengths,
)
# Fuse streams to joint sequence.
joint_hidden_states = hidden_states.new_zeros(batch_size, max(seq_lengths), self.hidden_size)
for i, (encoder_seq_len, seq_len) in enumerate(zip(encoder_seq_lengths, seq_lengths)):
joint_hidden_states = hidden_states.new_zeros(
batch_size,
rotary_emb[0].shape[1],
self.hidden_size,
)
for i, (encoder_seq_len, seq_len) in enumerate(zip(local_encoder_lengths, seq_lengths)):
joint_hidden_states[i, :encoder_seq_len] = instruct_hidden_states[i, :encoder_seq_len]
joint_hidden_states[i, encoder_seq_len:seq_len] = img_hidden_states[i, : seq_len - encoder_seq_len]
@@ -1694,12 +1917,23 @@ class BooguImageTransformer2DModel(nn.Module):
# Output projection.
hidden_states = self.norm_out(hidden_states, temb)
# Extract this rank's noise-image shard and gather it once.
local_img_output = hidden_states.new_zeros(
batch_size,
img_mask.shape[1],
hidden_states.shape[-1],
)
for i, (img_len, seq_len) in enumerate(zip(local_img_lengths, seq_lengths)):
local_img_output[i, :img_len] = hidden_states[i, seq_len - img_len : seq_len]
image_tokens = self.sp_gather_boundary(local_img_output)
# Reshape back to image format.
p = self.patch_size
output = []
for i, (img_size, img_len, seq_len) in enumerate(zip(img_sizes, l_effective_img_len, seq_lengths)):
for i, (img_size, img_len) in enumerate(zip(img_sizes, global_img_lengths)):
height, width = img_size
img_tokens = hidden_states[i][seq_len - img_len : seq_len]
img_tokens = image_tokens[i, :img_len]
img_output = rearrange(
img_tokens,
"(h w) (p1 p2 c) -> c (h p1) (w p2)",
@@ -62,6 +62,7 @@ from vllm_omni.diffusion.models.utils import create_transformers_model_with_vllm
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.platforms import current_omni_platform
from vllm_omni.quantization.component_config import resolve_component_quant_config
logger = init_logger(__name__)
@@ -382,7 +383,36 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
if parallel_config.tensor_parallel_size > 1:
raise NotImplementedError("Tensor parallelism is not supported by BooguImagePipeline.")
if (parallel_config.sequence_parallel_size or 1) > 1:
raise NotImplementedError("Sequence parallelism is not supported by BooguImagePipeline.")
if parallel_config.cfg_parallel_size > 1:
# SP × CFG-Parallel is unvalidated: the combined path runs
# without crashing but drifts far from the SP=1 baseline
# (~19 dB PSNR at 4 steps), so guidance semantics differ.
# Remove this guard only alongside a parity test.
raise NotImplementedError(
"BooguImagePipeline: sequence parallelism combined with CFG parallelism is not validated."
)
if parallel_config.ring_degree > 1 or getattr(parallel_config, "allgather_degree", 1) > 1:
raise NotImplementedError(
"BooguImagePipeline currently supports sequence parallelism through Ulysses only."
)
if not current_omni_platform.is_cuda():
raise NotImplementedError("BooguImagePipeline sequence parallelism currently requires CUDA.")
if parallel_config.ulysses_mode == "strict":
# Subscript rather than get(): a missing key means the config
# schema has drifted and we would silently validate against a
# stale default, not the actual head count.
tf_params = self.od_config.tf_model_config.params
num_heads = tf_params["num_attention_heads"]
num_kv_heads = tf_params["num_kv_heads"]
if (
num_heads % parallel_config.ulysses_degree != 0
or num_kv_heads % parallel_config.ulysses_degree != 0
):
raise ValueError(
"BooguImagePipeline GQA heads are not divisible by the "
"configured Ulysses degree; set "
"parallel_config.ulysses_mode='advanced_uaa'."
)
if parallel_config.use_hsdp:
raise NotImplementedError("HSDP is not supported by BooguImagePipeline.")
if self.od_config.cache_backend not in (None, "", "none"):
@@ -0,0 +1,188 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Shard-layout arithmetic for BOOGU Image sequence parallelism.
BOOGU splits three independent sequences (noise image, reference images, and
instruction context) at one SP boundary. The framework records each sequence's
pre-padding global length under a ``shard_group`` key; everything else -- how
that global length maps onto a given rank's shard -- is arithmetic, so every
rank can derive the layout of *all* ranks without communicating.
That property is what lets the model build attention masks for the global,
rank-concatenated sequence that Ulysses produces after its all-to-all, instead
of all-gathering rank-local masks inside the attention layer.
"""
from __future__ import annotations
from dataclasses import dataclass
import torch
from vllm_omni.diffusion.forward_context import get_sp_shard_original_seq_len
# (cos, sin) -- optionally (cos, sin, packed_table) where packed_table is the
# fp32 [tokens, head_dim] = [cos(theta) | sin(theta)] layout the fused
# qk-norm+RoPE op consumes; the eager path ignores the third element.
RotaryEmbedding = tuple[torch.Tensor, ...]
@dataclass(frozen=True, slots=True)
class ShardLayout:
"""How one globally padded sequence maps onto the SP ranks."""
original_seq_len: int
world_size: int
rank: int
@classmethod
def resolve(cls, shard_group: str, *, local_seq_len: int) -> ShardLayout:
"""Read a boundary's layout from the ForwardContext.
Falls back to an unsharded layout (world_size=1) when SP is off or the
tensor was never split, in which case `local_seq_len` is the whole
sequence.
"""
from vllm_omni.diffusion.distributed.parallel_state import (
get_sequence_parallel_rank,
get_sequence_parallel_world_size,
)
original_seq_len = get_sp_shard_original_seq_len(shard_group)
if original_seq_len is None:
return cls(original_seq_len=local_seq_len, world_size=1, rank=0)
return cls(
original_seq_len=original_seq_len,
world_size=get_sequence_parallel_world_size(),
rank=get_sequence_parallel_rank(),
)
@property
def padded_seq_len(self) -> int:
ws = self.world_size
return ((self.original_seq_len + ws - 1) // ws) * ws
@property
def local_seq_len(self) -> int:
return self.padded_seq_len // self.world_size
@property
def padding_size(self) -> int:
return self.padded_seq_len - self.original_seq_len
def bounds(self, rank: int) -> tuple[int, int]:
"""Half-open [start, end) span of the global sequence owned by `rank`."""
start = rank * self.local_seq_len
return start, start + self.local_seq_len
def valid_lengths(self, global_lengths: list[int], *, rank: int) -> list[int]:
"""Per-sample valid prefix lengths clipped to `rank`'s shard."""
start, end = self.bounds(rank)
return [max(0, min(int(length), end) - start) for length in global_lengths]
def segment_lengths(self, global_segments: list[list[int]], *, rank: int) -> list[list[int]]:
"""Per-sample contiguous segments intersected with `rank`'s shard."""
start, end = self.bounds(rank)
local: list[list[int]] = []
for sample in global_segments:
sample_local: list[int] = []
offset = 0
for length in sample:
segment_end = offset + int(length)
sample_local.append(max(0, min(segment_end, end) - max(offset, start)))
offset = segment_end
local.append(sample_local)
return local
def rank_concat_mask_or_none(
per_rank_lengths: list[list[int]],
capacity: int,
*,
like: torch.Tensor,
required: bool = False,
) -> torch.Tensor | None:
"""Mask over the rank-concatenated sequence Ulysses builds post all-to-all.
``per_rank_lengths[r][i]`` is sample ``i``'s valid length inside rank ``r``'s
shard, and every shard has the same ``capacity`` (guaranteed by auto_pad),
so the global sequence is ``world_size * capacity`` long. Returns ``None``
for an all-valid mask unless a padding contract requires one.
"""
if not required and all(int(length) == capacity for lengths in per_rank_lengths for length in lengths):
return None
batch_size = len(per_rank_lengths[0])
mask = like.new_zeros(batch_size, len(per_rank_lengths) * capacity, dtype=torch.bool)
for rank, lengths in enumerate(per_rank_lengths):
base = rank * capacity
for i, length in enumerate(lengths):
mask[i, base : base + int(length)] = True
return mask
def pack_local_rotary(
context_rotary_emb: RotaryEmbedding,
ref_img_rotary_emb: RotaryEmbedding,
noise_rotary_emb: RotaryEmbedding,
encoder_seq_lengths: list[int],
ref_img_seq_lengths: list[list[int]],
img_seq_lengths: list[int],
) -> tuple[RotaryEmbedding, RotaryEmbedding, list[int], list[int]]:
"""Pack local RoPE as ``[context, references, noise]``.
Capacities stay equal across ranks; returned lengths exclude padding.
Rotary embeddings arrive as ``(cos, sin)`` pairs -- the same packing is
applied component-wise so both halves stay index-aligned.
"""
context_cos, context_sin = context_rotary_emb
ref_cos, ref_sin = ref_img_rotary_emb
noise_cos, noise_sin = noise_rotary_emb
combined_img_seq_lengths = [
sum(ref_lengths) + img_length
for ref_lengths, img_length in zip(
ref_img_seq_lengths,
img_seq_lengths,
)
]
seq_lengths = [
context_length + combined_length
for context_length, combined_length in zip(
encoder_seq_lengths,
combined_img_seq_lengths,
)
]
def _pack_component(
context_t: torch.Tensor, ref_t: torch.Tensor, noise_t: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
batch_size = context_t.shape[0]
rotary_dim = context_t.shape[-1]
combined_img_capacity = ref_t.shape[1] + noise_t.shape[1]
combined_img = context_t.new_zeros(batch_size, combined_img_capacity, rotary_dim)
rotary = context_t.new_zeros(
batch_size,
context_t.shape[1] + combined_img_capacity,
rotary_dim,
)
for i, (context_length, ref_lengths, img_length) in enumerate(
zip(encoder_seq_lengths, ref_img_seq_lengths, img_seq_lengths)
):
ref_length = sum(ref_lengths)
combined_length = ref_length + img_length
combined_img[i, :ref_length] = ref_t[i, :ref_length]
combined_img[i, ref_length:combined_length] = noise_t[i, :img_length]
rotary[i, :context_length] = context_t[i, :context_length]
rotary[i, context_length : context_length + combined_length] = combined_img[i, :combined_length]
return rotary, combined_img
rotary_cos, combined_img_cos = _pack_component(context_cos, ref_cos, noise_cos)
rotary_sin, combined_img_sin = _pack_component(context_sin, ref_sin, noise_sin)
return (
(rotary_cos, rotary_sin),
(combined_img_cos, combined_img_sin),
seq_lengths,
combined_img_seq_lengths,
)