Cosmos3 transfer fix (#5614)

Signed-off-by: Maciej Bala <mbala@nvidia.com>
This commit is contained in:
MaciejBalaNV authored and GitHub committed 2026-08-20 11:40:51 -07:00
1 parent ebb4abde0a
commit b3270dec8d
12 files changed
+629 -55

No files matched your search

@@ -163,6 +163,14 @@ COSMOS3_INVERSE_IMAGE_RESOLUTION_TEMPLATE = "This image is not of {height}x{widt
# NOTE: Intentional typo in "give" instead of "given" to match training setup.
COSMOS3_SYSTEM_PROMPT = "You are a helpful assistant who will generate videos from a give prompt."
COSMOS3_T2I_SYSTEM_PROMPT = "You are a helpful assistant who will generate images from a give prompt."
COSMOS3_TRANSFER_SYSTEM_PROMPT = (
"You are a helpful assistant that generates images or videos following the user's instructions"
" and control signals (edge maps, blur, depth, or segmentation)."
)
COSMOS3_TRANSFER_CONTROL_DIRECTIVE_TEMPLATE = (
"Follow the {hint_names} control video precisely: shape, contour, silhouette, position, and motion of every "
"visible structure must align with the {hint_names} signal at every frame."
)
COSMOS3_T2V_DEFAULT_HEIGHT = 720
COSMOS3_T2V_DEFAULT_WIDTH = 1280
@@ -2068,6 +2076,11 @@ class Cosmos3OmniDiffusersPipeline(
sp: OmniDiffusionSamplingParams,
use_system_prompt: bool = False,
is_t2i: bool = False,
system_prompt: str | None = None,
prompt_suffix: str | None = None,
use_duration_template: bool | None = None,
use_resolution_template: bool | None = None,
negative_metadata_mode: str | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Format prompts with metadata templates and tokenize.
@@ -2075,14 +2088,30 @@ class Cosmos3OmniDiffusersPipeline(
For T2I (``is_t2i=True``) the duration template is suppressed (no FPS
or duration concept for a single image) and the image-flavored
resolution template is used.
resolution template is used. ``prompt_suffix`` is appended only to the
positive prompt, after metadata formatting. ``negative_metadata_mode``
controls whether the negative branch receives no metadata, the same
metadata as the positive branch, or inverse metadata.
"""
# Route cosmos3-specific controls through ``_get_sp_param`` so they
# are picked up from ``extra_args`` (OpenAI endpoint path) as well
# as from direct attributes.
use_duration_template = bool(self._get_sp_param(sp, "use_duration_template", False)) and not is_t2i
if use_duration_template is None:
use_duration_template = bool(self._get_sp_param(sp, "use_duration_template", False))
if use_resolution_template is None:
use_resolution_template = bool(self._get_sp_param(sp, "use_resolution_template", False))
if negative_metadata_mode is None:
negative_metadata_mode = str(self._get_sp_param(sp, "negative_metadata_mode", "inverse"))
negative_metadata_mode = negative_metadata_mode.strip().lower()
if negative_metadata_mode not in {"none", "same", "inverse"}:
raise ValueError(
"Cosmos3 negative_metadata_mode must be one of 'none', 'same', or 'inverse'; "
f"got {negative_metadata_mode!r}."
)
use_duration_template = use_duration_template and not is_t2i
dur_tmpl = COSMOS3_DURATION_TEMPLATE if use_duration_template else None
if bool(self._get_sp_param(sp, "use_resolution_template", False)):
if use_resolution_template:
res_tmpl = COSMOS3_IMAGE_RESOLUTION_TEMPLATE if is_t2i else COSMOS3_RESOLUTION_TEMPLATE
else:
res_tmpl = None
@@ -2106,37 +2135,44 @@ class Cosmos3OmniDiffusersPipeline(
duration_template=dur_tmpl,
resolution_template=res_tmpl,
)
if prompt_suffix:
prompt = f"{prompt.rstrip()} {prompt_suffix.lstrip()}".strip()
if _is_rank_zero():
logger.info("Final prompt: '%s'", prompt)
# Negative prompt: inverse templates ("not {duration}...", "not {height}x{width}...").
# Applied whenever the matching positive template is enabled; an empty
# negative_prompt yields output that starts with the template, not a dot.
inv_dur = COSMOS3_INVERSE_DURATION_TEMPLATE if dur_tmpl else None
if res_tmpl is None:
inv_res = None
elif is_t2i:
inv_res = COSMOS3_INVERSE_IMAGE_RESOLUTION_TEMPLATE
if negative_metadata_mode == "none":
negative_dur_tmpl = None
negative_res_tmpl = None
elif negative_metadata_mode == "same":
negative_dur_tmpl = dur_tmpl
negative_res_tmpl = res_tmpl
else:
inv_res = COSMOS3_INVERSE_RESOLUTION_TEMPLATE
negative_dur_tmpl = COSMOS3_INVERSE_DURATION_TEMPLATE if dur_tmpl else None
if res_tmpl is None:
negative_res_tmpl = None
elif is_t2i:
negative_res_tmpl = COSMOS3_INVERSE_IMAGE_RESOLUTION_TEMPLATE
else:
negative_res_tmpl = COSMOS3_INVERSE_RESOLUTION_TEMPLATE
negative_prompt = self._apply_metadata_templates(
negative_prompt,
num_frames,
frame_rate,
height,
width,
duration_template=inv_dur,
resolution_template=inv_res,
force_duration_template=True,
duration_template=negative_dur_tmpl,
resolution_template=negative_res_tmpl,
force_duration_template=negative_metadata_mode == "inverse",
)
default_sys_prompt = COSMOS3_T2I_SYSTEM_PROMPT if is_t2i else COSMOS3_SYSTEM_PROMPT
sys_prompt = self._get_sp_param(sp, "system_prompt", default_sys_prompt) or default_sys_prompt
if system_prompt is None:
default_sys_prompt = COSMOS3_T2I_SYSTEM_PROMPT if is_t2i else COSMOS3_SYSTEM_PROMPT
system_prompt = self._get_sp_param(sp, "system_prompt", default_sys_prompt) or default_sys_prompt
cond_ids, cond_mask = self._tokenize_prompt(
prompt, max_sequence_length, use_system_prompt, system_prompt=sys_prompt
prompt, max_sequence_length, use_system_prompt, system_prompt=system_prompt
)
uncond_ids, uncond_mask = self._tokenize_prompt(
negative_prompt, max_sequence_length, use_system_prompt, system_prompt=sys_prompt
negative_prompt, max_sequence_length, use_system_prompt, system_prompt=system_prompt
)
return cond_ids, cond_mask, uncond_ids, uncond_mask
@@ -2890,6 +2926,7 @@ class Cosmos3OmniDiffusersPipeline(
control_latents: list[torch.Tensor],
shared_kwargs: dict[str, Any],
*,
control_weights: list[float] | None = None,
velocity_mask: torch.Tensor,
condition_latents: torch.Tensor,
guidance_interval: tuple[float, float] | None = None,
@@ -2925,6 +2962,7 @@ class Cosmos3OmniDiffusersPipeline(
text_ids=cond_ids,
text_mask=cond_mask,
control_latents=control_latents,
control_weights=control_weights,
_cosmos3_cache_key="transfer_cond_full",
**shared_kwargs,
)
@@ -2946,6 +2984,7 @@ class Cosmos3OmniDiffusersPipeline(
text_ids=uncond_ids,
text_mask=uncond_mask,
control_latents=control_latents,
control_weights=control_weights,
_cosmos3_cache_key="transfer_uncond_full",
**shared_kwargs,
),
@@ -2993,6 +3032,7 @@ class Cosmos3OmniDiffusersPipeline(
text_ids=uncond_ids,
text_mask=uncond_mask,
control_latents=control_latents,
control_weights=control_weights,
_cosmos3_cache_key="transfer_uncond_full",
**shared_kwargs,
),
@@ -3113,7 +3153,10 @@ class Cosmos3OmniDiffusersPipeline(
self._get_sp_param(sp, "max_sequence_length", COSMOS3_DEFAULT_MAX_SEQUENCE_LENGTH)
or COSMOS3_DEFAULT_MAX_SEQUENCE_LENGTH
)
use_system_prompt = bool(self._get_sp_param(sp, "use_system_prompt", False))
transfer_prompt_suffix = None
if transfer_config.emphasize_control_in_prompt:
hint_names = ", ".join(hint.key for hint in transfer_config.ordered_hints)
transfer_prompt_suffix = COSMOS3_TRANSFER_CONTROL_DIRECTIVE_TEMPLATE.format(hint_names=hint_names)
self._guidance_scale = guidance_scale
self._num_timesteps = num_inference_steps
@@ -3124,6 +3167,13 @@ class Cosmos3OmniDiffusersPipeline(
if generator is None:
generator = torch.Generator(device=self.device).manual_seed(seed)
for ignored_key in ("system_prompt", "use_system_prompt"):
if self._get_sp_param(sp, ignored_key, None) is not None:
logger.warning_once(
"Cosmos3 transfer ignores the '%s' request parameter and always "
"tokenizes both CFG branches with the transfer-specific system prompt.",
ignored_key,
)
cond_ids, cond_mask, uncond_ids, uncond_mask = self._format_and_tokenize_prompts(
prompt,
negative_prompt,
@@ -3133,8 +3183,13 @@ class Cosmos3OmniDiffusersPipeline(
width,
max_sequence_length,
sp,
use_system_prompt,
use_system_prompt=True,
is_t2i=False,
system_prompt=COSMOS3_TRANSFER_SYSTEM_PROMPT,
prompt_suffix=transfer_prompt_suffix,
use_duration_template=bool(self._get_sp_param(sp, "use_duration_template", True)),
use_resolution_template=bool(self._get_sp_param(sp, "use_resolution_template", True)),
negative_metadata_mode=str(self._get_sp_param(sp, "negative_metadata_mode", "same")),
)
output_chunks: list[torch.Tensor] = []
@@ -3227,6 +3282,7 @@ class Cosmos3OmniDiffusersPipeline(
control_guidance=transfer_config.control_guidance,
control_guidance_interval=transfer_config.control_guidance_interval,
control_latents=control_latents,
control_weights=transfer_config.normalized_control_weights,
shared_kwargs=shared_kwargs,
velocity_mask=velocity_mask,
condition_latents=condition_latents,
+46 -1
View File
@@ -14,6 +14,7 @@ generation, or action generation.
from __future__ import annotations
import importlib
import math
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
@@ -25,6 +26,14 @@ import torch
import torch.nn.functional as F
TRANSFER_HINT_KEYS: tuple[str, ...] = ("edge", "blur", "depth", "seg", "wsm")
_TRANSFER_HINT_COMMON_FIELDS = frozenset({"control_path", "control", "control_weight"})
_TRANSFER_HINT_FIELDS: dict[str, frozenset[str]] = {
"edge": _TRANSFER_HINT_COMMON_FIELDS | {"preset_edge_threshold"},
"blur": _TRANSFER_HINT_COMMON_FIELDS | {"preset_blur_strength"},
"depth": _TRANSFER_HINT_COMMON_FIELDS,
"seg": _TRANSFER_HINT_COMMON_FIELDS,
"wsm": _TRANSFER_HINT_COMMON_FIELDS,
}
TRANSFER_SAMPLE_DEFAULTS: dict[str, Any] = {
"num_video_frames_per_chunk": 93,
"num_conditional_frames": 1,
@@ -33,6 +42,7 @@ TRANSFER_SAMPLE_DEFAULTS: dict[str, Any] = {
"show_input": False,
"num_first_chunk_conditional_frames": 0,
"share_vision_temporal_positions": True,
"emphasize_control_in_prompt": True,
}
TRANSFER_DEFAULTS: dict[str, dict[str, Any]] = {
"edge": {"guidance_scale": 3.0, "control_guidance": 1.5, "flow_shift": 10.0},
@@ -85,6 +95,7 @@ class Cosmos3TransferHint:
key: str
control_path: str | None = None
control: Any | None = None
control_weight: float = 1.0
preset_edge_threshold: str = "medium"
preset_blur_strength: str = "medium"
@@ -103,6 +114,7 @@ class Cosmos3TransferConfig:
show_input: bool = False
num_first_chunk_conditional_frames: int = 0
share_vision_temporal_positions: bool = True
emphasize_control_in_prompt: bool = True
num_frames: int | None = None
fps: float | None = None
@@ -110,6 +122,16 @@ class Cosmos3TransferConfig:
def ordered_hints(self) -> list[Cosmos3TransferHint]:
return [self.hints[key] for key in TRANSFER_HINT_KEYS if key in self.hints]
@property
def normalized_control_weights(self) -> list[float]:
weights = [hint.control_weight for hint in self.ordered_hints]
if any(not math.isfinite(weight) or weight < 0.0 for weight in weights):
raise ValueError(f"Cosmos3 transfer control_weight values must be finite and non-negative, got {weights}.")
total = sum(weights)
if total <= 0.0:
raise ValueError("Cosmos3 transfer control_weight values must have a positive sum.")
return [weight / total for weight in weights]
def _extra_args(sp: Any) -> Mapping[str, Any]:
extra = getattr(sp, "extra_args", None)
@@ -184,7 +206,7 @@ def _as_interval(value: Any) -> tuple[float, float] | None:
return None
if isinstance(value, str):
value = [item.strip() for item in value.split(",") if item.strip()]
if not isinstance(value, (list, tuple)) or len(value) != 2:
if not isinstance(value, list | tuple) or len(value) != 2:
raise ValueError("Cosmos3 transfer control_guidance_interval must contain exactly two values.")
lo, hi = float(value[0]), float(value[1])
if lo > hi:
@@ -220,10 +242,27 @@ def resolve_transfer_config(sp: Any, prompt_data: Any = None) -> Cosmos3Transfer
raise TypeError(
f"Cosmos3 transfer hint '{key}' must be an object, path string, or true; got {type(raw)!r}."
)
unknown_fields = set(raw) - _TRANSFER_HINT_FIELDS[key]
if unknown_fields:
raise ValueError(
f"Unsupported Cosmos3 transfer hint '{key}' fields: {sorted(unknown_fields)}. "
f"Supported fields are: {sorted(_TRANSFER_HINT_FIELDS[key])}."
)
try:
control_weight = float(raw.get("control_weight", 1.0))
except (TypeError, ValueError) as exc:
raise TypeError(
f"Cosmos3 transfer hint '{key}' control_weight must be a finite non-negative number."
) from exc
if not math.isfinite(control_weight) or control_weight < 0.0:
raise ValueError(
f"Cosmos3 transfer hint '{key}' control_weight must be finite and non-negative, got {control_weight!r}."
)
hints[key] = Cosmos3TransferHint(
key=key,
control_path=str(raw["control_path"]) if raw.get("control_path") is not None else None,
control=raw.get("control"),
control_weight=control_weight,
preset_edge_threshold=str(raw.get("preset_edge_threshold") or "medium").lower(),
preset_blur_strength=str(raw.get("preset_blur_strength") or "medium").lower(),
)
@@ -239,6 +278,7 @@ def resolve_transfer_config(sp: Any, prompt_data: Any = None) -> Cosmos3Transfer
"show_input",
"num_first_chunk_conditional_frames",
"share_vision_temporal_positions",
"emphasize_control_in_prompt",
)
if any(_is_user_field(extra, sp, prompt_data, key) for key in transfer_only):
raise ValueError("Cosmos3 transfer options were provided, but no transfer hint was selected.")
@@ -293,6 +333,10 @@ def resolve_transfer_config(sp: Any, prompt_data: Any = None) -> Cosmos3Transfer
_param(extra, sp, prompt_data, "share_vision_temporal_positions", None),
bool(TRANSFER_SAMPLE_DEFAULTS["share_vision_temporal_positions"]),
),
emphasize_control_in_prompt=_as_bool(
_param(extra, sp, prompt_data, "emphasize_control_in_prompt", None),
bool(TRANSFER_SAMPLE_DEFAULTS["emphasize_control_in_prompt"]),
),
num_frames=(
int(_param(extra, sp, prompt_data, "num_frames"))
if _param(extra, sp, prompt_data, "num_frames", None) is not None
@@ -328,6 +372,7 @@ def resolve_transfer_config(sp: Any, prompt_data: Any = None) -> Cosmos3Transfer
raise ValueError(f"Unsupported Cosmos3 edge preset: {hint.preset_edge_threshold!r}.")
if hint.key == "blur" and hint.preset_blur_strength not in BLUR_DOWNUP_PRESETS:
raise ValueError(f"Unsupported Cosmos3 blur preset: {hint.preset_blur_strength!r}.")
_ = config.normalized_control_weights
return config
@@ -651,6 +651,19 @@ class Cosmos3CrossAttention(nn.Module):
softmax_scale=1.0 / (self.head_dim**0.5),
num_kv_heads=self.num_kv_heads,
)
# Multi-control attention operates on one full [control_i, target]
# sequence at a time. Keep those sequences replicated when Ulysses is
# active; sharding the concatenated [control_1, ..., control_N, target]
# layout would split the per-control ranges across ranks.
self.multi_control_attn = FrameworkAttention(
num_heads=self.num_heads,
head_size=self.head_dim,
causal=False,
softmax_scale=1.0 / (self.head_dim**0.5),
num_kv_heads=self.num_kv_heads,
prefix=f"{prefix}.multi_control_attn",
skip_sequence_parallel=True,
)
# TODO(follow-up): collapse _forward_local and _forward_sp into a single
# joint-based path when NoParallelAttention can process joint_key/value.
@@ -701,6 +714,61 @@ class Cosmos3CrossAttention(nn.Module):
out = self.attn(q, k, v, attn_metadata)
return out.reshape(B, S_gen, -1)
def _forward_multi_control(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
k_und: torch.Tensor,
v_und: torch.Tensor,
control_token_sizes: tuple[int, ...],
control_weights: tuple[float, ...],
) -> torch.Tensor:
"""Run independent attention per control and weight target outputs.
For control ``i``, both its queries and the target queries attend to
``[text, control_i, target]``. Each control keeps the output from its
own pass, while target outputs are combined using normalized weights.
"""
if len(control_token_sizes) != len(control_weights):
raise ValueError(
"Cosmos3 control token sizes and weights must have the same length: "
f"sizes={len(control_token_sizes)}, weights={len(control_weights)}."
)
control_tokens = sum(control_token_sizes)
if control_tokens <= 0 or control_tokens >= q.shape[1]:
raise ValueError(
"Cosmos3 multi-control attention requires non-empty control and target token ranges, "
f"got control_tokens={control_tokens}, total_tokens={q.shape[1]}."
)
q_target = q[:, control_tokens:]
k_target = k[:, control_tokens:]
v_target = v[:, control_tokens:]
control_outputs: list[torch.Tensor] = []
target_output: torch.Tensor | None = None
start = 0
for size, weight in zip(control_token_sizes, control_weights, strict=True):
if size <= 0:
raise ValueError(f"Cosmos3 control token sizes must be positive, got {control_token_sizes}.")
end = start + size
q_control = q[:, start:end]
k_control = k[:, start:end]
v_control = v[:, start:end]
q_pair = torch.cat([q_control, q_target], dim=1)
k_pair = torch.cat([k_und, k_control, k_target], dim=1)
v_pair = torch.cat([v_und, v_control, v_target], dim=1)
pair_output = self.multi_control_attn(q_pair, k_pair, v_pair)
control_outputs.append(pair_output[:, :size])
weighted_target = pair_output[:, size:] * weight
target_output = weighted_target if target_output is None else target_output + weighted_target
start = end
if start != control_tokens or target_output is None:
raise RuntimeError("Cosmos3 multi-control attention failed to cover all control token ranges.")
output = torch.cat([*control_outputs, target_output], dim=1)
return output.reshape(q.shape[0], q.shape[1], -1)
# -- Public forward: routes to the appropriate path ----------------------
def forward(
@@ -710,6 +778,8 @@ class Cosmos3CrossAttention(nn.Module):
v_und: torch.Tensor,
freqs_cos: torch.Tensor,
freqs_sin: torch.Tensor,
control_token_sizes: tuple[int, ...] | None = None,
control_weights: tuple[float, ...] | None = None,
) -> torch.Tensor:
"""
Args:
@@ -733,7 +803,19 @@ class Cosmos3CrossAttention(nn.Module):
# Qwen3-style RoPE
q, k = _apply_rotary_pos_emb(q, k, freqs_cos, freqs_sin)
if _is_sp_active():
if control_token_sizes is not None or control_weights is not None:
if control_token_sizes is None or control_weights is None:
raise ValueError("Cosmos3 multi-control attention requires both control token sizes and weights.")
out = self._forward_multi_control(
q,
k,
v,
k_und,
v_und,
control_token_sizes,
control_weights,
)
elif _is_sp_active():
out = self._forward_sp(q, k, v, k_und, v_und)
else:
out = self._forward_local(q, k, v, k_und, v_und)
@@ -847,6 +929,8 @@ class Cosmos3GenDecoderLayer(nn.Module):
freqs_sin: torch.Tensor | None = None,
cached_kv: list[tuple[torch.Tensor, torch.Tensor]] | None = None,
freqs_gen: tuple[torch.Tensor, torch.Tensor] | None = None,
control_token_sizes: tuple[int, ...] | None = None,
control_weights: tuple[float, ...] | None = None,
) -> torch.Tensor:
if cached_kv is not None:
if self.layer_idx is None:
@@ -861,7 +945,13 @@ class Cosmos3GenDecoderLayer(nn.Module):
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.cross_attention(
hidden_states, k_und=k_und, v_und=v_und, freqs_cos=freqs_cos, freqs_sin=freqs_sin
hidden_states,
k_und=k_und,
v_und=v_und,
freqs_cos=freqs_cos,
freqs_sin=freqs_sin,
control_token_sizes=control_token_sizes,
control_weights=control_weights,
)
hidden_states = residual + hidden_states
@@ -1579,6 +1669,7 @@ class Cosmos3VFMTransformer(nn.Module):
sound_latents: torch.Tensor | None = None,
noisy_frame_mask: torch.Tensor | None = None,
control_latents: list[torch.Tensor] | tuple[torch.Tensor, ...] | torch.Tensor | None = None,
control_weights: list[float] | tuple[float, ...] | torch.Tensor | None = None,
transfer_share_vision_temporal_positions: bool = True,
**kwargs,
) -> torch.Tensor | tuple[torch.Tensor, ...]:
@@ -1601,6 +1692,8 @@ class Cosmos3VFMTransformer(nn.Module):
frames are noisy, as in T2I/T2V.
control_latents: Optional transfer-control latents. Controls are
clean vision context and are packed before the noisy target.
control_weights: Optional non-negative relative weights for
transfer controls. Values are normalized to sum to one.
Returns:
[B, C, t, h, w] velocity prediction, or
@@ -1629,6 +1722,31 @@ class Cosmos3VFMTransformer(nn.Module):
else:
control_latent_list = list(control_latents)
has_control = len(control_latent_list) > 0
if control_weights is None:
normalized_control_weights = (
[1.0 / len(control_latent_list)] * len(control_latent_list) if has_control else []
)
else:
if isinstance(control_weights, torch.Tensor):
raw_control_weights = control_weights.detach().cpu().flatten().tolist()
else:
raw_control_weights = list(control_weights)
if len(raw_control_weights) != len(control_latent_list):
raise ValueError(
"Cosmos3 transfer control_weights length must match control_latents: "
f"weights={len(raw_control_weights)}, controls={len(control_latent_list)}."
)
normalized_control_weights = [float(weight) for weight in raw_control_weights]
if any(not math.isfinite(weight) or weight < 0.0 for weight in normalized_control_weights):
raise ValueError(
"Cosmos3 transfer control_weights must be finite and non-negative, "
f"got {normalized_control_weights}."
)
control_weight_sum = sum(normalized_control_weights)
if control_weight_sum <= 0.0:
raise ValueError("Cosmos3 transfer control_weights must have a positive sum.")
normalized_control_weights = [weight / control_weight_sum for weight in normalized_control_weights]
use_multi_control_attention = len(control_latent_list) > 1
if has_control and (has_action or has_sound):
raise ValueError("Cosmos3 transfer control latents cannot be combined with action or sound latents.")
if has_action and not self.action_gen:
@@ -1646,6 +1764,13 @@ class Cosmos3VFMTransformer(nn.Module):
# Query Ulysses state at runtime
ulysses_size, _, _ = _get_ulysses_state()
if use_multi_control_attention and ulysses_size > 1:
logger.warning_once(
"Cosmos3 multi-control attention requires full [control_i | target] "
"sequences, so the GEN pathway runs replicated on every Ulysses rank. "
"Sequence parallelism will not reduce per-rank memory or latency for "
"multi-control transfer requests."
)
# Pack action/sound tokens (no learned weights) up front so the UND
# cache sizing knows their token lengths. The modality projections are
@@ -1722,6 +1847,9 @@ class Cosmos3VFMTransformer(nn.Module):
)
hidden_controls.append(hidden_control)
s_control += hidden_control.shape[1]
control_token_sizes = tuple(control.shape[1] for control in hidden_controls)
multi_control_weights = tuple(normalized_control_weights) if use_multi_control_attention else None
multi_control_token_sizes = control_token_sizes if use_multi_control_attention else None
hidden_action = None
hidden_sound = None
if action_tokens is not None:
@@ -1788,10 +1916,11 @@ class Cosmos3VFMTransformer(nn.Module):
has_action=has_action,
has_sound=has_sound,
has_control=has_control,
ulysses_size=ulysses_size,
ulysses_size=1 if use_multi_control_attention else ulysses_size,
)
freqs_cos, freqs_sin = self.cached_freqs_gen
hidden_gen, freqs_cos, freqs_sin = self.gen_sp_prepare(hidden_gen, freqs_cos, freqs_sin)
if not use_multi_control_attention:
hidden_gen, freqs_cos, freqs_sin = self.gen_sp_prepare(hidden_gen, freqs_cos, freqs_sin)
freqs_gen = (freqs_cos, freqs_sin)
if len(self.gen_layers) == len(self.cached_kv):
@@ -1802,6 +1931,8 @@ class Cosmos3VFMTransformer(nn.Module):
v_und=v_und,
freqs_cos=freqs_cos,
freqs_sin=freqs_sin,
control_token_sizes=multi_control_token_sizes,
control_weights=multi_control_weights,
)
# Cache-dit's block wrapper may return a tuple; unwrap it.
if isinstance(hidden_gen, tuple):
@@ -1813,11 +1944,14 @@ class Cosmos3VFMTransformer(nn.Module):
hidden_gen,
cached_kv=self.cached_kv,
freqs_gen=freqs_gen,
control_token_sizes=multi_control_token_sizes,
control_weights=multi_control_weights,
)
if isinstance(hidden_gen, tuple):
hidden_gen = hidden_gen[0]
hidden_gen = self.gen_sp_gather(hidden_gen)
if not use_multi_control_attention:
hidden_gen = self.gen_sp_gather(hidden_gen)
# Final norm and project back to latent space
hidden_gen = self.norm_moe_gen(hidden_gen)