Skip to content
Python

added big VRAM optimizations to LTX 2 + IC Loras support

DeepBeepMeepef3dd17eb283
diff --git a/README.md b/README.md
index e0d5b80..d170cc5 100644
--- a/README.md
+++ b/README.md
@@ -36,13 +36,22 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models
-----
## 🔥 Latest Updates :
-### January 9st 2026: WanGP v10.11, Spoiled again
+### January 11th 2026: WanGP v10.12, When there is no VRAM left there is still some VRAM left ...
- **LTX 2**: here is the long awaited *Ovi Challenger*, LTX-2 generates video and an audio soundtrack. As usual this WanGP version is *low VRAM*. You should be able to run it with as low as 10 GB of VRAM. If you have at least 24 GB of VRAM you will be able to generate 20s at 720p in a single window in only 2 minutes with the distilled model. WanGP LTX 2 version supports on day one, *Start/End keyframes*, *Sliding-Window* / *Video Continuation* and *Generation Preview*. A *LTX 2 distilled* is part of the package for a very fast generation.
With WanGP v10.11 you can now force your soundtrack, it works like *Multitalk* / *Avatar* except in theory it should work with any kind of sound (not just vocals). Thanks to *Kijai* for showing it was possible.
-- **Z Image Twin Folder Turbo**: Z Image even faster as this variant can generate images with as little as 1 step (3 steps recommend)
+- **LTX 2 - SUPER VRAM OPTIMIZATONS** (new with WanGP v10.12): LTX Team said this video gen was for 4k. So I had no choice but to squeeze more VRAM for further optimizations:
+After much suffering I have managed to reduce by at least 1/3 the VRAM requirements for LTX 2, which means:
+ - 10s at 720p can be done with only 8GB of VRAM
+ - 10s at 1080p with only 12 GB of VRAM
+ - 20s at 1080p with only 16 GB of VRAM
+ - 10s at Full 4k (3840 x 2176 !!!) with 24 GB of VRAM. However the bad news is LTX 2 video is not for 4K, as 4K outputs may give you nightmares ...
+
+ Oh and I also added *Ic Lora support* (*Control Video* with Pose, Depth, Canny Edge transfer) , *Start Image Strength* (values lower than 1 seems to reduce the static image effect, that one gets sometime with LTX2 i2v)...
+
+- **Z Image Twin Folder Turbo**: Z Image even faster as this variant can generate images with as little as 1 step (3 steps recommended)
- **Qwen LanPaint**: very precise *In Painting*, offers a better integration of the inpainted area in the rest of the image. Beware it is up to 5x slower as it "searches" for the best replacement.
diff --git a/defaults/ltx2_19B.json b/defaults/ltx2_19B.json
index 7ccd4d6..e344f0e 100644
--- a/defaults/ltx2_19B.json
+++ b/defaults/ltx2_19B.json
@@ -7,6 +7,11 @@
"https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-dev.safetensors",
"https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-dev-fp8.safetensors"
],
+ "preload_URLs": [
+ "https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-ic-lora-pose-control.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-ic-lora-depth-control.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-ic-lora-canny-control.safetensors"
+ ],
"loras": [
"https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-distilled-lora-384.safetensors"
],
diff --git a/defaults/ltx2_distilled.json b/defaults/ltx2_distilled.json
index 1de9075..36f0589 100644
--- a/defaults/ltx2_distilled.json
+++ b/defaults/ltx2_distilled.json
@@ -7,6 +7,7 @@
"https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-distilled.safetensors",
"https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b-distilled-fp8.safetensors"
],
+ "preload_URLs": "ltx2_19B",
"ltx2_pipeline": "distilled"
},
"prompt": "A warm sunny backyard. The camera starts in a tight cinematic close-up of a woman and a man in their 30s, facing each other with serious expressions. The woman, emotional and dramatic, says softly, \"That's it... Dad's lost it. And we've lost Dad.\"The man exhales, slightly annoyed: \"Stop being so dramatic, Jess.\"A beat. He glances aside, then mutters defensively, \"He's just having fun.\"The camera slowly pans right, revealing the grandfather in the garden wearing enormous butterfly wings, waving his arms in the air like he's trying to take off.He shouts, \"Wheeeew!\" as he flaps his wings with full commitment.The woman covers her face, on the verge of tears. The tone is deadpan, absurd, and quietly tragic.",
diff --git a/models/_settings.json b/models/_settings.json
index 5a48872..b3f298d 100644
--- a/models/_settings.json
+++ b/models/_settings.json
@@ -8,6 +8,7 @@
"keep_frames_video_source": "",
"video_prompt_type": "",
"denoising_strength": 0.5,
+ "input_video_strength": 1.0,
"keep_frames_video_guide": "",
"video_guide_outpainting": "#",
"masking_strength": 1,
diff --git a/models/ltx2/ltx2.py b/models/ltx2/ltx2.py
index 5d9f1a8..426032a 100644
--- a/models/ltx2/ltx2.py
+++ b/models/ltx2/ltx2.py
@@ -19,6 +19,7 @@ from .ltx_pipelines.utils.constants import AUDIO_SAMPLE_RATE, DEFAULT_NEGATIVE_P
_GEMMA_FOLDER = "gemma-3-12b-it-qat-q4_0-unquantized"
_SPATIAL_UPSCALER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"
+LTX2_USE_FP32_ROPE_FREQS = True #False
class _AudioVAEWrapper(torch.nn.Module):
@@ -302,6 +303,10 @@ class LTX2:
self.model_def = model_def
self._interrupt = False
self.vae = _LTX2VAEHelper()
+ from .ltx_core.model.transformer import rope as rope_utils
+
+ self.use_fp32_rope_freqs = bool(model_def.get("ltx2_rope_freqs_fp32", LTX2_USE_FP32_ROPE_FREQS))
+ rope_utils.set_use_fp32_rope_freqs(self.use_fp32_rope_freqs)
if isinstance(model_filename, (list, tuple)):
if not model_filename:
@@ -449,6 +454,24 @@ class LTX2:
trans = self.model
return trans, None
+ def get_loras_transformer(self, get_model_recursive_prop, model_type, video_prompt_type, **kwargs):
+ map = {
+ "P": "pose",
+ "D": "depth",
+ "E": "canny",
+ }
+ loras = []
+ video_prompt_type = video_prompt_type or ""
+ preload_urls = get_model_recursive_prop(model_type, "preload_URLs")
+ for letter, signature in map.items():
+ if letter in video_prompt_type:
+ for file_name in preload_urls:
+ if signature in file_name:
+ loras.append(fl.locate_file(os.path.basename(file_name)))
+ break
+ loras_mult = [1.0] * len(loras)
+ return loras, loras_mult
+
def generate(
self,
input_prompt: str,
@@ -474,6 +497,112 @@ class LTX2:
input_video = kwargs.get("input_video")
prefix_frames_count = int(kwargs.get("prefix_frames_count") or 0)
+ input_frames = kwargs.get("input_frames")
+ input_frames2 = kwargs.get("input_frames2")
+ input_masks = kwargs.get("input_masks")
+ input_masks2 = kwargs.get("input_masks2")
+ masking_strength = kwargs.get("masking_strength")
+ input_video_strength = kwargs.get("input_video_strength")
+ return_latent_slice = kwargs.get("return_latent_slice")
+ video_prompt_type = kwargs.get("video_prompt_type") or ""
+ denoising_strength = kwargs.get("denoising_strength")
+
+ def _get_frame_dim(video_tensor: torch.Tensor) -> int | None:
+ if video_tensor.dim() < 2:
+ return None
+ if video_tensor.dim() == 5:
+ if video_tensor.shape[1] in (1, 3, 4):
+ return 2
+ if video_tensor.shape[-1] in (1, 3, 4):
+ return 1
+ if video_tensor.shape[0] in (1, 3, 4):
+ return 1
+ if video_tensor.shape[-1] in (1, 3, 4):
+ return 0
+ return 0
+
+ def _frame_count(video_value) -> int | None:
+ if not torch.is_tensor(video_value):
+ return None
+ frame_dim = _get_frame_dim(video_value)
+ if frame_dim is None:
+ return None
+ return int(video_value.shape[frame_dim])
+
+ def _slice_frames(video_value: torch.Tensor, start: int, end: int) -> torch.Tensor:
+ frame_dim = _get_frame_dim(video_value)
+ if frame_dim == 1:
+ return video_value[:, start:end]
+ if frame_dim == 2:
+ return video_value[:, :, start:end]
+ return video_value[start:end]
+
+ def _maybe_trim_control(video_value, target_frames: int):
+ if not torch.is_tensor(video_value) or target_frames <= 0:
+ return video_value, None
+ current_frames = _frame_count(video_value)
+ if current_frames is None:
+ return video_value, None
+ if current_frames > target_frames:
+ video_value = _slice_frames(video_value, 0, target_frames)
+ current_frames = target_frames
+ return video_value, current_frames
+
+ try:
+ masking_strength = float(masking_strength) if masking_strength is not None else 0.0
+ except (TypeError, ValueError):
+ masking_strength = 0.0
+ try:
+ input_video_strength = float(input_video_strength) if input_video_strength is not None else 1.0
+ except (TypeError, ValueError):
+ input_video_strength = 1.0
+ input_video_strength = max(0.0, min(1.0, input_video_strength))
+ if "G" not in video_prompt_type:
+ denoising_strength = 1.0
+ masking_strength = 0.0
+
+ video_conditioning = None
+ masking_source = None
+ if input_frames is not None or input_frames2 is not None:
+ control_start_frame = int(prefix_frames_count)
+ expected_guide_frames = max(1, int(frame_num) - control_start_frame + (1 if prefix_frames_count > 1 else 0))
+ if prefix_frames_count > 1:
+ control_start_frame = -control_start_frame
+ input_frames, frames_len = _maybe_trim_control(input_frames, expected_guide_frames)
+ input_frames2, frames_len2 = _maybe_trim_control(input_frames2, expected_guide_frames)
+ input_masks, _ = _maybe_trim_control(input_masks, expected_guide_frames)
+ input_masks2, _ = _maybe_trim_control(input_masks2, expected_guide_frames)
+
+ control_strength = 1.0
+ if denoising_strength is not None and "G" in video_prompt_type:
+ try:
+ control_strength = float(denoising_strength)
+ except (TypeError, ValueError):
+ control_strength = 1.0
+ control_strength = max(0.0, min(1.0, control_strength))
+
+ conditioning_entries = []
+ if input_frames is not None:
+ conditioning_entries.append((input_frames, control_start_frame, control_strength))
+ if input_frames2 is not None:
+ conditioning_entries.append((input_frames2, control_start_frame, control_strength))
+ if conditioning_entries:
+ video_conditioning = conditioning_entries
+ if masking_strength > 0.0:
+ if input_masks is not None and input_frames is not None:
+ masking_source = {
+ "video": input_frames,
+ "mask": input_masks,
+ "start_frame": control_start_frame,
+ }
+ elif input_masks2 is not None and input_frames2 is not None:
+ masking_source = {
+ "video": input_frames2,
+ "mask": input_masks2,
+ "start_frame": control_start_frame,
+ }
+
+ latent_conditioning_stage2 = None
latent_stride = 8
if hasattr(self.pipeline, "pipeline_components"):
@@ -502,7 +631,7 @@ class LTX2:
# Ensure the latest prefix frame dominates its latent slot.
frame_indices.append(last_idx)
for frame_idx in frame_indices:
- entry = (input_video[:, frame_idx], _to_latent_index(frame_idx, latent_stride), 1.0)
+ entry = (input_video[:, frame_idx], _to_latent_index(frame_idx, latent_stride), input_video_strength)
target_list.append(entry)
if extra_list is not None:
extra_list.append(entry)
@@ -516,7 +645,7 @@ class LTX2:
images_stage2.append(entry)
if image_start is not None:
- entry = (image_start, _to_latent_index(0, latent_stride), 1.0, "lanczos")
+ entry = (image_start, _to_latent_index(0, latent_stride), input_video_strength, "lanczos")
if use_guiding_start_image:
guiding_images.append(entry)
images_stage2.append(entry)
@@ -527,7 +656,7 @@ class LTX2:
else:
_append_prefix_entries(images)
if image_start is not None:
- images.append((image_start, _to_latent_index(0, latent_stride), 1.0, "lanczos"))
+ images.append((image_start, _to_latent_index(0, latent_stride), input_video_strength, "lanczos"))
if image_end is not None:
images.append((image_end, _to_latent_index(frame_num - 1, latent_stride), 1.0))
@@ -632,9 +761,20 @@ class LTX2:
if target_width % 64 != 0:
target_width = int(math.ceil(target_width / 64) * 64)
+ if latent_conditioning_stage2 is not None:
+ expected_lat_h = target_height // 32
+ expected_lat_w = target_width // 32
+ if (
+ latent_conditioning_stage2.shape[3] != expected_lat_h
+ or latent_conditioning_stage2.shape[4] != expected_lat_w
+ ):
+ latent_conditioning_stage2 = None
+ else:
+ latent_conditioning_stage2 = latent_conditioning_stage2.to(device=self.device, dtype=self.dtype)
+
if isinstance(self.pipeline, TI2VidTwoStagesPipeline):
negative_prompt = n_prompt if n_prompt else DEFAULT_NEGATIVE_PROMPT
- video, audio = self.pipeline(
+ pipeline_output = self.pipeline(
prompt=input_prompt,
negative_prompt=negative_prompt,
seed=int(seed),
@@ -647,6 +787,8 @@ class LTX2:
images=images,
guiding_images=guiding_images or None,
images_stage2=images_stage2 if stage2_override else None,
+ video_conditioning=video_conditioning,
+ latent_conditioning_stage2=latent_conditioning_stage2,
tiling_config=tiling_config,
enhance_prompt=False,
audio_conditionings=audio_conditionings,
@@ -654,9 +796,12 @@ class LTX2:
interrupt_check=interrupt_check,
loras_slists=loras_slists,
text_connectors=text_connectors,
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ return_latent_slice=return_latent_slice,
)
else:
- video, audio = self.pipeline(
+ pipeline_output = self.pipeline(
prompt=input_prompt,
seed=int(seed),
height=target_height,
@@ -664,6 +809,8 @@ class LTX2:
num_frames=int(frame_num),
frame_rate=float(fps),
images=images,
+ video_conditioning=video_conditioning,
+ latent_conditioning_stage2=latent_conditioning_stage2,
tiling_config=tiling_config,
enhance_prompt=False,
audio_conditionings=audio_conditionings,
@@ -671,8 +818,17 @@ class LTX2:
interrupt_check=interrupt_check,
loras_slists=loras_slists,
text_connectors=text_connectors,
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ return_latent_slice=return_latent_slice,
)
+ latent_slice = None
+ if isinstance(pipeline_output, tuple) and len(pipeline_output) == 3:
+ video, audio, latent_slice = pipeline_output
+ else:
+ video, audio = pipeline_output
+
if video is None or audio is None:
return None
@@ -687,8 +843,11 @@ class LTX2:
if audio_np is not None and audio_np.ndim == 2:
if audio_np.shape[0] in (1, 2) and audio_np.shape[1] > audio_np.shape[0]:
audio_np = audio_np.T
- return {
+ result = {
"x": video_tensor,
"audio": audio_np,
"audio_sampling_rate": AUDIO_SAMPLE_RATE,
}
+ if latent_slice is not None:
+ result["latent_slice"] = latent_slice
+ return result
diff --git a/models/ltx2/ltx2_handler.py b/models/ltx2/ltx2_handler.py
index 4276a68..52fee4e 100644
--- a/models/ltx2/ltx2_handler.py
+++ b/models/ltx2/ltx2_handler.py
@@ -60,8 +60,24 @@ class family_handler:
"show_label": False,
},
"audio_guide_window_slicing": True,
+ "custom_denoising_strength": True,
"profiles_dir": ["ltx2_19B"],
}
+ extra_model_def["extra_control_frames"] = 1
+ extra_model_def["dont_cat_preguide"] = True
+ extra_model_def["input_video_strength"] = "Image / Source Video Strength (you may try values lower value than 1 to get more motion)"
+ extra_model_def["guide_preprocessing"] = {
+ "selection": ["", "PVG", "DVG", "EVG", "VG"],
+ "labels": {
+ "PVG": "Transfer Human Motion",
+ "DVG": "Transfer Depth",
+ "EVG": "Transfer Canny Edges",
+ "VG": "Use LTX-2 raw format",
+ },
+ }
+ extra_model_def["mask_preprocessing"] = {
+ "selection": ["", "A", "NA", "XA", "XNA"],
+ }
extra_model_def["sliding_window_defaults"] = {
"overlap_min": 1,
"overlap_max": 97,
@@ -207,7 +223,9 @@ class family_handler:
ui_defaults.update(
{
"sliding_window_size": 481,
- "sliding_window_overlap": 9,
+ "sliding_window_overlap": 17,
+ "denoising_strength": 1.0,
+ "masking_strength": 0,
}
)
ui_defaults.setdefault("audio_scale", 1.0)
diff --git a/models/ltx2/ltx_core/conditioning/types/keyframe_cond.py b/models/ltx2/ltx_core/conditioning/types/keyframe_cond.py
index b57739b..9f2e546 100644
--- a/models/ltx2/ltx_core/conditioning/types/keyframe_cond.py
+++ b/models/ltx2/ltx_core/conditioning/types/keyframe_cond.py
@@ -33,7 +33,11 @@ class VideoConditionByKeyframeIndex(ConditioningItem):
scale_factors=latent_tools.scale_factors,
causal_fix=latent_tools.causal_fix if self.frame_idx == 0 else False,
)
-
+ remove_prepend = False
+ if self.frame_idx < 0:
+ self.frame_idx = - self.frame_idx
+ remove_prepend = True
+
positions[:, 0, ...] += self.frame_idx
positions = positions.to(dtype=torch.float32)
positions[:, 0, ...] /= latent_tools.fps
@@ -44,6 +48,11 @@ class VideoConditionByKeyframeIndex(ConditioningItem):
device=self.keyframes.device,
dtype=self.keyframes.dtype,
)
+ if remove_prepend:
+ latent_frame_tokens = self.keyframes.shape[-1] * self.keyframes.shape[-2]
+ tokens = tokens[:, latent_frame_tokens:]
+ denoise_mask = denoise_mask[:, latent_frame_tokens:]
+ positions = positions[:, :, latent_frame_tokens:]
return LatentState(
latent=torch.cat([latent_state.latent, tokens], dim=1),
diff --git a/models/ltx2/ltx_core/model/transformer/attention.py b/models/ltx2/ltx_core/model/transformer/attention.py
index 73a0665..823f650 100644
--- a/models/ltx2/ltx_core/model/transformer/attention.py
+++ b/models/ltx2/ltx_core/model/transformer/attention.py
@@ -141,6 +141,35 @@ class AttentionFunction(Enum):
)
+class DBMRMSNorm(torch.nn.Module):
+
+ def __init__(self, dim, eps=1e-5):
+ super().__init__()
+ self.dim = dim
+ self.eps = eps
+ self.weight = torch.nn.Parameter(torch.ones(dim))
+
+ def forward(self, x, in_place= True):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L, C]
+ """
+ y = x.float()
+ y.pow_(2)
+ y = y.mean(dim=-1, keepdim=True)
+ y += self.eps
+ y.rsqrt_()
+ if in_place:
+ x *= y
+ else:
+ x = x * y
+ x *= self.weight
+ return x
+ # return self._norm(x).type_as(x) * self.weight
+
+ def _norm(self, x):
+ return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
+
class Attention(torch.nn.Module):
def __init__(
self,
@@ -162,8 +191,8 @@ class Attention(torch.nn.Module):
self.heads = heads
self.dim_head = dim_head
- self.q_norm = torch.nn.RMSNorm(inner_dim, eps=norm_eps)
- self.k_norm = torch.nn.RMSNorm(inner_dim, eps=norm_eps)
+ self.q_norm = DBMRMSNorm(inner_dim, eps=norm_eps)
+ self.k_norm = DBMRMSNorm(inner_dim, eps=norm_eps)
self.to_q = torch.nn.Linear(query_dim, inner_dim, bias=True)
self.to_k = torch.nn.Linear(context_dim, inner_dim, bias=True)
@@ -183,19 +212,27 @@ class Attention(torch.nn.Module):
def forward(
self,
- x: torch.Tensor,
- context: torch.Tensor | None = None,
+ x_list: torch.Tensor,
+ context_list: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
pe: torch.Tensor | None = None,
k_pe: torch.Tensor | None = None,
) -> torch.Tensor:
+ x = x_list[0]
+ x_list.clear()
+ context = None
+ if context_list is not None:
+ context = context_list[0]
+ context_list.clear()
+ cross_attn = context is not None
q = self.to_q(x)
context = x if context is None else context
+ x = None
k = self.to_k(context)
v = self.to_v(context)
-
- q = self.q_norm(q)
- k = self.k_norm(k)
+ context = None
+ self.q_norm(q)
+ self.k_norm(k)
if pe is not None:
apply_rotary_emb_inplace(q, pe, self.rope_type)
@@ -213,7 +250,7 @@ class Attention(torch.nn.Module):
attention_mask=mask,
force_attention=force_attention,
version=attention_version,
- cross_attn=context is not None,
+ cross_attn=cross_attn
)
out = out.flatten(2, 3)
out = self.to_out(out)
diff --git a/models/ltx2/ltx_core/model/transformer/model.py b/models/ltx2/ltx_core/model/transformer/model.py
index a07536c..f60e0ef 100644
--- a/models/ltx2/ltx_core/model/transformer/model.py
+++ b/models/ltx2/ltx_core/model/transformer/model.py
@@ -9,7 +9,7 @@ from .attention import AttentionCallable, AttentionFunction
from .modality import Modality
from .rope import LTXRopeType
from .text_projection import PixArtAlphaTextProjection
-from .transformer import BasicAVTransformerBlock, TransformerConfig
+from .transformer import BasicAVTransformerBlock, TransformerConfig, _apply_scale_shift
from .transformer_args import (
MultiModalTransformerArgsPreprocessor,
TransformerArgs,
@@ -392,7 +392,7 @@ class LTXModel(torch.nn.Module):
shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1]
x = norm_out(x)
- x = x * (1 + scale) + shift
+ x = _apply_scale_shift(x, scale, shift)
x = proj_out(x)
return x
diff --git a/models/ltx2/ltx_core/model/transformer/rope.py b/models/ltx2/ltx_core/model/transformer/rope.py
index ba050c1..ef275e7 100644
--- a/models/ltx2/ltx_core/model/transformer/rope.py
+++ b/models/ltx2/ltx_core/model/transformer/rope.py
@@ -1,11 +1,19 @@
-import functools
import math
+import warnings
+from dataclasses import dataclass
from enum import Enum
from typing import Callable, Tuple
import numpy as np
import torch
-from einops import rearrange
+
+
+USE_FP32_ROPE_FREQS = False
+
+
+def set_use_fp32_rope_freqs(enabled: bool) -> None:
+ global USE_FP32_ROPE_FREQS
+ USE_FP32_ROPE_FREQS = bool(enabled)
class LTXRopeType(Enum):
@@ -13,45 +21,151 @@ class LTXRopeType(Enum):
SPLIT = "split"
-def apply_rotary_emb(
- input_tensor: torch.Tensor,
- freqs_cis: Tuple[torch.Tensor, torch.Tensor],
- rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
-) -> torch.Tensor:
- if rope_type == LTXRopeType.INTERLEAVED:
- return apply_interleaved_rotary_emb(input_tensor, *freqs_cis)
- elif rope_type == LTXRopeType.SPLIT:
- return apply_split_rotary_emb(input_tensor, *freqs_cis)
- else:
- raise ValueError(f"Invalid rope type: {rope_type}")
+@dataclass(frozen=True)
+class RopeCache:
+ cos: torch.Tensor | tuple[torch.Tensor, ...]
+ sin: torch.Tensor | tuple[torch.Tensor, ...]
+ grid_sizes: tuple[int, ...] | None
+ rope_axes: tuple[int, ...] | None
+ pad_size: int
+ rope_type: LTXRopeType
+ num_attention_heads: int | None = None
+ split_head_axes: torch.Tensor | None = None
+ split_head_freqs: torch.Tensor | None = None
+ use_fp32_freqs: bool = False
+
+ def is_grid(self) -> bool:
+ return self.grid_sizes is not None and self.rope_axes is not None and isinstance(self.cos, tuple)
def apply_rotary_emb_inplace(
input_tensor: torch.Tensor,
- freqs_cis: Tuple[torch.Tensor, torch.Tensor],
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] | RopeCache,
rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
) -> torch.Tensor:
- if rope_type == LTXRopeType.INTERLEAVED:
- return apply_interleaved_rotary_emb_inplace(input_tensor, *freqs_cis)
- elif rope_type == LTXRopeType.SPLIT:
- return apply_split_rotary_emb_inplace(input_tensor, *freqs_cis)
- else:
- raise ValueError(f"Invalid rope type: {rope_type}")
+ if isinstance(freqs_cis, RopeCache):
+ return apply_split_rope_cache_inplace(input_tensor, freqs_cis)
+ return _apply_rotary_emb_inplace_tensor(input_tensor, freqs_cis, rope_type)
-def apply_interleaved_rotary_emb_inplace(
- input_tensor: torch.Tensor, cos_freqs: torch.Tensor, sin_freqs: torch.Tensor
+def _apply_rotary_emb_inplace_tensor(
+ input_tensor: torch.Tensor,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor],
+ rope_type: LTXRopeType,
) -> torch.Tensor:
- x = input_tensor.view(*input_tensor.shape[:-1], -1, 2)
- cos = cos_freqs.view(*cos_freqs.shape[:-1], -1, 2)
- sin = sin_freqs.view(*sin_freqs.shape[:-1], -1, 2)
-
- x0 = x[..., 0]
- x1 = x[..., 1]
- x0_orig = x0.clone()
- x0.mul_(cos[..., 0]).addcmul_(x1, sin[..., 0], value=-1)
- x1.mul_(cos[..., 1]).addcmul_(x0_orig, sin[..., 1])
+ cos, sin = freqs_cis
+ use_fp32 = USE_FP32_ROPE_FREQS
+ target_dtype = torch.float32 if use_fp32 else input_tensor.dtype
+ if cos.device != input_tensor.device or cos.dtype != target_dtype:
+ cos = cos.to(device=input_tensor.device, dtype=target_dtype)
+ if sin.device != input_tensor.device or sin.dtype != target_dtype:
+ sin = sin.to(device=input_tensor.device, dtype=target_dtype)
+
+ if use_fp32 and input_tensor.dtype != torch.float32:
+ x_work = input_tensor.to(torch.float32)
+ apply_split_rotary_emb_inplace(x_work, cos, sin)
+ input_tensor.copy_(x_work.to(input_tensor.dtype))
+ return input_tensor
+
+ return apply_split_rotary_emb_inplace(input_tensor, cos, sin)
+
+
+
+def apply_split_rope_cache_inplace(input_tensor: torch.Tensor, rope_cache: RopeCache) -> torch.Tensor:
+ grid_sizes = rope_cache.grid_sizes
+ rope_axes = rope_cache.rope_axes
+ cos_tables = rope_cache.cos
+ sin_tables = rope_cache.sin
+
+ b, tokens, dim = input_tensor.shape
+ grid_volume = math.prod(grid_sizes)
+ if grid_volume != tokens:
+ return input_tensor
+
+ axis_count = len(rope_axes)
+ axis_dim = cos_tables[0].shape[-1] if axis_count > 0 else 0
+ if axis_count == 0:
+ return input_tensor
+
+ num_heads = rope_cache.num_attention_heads
+ if num_heads is None:
+ return input_tensor
+ dim_head = dim // num_heads
+ if dim_head % 2 != 0:
+ return input_tensor
+ half_dim = dim_head // 2
+ expected_freqs = num_heads * half_dim
+ pad_size = rope_cache.pad_size
+ dim_no_pad = expected_freqs - pad_size
+ if axis_dim <= 0 or dim_no_pad <= 0 or dim_no_pad % axis_count != 0:
+ return input_tensor
+ if axis_dim * axis_count != dim_no_pad:
+ return input_tensor
+
+ x_view = input_tensor.reshape(b, *grid_sizes, num_heads, dim_head)
+ x0 = x_view[..., :half_dim]
+ x1 = x_view[..., half_dim:]
+ x0_flat = x0.reshape(b, *grid_sizes, expected_freqs)
+ x1_flat = x1.reshape(b, *grid_sizes, expected_freqs)
+
+ if pad_size:
+ x0_rope = x0_flat[..., pad_size:]
+ x1_rope = x1_flat[..., pad_size:]
+ else:
+ x0_rope = x0_flat
+ x1_rope = x1_flat
+
+ rope_width = axis_dim * axis_count
+ if x0_rope.shape[-1] != rope_width:
+ return input_tensor
+
+ x0_rope = x0_rope.reshape(b, *grid_sizes, axis_dim, axis_count)
+ x1_rope = x1_rope.reshape(b, *grid_sizes, axis_dim, axis_count)
+
+ x_dtype = input_tensor.dtype
+ device = input_tensor.device
+ work_dtype = torch.float32 if rope_cache.use_fp32_freqs else x_dtype
+ if work_dtype == x_dtype:
+ x0_tmp = torch.empty_like(x0_rope[..., 0])
+ x1_tmp = None
+ x0_orig_tmp = x0_tmp
+ else:
+ x0_tmp = torch.empty_like(x0_rope[..., 0], dtype=work_dtype, device=device)
+ x1_tmp = torch.empty_like(x1_rope[..., 0], dtype=work_dtype, device=device)
+ x0_orig_tmp = torch.empty_like(x0_tmp)
+
+ for axis_index, axis in enumerate(rope_axes):
+ cos_axis = cos_tables[axis_index]
+ sin_axis = sin_tables[axis_index]
+ shape = [1] * len(grid_sizes) + [axis_dim]
+ shape[axis] = grid_sizes[axis]
+ cos_axis = cos_axis.view(*shape)
+ sin_axis = sin_axis.view(*shape)
+ if cos_axis.device != device or cos_axis.dtype != work_dtype:
+ cos_axis = cos_axis.to(device=device, dtype=work_dtype)
+ if sin_axis.device != device or sin_axis.dtype != work_dtype:
+ sin_axis = sin_axis.to(device=device, dtype=work_dtype)
+
+ x0_axis = x0_rope[..., axis_index]
+ x1_axis = x1_rope[..., axis_index]
+ if work_dtype == x_dtype:
+ x0_orig_tmp.copy_(x0_axis)
+ x0_axis.mul_(cos_axis).addcmul_(x1_axis, sin_axis, value=-1)
+ x1_axis.mul_(cos_axis).addcmul_(x0_orig_tmp, sin_axis)
+ else:
+ x0_orig_tmp.copy_(x0_axis)
+ x1_tmp.copy_(x1_axis)
+ x0_tmp.copy_(x0_orig_tmp)
+ x0_tmp.mul_(cos_axis).addcmul_(x1_tmp, sin_axis, value=-1)
+ x1_tmp.mul_(cos_axis).addcmul_(x0_orig_tmp, sin_axis)
+ x0_axis.copy_(x0_tmp)
+ x1_axis.copy_(x1_tmp)
+
+ x0.copy_(x0_flat.reshape_as(x0))
+ x1.copy_(x1_flat.reshape_as(x1))
return input_tensor
+#used
+
def apply_split_rotary_emb_inplace(
@@ -74,49 +188,8 @@ def apply_split_rotary_emb_inplace(
x1.mul_(cos_freqs).addcmul_(x0_orig, sin_freqs)
return input_tensor
+#used
-
-def apply_interleaved_rotary_emb(
- input_tensor: torch.Tensor, cos_freqs: torch.Tensor, sin_freqs: torch.Tensor
-) -> torch.Tensor:
- t_dup = rearrange(input_tensor, "... (d r) -> ... d r", r=2)
- t1, t2 = t_dup.unbind(dim=-1)
- t_dup = torch.stack((-t2, t1), dim=-1)
- input_tensor_rot = rearrange(t_dup, "... d r -> ... (d r)")
-
- out = input_tensor * cos_freqs + input_tensor_rot * sin_freqs
-
- return out
-
-
-def apply_split_rotary_emb(
- input_tensor: torch.Tensor, cos_freqs: torch.Tensor, sin_freqs: torch.Tensor
-) -> torch.Tensor:
- needs_reshape = False
- if input_tensor.ndim != 4 and cos_freqs.ndim == 4:
- b, h, t, _ = cos_freqs.shape
- input_tensor = input_tensor.reshape(b, t, h, -1).swapaxes(1, 2)
- needs_reshape = True
-
- split_input = rearrange(input_tensor, "... (d r) -> ... d r", d=2)
- first_half_input = split_input[..., :1, :]
- second_half_input = split_input[..., 1:, :]
-
- output = split_input * cos_freqs.unsqueeze(-2)
- first_half_output = output[..., :1, :]
- second_half_output = output[..., 1:, :]
-
- first_half_output.addcmul_(-sin_freqs.unsqueeze(-2), second_half_input)
- second_half_output.addcmul_(sin_freqs.unsqueeze(-2), first_half_input)
-
- output = rearrange(output, "... d r -> ... (d r)")
- if needs_reshape:
- output = output.swapaxes(1, 2).reshape(b, t, -1)
-
- return output
-
-
[email protected]_cache(maxsize=5)
def generate_freq_grid_np(
positional_embedding_theta: float, positional_embedding_max_pos_count: int, inner_dim: int
) -> torch.Tensor:
@@ -137,7 +210,6 @@ def generate_freq_grid_np(
return torch.tensor(pow_indices * math.pi / 2, dtype=torch.float32)
[email protected]_cache(maxsize=5)
def generate_freq_grid_pytorch(
positional_embedding_theta: float, positional_embedding_max_pos_count: int, inner_dim: int
) -> torch.Tensor:
@@ -238,6 +310,7 @@ def precompute_freqs_cis(
) -> tuple[torch.Tensor, torch.Tensor]:
if max_pos is None:
max_pos = [20, 2048, 2048]
+ freqs_dtype = torch.float32 if USE_FP32_ROPE_FREQS else out_dtype
indices = freq_grid_generator(theta, indices_grid.shape[1], dim)
freqs = generate_freqs(indices, indices_grid, max_pos, use_middle_indices_grid)
@@ -251,4 +324,141 @@ def precompute_freqs_cis(
# 2 because of cos and sin by 3 for (t, x, y), 1 for temporal only
n_elem = 2 * indices_grid.shape[1]
cos_freq, sin_freq = interleaved_freqs_cis(freqs, dim % n_elem)
- return cos_freq.to(out_dtype), sin_freq.to(out_dtype)
+ return cos_freq.to(freqs_dtype), sin_freq.to(freqs_dtype)
+
+
+def _reduce_positions(positions: torch.Tensor, use_middle_indices_grid: bool) -> torch.Tensor:
+ if positions.ndim == 4:
+ if use_middle_indices_grid:
+ return positions.mean(dim=-1)
+ return positions[..., 0]
+ return positions
+
+
+def _infer_grid_sizes(positions: torch.Tensor) -> tuple[list[torch.Tensor], tuple[int, ...]]:
+ axis_values = []
+ for axis in range(positions.shape[1]):
+ axis_values.append(torch.unique(positions[0, axis], sorted=True))
+ grid_sizes = tuple(values.numel() for values in axis_values)
+ return axis_values, grid_sizes
+
+
+def _build_axis_freqs(indices: torch.Tensor, axis_values: torch.Tensor, axis_max: int) -> torch.Tensor:
+ fractional_positions = axis_values / axis_max
+ return indices * (fractional_positions.unsqueeze(-1) * 2 - 1)
+
+
+def _can_broadcast_frames(frame_indices: torch.Tensor, frame_count: int) -> bool:
+ if frame_indices.ndim != 2:
+ return False
+ token_count = frame_indices.shape[1]
+ if frame_count <= 0 or token_count % frame_count != 0:
+ return False
+ tokens_per_frame = token_count // frame_count
+ if tokens_per_frame == 0:
+ return False
+ try:
+ frame_view = frame_indices.reshape(frame_indices.shape[0], frame_count, tokens_per_frame)
+ except RuntimeError:
+ return False
+ expected = torch.arange(frame_count, device=frame_indices.device).view(1, frame_count, 1)
+ return torch.equal(frame_view, expected.expand(frame_indices.shape[0], -1, tokens_per_frame))
+
+
+def build_rope_cache(
+ positions: torch.Tensor,
+ dim: int,
+ out_dtype: torch.dtype,
+ theta: float = 10000.0,
+ max_pos: list[int] | None = None,
+ use_middle_indices_grid: bool = False,
+ num_attention_heads: int = 32,
+ rope_type: LTXRopeType = LTXRopeType.INTERLEAVED,
+ rope_axes: tuple[int, ...] | None = None,
+ frame_indices: torch.Tensor | None = None,
+ grid_sizes: tuple[int, ...] | None = None,
+ rope_max_pos: list[int] | None = None,
+ freq_grid_generator: Callable[[float, int, int], torch.Tensor] = generate_freq_grid_pytorch,
+) -> RopeCache | tuple[torch.Tensor, torch.Tensor]:
+ if max_pos is None:
+ max_pos = [20, 2048, 2048]
+ freqs_dtype = torch.float32 if USE_FP32_ROPE_FREQS else out_dtype
+
+ positions_mid = _reduce_positions(positions, use_middle_indices_grid)
+ pos_dims = positions_mid.shape[1]
+ if rope_axes is None:
+ rope_axes = tuple(range(pos_dims))
+
+ axis_values_all, grid_sizes = _infer_grid_sizes(positions_mid)
+ token_count = positions_mid.shape[-1]
+ grid_volume = math.prod(grid_sizes)
+
+ rope_positions = positions[:, rope_axes, ...]
+ rope_max = rope_max_pos if rope_max_pos is not None else [max_pos[axis] for axis in rope_axes]
+ num_rope_axes = len(rope_axes)
+
+ # Use per-axis RoPE tables when tokens form a full grid; fall back for irregular layouts.
+ can_use_grid = token_count == grid_volume
+ if can_use_grid and frame_indices is not None:
+ frame_count = int(frame_indices.max().item()) + 1
+ can_use_grid = _can_broadcast_frames(frame_indices, frame_count)
+
+ indices = freq_grid_generator(theta, num_rope_axes, dim).to(device=positions_mid.device)
+ if can_use_grid and num_rope_axes > 0:
+ axis_cos_tables = []
+ axis_sin_tables = []
+ if rope_type == LTXRopeType.SPLIT:
+ expected_freqs = dim // 2
+ current_freqs = indices.shape[0] * num_rope_axes
+ pad_size = expected_freqs - current_freqs
+ else:
+ pad_size = dim % (2 * num_rope_axes)
+
+ for axis_index, axis in enumerate(rope_axes):
+ axis_values = axis_values_all[axis].to(device=positions_mid.device)
+ axis_freqs = _build_axis_freqs(indices, axis_values, rope_max[axis_index])
+ if rope_type == LTXRopeType.SPLIT:
+ cos_axis = axis_freqs.cos()
+ sin_axis = axis_freqs.sin()
+ else:
+ cos_axis = axis_freqs.cos().repeat_interleave(2, dim=-1)
+ sin_axis = axis_freqs.sin().repeat_interleave(2, dim=-1)
+ axis_cos_tables.append(cos_axis.to(freqs_dtype))
+ axis_sin_tables.append(sin_axis.to(freqs_dtype))
+
+ return RopeCache(
+ cos=tuple(axis_cos_tables),
+ sin=tuple(axis_sin_tables),
+ grid_sizes=grid_sizes,
+ rope_axes=rope_axes,
+ pad_size=pad_size,
+ rope_type=rope_type,
+ num_attention_heads=num_attention_heads,
+ use_fp32_freqs=USE_FP32_ROPE_FREQS,
+ )
+
+ if num_rope_axes > 0:
+ warnings.warn(
+ "LTX2 RoPE fallback: using per-token freqs because tokens are not a regular grid.",
+ RuntimeWarning,
+ stacklevel=2,
+ )
+
+ freqs = generate_freqs(indices, rope_positions, rope_max, use_middle_indices_grid)
+
+ if rope_type == LTXRopeType.SPLIT:
+ expected_freqs = dim // 2
+ current_freqs = freqs.shape[-1]
+ pad_size = expected_freqs - current_freqs
+ cos_freq, sin_freq = split_freqs_cis(freqs, pad_size, num_attention_heads)
+ else:
+ pad_size = dim % (2 * num_rope_axes)
+ cos_freq, sin_freq = interleaved_freqs_cis(freqs, pad_size)
+
+ cos_freq = cos_freq.to(freqs_dtype)
+ sin_freq = sin_freq.to(freqs_dtype)
+ if cos_freq.ndim == 3 and cos_freq.shape[0] == 1:
+ cos_freq = cos_freq[0]
+ sin_freq = sin_freq[0]
+
+ return cos_freq, sin_freq
diff --git a/models/ltx2/ltx_core/model/transformer/transformer.py b/models/ltx2/ltx_core/model/transformer/transformer.py
index 72bfda4..b73b6b4 100644
--- a/models/ltx2/ltx_core/model/transformer/transformer.py
+++ b/models/ltx2/ltx_core/model/transformer/transformer.py
@@ -1,3 +1,6 @@
+# Original Code by LightTricks (https://github.com/Lightricks/LTX-2)
+# VRAM Optimizations by DeepBeepMeep (c) 2026. Please quote DeepBeepMeep / WanGP if reused
+
from dataclasses import dataclass, replace
import torch
@@ -10,6 +13,34 @@ from .transformer_args import TransformerArgs
from ...utils import rms_norm
+def _reshape_hidden_states(hidden_states: torch.Tensor, frames: int) -> torch.Tensor:
+ return hidden_states.reshape(hidden_states.shape[0], frames, -1, hidden_states.shape[-1])
+
+
+def _restore_hidden_states_shape(hidden_states: torch.Tensor) -> torch.Tensor:
+ return hidden_states.reshape(hidden_states.shape[0], -1, hidden_states.shape[-1])
+
+
+def _apply_scale_shift(
+ hidden_states: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor
+) -> torch.Tensor:
+ if scale.shape[1] == hidden_states.shape[1]:
+ hidden_states.mul_(1 + scale).add_(shift)
+ return hidden_states
+ hidden_states = _reshape_hidden_states(hidden_states, scale.shape[1])
+ hidden_states.mul_(1 + scale.unsqueeze(2)).add_(shift.unsqueeze(2))
+ return _restore_hidden_states_shape(hidden_states)
+
+
+def _apply_gate(hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
+ if gate.shape[1] == hidden_states.shape[1]:
+ hidden_states.mul_(gate)
+ return hidden_states
+ hidden_states = _reshape_hidden_states(hidden_states, gate.shape[1])
+ hidden_states.mul_(gate.unsqueeze(2))
+ return _restore_hidden_states_shape(hidden_states)
+
+
@dataclass
class TransformerConfig:
dim: int
@@ -172,17 +203,19 @@ class BasicAVTransformerBlock(torch.nn.Module):
vgate_msa = vgate_msa.to(vx.dtype)
if not perturbations.all_in_batch(PerturbationType.SKIP_VIDEO_SELF_ATTN, self.idx):
norm_vx = rms_norm(vx, eps=self.norm_eps)
- norm_vx.mul_(1 + vscale_msa).add_(vshift_msa)
+ norm_vx = _apply_scale_shift(norm_vx, vscale_msa, vshift_msa)
v_mask = perturbations.mask_like(PerturbationType.SKIP_VIDEO_SELF_ATTN, self.idx, vx)
- attn_out = self.attn1(norm_vx, pe=video.positional_embeddings)
- attn_out.mul_(vgate_msa).mul_(v_mask)
+ x_list = [norm_vx]
+ del norm_vx
+ attn_out = self.attn1(x_list, pe=video.positional_embeddings)
+ attn_out = _apply_gate(attn_out, vgate_msa)
+ attn_out.mul_(v_mask)
vx.add_(attn_out)
attn_out = None
-
- attn_out = self.attn2(rms_norm(vx, eps=self.norm_eps), context=video.context, mask=video.context_mask)
+ x_list, context_list = [rms_norm(vx, eps=self.norm_eps)], [video.context]
+ attn_out = self.attn2(x_list, context_list=context_list, mask=video.context_mask)
vx.add_(attn_out)
attn_out = None
-
del vshift_msa, vscale_msa, vgate_msa
if run_ax:
@@ -195,17 +228,19 @@ class BasicAVTransformerBlock(torch.nn.Module):
if not perturbations.all_in_batch(PerturbationType.SKIP_AUDIO_SELF_ATTN, self.idx):
norm_ax = rms_norm(ax, eps=self.norm_eps)
- norm_ax.mul_(1 + ascale_msa).add_(ashift_msa)
+ norm_ax = _apply_scale_shift(norm_ax, ascale_msa, ashift_msa)
a_mask = perturbations.mask_like(PerturbationType.SKIP_AUDIO_SELF_ATTN, self.idx, ax)
- attn_out = self.audio_attn1(norm_ax, pe=audio.positional_embeddings)
- attn_out.mul_(agate_msa).mul_(a_mask)
+ x_list = [norm_ax]
+ del norm_ax
+ attn_out = self.audio_attn1(x_list, pe=audio.positional_embeddings)
+ attn_out = _apply_gate(attn_out, agate_msa)
+ attn_out.mul_(a_mask)
ax.add_(attn_out)
attn_out = None
-
- attn_out = self.audio_attn2(rms_norm(ax, eps=self.norm_eps), context=audio.context, mask=audio.context_mask)
+ x_list, context_list = [rms_norm(ax, eps=self.norm_eps)], [audio.context]
+ attn_out = self.audio_attn2(x_list, context_list=context_list, mask=audio.context_mask)
ax.add_(attn_out)
attn_out = None
-
del ashift_msa, ascale_msa, agate_msa
# Audio - Video cross attention.
@@ -250,30 +285,52 @@ class BasicAVTransformerBlock(torch.nn.Module):
gate_out_a2v = gate_out_a2v.to(vx.dtype)
if run_a2v:
- vx_scaled = vx_norm3 * (1 + scale_ca_video_hidden_states_a2v) + shift_ca_video_hidden_states_a2v
- ax_scaled = ax_norm3 * (1 + scale_ca_audio_hidden_states_a2v) + shift_ca_audio_hidden_states_a2v
+ vx_scaled = _apply_scale_shift(
+ vx_norm3.clone(),
+ scale_ca_video_hidden_states_a2v,
+ shift_ca_video_hidden_states_a2v,
+ )
+ ax_scaled = _apply_scale_shift(
+ ax_norm3.clone(),
+ scale_ca_audio_hidden_states_a2v,
+ shift_ca_audio_hidden_states_a2v,
+ )
a2v_mask = perturbations.mask_like(PerturbationType.SKIP_A2V_CROSS_ATTN, self.idx, vx)
+ x_list, context_list = [vx_scaled], [ax_scaled]
+ del vx_scaled, ax_scaled
attn_out = self.audio_to_video_attn(
- vx_scaled,
- context=ax_scaled,
+ x_list,
+ context_list=context_list,
pe=video.cross_positional_embeddings,
k_pe=audio.cross_positional_embeddings,
)
- attn_out.mul_(gate_out_a2v).mul_(a2v_mask)
+ attn_out = _apply_gate(attn_out, gate_out_a2v)
+ attn_out.mul_(a2v_mask)
vx.add_(attn_out)
attn_out = vx_scaled = ax_scaled = None
if run_v2a:
- ax_scaled = ax_norm3 * (1 + scale_ca_audio_hidden_states_v2a) + shift_ca_audio_hidden_states_v2a
- vx_scaled = vx_norm3 * (1 + scale_ca_video_hidden_states_v2a) + shift_ca_video_hidden_states_v2a
+ ax_scaled = _apply_scale_shift(
+ ax_norm3,
+ scale_ca_audio_hidden_states_v2a,
+ shift_ca_audio_hidden_states_v2a,
+ )
+ vx_scaled = _apply_scale_shift(
+ vx_norm3,
+ scale_ca_video_hidden_states_v2a,
+ shift_ca_video_hidden_states_v2a,
+ )
v2a_mask = perturbations.mask_like(PerturbationType.SKIP_V2A_CROSS_ATTN, self.idx, ax)
+ x_list, context_list = [ax_scaled], [vx_scaled]
+ del ax_scaled, vx_scaled
attn_out = self.video_to_audio_attn(
- ax_scaled,
- context=vx_scaled,
+ x_list,
+ context_list=context_list,
pe=audio.cross_positional_embeddings,
k_pe=video.cross_positional_embeddings,
)
- attn_out.mul_(gate_out_v2a).mul_(v2a_mask)
+ attn_out = _apply_gate(attn_out, gate_out_v2a)
+ attn_out.mul_(v2a_mask)
ax.add_(attn_out)
attn_out = ax_scaled = vx_scaled = None
@@ -297,9 +354,9 @@ class BasicAVTransformerBlock(torch.nn.Module):
vscale_mlp = vscale_mlp.to(vx.dtype)
vgate_mlp = vgate_mlp.to(vx.dtype)
vx_scaled = rms_norm(vx, eps=self.norm_eps)
- vx_scaled.mul_(1 + vscale_mlp).add_(vshift_mlp)
+ vx_scaled = _apply_scale_shift(vx_scaled, vscale_mlp, vshift_mlp)
ff_out = self._apply_ffn_chunked(self.ff, vx_scaled)
- ff_out.mul_(vgate_mlp)
+ ff_out = _apply_gate(ff_out, vgate_mlp)
vx.add_(ff_out)
ff_out = vx_scaled = None
@@ -313,9 +370,9 @@ class BasicAVTransformerBlock(torch.nn.Module):
ascale_mlp = ascale_mlp.to(ax.dtype)
agate_mlp = agate_mlp.to(ax.dtype)
ax_scaled = rms_norm(ax, eps=self.norm_eps)
- ax_scaled.mul_(1 + ascale_mlp).add_(ashift_mlp)
+ ax_scaled = _apply_scale_shift(ax_scaled, ascale_mlp, ashift_mlp)
ff_out = self.audio_ff(ax_scaled)
- ff_out.mul_(agate_mlp)
+ ff_out = _apply_gate(ff_out, agate_mlp)
ax.add_(ff_out)
ff_out = ax_scaled = None
diff --git a/models/ltx2/ltx_core/model/transformer/transformer_args.py b/models/ltx2/ltx_core/model/transformer/transformer_args.py
index 3ad63eb..5a9f831 100644
--- a/models/ltx2/ltx_core/model/transformer/transformer_args.py
+++ b/models/ltx2/ltx_core/model/transformer/transformer_args.py
@@ -6,9 +6,10 @@ from .adaln import AdaLayerNormSingle
from .modality import Modality
from .rope import (
LTXRopeType,
+ RopeCache,
+ build_rope_cache,
generate_freq_grid_np,
generate_freq_grid_pytorch,
- precompute_freqs_cis,
)
from .text_projection import PixArtAlphaTextProjection
@@ -20,13 +21,47 @@ class TransformerArgs:
context_mask: torch.Tensor
timesteps: torch.Tensor
embedded_timestep: torch.Tensor
- positional_embeddings: torch.Tensor
- cross_positional_embeddings: torch.Tensor | None
+ positional_embeddings: torch.Tensor | RopeCache | tuple[torch.Tensor, torch.Tensor]
+ cross_positional_embeddings: torch.Tensor | RopeCache | tuple[torch.Tensor, torch.Tensor] | None
cross_scale_shift_timestep: torch.Tensor | None
cross_gate_timestep: torch.Tensor | None
enabled: bool
+def _can_broadcast_timesteps(frame_indices: torch.Tensor | None, frame_count: int) -> bool:
+ if frame_indices is None or frame_indices.ndim != 2:
+ return False
+ token_count = frame_indices.shape[1]
+ if frame_count <= 0 or token_count % frame_count != 0:
+ return False
+ tokens_per_frame = token_count // frame_count
+ if tokens_per_frame == 0:
+ return False
+ try:
+ frame_view = frame_indices.reshape(frame_indices.shape[0], frame_count, tokens_per_frame)
+ except RuntimeError:
+ return False
+ expected = torch.arange(frame_count, device=frame_indices.device).view(1, frame_count, 1)
+ return torch.equal(frame_view, expected.expand(frame_indices.shape[0], -1, tokens_per_frame))
+
+
+def _maybe_compress_timesteps(
+ timestep: torch.Tensor, frame_indices: torch.Tensor | None, batch_size: int
+) -> torch.Tensor:
+ if frame_indices is None or timestep.ndim != 2:
+ return timestep
+ token_count = frame_indices.shape[1]
+ if timestep.shape[1] != token_count:
+ return timestep
+ frame_count = int(frame_indices.max().item()) + 1
+ if not _can_broadcast_timesteps(frame_indices, frame_count):
+ return timestep
+ tokens_per_frame = token_count // frame_count
+ if tokens_per_frame <= 1:
+ return timestep
+ return timestep.reshape(batch_size, frame_count, tokens_per_frame)[:, :, 0]
+
+
class TransformerArgsPreprocessor:
def __init__( # noqa: PLR0913
self,
@@ -64,15 +99,7 @@ class TransformerArgsPreprocessor:
"""Prepare timestep embeddings."""
timestep = timestep * self.timestep_scale_multiplier
- if frame_indices is None:
- timestep, embedded_timestep = self.adaln(
- timestep.flatten(),
- hidden_dtype=hidden_dtype,
- )
- timestep = timestep.view(batch_size, -1, timestep.shape[-1])
- embedded_timestep = embedded_timestep.view(batch_size, -1, embedded_timestep.shape[-1])
- return timestep, embedded_timestep
-
+ timestep = _maybe_compress_timesteps(timestep, frame_indices, batch_size)
timestep, embedded_timestep = self.adaln(
timestep.flatten(),
hidden_dtype=hidden_dtype,
@@ -80,6 +107,9 @@ class TransformerArgsPreprocessor:
timestep = timestep.view(batch_size, -1, timestep.shape[-1])
embedded_timestep = embedded_timestep.view(batch_size, -1, embedded_timestep.shape[-1])
+ if frame_indices is None or _can_broadcast_timesteps(frame_indices, timestep.shape[1]):
+ return timestep, embedded_timestep
+
gather_index = frame_indices.unsqueeze(-1)
timestep = timestep.gather(1, gather_index.expand(-1, -1, timestep.shape[-1]))
embedded_timestep = embedded_timestep.gather(1, gather_index.expand(-1, -1, embedded_timestep.shape[-1]))
@@ -115,11 +145,14 @@ class TransformerArgsPreprocessor:
use_middle_indices_grid: bool,
num_attention_heads: int,
x_dtype: torch.dtype,
- ) -> torch.Tensor:
+ frame_indices: torch.Tensor | None = None,
+ rope_axes: tuple[int, ...] | None = None,
+ rope_max_pos: list[int] | None = None,
+ ) -> RopeCache | tuple[torch.Tensor, torch.Tensor]:
"""Prepare positional embeddings."""
freq_grid_generator = generate_freq_grid_np if self.double_precision_rope else generate_freq_grid_pytorch
- pe = precompute_freqs_cis(
- positions,
+ return build_rope_cache(
+ positions=positions,
dim=inner_dim,
out_dtype=x_dtype,
theta=self.positional_embedding_theta,
@@ -127,9 +160,11 @@ class TransformerArgsPreprocessor:
use_middle_indices_grid=use_middle_indices_grid,
num_attention_heads=num_attention_heads,
rope_type=self.rope_type,
+ rope_axes=rope_axes,
+ frame_indices=frame_indices,
+ rope_max_pos=rope_max_pos,
freq_grid_generator=freq_grid_generator,
)
- return pe
def prepare(
self,
@@ -151,6 +186,7 @@ class TransformerArgsPreprocessor:
use_middle_indices_grid=self.use_middle_indices_grid,
num_attention_heads=self.num_attention_heads,
x_dtype=modality.latent.dtype,
+ frame_indices=modality.frame_indices,
)
return TransformerArgs(
x=x,
@@ -211,12 +247,15 @@ class MultiModalTransformerArgsPreprocessor:
) -> TransformerArgs:
transformer_args = self.simple_preprocessor.prepare(modality)
cross_pe = self.simple_preprocessor._prepare_positional_embeddings(
- positions=modality.positions[:, 0:1, :],
+ positions=modality.positions,
inner_dim=self.audio_cross_attention_dim,
- max_pos=[self.cross_pe_max_pos],
+ max_pos=self.simple_preprocessor.max_pos,
use_middle_indices_grid=True,
num_attention_heads=self.simple_preprocessor.num_attention_heads,
x_dtype=modality.latent.dtype,
+ frame_indices=modality.frame_indices,
+ rope_axes=(0,),
+ rope_max_pos=[self.cross_pe_max_pos],
)
cross_scale_shift_timestep, cross_gate_timestep = self._prepare_cross_attention_timestep(
@@ -244,22 +283,10 @@ class MultiModalTransformerArgsPreprocessor:
) -> tuple[torch.Tensor, torch.Tensor]:
"""Prepare cross attention timestep embeddings."""
timestep = timestep * timestep_scale_multiplier
+ timestep = _maybe_compress_timesteps(timestep, frame_indices, batch_size)
av_ca_factor = self.av_ca_timestep_scale_multiplier / timestep_scale_multiplier
- if frame_indices is None:
- scale_shift_timestep, _ = self.cross_scale_shift_adaln(
- timestep.flatten(),
- hidden_dtype=hidden_dtype,
- )
- scale_shift_timestep = scale_shift_timestep.view(batch_size, -1, scale_shift_timestep.shape[-1])
- gate_noise_timestep, _ = self.cross_gate_adaln(
- timestep.flatten() * av_ca_factor,
- hidden_dtype=hidden_dtype,
- )
- gate_noise_timestep = gate_noise_timestep.view(batch_size, -1, gate_noise_timestep.shape[-1])
- return scale_shift_timestep, gate_noise_timestep
-
scale_shift_timestep, _ = self.cross_scale_shift_adaln(
timestep.flatten(),
hidden_dtype=hidden_dtype,
@@ -271,6 +298,9 @@ class MultiModalTransformerArgsPreprocessor:
)
gate_noise_timestep = gate_noise_timestep.view(batch_size, -1, gate_noise_timestep.shape[-1])
+ if frame_indices is None or _can_broadcast_timesteps(frame_indices, scale_shift_timestep.shape[1]):
+ return scale_shift_timestep, gate_noise_timestep
+
gather_index = frame_indices.unsqueeze(-1)
scale_shift_timestep = scale_shift_timestep.gather(
1, gather_index.expand(-1, -1, scale_shift_timestep.shape[-1])
diff --git a/models/ltx2/ltx_core/model/video_vae/__init__.py b/models/ltx2/ltx_core/model/video_vae/__init__.py
index 03ad817..e2e314a 100644
--- a/models/ltx2/ltx_core/model/video_vae/__init__.py
+++ b/models/ltx2/ltx_core/model/video_vae/__init__.py
@@ -7,7 +7,7 @@ from .model_configurator import (
VideoEncoderConfigurator,
)
from .tiling import SpatialTilingConfig, TemporalTilingConfig, TilingConfig
-from .video_vae import VideoDecoder, VideoEncoder, decode_video, get_video_chunks_number
+from .video_vae import VideoDecoder, VideoEncoder, decode_video, encode_video, get_video_chunks_number
__all__ = [
"VAE_DECODER_COMFY_KEYS_FILTER",
@@ -20,5 +20,6 @@ __all__ = [
"VideoEncoder",
"VideoEncoderConfigurator",
"decode_video",
+ "encode_video",
"get_video_chunks_number",
]
diff --git a/models/ltx2/ltx_core/model/video_vae/video_vae.py b/models/ltx2/ltx_core/model/video_vae/video_vae.py
index 88c2745..2fb17cf 100644
--- a/models/ltx2/ltx_core/model/video_vae/video_vae.py
+++ b/models/ltx2/ltx_core/model/video_vae/video_vae.py
@@ -1,4 +1,5 @@
from dataclasses import replace
+import itertools
from typing import Any, Callable, Iterator, List, Optional, Tuple
import torch
@@ -23,7 +24,7 @@ from .tiling import (
compute_trapezoidal_mask_1d,
create_tiles,
)
-from ...types import SpatioTemporalScaleFactors, VideoLatentShape
+from ...types import SpatioTemporalScaleFactors, VideoLatentShape, VideoPixelShape, VIDEO_SCALE_FACTORS
def _make_encoder_block(
@@ -674,6 +675,11 @@ class VideoDecoder(nn.Module):
temporal_groups = self._group_tiles_by_temporal_slice(tiles)
+ # Accumulate tiles on CPU to avoid VRAM spikes from large temporal buffers.
+ accumulation_device = latent.device
+ if accumulation_device.type == "cuda":
+ accumulation_device = torch.device("cpu")
+
# State for temporal overlap handling
previous_chunk = None
previous_weights = None
@@ -696,7 +702,7 @@ class VideoDecoder(nn.Module):
buffer = torch.zeros(
temporal_tile_buffer_shape.to_torch_shape(),
- device=latent.device,
+ device=accumulation_device,
dtype=latent.dtype,
)
@@ -816,6 +822,9 @@ class VideoDecoder(nn.Module):
# Slice decoded_tile and mask to match the actual length we're writing
decoded_slice = decoded_tile[:, :, :actual_temporal_len, :, :]
+ if decoded_slice.device != buffer.device or decoded_slice.dtype != buffer.dtype:
+ decoded_slice = decoded_slice.to(device=buffer.device, dtype=buffer.dtype)
+ del decoded_tile
mask_slice = mask[:, :, :actual_temporal_len, :, :] if mask.shape[2] > 1 else mask
buffer[chunk_coords] += decoded_slice * mask_slice
@@ -852,6 +861,176 @@ def decode_video(
yield convert_to_uint8(decoded_video)
+def _default_intervals(length: int) -> DimensionIntervals:
+ return DEFAULT_SPLIT_OPERATION(length)
+
+
+def _build_temporal_intervals(
+ length: int,
+ tiling_config: TilingConfig | None,
+ scale: int,
+) -> DimensionIntervals:
+ if (
+ tiling_config is None
+ or tiling_config.temporal_config is None
+ or length <= 0
+ ):
+ return _default_intervals(length)
+ cfg = tiling_config.temporal_config
+ tile_size = max(1, cfg.tile_size_in_frames // scale)
+ overlap = max(0, cfg.tile_overlap_in_frames // scale)
+ overlap = min(overlap, max(tile_size - 1, 0))
+ return split_in_temporal(tile_size, overlap)(length)
+
+
+def _build_spatial_intervals(
+ length: int,
+ tiling_config: TilingConfig | None,
+ factor: int,
+ long_side: int,
+) -> DimensionIntervals:
+ if (
+ tiling_config is None
+ or tiling_config.spatial_config is None
+ or length <= 0
+ ):
+ return _default_intervals(length)
+ cfg = tiling_config.spatial_config
+ size = cfg.tile_size_in_pixels // factor
+ overlap = cfg.tile_overlap_in_pixels // factor
+ lower_threshold = max(2, overlap + 1)
+ tile_size = max(lower_threshold, round(size * length / max(1, long_side)))
+ return split_in_spatial(tile_size, overlap)(length)
+
+
+def _make_mask_1d(
+ length: int,
+ left_ramp: int,
+ right_ramp: int,
+ *,
+ left_starts_from_0: bool,
+ device: torch.device,
+ dtype: torch.dtype,
+) -> torch.Tensor:
+ if length <= 0:
+ return torch.ones(0, device=device, dtype=dtype)
+ mask = compute_trapezoidal_mask_1d(length, left_ramp, right_ramp, left_starts_from_0)
+ return mask.to(device=device, dtype=dtype)
+
+
+def encode_video(
+ video: torch.Tensor,
+ video_encoder: VideoEncoder,
+ tiling_config: TilingConfig | None = None,
+) -> torch.Tensor:
+ """
+ Encode a video tensor with the given encoder, optionally using spatial/temporal tiling.
+ Args:
+ video: Tensor [b, c, f, h, w]
+ video_encoder: Encoder module.
+ tiling_config: Optional tiling settings.
+ Returns:
+ Encoded latent tensor [b, c_l, f_l, h_l, w_l].
+ """
+ if tiling_config is None or (
+ tiling_config.spatial_config is None and tiling_config.temporal_config is None
+ ):
+ return video_encoder(video)
+
+ b, _, frames, height, width = video.shape
+ scale = VIDEO_SCALE_FACTORS
+ latent_shape = VideoLatentShape.from_pixel_shape(
+ VideoPixelShape(batch=b, frames=frames, height=height, width=width, fps=1.0),
+ latent_channels=getattr(video_encoder, "latent_channels", 128),
+ scale_factors=scale,
+ )
+
+ long_side = max(latent_shape.height, latent_shape.width)
+ temporal_intervals = _build_temporal_intervals(latent_shape.frames, tiling_config, scale.time)
+ height_intervals = _build_spatial_intervals(latent_shape.height, tiling_config, scale.height, long_side)
+ width_intervals = _build_spatial_intervals(latent_shape.width, tiling_config, scale.width, long_side)
+
+ output = None
+ weights = None
+
+ for t_idx, h_idx, w_idx in itertools.product(
+ range(len(temporal_intervals.starts)),
+ range(len(height_intervals.starts)),
+ range(len(width_intervals.starts)),
+ ):
+ t_start = temporal_intervals.starts[t_idx]
+ t_end = temporal_intervals.ends[t_idx]
+ t_left = temporal_intervals.left_ramps[t_idx]
+ t_right = temporal_intervals.right_ramps[t_idx]
+ h_start = height_intervals.starts[h_idx]
+ h_end = height_intervals.ends[h_idx]
+ h_left = height_intervals.left_ramps[h_idx]
+ h_right = height_intervals.right_ramps[h_idx]
+ w_start = width_intervals.starts[w_idx]
+ w_end = width_intervals.ends[w_idx]
+ w_left = width_intervals.left_ramps[w_idx]
+ w_right = width_intervals.right_ramps[w_idx]
+
+ t_slice, _ = map_temporal_slice(t_start, t_end, t_left, t_right, scale.time)
+ h_slice, _ = map_spatial_slice(h_start, h_end, h_left, h_right, scale.height)
+ w_slice, _ = map_spatial_slice(w_start, w_end, w_left, w_right, scale.width)
+
+ tile = video[:, :, t_slice, h_slice, w_slice]
+ encoded_tile = video_encoder(tile)
+
+ t_len = t_end - t_start
+ h_len = h_end - h_start
+ w_len = w_end - w_start
+ encoded_tile = encoded_tile[:, :, :t_len, :h_len, :w_len]
+
+ if output is None:
+ output = torch.zeros(
+ latent_shape.to_torch_shape(),
+ device=encoded_tile.device,
+ dtype=encoded_tile.dtype,
+ )
+ weights = torch.zeros(
+ (1, 1, latent_shape.frames, latent_shape.height, latent_shape.width),
+ device=encoded_tile.device,
+ dtype=encoded_tile.dtype,
+ )
+
+ mask_t = _make_mask_1d(
+ t_len,
+ t_left,
+ t_right,
+ left_starts_from_0=True,
+ device=encoded_tile.device,
+ dtype=encoded_tile.dtype,
+ )
+ mask_h = _make_mask_1d(
+ h_len,
+ h_left,
+ h_right,
+ left_starts_from_0=False,
+ device=encoded_tile.device,
+ dtype=encoded_tile.dtype,
+ )
+ mask_w = _make_mask_1d(
+ w_len,
+ w_left,
+ w_right,
+ left_starts_from_0=False,
+ device=encoded_tile.device,
+ dtype=encoded_tile.dtype,
+ )
+ mask = mask_t[:, None, None] * mask_h[None, :, None] * mask_w[None, None, :]
+ mask = mask.unsqueeze(0).unsqueeze(0)
+
+ output[:, :, t_start:t_end, h_start:h_end, w_start:w_end] += encoded_tile * mask
+ weights[:, :, t_start:t_end, h_start:h_end, w_start:w_end] += mask
+
+ if output is None or weights is None:
+ return video_encoder(video)
+ weights = weights.clamp_min(1e-6)
+ return output / weights
+
+
def get_video_chunks_number(num_frames: int, tiling_config: TilingConfig | None = None) -> int:
"""
Get the number of video chunks for a given number of frames and tiling configuration.
diff --git a/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py b/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py
index 9a89af4..ce616ff 100644
--- a/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py
+++ b/models/ltx2/ltx_core/text_encoders/gemma/embeddings_connector.py
@@ -48,7 +48,9 @@ class _BasicTransformerBlock1D(torch.nn.Module):
norm_hidden_states = norm_hidden_states.squeeze(1)
# 2. Self-Attention
- attn_output = self.attn1(norm_hidden_states, mask=attention_mask, pe=pe)
+ x_list = [norm_hidden_states]
+ del norm_hidden_states
+ attn_output = self.attn1(x_list, mask=attention_mask, pe=pe)
hidden_states = attn_output + hidden_states
if hidden_states.ndim == 4:
diff --git a/models/ltx2/ltx_core/utils.py b/models/ltx2/ltx_core/utils.py
index a7a3acb..f5f6c60 100644
--- a/models/ltx2/ltx_core/utils.py
+++ b/models/ltx2/ltx_core/utils.py
@@ -3,12 +3,23 @@ from typing import Any
import torch
-def rms_norm(x: torch.Tensor, weight: torch.Tensor | None = None, eps: float = 1e-6) -> torch.Tensor:
- """Root-mean-square (RMS) normalize `x` over its last dimension.
- Thin wrapper around `torch.nn.functional.rms_norm` that infers the normalized
- shape and forwards `weight` and `eps`.
- """
- return torch.nn.functional.rms_norm(x, (x.shape[-1],), weight=weight, eps=eps)
+def rms_norm(x: torch.Tensor, weight: torch.Tensor | None = None, eps: float = 1e-6, in_place = False) -> torch.Tensor:
+ # deepbeepmeep RMS Norm
+ dtype = x.dtype
+ y = x.float()
+ y.pow_(2)
+ y = y.mean(dim=-1, keepdim=True)
+ y += eps
+ y.rsqrt_()
+ if in_place:
+ x *= y
+ else:
+ x = x * y.to(dtype)
+ if weight is not None:
+ x *= weight
+ return x
+
+ # return torch.nn.functional.rms_norm(x, (x.shape[-1],), weight=weight, eps=eps)
def check_config_value(config: dict, key: str, expected: Any) -> None: # noqa: ANN401
diff --git a/models/ltx2/ltx_pipelines/distilled.py b/models/ltx2/ltx_pipelines/distilled.py
index 149bd68..ce70773 100644
--- a/models/ltx2/ltx_pipelines/distilled.py
+++ b/models/ltx2/ltx_pipelines/distilled.py
@@ -30,7 +30,10 @@ from .utils.helpers import (
generate_enhanced_prompt,
get_device,
image_conditionings_by_replacing_latent,
+ latent_conditionings_by_latent_sequence,
+ prepare_mask_injection,
simple_denoising_func,
+ video_conditionings_by_keyframe,
)
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
@@ -83,6 +86,8 @@ class DistilledPipeline:
num_frames: int,
frame_rate: float,
images: list[tuple[str, int, float]],
+ video_conditioning: list[tuple[str, float]] | None = None,
+ latent_conditioning_stage2: torch.Tensor | None = None,
tiling_config: TilingConfig | None = None,
enhance_prompt: bool = False,
audio_conditionings: list | None = None,
@@ -90,10 +95,14 @@ class DistilledPipeline:
interrupt_check: Callable[[], bool] | None = None,
loras_slists: dict | None = None,
text_connectors: dict | None = None,
+ masking_source: dict | None = None,
+ masking_strength: float | None = None,
+ return_latent_slice: slice | None = None,
) -> tuple[Iterator[torch.Tensor], torch.Tensor]:
assert_resolution(height=height, width=width, is_two_stage=True)
generator = torch.Generator(device=self.device).manual_seed(seed)
+ mask_generator = torch.Generator(device=self.device).manual_seed(int(seed) + 1)
noiser = GaussianNoiser(generator=generator)
stepper = EulerDiffusionStep()
dtype = torch.bfloat16
@@ -120,6 +129,7 @@ class DistilledPipeline:
video_encoder = self.model_ledger.video_encoder()
transformer = self.model_ledger.transformer()
bind_interrupt_check(transformer, interrupt_check)
+ # DISTILLED_SIGMA_VALUES = [0.421875, 0]
stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device)
pass_no = 1
if loras_slists is not None:
@@ -141,6 +151,7 @@ class DistilledPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -152,6 +163,7 @@ class DistilledPipeline:
audio_context=audio_context,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -172,8 +184,32 @@ class DistilledPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
)
+ if video_conditioning:
+ stage_1_conditionings += video_conditionings_by_keyframe(
+ video_conditioning=video_conditioning,
+ height=stage_1_output_shape.height,
+ width=stage_1_output_shape.width,
+ num_frames=num_frames,
+ video_encoder=video_encoder,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_1_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(stage_1_sigmas) - 1,
+ )
video_state, audio_state = denoise_audio_video(
output_shape=stage_1_output_shape,
conditionings=stage_1_conditionings,
@@ -185,6 +221,7 @@ class DistilledPipeline:
components=self.pipeline_components,
dtype=dtype,
device=self.device,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -220,6 +257,25 @@ class DistilledPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
+ )
+ if latent_conditioning_stage2 is not None:
+ stage_2_conditionings += latent_conditionings_by_latent_sequence(
+ latent_conditioning_stage2,
+ strength=1.0,
+ start_index=0,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_2_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(stage_2_sigmas) - 1,
)
video_state, audio_state = denoise_audio_video(
output_shape=stage_2_output_shape,
@@ -235,6 +291,7 @@ class DistilledPipeline:
noise_scale=stage_2_sigmas[0],
initial_video_latent=upscaled_video_latent,
initial_audio_latent=audio_state.latent,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -246,10 +303,15 @@ class DistilledPipeline:
del video_encoder
cleanup_memory()
+ latent_slice = None
+ if return_latent_slice is not None:
+ latent_slice = video_state.latent[:, :, return_latent_slice].detach().to("cpu")
decoded_video = vae_decode_video(video_state.latent, self.model_ledger.video_decoder(), tiling_config)
decoded_audio = vae_decode_audio(
audio_state.latent, self.model_ledger.audio_decoder(), self.model_ledger.vocoder()
)
+ if latent_slice is not None:
+ return decoded_video, decoded_audio, latent_slice
return decoded_video, decoded_audio
diff --git a/models/ltx2/ltx_pipelines/ic_lora.py b/models/ltx2/ltx_pipelines/ic_lora.py
index eb84d13..5e307ac 100644
--- a/models/ltx2/ltx_pipelines/ic_lora.py
+++ b/models/ltx2/ltx_pipelines/ic_lora.py
@@ -6,7 +6,7 @@ import torch
from ..ltx_core.components.diffusion_steps import EulerDiffusionStep
from ..ltx_core.components.noisers import GaussianNoiser
from ..ltx_core.components.protocols import DiffusionStepProtocol
-from ..ltx_core.conditioning import ConditioningItem, VideoConditionByKeyframeIndex
+from ..ltx_core.conditioning import ConditioningItem
from ..ltx_core.loader import LoraPathStrengthAndSDOps
from ..ltx_core.model.audio_vae import decode_audio as vae_decode_audio
from ..ltx_core.model.upsampler import upsample_video
@@ -31,9 +31,11 @@ from .utils.helpers import (
generate_enhanced_prompt,
get_device,
image_conditionings_by_replacing_latent,
+ prepare_mask_injection,
simple_denoising_func,
+ video_conditionings_by_keyframe,
)
-from .utils.media_io import encode_video, load_video_conditioning
+from .utils.media_io import encode_video
from .utils.types import PipelineComponents
from shared.utils.loras_mutipliers import update_loras_slists
@@ -102,10 +104,13 @@ class ICLoraPipeline:
interrupt_check: Callable[[], bool] | None = None,
loras_slists: dict | None = None,
text_connectors: dict | None = None,
+ masking_source: dict | None = None,
+ masking_strength: float | None = None,
) -> tuple[Iterator[torch.Tensor], torch.Tensor]:
assert_resolution(height=height, width=width, is_two_stage=True)
generator = torch.Generator(device=self.device).manual_seed(seed)
+ mask_generator = torch.Generator(device=self.device).manual_seed(int(seed) + 1)
noiser = GaussianNoiser(generator=generator)
stepper = EulerDiffusionStep()
dtype = torch.bfloat16
@@ -155,6 +160,7 @@ class ICLoraPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -166,6 +172,7 @@ class ICLoraPipeline:
audio_context=audio_context,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -186,6 +193,19 @@ class ICLoraPipeline:
width=stage_1_output_shape.width,
video_encoder=video_encoder,
num_frames=num_frames,
+ tiling_config=tiling_config,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_1_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(stage_1_sigmas) - 1,
)
video_state, audio_state = denoise_audio_video(
output_shape=stage_1_output_shape,
@@ -198,6 +218,7 @@ class ICLoraPipeline:
components=self.pipeline_components,
dtype=dtype,
device=self.device,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -240,6 +261,7 @@ class ICLoraPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -251,6 +273,7 @@ class ICLoraPipeline:
audio_context=audio_context,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -265,8 +288,21 @@ class ICLoraPipeline:
video_encoder=video_encoder,
dtype=self.dtype,
device=self.device,
+ tiling_config=tiling_config,
)
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_2_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(distilled_sigmas) - 1,
+ )
video_state, audio_state = denoise_audio_video(
output_shape=stage_2_output_shape,
conditionings=stage_2_conditionings,
@@ -281,6 +317,7 @@ class ICLoraPipeline:
noise_scale=distilled_sigmas[0],
initial_video_latent=upscaled_video_latent,
initial_audio_latent=audio_state.latent,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -306,6 +343,7 @@ class ICLoraPipeline:
width: int,
num_frames: int,
video_encoder: VideoEncoder,
+ tiling_config: TilingConfig | None = None,
) -> list[ConditioningItem]:
conditionings = image_conditionings_by_replacing_latent(
images=images,
@@ -314,19 +352,20 @@ class ICLoraPipeline:
video_encoder=video_encoder,
dtype=self.dtype,
device=self.device,
+ tiling_config=tiling_config,
)
- for video_path, strength in video_conditioning:
- video = load_video_conditioning(
- video_path=video_path,
+ if video_conditioning:
+ conditionings += video_conditionings_by_keyframe(
+ video_conditioning=video_conditioning,
height=height,
width=width,
- frame_cap=num_frames,
+ num_frames=num_frames,
+ video_encoder=video_encoder,
dtype=self.dtype,
device=self.device,
+ tiling_config=tiling_config,
)
- encoded_video = video_encoder(video)
- conditionings.append(VideoConditionByKeyframeIndex(keyframes=encoded_video, frame_idx=0, strength=strength))
return conditionings
diff --git a/models/ltx2/ltx_pipelines/keyframe_interpolation.py b/models/ltx2/ltx_pipelines/keyframe_interpolation.py
index 0c0afc4..466e557 100644
--- a/models/ltx2/ltx_pipelines/keyframe_interpolation.py
+++ b/models/ltx2/ltx_pipelines/keyframe_interpolation.py
@@ -32,6 +32,7 @@ from .utils.helpers import (
get_device,
guider_denoising_func,
image_conditionings_by_adding_guiding_latent,
+ prepare_mask_injection,
simple_denoising_func,
)
from .utils.media_io import encode_video
@@ -98,10 +99,13 @@ class KeyframeInterpolationPipeline:
interrupt_check: Callable[[], bool] | None = None,
loras_slists: dict | None = None,
text_connectors: dict | None = None,
+ masking_source: dict | None = None,
+ masking_strength: float | None = None,
) -> tuple[Iterator[torch.Tensor], torch.Tensor]:
assert_resolution(height=height, width=width, is_two_stage=True)
generator = torch.Generator(device=self.device).manual_seed(seed)
+ mask_generator = torch.Generator(device=self.device).manual_seed(int(seed) + 1)
noiser = GaussianNoiser(generator=generator)
stepper = EulerDiffusionStep()
cfg_guider = CFGGuider(cfg_guidance_scale)
@@ -153,6 +157,7 @@ class KeyframeInterpolationPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -167,6 +172,7 @@ class KeyframeInterpolationPipeline:
a_context_n,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -187,6 +193,19 @@ class KeyframeInterpolationPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_1_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(sigmas) - 1,
)
video_state, audio_state = denoise_audio_video(
output_shape=stage_1_output_shape,
@@ -199,6 +218,7 @@ class KeyframeInterpolationPipeline:
components=self.pipeline_components,
dtype=dtype,
device=self.device,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -241,6 +261,7 @@ class KeyframeInterpolationPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -252,6 +273,7 @@ class KeyframeInterpolationPipeline:
audio_context=a_context_p,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -266,6 +288,19 @@ class KeyframeInterpolationPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_2_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(distilled_sigmas) - 1,
)
video_state, audio_state = denoise_audio_video(
output_shape=stage_2_output_shape,
@@ -281,6 +316,7 @@ class KeyframeInterpolationPipeline:
noise_scale=distilled_sigmas[0],
initial_video_latent=upscaled_video_latent,
initial_audio_latent=audio_state.latent,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
diff --git a/models/ltx2/ltx_pipelines/ti2vid_one_stage.py b/models/ltx2/ltx_pipelines/ti2vid_one_stage.py
index ee7f38e..f575517 100644
--- a/models/ltx2/ltx_pipelines/ti2vid_one_stage.py
+++ b/models/ltx2/ltx_pipelines/ti2vid_one_stage.py
@@ -27,6 +27,7 @@ from .utils.helpers import (
get_device,
guider_denoising_func,
image_conditionings_by_replacing_latent,
+ prepare_mask_injection,
)
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
@@ -84,10 +85,13 @@ class TI2VidOneStagePipeline:
interrupt_check: Callable[[], bool] | None = None,
loras_slists: dict | None = None,
text_connectors: dict | None = None,
+ masking_source: dict | None = None,
+ masking_strength: float | None = None,
) -> tuple[Iterator[torch.Tensor], torch.Tensor]:
assert_resolution(height=height, width=width, is_two_stage=False)
generator = torch.Generator(device=self.device).manual_seed(seed)
+ mask_generator = torch.Generator(device=self.device).manual_seed(int(seed) + 1)
noiser = GaussianNoiser(generator=generator)
stepper = EulerDiffusionStep()
cfg_guider = CFGGuider(cfg_guidance_scale)
@@ -139,6 +143,7 @@ class TI2VidOneStagePipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -153,6 +158,7 @@ class TI2VidOneStagePipeline:
a_context_n,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -169,6 +175,18 @@ class TI2VidOneStagePipeline:
device=self.device,
)
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_1_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=None,
+ generator=mask_generator,
+ num_steps=len(sigmas) - 1,
+ )
video_state, audio_state = denoise_audio_video(
output_shape=stage_1_output_shape,
conditionings=stage_1_conditionings,
@@ -180,6 +198,7 @@ class TI2VidOneStagePipeline:
components=self.pipeline_components,
dtype=dtype,
device=self.device,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
diff --git a/models/ltx2/ltx_pipelines/ti2vid_two_stages.py b/models/ltx2/ltx_pipelines/ti2vid_two_stages.py
index 69c6f00..2b6a40c 100644
--- a/models/ltx2/ltx_pipelines/ti2vid_two_stages.py
+++ b/models/ltx2/ltx_pipelines/ti2vid_two_stages.py
@@ -33,7 +33,10 @@ from .utils.helpers import (
guider_denoising_func,
image_conditionings_by_adding_guiding_latent,
image_conditionings_by_replacing_latent,
+ latent_conditionings_by_latent_sequence,
+ prepare_mask_injection,
simple_denoising_func,
+ video_conditionings_by_keyframe,
)
from .utils.media_io import encode_video
from .utils.types import PipelineComponents
@@ -102,6 +105,8 @@ class TI2VidTwoStagesPipeline:
images: list[tuple[str, int, float]],
guiding_images: list[tuple[str, int, float]] | None = None,
images_stage2: list[tuple[str, int, float]] | None = None,
+ video_conditioning: list[tuple[str, float]] | None = None,
+ latent_conditioning_stage2: torch.Tensor | None = None,
tiling_config: TilingConfig | None = None,
enhance_prompt: bool = False,
audio_conditionings: list | None = None,
@@ -109,10 +114,14 @@ class TI2VidTwoStagesPipeline:
interrupt_check: Callable[[], bool] | None = None,
loras_slists: dict | None = None,
text_connectors: dict | None = None,
+ masking_source: dict | None = None,
+ masking_strength: float | None = None,
+ return_latent_slice: slice | None = None,
) -> tuple[Iterator[torch.Tensor], torch.Tensor]:
assert_resolution(height=height, width=width, is_two_stage=True)
generator = torch.Generator(device=self.device).manual_seed(seed)
+ mask_generator = torch.Generator(device=self.device).manual_seed(int(seed) + 1)
noiser = GaussianNoiser(generator=generator)
stepper = EulerDiffusionStep()
cfg_guider = CFGGuider(cfg_guidance_scale)
@@ -168,6 +177,7 @@ class TI2VidTwoStagesPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -182,6 +192,7 @@ class TI2VidTwoStagesPipeline:
a_context_n,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -202,6 +213,7 @@ class TI2VidTwoStagesPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
)
if guiding_images:
stage_1_conditionings += image_conditionings_by_adding_guiding_latent(
@@ -211,7 +223,31 @@ class TI2VidTwoStagesPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
)
+ if video_conditioning:
+ stage_1_conditionings += video_conditionings_by_keyframe(
+ video_conditioning=video_conditioning,
+ height=stage_1_output_shape.height,
+ width=stage_1_output_shape.width,
+ num_frames=num_frames,
+ video_encoder=video_encoder,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_1_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(sigmas) - 1,
+ )
video_state, audio_state = denoise_audio_video(
output_shape=stage_1_output_shape,
conditionings=stage_1_conditionings,
@@ -223,6 +259,7 @@ class TI2VidTwoStagesPipeline:
components=self.pipeline_components,
dtype=dtype,
device=self.device,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -265,6 +302,7 @@ class TI2VidTwoStagesPipeline:
audio_state: LatentState,
stepper: DiffusionStepProtocol,
preview_tools: VideoLatentTools | None = None,
+ mask_context=None,
) -> tuple[LatentState, LatentState]:
return euler_denoising_loop(
sigmas=sigmas,
@@ -276,6 +314,7 @@ class TI2VidTwoStagesPipeline:
audio_context=a_context_p,
transformer=transformer, # noqa: F821
),
+ mask_context=mask_context,
interrupt_check=interrupt_check,
callback=callback,
preview_tools=preview_tools,
@@ -291,6 +330,25 @@ class TI2VidTwoStagesPipeline:
video_encoder=video_encoder,
dtype=dtype,
device=self.device,
+ tiling_config=tiling_config,
+ )
+ if latent_conditioning_stage2 is not None:
+ stage_2_conditionings += latent_conditionings_by_latent_sequence(
+ latent_conditioning_stage2,
+ strength=1.0,
+ start_index=0,
+ )
+ mask_context = prepare_mask_injection(
+ masking_source=masking_source,
+ masking_strength=masking_strength,
+ output_shape=stage_2_output_shape,
+ video_encoder=video_encoder,
+ components=self.pipeline_components,
+ dtype=dtype,
+ device=self.device,
+ tiling_config=tiling_config,
+ generator=mask_generator,
+ num_steps=len(distilled_sigmas) - 1,
)
video_state, audio_state = denoise_audio_video(
output_shape=stage_2_output_shape,
@@ -306,6 +364,7 @@ class TI2VidTwoStagesPipeline:
noise_scale=distilled_sigmas[0],
initial_video_latent=upscaled_video_latent,
initial_audio_latent=audio_state.latent,
+ mask_context=mask_context,
)
if video_state is None or audio_state is None:
return None, None
@@ -317,11 +376,15 @@ class TI2VidTwoStagesPipeline:
del video_encoder
cleanup_memory()
+ latent_slice = None
+ if return_latent_slice is not None:
+ latent_slice = video_state.latent[:, :, return_latent_slice].detach().to("cpu")
decoded_video = vae_decode_video(video_state.latent, self.stage_2_model_ledger.video_decoder(), tiling_config)
decoded_audio = vae_decode_audio(
audio_state.latent, self.stage_2_model_ledger.audio_decoder(), self.stage_2_model_ledger.vocoder()
)
-
+ if latent_slice is not None:
+ return decoded_video, decoded_audio, latent_slice
return decoded_video, decoded_audio
diff --git a/models/ltx2/ltx_pipelines/utils/helpers.py b/models/ltx2/ltx_pipelines/utils/helpers.py
index 75ea5f5..245ffc9 100644
--- a/models/ltx2/ltx_pipelines/utils/helpers.py
+++ b/models/ltx2/ltx_pipelines/utils/helpers.py
@@ -1,10 +1,12 @@
import gc
import inspect
import logging
+import math
from collections.abc import Callable
-from dataclasses import replace
+from dataclasses import dataclass, replace
import torch
+import torch.nn.functional as F
from tqdm import tqdm
from mmgp import offload
@@ -17,12 +19,12 @@ from ...ltx_core.conditioning import (
VideoConditionByLatentIndex,
)
from ...ltx_core.model.transformer import Modality, X0Model
-from ...ltx_core.model.video_vae import VideoEncoder
+from ...ltx_core.model.video_vae import VideoEncoder, TilingConfig, encode_video as vae_encode_video
from ...ltx_core.text_encoders.gemma import GemmaTextEncoderModelBase
from ...ltx_core.tools import AudioLatentTools, LatentTools, VideoLatentTools
from ...ltx_core.types import AudioLatentShape, LatentState, VideoLatentShape, VideoPixelShape
from ...ltx_core.utils import to_denoised, to_velocity
-from .media_io import decode_image, load_image_conditioning, resize_aspect_ratio_preserving
+from .media_io import decode_image, load_image_conditioning, load_video_conditioning, resize_aspect_ratio_preserving
from .types import (
DenoisingFunc,
DenoisingLoopFunc,
@@ -49,6 +51,7 @@ def image_conditionings_by_replacing_latent(
video_encoder: VideoEncoder,
dtype: torch.dtype,
device: torch.device,
+ tiling_config: TilingConfig | None = None,
) -> list[ConditioningItem]:
conditionings = []
for image_entry in images:
@@ -65,7 +68,7 @@ def image_conditionings_by_replacing_latent(
device=device,
resample=resample,
)
- encoded_image = video_encoder(image)
+ encoded_image = vae_encode_video(image, video_encoder, tiling_config)
conditionings.append(
VideoConditionByLatentIndex(
latent=encoded_image,
@@ -84,6 +87,7 @@ def image_conditionings_by_adding_guiding_latent(
video_encoder: VideoEncoder,
dtype: torch.dtype,
device: torch.device,
+ tiling_config: TilingConfig | None = None,
) -> list[ConditioningItem]:
conditionings = []
for image_entry in images:
@@ -100,13 +104,283 @@ def image_conditionings_by_adding_guiding_latent(
device=device,
resample=resample,
)
- encoded_image = video_encoder(image)
+ encoded_image = vae_encode_video(image, video_encoder, tiling_config)
conditionings.append(
VideoConditionByKeyframeIndex(keyframes=encoded_image, frame_idx=frame_idx, strength=strength)
)
return conditionings
+def video_conditionings_by_keyframe(
+ video_conditioning: list[tuple],
+ height: int,
+ width: int,
+ num_frames: int,
+ video_encoder: VideoEncoder,
+ dtype: torch.dtype,
+ device: torch.device,
+ tiling_config: TilingConfig | None = None,
+) -> list[ConditioningItem]:
+ conditionings = []
+ for entry in video_conditioning:
+ if len(entry) == 2:
+ video_path, strength = entry
+ frame_idx = 0
+ elif len(entry) == 3:
+ video_path, frame_idx, strength = entry
+ else:
+ raise ValueError("Video conditioning entries must be (video, strength) or (video, frame_idx, strength).")
+ video = load_video_conditioning(
+ video_path=video_path,
+ height=height,
+ width=width,
+ frame_cap=num_frames,
+ dtype=dtype,
+ device=device,
+ )
+ # remove_prepend = False
+ # if frame_idx < 0:
+ # remove_prepend = True
+ # frame_idx = -frame_idx
+ # if frame_idx < 0:
+ # encoded_video = vae_encode_video(video, video_encoder, tiling_config)
+ # encoded_video = encoded_video[:, :, 1:]
+ # frame_idx = -frame_idx + 1
+ # else:
+ # encoded_video = vae_encode_video(video, video_encoder, tiling_config)
+
+ encoded_video = vae_encode_video(video, video_encoder, tiling_config)
+ cond =VideoConditionByKeyframeIndex(keyframes=encoded_video, frame_idx=frame_idx, strength=strength)
+ conditionings.append(cond)
+
+ return conditionings
+
+
+def latent_conditionings_by_latent_sequence(
+ latents: torch.Tensor,
+ strength: float = 1.0,
+ start_index: int = 0,
+) -> list[ConditioningItem]:
+ if latents.dim() == 4:
+ latents = latents.unsqueeze(0)
+ if latents.dim() != 5:
+ raise ValueError(f"Expected latent tensor with 5 dimensions; got {latents.shape}.")
+ if latents.shape[2] == 0:
+ return []
+ conditionings = []
+ for latent_idx in range(latents.shape[2]):
+ conditionings.append(
+ VideoConditionByLatentIndex(
+ latent=latents[:, :, latent_idx : latent_idx + 1],
+ strength=strength,
+ latent_idx=start_index + latent_idx,
+ )
+ )
+ return conditionings
+
+
+@dataclass(frozen=True)
+class MaskInjection:
+ mask_tokens: torch.Tensor
+ source_tokens: torch.Tensor
+ noise_tokens: torch.Tensor
+ token_slice: slice
+ masked_steps: int
+
+
+def _pixel_to_latent_index(frame_idx: int, stride: int) -> int:
+ if frame_idx <= 0:
+ return 0
+ return (frame_idx - 1) // stride + 1
+
+
+def _coerce_mask_tensor(mask: torch.Tensor) -> torch.Tensor:
+ if mask.ndim == 5:
+ if mask.shape[1] in (1, 3, 4):
+ return mask[:, :1]
+ if mask.shape[-1] in (1, 3, 4):
+ return mask.permute(0, 4, 1, 2, 3)[:, :1]
+ elif mask.ndim == 4:
+ if mask.shape[0] in (1, 3, 4):
+ return mask.unsqueeze(0)[:, :1]
+ if mask.shape[-1] in (1, 3, 4):
+ return mask.permute(3, 0, 1, 2).unsqueeze(0)[:, :1]
+ return mask.unsqueeze(1)
+ elif mask.ndim == 3:
+ if mask.shape[-1] in (1, 3, 4):
+ return mask.permute(2, 0, 1).unsqueeze(0).unsqueeze(2)[:, :1]
+ if mask.shape[0] in (1, 3, 4):
+ return mask.unsqueeze(0).unsqueeze(2)[:, :1]
+ return mask.unsqueeze(0).unsqueeze(0)
+ elif mask.ndim == 2:
+ return mask.unsqueeze(0).unsqueeze(0).unsqueeze(0)
+ raise ValueError(f"Unsupported mask tensor shape: {tuple(mask.shape)}")
+
+
+def _normalize_mask_values(mask: torch.Tensor) -> torch.Tensor:
+ mask = mask.float()
+ if mask.min() < 0.0:
+ mask = (mask + 1.0) * 0.5
+ elif mask.max() > 1.0:
+ mask = mask / 255.0
+ return mask.clamp(0.0, 1.0)
+
+
+def _resize_mask_spatial(mask: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ if mask.shape[3] == height and mask.shape[4] == width:
+ return mask
+ return F.interpolate(mask, size=(mask.shape[2], height, width), mode="nearest")
+
+
+def _mask_to_latents(mask: torch.Tensor, target_frames: int, target_h: int, target_w: int) -> torch.Tensor:
+ if target_frames <= 0 or mask.shape[2] == 0:
+ raise ValueError("Mask has no frames to map into latent space.")
+ if mask.shape[2] == 1:
+ mask = F.interpolate(mask, size=(1, target_h, target_w), mode="nearest")
+ if target_frames > 1:
+ mask = mask.expand(-1, -1, target_frames, -1, -1)
+ return mask
+ if target_frames == 1:
+ return F.interpolate(mask[:, :, :1], size=(1, target_h, target_w), mode="nearest")
+ first = F.interpolate(mask[:, :, :1], size=(1, target_h, target_w), mode="nearest")
+ rest = mask[:, :, 1:]
+ if rest.shape[2] == 0:
+ rest = torch.ones(
+ (mask.shape[0], 1, target_frames - 1, target_h, target_w),
+ device=mask.device,
+ dtype=mask.dtype,
+ )
+ else:
+ rest = F.interpolate(rest, size=(target_frames - 1, target_h, target_w), mode="nearest")
+ return torch.cat([first, rest], dim=2)
+
+
+def prepare_mask_injection( # noqa: PLR0913
+ masking_source: dict | None,
+ masking_strength: float | None,
+ output_shape: VideoPixelShape,
+ video_encoder: VideoEncoder,
+ components: PipelineComponents,
+ dtype: torch.dtype,
+ device: torch.device,
+ tiling_config: TilingConfig | None,
+ generator: torch.Generator,
+ num_steps: int,
+) -> MaskInjection | None:
+ if masking_source is None:
+ return None
+ try:
+ strength = float(masking_strength or 0.0)
+ except (TypeError, ValueError):
+ return None
+ strength = max(0.0, min(1.0, strength))
+ if strength <= 0.0 or num_steps <= 0:
+ return None
+ masked_steps = min(num_steps, int(math.ceil(num_steps * strength)))
+ if masked_steps <= 0:
+ return None
+
+ video = masking_source.get("video")
+ mask = masking_source.get("mask")
+ if video is None or mask is None:
+ return None
+ start_frame = int(masking_source.get("start_frame") or 0)
+
+ video_tensor = load_video_conditioning(
+ video_path=video,
+ height=output_shape.height,
+ width=output_shape.width,
+ frame_cap=None,
+ dtype=dtype,
+ device=device,
+ )
+
+ mask_tensor = _coerce_mask_tensor(mask).to(device=device)
+ mask_tensor = _normalize_mask_values(mask_tensor)
+ if mask_tensor.shape[0] != video_tensor.shape[0]:
+ if mask_tensor.shape[0] == 1:
+ mask_tensor = mask_tensor.expand(video_tensor.shape[0], -1, -1, -1, -1)
+ else:
+ return None
+ mask_tensor = _resize_mask_spatial(mask_tensor, output_shape.height, output_shape.width)
+ if mask_tensor.shape[2] < video_tensor.shape[2]:
+ pad_frames = video_tensor.shape[2] - mask_tensor.shape[2]
+ pad = torch.ones(
+ (mask_tensor.shape[0], 1, pad_frames, mask_tensor.shape[3], mask_tensor.shape[4]),
+ device=mask_tensor.device,
+ dtype=mask_tensor.dtype,
+ )
+ mask_tensor = torch.cat([mask_tensor, pad], dim=2)
+ elif mask_tensor.shape[2] > video_tensor.shape[2]:
+ mask_tensor = mask_tensor[:, :, : video_tensor.shape[2]]
+ if video_tensor.shape[2] == 0 or mask_tensor.shape[2] == 0:
+ return None
+
+ source_latents = vae_encode_video(video_tensor, video_encoder, tiling_config).to(device=device, dtype=dtype)
+ try:
+ mask_latents = _mask_to_latents(
+ mask_tensor, source_latents.shape[2], source_latents.shape[3], source_latents.shape[4]
+ )
+ except ValueError:
+ return None
+ mask_latents = (mask_latents >= 0.5).to(dtype)
+
+ output_latent_shape = VideoLatentShape.from_pixel_shape(
+ shape=output_shape,
+ latent_channels=components.video_latent_channels,
+ scale_factors=components.video_scale_factors,
+ )
+ start_latent = _pixel_to_latent_index(start_frame, components.video_scale_factors.time)
+ if start_latent >= output_latent_shape.frames:
+ return None
+ available_frames = output_latent_shape.frames - start_latent
+ control_frames = min(source_latents.shape[2], available_frames)
+ if control_frames <= 0:
+ return None
+ source_latents = source_latents[:, :, :control_frames]
+ mask_latents = mask_latents[:, :, :control_frames]
+
+ source_tokens = components.video_patchifier.patchify(source_latents)
+ mask_tokens = components.video_patchifier.patchify(mask_latents).to(dtype=source_tokens.dtype)
+ noise_tokens = torch.randn(
+ source_tokens.shape,
+ device=source_tokens.device,
+ dtype=source_tokens.dtype,
+ generator=generator,
+ )
+
+ patch_t, patch_h, patch_w = components.video_patchifier.patch_size
+ if patch_t != 1:
+ raise ValueError("Mask injection expects temporal patch size of 1.")
+ tokens_per_frame = (output_latent_shape.height // patch_h) * (output_latent_shape.width // patch_w)
+ token_offset = start_latent * tokens_per_frame
+ token_count = control_frames * tokens_per_frame
+ token_slice = slice(token_offset, token_offset + token_count)
+
+ return MaskInjection(
+ mask_tokens=mask_tokens,
+ source_tokens=source_tokens,
+ noise_tokens=noise_tokens,
+ token_slice=token_slice,
+ masked_steps=masked_steps,
+ )
+
+
+def _apply_mask_injection(
+ video_state: LatentState,
+ sigmas: torch.Tensor,
+ step_idx: int,
+ mask_context: MaskInjection,
+) -> None:
+ if step_idx >= mask_context.masked_steps:
+ return
+ sigma_next = sigmas[step_idx + 1].to(mask_context.source_tokens.dtype)
+ token_slice = mask_context.token_slice
+ current = video_state.latent[:, token_slice]
+ noisy_source = mask_context.noise_tokens * sigma_next + (1 - sigma_next) * mask_context.source_tokens
+ video_state.latent[:, token_slice] = noisy_source * (1 - mask_context.mask_tokens) + mask_context.mask_tokens * current
+
+
def euler_denoising_loop(
sigmas: torch.Tensor,
video_state: LatentState,
@@ -114,6 +388,7 @@ def euler_denoising_loop(
stepper: DiffusionStepProtocol,
denoise_fn: DenoisingFunc,
*,
+ mask_context: MaskInjection | None = None,
interrupt_check: Callable[[], bool] | None = None,
callback: Callable[..., None] | None = None,
preview_tools: VideoLatentTools | None = None,
@@ -162,6 +437,8 @@ def euler_denoising_loop(
video_state = replace(video_state, latent=stepper.step(video_state.latent, denoised_video, sigmas, step_idx))
audio_state = replace(audio_state, latent=stepper.step(audio_state.latent, denoised_audio, sigmas, step_idx))
+ if mask_context is not None:
+ _apply_mask_injection(video_state, sigmas, step_idx, mask_context)
_invoke_callback(callback, step_idx, pass_no, video_state, preview_tools)
return (video_state, audio_state)
@@ -175,6 +452,7 @@ def gradient_estimating_euler_denoising_loop(
denoise_fn: DenoisingFunc,
ge_gamma: float = 2.0,
*,
+ mask_context: MaskInjection | None = None,
interrupt_check: Callable[[], bool] | None = None,
callback: Callable[..., None] | None = None,
preview_tools: VideoLatentTools | None = None,
@@ -239,6 +517,8 @@ def gradient_estimating_euler_denoising_loop(
video_state = replace(video_state, latent=stepper.step(video_state.latent, denoised_video, sigmas, step_idx))
audio_state = replace(audio_state, latent=stepper.step(audio_state.latent, denoised_audio, sigmas, step_idx))
+ if mask_context is not None:
+ _apply_mask_injection(video_state, sigmas, step_idx, mask_context)
_invoke_callback(callback, step_idx, pass_no, video_state, preview_tools)
return (video_state, audio_state)
@@ -503,6 +783,7 @@ def denoise_audio_video( # noqa: PLR0913
noise_scale: float = 1.0,
initial_video_latent: torch.Tensor | None = None,
initial_audio_latent: torch.Tensor | None = None,
+ mask_context: MaskInjection | None = None,
) -> tuple[LatentState | None, LatentState | None]:
video_state, video_tools = noise_video_state(
output_shape=output_shape,
@@ -528,6 +809,8 @@ def denoise_audio_video( # noqa: PLR0913
loop_kwargs = {}
if "preview_tools" in inspect.signature(denoising_loop_fn).parameters:
loop_kwargs["preview_tools"] = video_tools
+ if "mask_context" in inspect.signature(denoising_loop_fn).parameters:
+ loop_kwargs["mask_context"] = mask_context
video_state, audio_state = denoising_loop_fn(
sigmas,
video_state,
diff --git a/models/ltx2/ltx_pipelines/utils/media_io.py b/models/ltx2/ltx_pipelines/utils/media_io.py
index 8bbde44..f80da9e 100644
--- a/models/ltx2/ltx_pipelines/utils/media_io.py
+++ b/models/ltx2/ltx_pipelines/utils/media_io.py
@@ -141,6 +141,32 @@ def _normalize_image_tensor(image: torch.Tensor) -> torch.Tensor:
raise ValueError(f"Unsupported image tensor shape: {tuple(image.shape)}")
+def _coerce_video_input(video_input: object) -> torch.Tensor:
+ if isinstance(video_input, Image.Image):
+ image = np.array(video_input)[..., :3]
+ return torch.tensor(image, dtype=torch.float32)
+ if isinstance(video_input, np.ndarray):
+ return torch.tensor(video_input, dtype=torch.float32)
+ if torch.is_tensor(video_input):
+ return video_input.detach().clone().to(dtype=torch.float32)
+ raise TypeError(f"Unsupported video input type: {type(video_input)}")
+
+
+def _normalize_video_tensor(video: torch.Tensor) -> torch.Tensor:
+ if video.ndim == 3:
+ if video.shape[-1] in (1, 3, 4):
+ return video.unsqueeze(0)
+ if video.shape[0] in (1, 3, 4):
+ return video.permute(1, 2, 0).unsqueeze(0)
+ if video.ndim == 4:
+ if video.shape[-1] in (1, 3, 4):
+ return video
+ if video.shape[0] in (1, 3, 4):
+ return video.permute(1, 2, 3, 0)
+ if video.shape[1] in (1, 3, 4):
+ return video.permute(0, 2, 3, 1)
+ raise ValueError(f"Unsupported video tensor shape: {tuple(video.shape)}")
+
def _scale_to_255(image: torch.Tensor) -> torch.Tensor:
if not torch.is_floating_point(image):
return image.to(dtype=torch.float32)
@@ -180,19 +206,34 @@ def load_image_conditioning(
def load_video_conditioning(
- video_path: str, height: int, width: int, frame_cap: int, dtype: torch.dtype, device: torch.device
+ video_path: str | torch.Tensor | np.ndarray | Image.Image,
+ height: int,
+ width: int,
+ frame_cap: int,
+ dtype: torch.dtype,
+ device: torch.device,
) -> torch.Tensor:
"""
- Loads a video from a path and preprocesses it for conditioning.
+ Loads a video from a path or tensor and preprocesses it for conditioning.
Note: The video is resized to the nearest multiple of 2 for compatibility with video codecs.
"""
- frames = decode_video_from_file(path=video_path, frame_cap=frame_cap, device=device)
- result = None
- for f in frames:
- frame = resize_and_center_crop(f.to(torch.float32), height, width)
- frame = normalize_latent(frame, device, dtype)
- result = frame if result is None else torch.cat([result, frame], dim=2)
- return result
+ if isinstance(video_path, str):
+ frames = decode_video_from_file(path=video_path, frame_cap=frame_cap, device=device)
+ result = None
+ for f in frames:
+ frame = resize_and_center_crop(f.to(torch.float32), height, width)
+ frame = normalize_latent(frame, device, dtype)
+ result = frame if result is None else torch.cat([result, frame], dim=2)
+ return result
+
+ video = _coerce_video_input(video_path)
+ video = _normalize_video_tensor(video)
+ if frame_cap is not None and video.shape[0] > frame_cap:
+ video = video[:frame_cap]
+ video = _scale_to_255(video)
+ video = video.to(device=device)
+ video = resize_and_center_crop(video, height, width)
+ return normalize_latent(video, device, dtype)
def decode_image(image_path: str) -> np.ndarray:
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index 7305bc7..57ad809 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -30,7 +30,12 @@ from .modules.clip import CLIPModel
from shared.utils.fm_solvers import (FlowDPMSolverMultistepScheduler,
get_sampling_sigmas, retrieve_timesteps)
from shared.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
-from .modules.posemb_layers import get_rotary_pos_embed, get_nd_rotary_pos_embed
+from .modules.posemb_layers import (
+ get_rotary_pos_embed,
+ get_nd_rotary_pos_embed,
+ set_rope_freqs_dtype,
+ set_use_fp32_rope_freqs,
+)
from shared.utils.vace_preprocessor import VaceVideoProcessor
from shared.utils.basic_flowmatch import FlowMatchScheduler
from shared.utils.lcm_scheduler import LCMScheduler
@@ -42,6 +47,8 @@ from shared.utils.audio_video import save_video
from mmgp import safetensors2
from shared.utils import files_locator as fl
+WAN_USE_FP32_ROPE_FREQS = True
+
def optimized_scale(positive_flat, negative_flat):
# Calculate dot production
@@ -215,6 +222,10 @@ class WanAny2V:
save_quantized_model(self.model2, model_type, model_filename[1], dtype, base_config_file, submodel_no=2)
self.sample_neg_prompt = config.sample_neg_prompt
+ self.use_fp32_rope_freqs = bool(model_def.get("wan_rope_freqs_fp32", WAN_USE_FP32_ROPE_FREQS))
+ set_use_fp32_rope_freqs(self.use_fp32_rope_freqs)
+ set_rope_freqs_dtype(self.dtype)
+
self.model.apply_post_init_changes()
if self.model2 is not None: self.model2.apply_post_init_changes()
diff --git a/models/wan/modules/posemb_layers.py b/models/wan/modules/posemb_layers.py
index 8a99893..c0544cc 100644
--- a/models/wan/modules/posemb_layers.py
+++ b/models/wan/modules/posemb_layers.py
@@ -3,6 +3,33 @@ from typing import Union, Tuple, List, Optional
import numpy as np
+USE_FP32_ROPE_FREQS = True
+ROPE_FREQS_DTYPE = torch.bfloat16
+
+
+def set_use_fp32_rope_freqs(enabled: bool) -> None:
+ global USE_FP32_ROPE_FREQS
+ USE_FP32_ROPE_FREQS = bool(enabled)
+
+
+def set_rope_freqs_dtype(dtype: torch.dtype) -> None:
+ global ROPE_FREQS_DTYPE
+ ROPE_FREQS_DTYPE = dtype
+
+
+def _rope_freqs_dtype() -> torch.dtype:
+ return torch.float32 if USE_FP32_ROPE_FREQS else ROPE_FREQS_DTYPE
+
+
+def _coerce_rope_positions(pos):
+ rope_dtype = _rope_freqs_dtype()
+ if isinstance(pos, int):
+ return torch.arange(pos, dtype=rope_dtype)
+ if isinstance(pos, np.ndarray):
+ return torch.from_numpy(pos).to(dtype=rope_dtype)
+ return pos.to(dtype=rope_dtype)
+
+
###### Thanks to the RifleX project (https://github.com/thu-ml/RIFLEx/) for this alternative pos embed for long videos
#
def get_1d_rotary_pos_embed_riflex(
@@ -34,13 +61,10 @@ def get_1d_rotary_pos_embed_riflex(
"""
assert dim % 2 == 0
- if isinstance(pos, int):
- pos = torch.arange(pos)
- if isinstance(pos, np.ndarray):
- pos = torch.from_numpy(pos) # type: ignore # [S]
+ pos = _coerce_rope_positions(pos)
freqs = 1.0 / (
- theta ** (torch.arange(0, dim, 2, device=pos.device)[: (dim // 2)].float() / dim)
+ theta ** (torch.arange(0, dim, 2, device=pos.device, dtype=pos.dtype)[: (dim // 2)] / dim)
) # [D/2]
# === Riflex modification start ===
@@ -53,8 +77,8 @@ def get_1d_rotary_pos_embed_riflex(
freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
if use_real:
- freqs_cos = freqs.cos().repeat_interleave(2, dim=1).float() # [S, D]
- freqs_sin = freqs.sin().repeat_interleave(2, dim=1).float() # [S, D]
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
return freqs_cos, freqs_sin
else:
# lumina
@@ -100,7 +124,7 @@ def _to_tuple(x, dim=2):
raise ValueError(f"Expected length {dim} or int, but got {x}")
-def get_meshgrid_nd(start, *args, dim=2):
+def get_meshgrid_nd(start, *args, dim=2, dtype=None, device=None):
"""
Get n-D meshgrid with start, stop and num.
@@ -115,6 +139,7 @@ def get_meshgrid_nd(start, *args, dim=2):
Returns:
grid (np.ndarray): [dim, ...]
"""
+ grid_dtype = torch.float32 if dtype is None else dtype
if len(args) == 0:
# start is grid_size
num = _to_tuple(start, dim=dim)
@@ -138,9 +163,9 @@ def get_meshgrid_nd(start, *args, dim=2):
for i in range(dim):
a, b, n = start[i], stop[i], num[i]
if a == b:
- g = torch.tensor([a], dtype=torch.float32 )
+ g = torch.tensor([a], dtype=grid_dtype, device=device)
else:
- g = torch.linspace(a, b, n + 1, dtype=torch.float32)[:n]
+ g = torch.linspace(a, b, n + 1, dtype=grid_dtype, device=device)[:n]
axis_grid.append(g)
grid = torch.meshgrid(*axis_grid, indexing="ij") # dim x [W, H, D]
grid = torch.stack(grid, dim=0) # [dim, W, H, D]
@@ -222,11 +247,26 @@ def reshape_for_broadcast(
return freqs_cis.view(*shape)
-def rotate_half(x):
- x_real, x_imag = (
- x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
- ) # [B, S, H, D//2]
- return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
+
+def _apply_rope_inplace_inner(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> None:
+ x_view = x.view(*x.shape[:-1], -1, 2)
+ cos_view = cos.view(*cos.shape[:-1], -1, 2)
+ sin_view = sin.view(*sin.shape[:-1], -1, 2)
+ x0 = x_view[..., 0]
+ x1 = x_view[..., 1]
+ x0_orig = x0.clone()
+ x0.mul_(cos_view[..., 0]).addcmul_(x1, sin_view[..., 0], value=-1)
+ x1.mul_(cos_view[..., 1]).addcmul_(x0_orig, sin_view[..., 1])
+
+
+def _apply_rope_inplace(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, use_fp32: bool) -> torch.Tensor:
+ if use_fp32 and x.dtype != torch.float32:
+ x_work = x.to(torch.float32)
+ _apply_rope_inplace_inner(x_work, cos, sin)
+ x.copy_(x_work.to(x.dtype))
+ return x
+ _apply_rope_inplace_inner(x, cos, sin)
+ return x
def apply_rotary_emb_single( qklist,
freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
@@ -234,21 +274,15 @@ def apply_rotary_emb_single( qklist,
):
xq = qklist[0]
qklist.clear()
- xk_out = None
cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
- cos, sin = cos.to(xq.device), sin.to(xq.device)
- # real * cos - imag * sin
- # imag * cos + real * sin
- xq_dtype = xq.dtype
- xq_out = xq.to(torch.float)
- xq = None
- xq_rot = rotate_half(xq_out)
- xq_out *= cos
- xq_rot *= sin
- xq_out += xq_rot
- del xq_rot
- xq_out = xq_out.to(xq_dtype)
- return xq_out
+ use_fp32 = USE_FP32_ROPE_FREQS
+ target_dtype = torch.float32 if use_fp32 else xq.dtype
+ if cos.device != xq.device or cos.dtype != target_dtype:
+ cos = cos.to(device=xq.device, dtype=target_dtype)
+ if sin.device != xq.device or sin.dtype != target_dtype:
+ sin = sin.to(device=xq.device, dtype=target_dtype)
+ _apply_rope_inplace(xq, cos, sin, use_fp32)
+ return xq
def apply_rotary_emb( qklist,
@@ -275,30 +309,18 @@ def apply_rotary_emb( qklist,
"""
xq, xk = qklist
qklist.clear()
- xk_out = None
if isinstance(freqs_cis, tuple):
cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
- cos, sin = cos.to(xq.device), sin.to(xq.device)
- # real * cos - imag * sin
- # imag * cos + real * sin
- xq_dtype = xq.dtype
- xq_out = xq.to(torch.float)
- xq = None
- xq_rot = rotate_half(xq_out)
- xq_out *= cos
- xq_rot *= sin
- xq_out += xq_rot
- del xq_rot
- xq_out = xq_out.to(xq_dtype)
-
- xk_out = xk.to(torch.float)
- xk = None
- xk_rot = rotate_half(xk_out)
- xk_out *= cos
- xk_rot *= sin
- xk_out += xk_rot
- del xk_rot
- xk_out = xk_out.to(xq_dtype)
+ use_fp32 = USE_FP32_ROPE_FREQS
+ target_dtype = torch.float32 if use_fp32 else xq.dtype
+ if cos.device != xq.device or cos.dtype != target_dtype:
+ cos = cos.to(device=xq.device, dtype=target_dtype)
+ if sin.device != xq.device or sin.dtype != target_dtype:
+ sin = sin.to(device=xq.device, dtype=target_dtype)
+ _apply_rope_inplace(xq, cos, sin, use_fp32)
+ _apply_rope_inplace(xk, cos, sin, use_fp32)
+ xq_out = xq
+ xk_out = xk
else:
# view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex)
xq_ = torch.view_as_complex(
@@ -359,7 +381,7 @@ def get_nd_rotary_pos_embed(
), "sum(rope_dim_list) should equal to head_dim of attention layer"
grid = get_meshgrid_nd(
- start, *args, dim=len(rope_dim_list)
+ start, *args, dim=len(rope_dim_list), dtype=_rope_freqs_dtype()
) # [3, W, H, D] / [2, W, H]
if isinstance(theta_rescale_factor, int) or isinstance(theta_rescale_factor, float):
@@ -437,8 +459,7 @@ def get_1d_rotary_pos_embed(
freqs_cis: Precomputed frequency tensor with complex exponential. [S, D/2]
freqs_cos, freqs_sin: Precomputed frequency tensor with real and imaginary parts separately. [S, D]
"""
- if isinstance(pos, int):
- pos = torch.arange(pos).float()
+ pos = _coerce_rope_positions(pos)
# proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
# has some connection to NTK literature
@@ -446,7 +467,7 @@ def get_1d_rotary_pos_embed(
theta *= theta_rescale_factor ** (dim / (dim - 2))
freqs = 1.0 / (
- theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
+ theta ** (torch.arange(0, dim, 2, device=pos.device, dtype=pos.dtype)[: (dim // 2)] / dim)
) # [D/2]
# assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}"
freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2]
@@ -493,4 +514,4 @@ def get_rotary_pos_embed(latents_size, enable_RIFLEx = False):
L_test = latents_size[0],
enable_riflex = enable_RIFLEx
)
- return (freqs_cos, freqs_sin)
\ No newline at end of file
+ return (freqs_cos, freqs_sin)
diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.py
index 6a90c31..43bc399 100644
--- a/models/wan/wan_handler.py
+++ b/models/wan/wan_handler.py
@@ -194,6 +194,8 @@ class family_handler():
extra_model_def = {}
if "URLs2" in model_def:
extra_model_def["no_steps_skipping"] = True
+ extra_model_def["compile"] = ["transformer","transformer2"]
+
extra_model_def["i2v_class"] = i2v = test_class_i2v(base_model_type)
extra_model_def["t2v_class"] = t2v = test_class_t2v(base_model_type)
extra_model_def["multitalk_class"] = multitalk = test_multitalk(base_model_type)
diff --git a/plugins/wan2gp-configuration/plugin.py b/plugins/wan2gp-configuration/plugin.py
index aeb8e4e..727daab 100644
--- a/plugins/wan2gp-configuration/plugin.py
+++ b/plugins/wan2gp-configuration/plugin.py
@@ -140,7 +140,7 @@ class ConfigTabPlugin(WAN2GPPlugin):
)
with gr.Tab("Performance"):
- self.quantization_choice = gr.Dropdown(choices=[("Scaled Int8/Fp8 (recommended)", "int8"), ("16-bit (no quantization)", "bf16")], value=self.transformer_quantization, label="Transformer Model Quantization (if available)")
+ self.quantization_choice = gr.Dropdown(choices=[("Scaled Int8 (recommended)", "int8"), ("Scaled Fp8", "fp8"), ("16-bit (no quantization)", "bf16")], value=self.transformer_quantization, label="Transformer Model Quantization (if available otherwise get the closest available)")
self.transformer_dtype_policy_choice = gr.Dropdown(choices=[("Auto (Best for Hardware)", ""), ("FP16", "fp16"), ("BF16", "bf16")], value=self.transformer_dtype_policy, label="Transformer Data Type (if available)")
self.mixed_precision_choice = gr.Dropdown(choices=[("16-bit only (less VRAM)", "0"), ("Mixed 16/32-bit (better quality)", "1")], value=self.server_config.get("mixed_precision", "0"), label="Transformer Engine Precision")
self.text_encoder_quantization_choice = gr.Dropdown(choices=[("16-bit (more RAM, better quality)", "bf16"), ("8-bit (less RAM, slightly lower quality)", "int8")], value=self.text_encoder_quantization, label="Text Encoder Precision")
diff --git a/shared/qtypes/nvfp4.py b/shared/qtypes/nvfp4.py
index 62cf336..b772abb 100644
--- a/shared/qtypes/nvfp4.py
+++ b/shared/qtypes/nvfp4.py
@@ -1,4 +1,5 @@
import ast
+import os
import torch
from torch.utils import _pytree as pytree
@@ -6,13 +7,31 @@ from optimum.quanto import QModuleMixin
from optimum.quanto.tensor.qtensor import QTensor
from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quanto_qtypes
+def _maybe_add_nvfp4_cu13_dll_dir():
+ if os.name != "nt":
+ return
+ try:
+ import nvidia.cu13
+ dll_dir = os.path.join(nvidia.cu13.__path__[0], "bin", "x86_64")
+ if os.path.isdir(dll_dir):
+ os.add_dll_directory(dll_dir)
+ except Exception:
+ pass
+
+try:
+ from comfy_kitchen.backends import cuda as _ck_cuda
+ _ck_cuda_available = getattr(_ck_cuda, "_EXT_AVAILABLE", False)
+except Exception:
+ _ck_cuda = None
+ _ck_cuda_available = False
+
try:
- from lightx2v_kernel.gemm import scaled_nvfp4_quant, cutlass_scaled_nvfp4_mm
- _KERNEL_AVAILABLE = True
+ _maybe_add_nvfp4_cu13_dll_dir()
+ from lightx2v_kernel import gemm as _lx_gemm
+ _lx_gemm_available = True
except Exception:
- scaled_nvfp4_quant = None
- cutlass_scaled_nvfp4_mm = None
- _KERNEL_AVAILABLE = False
+ _lx_gemm = None
+ _lx_gemm_available = False
_NVFP4_QTYPE_NAME = "nvfp4"
if _NVFP4_QTYPE_NAME not in _quanto_qtypes:
@@ -26,13 +45,363 @@ if _NVFP4_QTYPE_NAME not in _quanto_qtypes:
)
_NVFP4_QTYPE = _quanto_qtypes[_NVFP4_QTYPE_NAME]
-def _supports_nvfp4_kernel(device):
- if not _KERNEL_AVAILABLE:
+_NVFP4_LAYOUT_LEGACY = "legacy"
+_NVFP4_LAYOUT_TENSORCORE = "tensorcore"
+
+_NVFP4_BACKEND_AUTO = "auto"
+_NVFP4_BACKEND_COMFY = "comfy"
+_NVFP4_BACKEND_LIGHTX2V = "lightx2v"
+
+_NVFP4_KERNEL_LOGGED = False
+_NVFP4_FALLBACK_LOGGED = False
+_NVFP4_LOAD_LOGGED = False
+_NVFP4_KERNEL_AVAILABLE = False
+_NVFP4_KERNEL_CHECKED = False
+_NVFP4_KERNEL_BACKEND = None
+_NVFP4_ACT_SCALE_CACHE = {}
+
+_NVFP4_BACKEND = os.environ.get("WGP_NVFP4_BACKEND", _NVFP4_BACKEND_AUTO).strip().lower()
+_NVFP4_BACKEND = _NVFP4_BACKEND_LIGHTX2V
+
+def _normalize_nvfp4_backend(name):
+ if name is None:
+ return _NVFP4_BACKEND_AUTO
+ norm = str(name).strip().lower()
+ if norm in ("", "auto", "default"):
+ return _NVFP4_BACKEND_AUTO
+ if norm in ("comfy", "comfy-kitchen", "comfy_kitchen", "ck"):
+ return _NVFP4_BACKEND_COMFY
+ if norm in ("lightx2v", "lightx2v_kernel", "lightx2v-kernel", "lx"):
+ return _NVFP4_BACKEND_LIGHTX2V
+ if norm in ("off", "none", "fallback", "disable", "disabled"):
+ return "fallback"
+ return norm
+
+
+_NVFP4_BACKEND = _normalize_nvfp4_backend(_NVFP4_BACKEND)
+
+
+def _nvfp4_backend_candidates():
+ if _NVFP4_BACKEND == _NVFP4_BACKEND_AUTO:
+ return [_NVFP4_BACKEND_COMFY, _NVFP4_BACKEND_LIGHTX2V]
+ if _NVFP4_BACKEND in (_NVFP4_BACKEND_COMFY, _NVFP4_BACKEND_LIGHTX2V):
+ return [_NVFP4_BACKEND]
+ return []
+
+
+def _nvfp4_backend_label(backend):
+ if backend == _NVFP4_BACKEND_LIGHTX2V:
+ return "lightx2v"
+ if backend == _NVFP4_BACKEND_COMFY:
+ return "comfy-kitchen"
+ return backend
+
+
+def _nvfp4_lightx2v_device_ok(device):
+ force = os.environ.get("WGP_NVFP4_LIGHTX2V_FORCE", "").strip().lower()
+ if force in ("1", "true", "yes", "y"):
+ return True
+ try:
+ props = torch.cuda.get_device_properties(device)
+ except Exception:
return False
+ return props.major >= 12
+
+
+def set_nvfp4_backend(name):
+ global _NVFP4_BACKEND, _NVFP4_KERNEL_CHECKED, _NVFP4_KERNEL_AVAILABLE, _NVFP4_KERNEL_BACKEND
+ global _NVFP4_KERNEL_LOGGED, _NVFP4_LOAD_LOGGED
+ _NVFP4_BACKEND = _normalize_nvfp4_backend(name)
+ _NVFP4_KERNEL_CHECKED = False
+ _NVFP4_KERNEL_AVAILABLE = False
+ _NVFP4_KERNEL_BACKEND = None
+ _NVFP4_KERNEL_LOGGED = False
+ _NVFP4_LOAD_LOGGED = False
+ _init_nvfp4_kernel_support()
+
+
+def _nvfp4_note_kernel():
+ global _NVFP4_KERNEL_LOGGED
+ if not _NVFP4_KERNEL_LOGGED:
+ label = _nvfp4_backend_label(_NVFP4_KERNEL_BACKEND) if _NVFP4_KERNEL_BACKEND else "CUDA"
+ print(f"NVFP4: using {label} kernel")
+ _NVFP4_KERNEL_LOGGED = True
+
+
+def _nvfp4_note_fallback():
+ global _NVFP4_FALLBACK_LOGGED
+ if not _NVFP4_FALLBACK_LOGGED:
+ print("NVFP4: linear fallback (dequantize)")
+ _NVFP4_FALLBACK_LOGGED = True
+
+
+def _nvfp4_note_load_backend():
+ global _NVFP4_LOAD_LOGGED
+ if _NVFP4_LOAD_LOGGED:
+ return
+ _NVFP4_LOAD_LOGGED = True
+ if _NVFP4_KERNEL_AVAILABLE:
+ label = _nvfp4_backend_label(_NVFP4_KERNEL_BACKEND) if _NVFP4_KERNEL_BACKEND else "unknown"
+ print(f"NVFP4: kernels available ({label}); optimized path will be used when compatible.")
+ else:
+ print("NVFP4: kernels unavailable; using dequantize fallback.")
+
+
+def _check_nvfp4_kernel_support(device, backend):
if device.type != "cuda":
return False
- major, _ = torch.cuda.get_device_capability(device)
- return major >= 12
+ if backend == _NVFP4_BACKEND_COMFY:
+ if not _ck_cuda_available:
+ return False
+ if not hasattr(_ck_cuda, "scaled_mm_nvfp4"):
+ return False
+ if not hasattr(_ck_cuda, "quantize_nvfp4"):
+ return False
+ if not (hasattr(torch.ops, "comfy_kitchen") and hasattr(torch.ops.comfy_kitchen, "scaled_mm_nvfp4")):
+ return False
+ major, minor = torch.cuda.get_device_capability(device)
+ return (major, minor) >= (10, 0)
+ if backend == _NVFP4_BACKEND_LIGHTX2V:
+ if not _lx_gemm_available:
+ return False
+ if not _nvfp4_lightx2v_device_ok(device):
+ return False
+ if not (hasattr(torch.ops, "lightx2v_kernel") and hasattr(torch.ops.lightx2v_kernel, "cutlass_scaled_nvfp4_mm_sm120")):
+ return False
+ if not hasattr(torch.ops.lightx2v_kernel, "scaled_nvfp4_quant_sm120"):
+ return False
+ major, minor = torch.cuda.get_device_capability(device)
+ return (major, minor) >= (12, 0)
+ return False
+
+
+def _init_nvfp4_kernel_support():
+ global _NVFP4_KERNEL_AVAILABLE, _NVFP4_KERNEL_CHECKED, _NVFP4_KERNEL_BACKEND
+ if _NVFP4_KERNEL_CHECKED:
+ return
+ _NVFP4_KERNEL_CHECKED = True
+ _NVFP4_KERNEL_AVAILABLE = False
+ _NVFP4_KERNEL_BACKEND = None
+ if not torch.cuda.is_available():
+ return
+ device = torch.device("cuda")
+ for backend in _nvfp4_backend_candidates():
+ try:
+ if _check_nvfp4_kernel_support(device, backend):
+ _NVFP4_KERNEL_AVAILABLE = True
+ _NVFP4_KERNEL_BACKEND = backend
+ break
+ except Exception:
+ continue
+
+
+def _supports_nvfp4_kernel(device):
+ if device.type != "cuda":
+ return False
+ if not _NVFP4_KERNEL_CHECKED:
+ _init_nvfp4_kernel_support()
+ return _NVFP4_KERNEL_AVAILABLE
+
+
+_init_nvfp4_kernel_support()
+
+
+def _nvfp4_layout(weight):
+ return getattr(weight, "_layout", _NVFP4_LAYOUT_LEGACY)
+
+
+def _nvfp4_can_use_kernel(input, weight):
+ if not torch.is_tensor(input):
+ return False
+ if not getattr(weight, "_allow_kernel", True):
+ return False
+ if not _supports_nvfp4_kernel(input.device):
+ return False
+ backend = _NVFP4_KERNEL_BACKEND
+ if backend is None:
+ return False
+ layout = _nvfp4_layout(weight)
+ if backend == _NVFP4_BACKEND_LIGHTX2V:
+ if input.shape[-1] % 32 != 0:
+ return False
+ if weight.size(0) % 32 != 0:
+ return False
+ else:
+ if layout == _NVFP4_LAYOUT_LEGACY:
+ if input.shape[-1] % 64 != 0:
+ return False
+ else:
+ if input.shape[-1] % 16 != 0:
+ return False
+ if weight.size(0) % 8 != 0:
+ return False
+ if weight._data.shape[1] * 2 != input.shape[-1]:
+ return False
+ if weight._block_size != 16:
+ return False
+ if not torch.is_tensor(weight._input_global_scale) or not torch.is_tensor(weight._alpha):
+ return False
+ if getattr(weight._input_global_scale, "is_meta", False):
+ return False
+ try:
+ if not torch.isfinite(weight._input_global_scale).all():
+ return False
+ except Exception:
+ return False
+ return True
+
+
+def _nvfp4_get_act_scale(device):
+ act_scale = _NVFP4_ACT_SCALE_CACHE.get(device)
+ if act_scale is None:
+ act_scale = torch.tensor(1.0, device=device, dtype=torch.float32)
+ _NVFP4_ACT_SCALE_CACHE[device] = act_scale
+ return act_scale
+
+
+def _nvfp4_swap_nibbles(tensor):
+ return ((tensor & 0x0F) << 4) | ((tensor & 0xF0) >> 4)
+
+
+def _nvfp4_linear_cuda_comfy(input, weight, bias=None):
+ _nvfp4_note_kernel()
+ x2d = input.reshape(-1, input.shape[-1])
+ if not x2d.is_floating_point():
+ x2d = x2d.to(torch.float16)
+ orig_dtype = x2d.dtype
+ if orig_dtype not in (torch.float16, torch.bfloat16):
+ x2d = x2d.to(torch.float16)
+ out_dtype = torch.float16
+ else:
+ out_dtype = orig_dtype
+ if not x2d.is_contiguous():
+ x2d = x2d.contiguous()
+ weight_fp4 = weight._data
+ weight_scale = weight._scale
+ input_scale = weight._input_global_scale
+ alpha = weight._alpha
+ layout = _nvfp4_layout(weight)
+ device = x2d.device
+ if weight_fp4.device != device:
+ weight_fp4 = weight_fp4.to(device)
+ if weight_scale.device != device:
+ weight_scale = weight_scale.to(device)
+ if input_scale.device != device:
+ input_scale = input_scale.to(device)
+ if alpha.device != device:
+ alpha = alpha.to(device)
+ if bias is not None and torch.is_tensor(bias) and bias.dtype != out_dtype:
+ bias = bias.to(out_dtype)
+ orig_rows = x2d.shape[0]
+ pad_16x = (orig_rows % 16) != 0
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ input_scale = input_scale.to(torch.float32)
+ tensor_scale = alpha.to(torch.float32)
+ qx, qx_scale = _ck_cuda.quantize_nvfp4(x2d, input_scale, 0.0, pad_16x)
+ out = _ck_cuda.scaled_mm_nvfp4(
+ qx,
+ weight_fp4,
+ tensor_scale_a=input_scale,
+ tensor_scale_b=tensor_scale,
+ block_scale_a=qx_scale,
+ block_scale_b=weight_scale,
+ bias=bias,
+ out_dtype=out_dtype,
+ )
+ else:
+ alpha = alpha * input_scale
+ if alpha.dtype != torch.float32:
+ alpha = alpha.to(torch.float32)
+ act_scale = _nvfp4_get_act_scale(device)
+ qx, qx_scale = _ck_cuda.quantize_nvfp4(x2d, act_scale, 0.0, pad_16x)
+ weight_fp4 = _nvfp4_swap_nibbles(weight_fp4)
+ out = _ck_cuda.scaled_mm_nvfp4(
+ qx,
+ weight_fp4,
+ act_scale,
+ input_scale,
+ qx_scale,
+ weight_scale,
+ bias=bias,
+ out_dtype=out_dtype,
+ alpha=alpha,
+ )
+ if pad_16x:
+ out = out[:orig_rows]
+ if out.dtype != orig_dtype:
+ out = out.to(orig_dtype)
+ return out.reshape(*input.shape[:-1], weight.size(0))
+
+
+def _nvfp4_linear_cuda_lightx2v(input, weight, bias=None):
+ _nvfp4_note_kernel()
+ x2d = input.reshape(-1, input.shape[-1])
+ if not x2d.is_floating_point():
+ x2d = x2d.to(torch.float16)
+ orig_dtype = x2d.dtype
+ if orig_dtype not in (torch.float16, torch.bfloat16):
+ x2d = x2d.to(torch.float16)
+ out_dtype = torch.float16
+ else:
+ out_dtype = orig_dtype
+ if not x2d.is_contiguous():
+ x2d = x2d.contiguous()
+ weight_fp4 = weight._data
+ weight_scale = weight._scale
+ input_scale = weight._input_global_scale
+ alpha = weight._alpha
+ layout = _nvfp4_layout(weight)
+ device = x2d.device
+ if weight_fp4.device != device:
+ weight_fp4 = weight_fp4.to(device)
+ if weight_scale.device != device:
+ weight_scale = weight_scale.to(device)
+ if not weight_fp4.is_contiguous():
+ weight_fp4 = weight_fp4.contiguous()
+ if not weight_scale.is_contiguous():
+ weight_scale = weight_scale.contiguous()
+ if input_scale.device != device:
+ input_scale = input_scale.to(device)
+ if alpha.device != device:
+ alpha = alpha.to(device)
+ if input_scale.dtype != torch.float32:
+ input_scale = input_scale.to(torch.float32)
+ if alpha.dtype != torch.float32:
+ alpha = alpha.to(torch.float32)
+ if bias is not None and torch.is_tensor(bias):
+ if bias.dtype != torch.bfloat16:
+ bias = bias.to(torch.bfloat16)
+ if not bias.is_contiguous():
+ bias = bias.contiguous()
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ quant_scale = torch.reciprocal(torch.clamp(input_scale, min=1e-8))
+ alpha = alpha * input_scale
+ else:
+ quant_scale = input_scale
+ qx, qx_scale = _lx_gemm.scaled_nvfp4_quant(x2d, quant_scale)
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ qx = _nvfp4_swap_nibbles(qx)
+ if not qx.is_contiguous():
+ qx = qx.contiguous()
+ if not qx_scale.is_contiguous():
+ qx_scale = qx_scale.contiguous()
+ out = _lx_gemm.cutlass_scaled_nvfp4_mm(
+ qx,
+ weight_fp4,
+ qx_scale,
+ weight_scale,
+ alpha=alpha,
+ bias=bias,
+ )
+ if out.dtype != orig_dtype:
+ out = out.to(orig_dtype)
+ return out.reshape(*input.shape[:-1], weight.size(0))
+
+
+def _nvfp4_linear_cuda(input, weight, bias=None):
+ if _NVFP4_KERNEL_BACKEND == _NVFP4_BACKEND_LIGHTX2V:
+ return _nvfp4_linear_cuda_lightx2v(input, weight, bias=bias)
+ return _nvfp4_linear_cuda_comfy(input, weight, bias=bias)
def _is_float8_dtype(dtype):
@@ -96,6 +465,7 @@ def _dequantize_nvfp4_weight(
dtype,
device,
block_size=16,
+ layout=_NVFP4_LAYOUT_LEGACY,
):
if weight_u8.device != device:
weight_u8 = weight_u8.to(device)
@@ -104,10 +474,18 @@ def _dequantize_nvfp4_weight(
alpha = alpha.to(device)
if input_global_scale.device != device:
input_global_scale = input_global_scale.to(device)
+ if layout == _NVFP4_LAYOUT_TENSORCORE and device.type == "cuda" and _ck_cuda_available:
+ try:
+ return _ck_cuda.dequantize_nvfp4(weight_u8, alpha.to(torch.float32), scale, output_type=dtype)
+ except Exception:
+ pass
m, k_bytes = weight_u8.shape
byte_lut = _get_fp4_byte_lut(device, dtype)
- idx = weight_u8.to(torch.int32)
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ idx = _nvfp4_swap_nibbles(weight_u8).to(torch.int32)
+ else:
+ idx = weight_u8.to(torch.int32)
out = byte_lut[idx].reshape(m, k_bytes * 2)
scale = _deswizzle_nvfp4_scale(scale, out.shape[1], block_size=block_size, dtype=dtype)
@@ -115,7 +493,10 @@ def _dequantize_nvfp4_weight(
out.mul_(scale.unsqueeze(-1))
out = out.view(out.shape[0], -1)
- scale_factor = alpha.to(dtype) * input_global_scale.to(dtype)
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ scale_factor = alpha.to(dtype)
+ else:
+ scale_factor = alpha.to(dtype) * input_global_scale.to(dtype)
out.mul_(scale_factor)
return out
@@ -129,20 +510,50 @@ def _collect_nvfp4_specs(state_dict):
continue
base = key[:-7]
scale_key = base + ".weight_scale"
- input_global_key = base + ".input_global_scale"
- alpha_key = base + ".alpha"
- if scale_key not in state_dict or input_global_key not in state_dict or alpha_key not in state_dict:
+ if scale_key not in state_dict:
continue
if not _is_float8_dtype(state_dict[scale_key].dtype):
continue
+
+ weight_scale_2_key = base + ".weight_scale_2"
+ input_scale_key = base + ".input_scale"
+ if weight_scale_2_key in state_dict:
+ specs.append(
+ {
+ "name": base,
+ "weight": tensor,
+ "weight_scale": state_dict[scale_key],
+ "weight_scale_2": state_dict[weight_scale_2_key],
+ "input_scale": state_dict.get(input_scale_key, None),
+ "bias": state_dict.get(base + ".bias", None),
+ "layout": _NVFP4_LAYOUT_TENSORCORE,
+ }
+ )
+ continue
+
+ input_global_key = base + ".input_global_scale"
+ alpha_key = base + ".alpha"
+ input_absmax_key = base + ".input_absmax"
+ weight_global_scale_key = base + ".weight_global_scale"
+ if input_global_key not in state_dict or alpha_key not in state_dict:
+ if input_absmax_key not in state_dict or weight_global_scale_key not in state_dict:
+ continue
+ input_absmax = state_dict[input_absmax_key]
+ weight_global_scale = state_dict[weight_global_scale_key]
+ input_global_scale = (2688.0 / input_absmax).to(torch.float32)
+ alpha = 1.0 / (input_global_scale * weight_global_scale.to(torch.float32))
+ else:
+ input_global_scale = state_dict[input_global_key]
+ alpha = state_dict[alpha_key]
specs.append(
{
"name": base,
"weight": tensor,
"weight_scale": state_dict[scale_key],
- "input_global_scale": state_dict[input_global_key],
- "alpha": state_dict[alpha_key],
+ "input_global_scale": input_global_scale,
+ "alpha": alpha,
"bias": state_dict.get(base + ".bias", None),
+ "layout": _NVFP4_LAYOUT_LEGACY,
}
)
return specs
@@ -162,7 +573,12 @@ def convert_nvfp4_to_quanto(state_dict, default_dtype=None, verboseLevel=1):
specs = _collect_nvfp4_specs(state_dict)
if not specs:
return {"state_dict": state_dict, "quant_map": {}}
- quant_map = {spec["name"]: {"weights": "nvfp4", "activations": "none"} for spec in specs}
+ _nvfp4_note_load_backend()
+ quant_map = {}
+ for spec in specs:
+ qcfg = {"weights": "nvfp4", "activations": "none"}
+ quant_map[spec["name"]] = qcfg
+ quant_map[spec["name"] + ".weight"] = qcfg
return {"state_dict": state_dict, "quant_map": quant_map}
@@ -192,14 +608,32 @@ class NVFP4WeightTensor(QTensor):
def create(
weight_u8,
weight_scale,
- input_global_scale,
- alpha,
size,
stride,
dtype,
+ input_global_scale=None,
+ alpha=None,
+ input_scale=None,
+ weight_scale_2=None,
device=None,
requires_grad=False,
+ layout=_NVFP4_LAYOUT_LEGACY,
+ allow_kernel=True,
):
+ if input_global_scale is None and input_scale is not None:
+ input_global_scale = input_scale
+ if alpha is None and weight_scale_2 is not None:
+ alpha = weight_scale_2
+ if layout == _NVFP4_LAYOUT_LEGACY and (weight_scale_2 is not None or input_scale is not None):
+ layout = _NVFP4_LAYOUT_TENSORCORE
+ if input_global_scale is None or alpha is None:
+ raise ValueError("NVFP4WeightTensor.create requires input_global_scale/alpha or input_scale/weight_scale_2")
+ if torch.is_tensor(input_global_scale):
+ try:
+ if not torch.isfinite(input_global_scale).all():
+ allow_kernel = False
+ except Exception:
+ allow_kernel = False
device = weight_u8.device if device is None else device
if weight_u8.device != device:
weight_u8 = weight_u8.to(device)
@@ -218,8 +652,10 @@ class NVFP4WeightTensor(QTensor):
weight_scale=weight_scale,
input_global_scale=input_global_scale,
alpha=alpha,
+ allow_kernel=allow_kernel,
dtype=dtype,
requires_grad=requires_grad,
+ layout=layout,
)
@staticmethod
@@ -234,7 +670,9 @@ class NVFP4WeightTensor(QTensor):
input_global_scale,
alpha,
dtype,
+ allow_kernel=True,
requires_grad=False,
+ layout=_NVFP4_LAYOUT_LEGACY,
):
return torch.Tensor._make_wrapper_subclass(
cls,
@@ -257,6 +695,8 @@ class NVFP4WeightTensor(QTensor):
alpha,
dtype,
requires_grad=False,
+ layout=_NVFP4_LAYOUT_LEGACY,
+ allow_kernel=True,
):
super().__init__(qtype, axis)
self._data = weight_u8
@@ -264,6 +704,8 @@ class NVFP4WeightTensor(QTensor):
self._input_global_scale = input_global_scale
self._alpha = alpha
self._block_size = 16
+ self._layout = layout
+ self._allow_kernel = allow_kernel
def dequantize(self, dtype=None, device=None):
if dtype is None:
@@ -278,9 +720,17 @@ class NVFP4WeightTensor(QTensor):
dtype=dtype,
device=device,
block_size=self._block_size,
+ layout=self._layout,
)
def get_quantized_subtensors(self):
+ if self._layout == _NVFP4_LAYOUT_TENSORCORE:
+ return [
+ ("weight_u8", self._data),
+ ("weight_scale", self._scale),
+ ("weight_scale_2", self._alpha),
+ ("input_scale", self._input_global_scale),
+ ]
return [
("weight_u8", self._data),
("weight_scale", self._scale),
@@ -298,9 +748,13 @@ class NVFP4WeightTensor(QTensor):
self._data = data
if "weight_scale" in sub_map and sub_map["weight_scale"] is not None:
self._scale = sub_map["weight_scale"]
- if "input_global_scale" in sub_map and sub_map["input_global_scale"] is not None:
+ if "input_scale" in sub_map and sub_map["input_scale"] is not None:
+ self._input_global_scale = sub_map["input_scale"]
+ elif "input_global_scale" in sub_map and sub_map["input_global_scale"] is not None:
self._input_global_scale = sub_map["input_global_scale"]
- if "alpha" in sub_map and sub_map["alpha"] is not None:
+ if "weight_scale_2" in sub_map and sub_map["weight_scale_2"] is not None:
+ self._alpha = sub_map["weight_scale_2"]
+ elif "alpha" in sub_map and sub_map["alpha"] is not None:
self._alpha = sub_map["alpha"]
def __tensor_flatten__(self):
@@ -311,6 +765,8 @@ class NVFP4WeightTensor(QTensor):
"size": str(list(self.size())),
"stride": str(list(self.stride())),
"dtype": str(self.dtype),
+ "layout": self._layout,
+ "allow_kernel": "1" if self._allow_kernel else "0",
}
return inner_tensors, meta
@@ -326,6 +782,8 @@ class NVFP4WeightTensor(QTensor):
dtype = getattr(torch, dtype_name, torch.float16)
else:
dtype = getattr(torch, dtype_str, torch.float16)
+ layout = meta.get("layout", _NVFP4_LAYOUT_LEGACY)
+ allow_kernel = str(meta.get("allow_kernel", "1")).strip().lower() not in ("0", "false", "no")
return NVFP4WeightTensor(
qtype=qtype,
axis=axis,
@@ -335,7 +793,9 @@ class NVFP4WeightTensor(QTensor):
weight_scale=inner_tensors["_scale"],
input_global_scale=inner_tensors["_input_global_scale"],
alpha=inner_tensors["_alpha"],
+ allow_kernel=allow_kernel,
dtype=dtype,
+ layout=layout,
)
@classmethod
@@ -346,25 +806,9 @@ class NVFP4WeightTensor(QTensor):
weight = args[1] if len(args) > 1 else kwargs.get("weight", None)
bias = args[2] if len(args) > 2 else kwargs.get("bias", None)
if isinstance(weight, NVFP4WeightTensor):
- if torch.is_tensor(input) and _supports_nvfp4_kernel(input.device):
- x2d = input.reshape(-1, input.shape[-1])
- if not x2d.is_floating_point():
- x2d = x2d.to(torch.float16)
- orig_dtype = x2d.dtype
- input_quant, input_scale = scaled_nvfp4_quant(x2d, weight._input_global_scale)
- if bias is not None and torch.is_tensor(bias) and bias.dtype != orig_dtype:
- bias = bias.to(orig_dtype)
- out = cutlass_scaled_nvfp4_mm(
- input_quant,
- weight._data,
- input_scale,
- weight._scale,
- alpha=weight._alpha,
- bias=bias,
- )
- if out.dtype != orig_dtype:
- out = out.to(orig_dtype)
- return out.reshape(*input.shape[:-1], weight.size(0))
+ if _nvfp4_can_use_kernel(input, weight):
+ return _nvfp4_linear_cuda(input, weight, bias=bias)
+ _nvfp4_note_fallback()
dtype = input.dtype if torch.is_tensor(input) else weight.dtype
device = input.device if torch.is_tensor(input) else weight.device
w = weight.dequantize(dtype=dtype, device=device)
@@ -382,25 +826,9 @@ class NVFP4WeightTensor(QTensor):
weight = args[1]
bias = args[2] if len(args) > 2 else None
if isinstance(weight, NVFP4WeightTensor):
- if torch.is_tensor(input) and _supports_nvfp4_kernel(input.device):
- x2d = input.reshape(-1, input.shape[-1])
- if not x2d.is_floating_point():
- x2d = x2d.to(torch.float16)
- orig_dtype = x2d.dtype
- input_quant, input_scale = scaled_nvfp4_quant(x2d, weight._input_global_scale)
- if bias is not None and torch.is_tensor(bias) and bias.dtype != orig_dtype:
- bias = bias.to(orig_dtype)
- out = cutlass_scaled_nvfp4_mm(
- input_quant,
- weight._data,
- input_scale,
- weight._scale,
- alpha=weight._alpha,
- bias=bias,
- )
- if out.dtype != orig_dtype:
- out = out.to(orig_dtype)
- return out.reshape(*input.shape[:-1], weight.size(0))
+ if _nvfp4_can_use_kernel(input, weight):
+ return _nvfp4_linear_cuda(input, weight, bias=bias)
+ _nvfp4_note_fallback()
dtype = input.dtype if torch.is_tensor(input) else weight.dtype
device = input.device if torch.is_tensor(input) else weight.device
w = weight.dequantize(dtype=dtype, device=device)
@@ -414,11 +842,13 @@ class NVFP4WeightTensor(QTensor):
weight_scale=op(t._scale),
input_global_scale=op(t._input_global_scale),
alpha=op(t._alpha),
+ allow_kernel=getattr(t, "_allow_kernel", True),
size=t.size(),
stride=t.stride(),
dtype=t.dtype,
device=t.device,
requires_grad=t.requires_grad,
+ layout=t._layout,
)
if op in (torch.ops.aten._to_copy, torch.ops.aten.to):
t = args[0]
@@ -435,11 +865,13 @@ class NVFP4WeightTensor(QTensor):
weight_scale=out_scale,
input_global_scale=out_igs,
alpha=out_alpha,
+ allow_kernel=getattr(t, "_allow_kernel", True),
size=t.size(),
stride=t.stride(),
dtype=t.dtype,
device=device,
requires_grad=t.requires_grad,
+ layout=t._layout,
)
return _nvfp4_qfallback(op, *args, **(kwargs or {}))
@@ -519,16 +951,22 @@ class QLinearNVFP4(QModuleMixin, torch.nn.Linear):
weight_key = prefix + "weight"
scale_key = prefix + "weight_scale"
+ scale2_key = prefix + "weight_scale_2"
igs_key = prefix + "input_global_scale"
alpha_key = prefix + "alpha"
+ input_absmax_key = prefix + "input_absmax"
+ weight_global_scale_key = prefix + "weight_global_scale"
bias_key = prefix + "bias"
input_scale_key = prefix + "input_scale"
output_scale_key = prefix + "output_scale"
weight_u8 = state_dict.pop(weight_key, None)
weight_scale = state_dict.pop(scale_key, None)
+ weight_scale_2 = state_dict.pop(scale2_key, None)
input_global_scale = state_dict.pop(igs_key, None)
alpha = state_dict.pop(alpha_key, None)
+ input_absmax = state_dict.pop(input_absmax_key, None)
+ weight_global_scale = state_dict.pop(weight_global_scale_key, None)
bias = state_dict.pop(bias_key, None)
input_scale = state_dict.pop(input_scale_key, None)
output_scale = state_dict.pop(output_scale_key, None)
@@ -537,25 +975,68 @@ class QLinearNVFP4(QModuleMixin, torch.nn.Linear):
missing_keys.append(weight_key)
if weight_scale is None:
missing_keys.append(scale_key)
- if input_global_scale is None:
- missing_keys.append(igs_key)
- if alpha is None:
- missing_keys.append(alpha_key)
+ layout = _NVFP4_LAYOUT_LEGACY
+ allow_kernel = True
+ if weight_scale_2 is not None or input_scale is not None:
+ layout = _NVFP4_LAYOUT_TENSORCORE
+ if weight_scale_2 is None:
+ missing_keys.append(scale2_key)
+ if input_scale is None:
+ allow_kernel = False
+ if torch.is_tensor(weight_scale_2):
+ input_scale = torch.full(
+ (),
+ float("nan"),
+ dtype=weight_scale_2.dtype,
+ device=weight_scale_2.device,
+ )
+ elif torch.is_tensor(weight_u8):
+ input_scale = torch.full((), float("nan"), dtype=torch.float32, device=weight_u8.device)
+ else:
+ input_scale = torch.tensor(float("nan"), dtype=torch.float32)
+ else:
+ if input_global_scale is None or alpha is None:
+ if input_absmax is not None and weight_global_scale is not None:
+ input_global_scale = (2688.0 / input_absmax).to(torch.float32)
+ alpha = 1.0 / (input_global_scale * weight_global_scale.to(torch.float32))
+ else:
+ if input_global_scale is None:
+ missing_keys.append(igs_key)
+ if alpha is None:
+ missing_keys.append(alpha_key)
target_dtype = self._nvfp4_default_dtype or self.weight.dtype
- if weight_u8 is not None and weight_scale is not None and input_global_scale is not None and alpha is not None:
- nvfp4_weight = NVFP4WeightTensor.create(
- weight_u8=weight_u8,
- weight_scale=weight_scale,
- input_global_scale=input_global_scale,
- alpha=alpha,
- size=self.weight.size(),
- stride=self.weight.stride(),
- dtype=target_dtype,
- device=weight_u8.device,
- requires_grad=False,
- )
- self.weight = torch.nn.Parameter(nvfp4_weight, requires_grad=False)
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ if weight_u8 is not None and weight_scale is not None and weight_scale_2 is not None and input_scale is not None:
+ nvfp4_weight = NVFP4WeightTensor.create(
+ weight_u8=weight_u8,
+ weight_scale=weight_scale,
+ input_global_scale=input_scale,
+ alpha=weight_scale_2,
+ allow_kernel=allow_kernel,
+ size=self.weight.size(),
+ stride=self.weight.stride(),
+ dtype=target_dtype,
+ device=weight_u8.device,
+ requires_grad=False,
+ layout=layout,
+ )
+ self.weight = torch.nn.Parameter(nvfp4_weight, requires_grad=False)
+ else:
+ if weight_u8 is not None and weight_scale is not None and input_global_scale is not None and alpha is not None:
+ nvfp4_weight = NVFP4WeightTensor.create(
+ weight_u8=weight_u8,
+ weight_scale=weight_scale,
+ input_global_scale=input_global_scale,
+ alpha=alpha,
+ size=self.weight.size(),
+ stride=self.weight.stride(),
+ dtype=target_dtype,
+ device=weight_u8.device,
+ requires_grad=False,
+ layout=layout,
+ )
+ self.weight = torch.nn.Parameter(nvfp4_weight, requires_grad=False)
if bias is not None:
if target_dtype is not None and bias.dtype != target_dtype:
@@ -586,3 +1067,122 @@ class QLinearNVFP4(QModuleMixin, torch.nn.Linear):
self.output_scale = torch.ones((), dtype=scale_dtype, device=scale_device)
return
+
+
+def validate_nvfp4_kernel(
+ state_dict=None,
+ checkpoint_path=None,
+ device=None,
+ max_layers=4,
+ seed=0,
+ batch_size=2,
+ dtype=torch.bfloat16,
+ verbose=True,
+):
+ """Compare kernel vs fallback outputs for a few NVFP4 layers."""
+ if state_dict is None:
+ if checkpoint_path is None:
+ raise ValueError("state_dict or checkpoint_path is required")
+ from mmgp import safetensors2
+
+ state_dict = {}
+ with safetensors2.safe_open(checkpoint_path, framework="pt", device="cpu", writable_tensors=False) as f:
+ for key in f.keys():
+ state_dict[key] = f.get_tensor(key)
+
+ specs = _collect_nvfp4_specs(state_dict)
+ if not specs:
+ return {"ok": False, "reason": "no nvfp4 weights found"}
+
+ candidates = sorted(specs, key=lambda spec: spec["weight"].numel())
+ if isinstance(max_layers, int) and max_layers > 0:
+ candidates = candidates[:max_layers]
+
+ device = device or (torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"))
+ torch.manual_seed(seed)
+ if torch.cuda.is_available():
+ torch.cuda.manual_seed_all(seed)
+
+ results = []
+ with torch.no_grad():
+ for spec in candidates:
+ weight = spec["weight"]
+ layout = spec.get("layout", _NVFP4_LAYOUT_LEGACY)
+ in_features = weight.shape[1] * 2
+ bias = spec.get("bias")
+
+ if layout == _NVFP4_LAYOUT_TENSORCORE:
+ input_scale = spec.get("input_scale")
+ tensor_scale = spec.get("weight_scale_2")
+ else:
+ input_scale = spec.get("input_global_scale")
+ tensor_scale = spec.get("alpha")
+
+ if input_scale is None or tensor_scale is None:
+ results.append({"name": spec["name"], "layout": layout, "kernel": False, "reason": "missing scales"})
+ continue
+
+ nvfp4_weight = NVFP4WeightTensor.create(
+ weight_u8=weight,
+ weight_scale=spec["weight_scale"],
+ input_global_scale=input_scale,
+ alpha=tensor_scale,
+ size=(weight.shape[0], in_features),
+ stride=(in_features, 1),
+ dtype=dtype,
+ device=device,
+ requires_grad=False,
+ layout=layout,
+ )
+
+ x = torch.randn(batch_size, in_features, device=device, dtype=dtype)
+ if bias is not None:
+ bias = bias.to(device=device, dtype=dtype)
+
+ kernel_ok = _nvfp4_can_use_kernel(x, nvfp4_weight)
+ y_kernel = _nvfp4_linear_cuda(x, nvfp4_weight, bias=bias) if kernel_ok else None
+ x_ref = x
+ if (
+ layout == _NVFP4_LAYOUT_TENSORCORE
+ and _ck_cuda_available
+ and device.type == "cuda"
+ and torch.is_tensor(input_scale)
+ ):
+ input_scale_fp32 = input_scale.to(device=device, dtype=torch.float32)
+ pad_16x = (x.shape[0] % 16) != 0
+ qx, qx_scale = _ck_cuda.quantize_nvfp4(x, input_scale_fp32, 0.0, pad_16x)
+ x_ref = _ck_cuda.dequantize_nvfp4(qx, input_scale_fp32, qx_scale, output_type=dtype)
+ if pad_16x:
+ x_ref = x_ref[: x.shape[0]]
+ y_ref = torch.nn.functional.linear(
+ x_ref,
+ nvfp4_weight.dequantize(dtype=dtype, device=device),
+ bias,
+ )
+
+ if y_kernel is None:
+ results.append({"name": spec["name"], "layout": layout, "kernel": False})
+ continue
+
+ diff = (y_kernel - y_ref).float()
+ results.append(
+ {
+ "name": spec["name"],
+ "layout": layout,
+ "kernel": True,
+ "max_abs": diff.abs().max().item(),
+ "mean_abs": diff.abs().mean().item(),
+ }
+ )
+
+ if verbose:
+ print("NVFP4 kernel validation:")
+ for entry in results:
+ if not entry.get("kernel"):
+ print(f" {entry['name']}: kernel skipped ({entry.get('reason', 'incompatible')})")
+ continue
+ print(
+ f" {entry['name']}: max_abs={entry['max_abs']:.6f} mean_abs={entry['mean_abs']:.6f}"
+ )
+
+ return {"ok": True, "results": results}
diff --git a/shared/utils/utils.py b/shared/utils/utils.py
index e6658f9..7dd9ed4 100644
--- a/shared/utils/utils.py
+++ b/shared/utils/utils.py
@@ -439,6 +439,8 @@ def prepare_video_guide_and_mask( video_guides, video_masks, pre_video_guide, im
src_video = torch.cat([src_video, torch.full( (3, current_video_length - src_video.shape[1], *src_video.shape[-2:] ), inpaint_color_compressed, dtype = src_video.dtype, device= src_video.device) ], dim=1)
elif src_video is not None:
new_num_frames = (src_video.shape[1] - 1) // latent_size * latent_size + 1
+ if new_num_frames < src_video.shape[1]:
+ print(f"invalid number of control frames {src_video.shape[1]}, potentially {src_video.shape[1]-new_num_frames} frames will be lost")
src_video = src_video[:, :new_num_frames]
if any_mask and src_video is not None:
diff --git a/wgp.py b/wgp.py
index 7f9b0c8..bc8dd65 100644
--- a/wgp.py
+++ b/wgp.py
@@ -85,7 +85,7 @@ AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAME
CONFIG_FILENAME = "wgp_config.json"
PROMPT_VARS_MAX = 10
target_mmgp_version = "3.6.11"
-WanGP_version = "10.11"
+WanGP_version = "10.12"
settings_version = 2.42
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None
@@ -116,6 +116,12 @@ quant_router.unregister_handler(".fp8_quanto_bridge")
for handler in _HANDLER_MODULES:
quant_router.register_handler(handler)
+try:
+ from mmgp import quanto_int8_inject
+ # quanto_int8_inject.init_quanto_int8_patch()
+except Exception:
+ pass
+
def set_wgp_global(variable_name: str, new_value: any) -> str:
if variable_name not in globals():
error_msg = f"Plugin tried to modify a non-existent global: '{variable_name}'."
@@ -607,6 +613,7 @@ def validate_settings(state, model_type, single_prompt, inputs):
keep_frames_video_source = inputs["keep_frames_video_source"]
denoising_strength= inputs["denoising_strength"]
masking_strength= inputs["masking_strength"]
+ input_video_strength = inputs.get("input_video_strength", 1.0)
sliding_window_size = inputs["sliding_window_size"]
sliding_window_overlap = inputs["sliding_window_overlap"]
sliding_window_discard_last_frames = inputs["sliding_window_discard_last_frames"]
@@ -724,6 +731,9 @@ def validate_settings(state, model_type, single_prompt, inputs):
else:
video_source = None
+ if len(model_def.get("input_video_strength", ""))==0 or not any_letters(image_prompt_type, "SVL"):
+ input_video_strength = 1.0
+
if "A" in audio_prompt_type:
if audio_guide == None:
gr.Info("You must provide an Audio Source")
@@ -788,7 +798,7 @@ def validate_settings(state, model_type, single_prompt, inputs):
image_mask = None
if "G" in video_prompt_type:
- if denoising_strength < 1.:
+ if denoising_strength < 1. and not model_def.get("custom_denoising_strength", False):
gr.Info(f"With Denoising Strength {denoising_strength:.1f}, Denoising will start at Step no {int(round(num_inference_steps * (1. - denoising_strength),4))} ")
else:
denoising_strength = 1.0
@@ -918,6 +928,7 @@ def validate_settings(state, model_type, single_prompt, inputs):
"video_source": video_source,
"frames_positions": frames_positions,
"keep_frames_video_source": keep_frames_video_source,
+ "input_video_strength": input_video_strength,
"keep_frames_video_guide": keep_frames_video_guide,
"denoising_strength": denoising_strength,
"masking_strength": masking_strength,
@@ -2439,16 +2450,19 @@ def get_model_filename(model_type, quantization ="int8", dtype_policy = "", modu
raw_filename = choices[0]
else:
quant_tokens = []
+ quant_order = []
if quantization != "bf16":
if quantization == "int8":
- quant_tokens = quant_router.get_quantization_tokens("int8") or []
- quant_tokens += quant_router.get_quantization_tokens("fp8") or []
+ quant_order =["int8", "fp8"]
+ elif quantization == "fp8":
+ quant_order =["fp8", "int8"]
- sub_choices = [
- name
- for name in choices
- if any(token in os.path.basename(name).lower() for token in quant_tokens)
- ]
+ for quant_type in quant_order:
+ quant_tokens += quant_router.get_quantization_tokens(quant_type) or []
+
+ sub_choices = []
+ for token in quant_tokens:
+ sub_choices += [name for name in choices if token in os.path.basename(name).lower()]
if len(sub_choices) > 0:
dtype_str = "fp16" if dtype == torch.float16 else "bf16"
@@ -4010,8 +4024,8 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
video_preprocesses += process_name if len(video_preprocesses) == 0 else ", " + process_name
return video_preprocesses
- video_preprocesses_in = gen_process_list(all_process_map_video_guide)
- video_preprocesses_out = gen_process_list(process_map_outside_mask)
+ video_preprocesses_in = gen_process_list(all_process_map_video_guide) if "V" else ""
+ video_preprocesses_out = gen_process_list(process_map_outside_mask) if "V" else ""
if "N" in video_video_prompt_type:
alt = video_preprocesses_in
video_preprocesses_in = video_preprocesses_out
@@ -4030,6 +4044,10 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
if len(video_outpainting) >0:
values += [video_outpainting]
labels += ["Outpainting"]
+ if len(model_def.get("input_video_strength", "")) and any_letters(video_image_prompt_type, "SVL"):
+ values += [configs.get("input_video_strength",1)]
+ labels += ["Input Image Strength"]
+
if "G" in video_video_prompt_type and "V" in video_video_prompt_type:
values += [configs.get("denoising_strength",1)]
labels += ["Denoising Strength"]
@@ -5182,6 +5200,7 @@ def generate_video(
model_mode,
video_source,
keep_frames_video_source,
+ input_video_strength,
video_prompt_type,
image_refs,
frames_positions,
@@ -6066,6 +6085,7 @@ def generate_video(
pace=pace,
temperature=temperature,
window_start_frame_no = window_start_frame,
+ input_video_strength = input_video_strength,
)
except Exception as e:
if len(control_audio_tracks) > 0 or len(source_audio_tracks) > 0:
@@ -7335,12 +7355,16 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
if any_audio_track(base_model_type) or not get_mmaudio_settings(server_config)[0]:
pop += ["MMAudio_setting", "MMAudio_prompt", "MMAudio_neg_prompt"]
+ image_prompt_type = inputs.get("image_prompt_type", "") or ""
video_prompt_type = inputs["video_prompt_type"]
if "G" not in video_prompt_type:
pop += ["denoising_strength"]
if "G" not in video_prompt_type and not model_def.get("mask_strength_always_enabled", False):
pop += ["masking_strength"]
+
+ if len(model_def.get("input_video_strength", ""))==0 or not any_letters(image_prompt_type, "SVL"):
+ pop += ["input_video_strength"]
if not (server_config.get("enhancer_enabled", 0) > 0 and server_config.get("enhancer_mode", 0) == 0):
@@ -7997,6 +8021,7 @@ def save_inputs(
model_mode,
video_source,
keep_frames_video_source,
+ input_video_strength,
video_guide_outpainting,
video_prompt_type,
image_refs,
@@ -8248,7 +8273,8 @@ def refresh_image_prompt_type_radio(state, image_prompt_type, image_prompt_type_
model_def = get_model_def(get_state_model_type(state))
image_prompt_types_allowed = model_def.get("image_prompt_types_allowed", "")
end_visible = "E" in image_prompt_types_allowed and any_letters(image_prompt_type, "SVL")
- return image_prompt_type, gr.update(visible = "S" in image_prompt_type ), gr.update(visible = end_visible and ("E" in image_prompt_type) ), gr.update(visible = "V" in image_prompt_type) , gr.update(visible = any_video_source), gr.update(visible = end_visible)
+ input_strength_visible = len(model_def.get("input_video_strength","")) and any_letters(image_prompt_type, "SVL")
+ return image_prompt_type, gr.update(visible = "S" in image_prompt_type ), gr.update(visible = end_visible and ("E" in image_prompt_type) ), gr.update(visible = "V" in image_prompt_type) , gr.update(visible = input_strength_visible), gr.update(visible = any_video_source), gr.update(visible = end_visible)
def refresh_image_prompt_type_endcheckbox(state, image_prompt_type, image_prompt_type_radio, end_checkbox):
image_prompt_type = del_in_sequence(image_prompt_type, "E")
@@ -8542,6 +8568,21 @@ def get_resolution_choices(current_resolution_choice, model_resolutions= None):
resolution_choices = custom_resolutions
if resolution_choices == None:
resolution_choices=[
+ # 4K
+ ("3840x2176 (16:9)", "3840x2176"),
+ ("2176x3840 (9:16)", "2176x3840"),
+ ("3840x1664 (21:9)", "3840x1664"),
+ ("1664x3840 (9:21)", "1664x3840"),
+ # 1440p
+ ("2560x1440 (16:9)", "2560x1440"),
+ ("1440x2560 (9:16)", "1440x2560"),
+ ("1920x1440 (4:3)", "1920x1440"),
+ ("1440x1920 (3:4)", "1440x1920"),
+ ("2160x1440 (3:2)", "2160x1440"),
+ ("1440x2160 (2:3)", "1440x2160"),
+ ("1440x1440 (1:1)", "1440x1440"),
+ ("2688x1152 (21:9)", "2688x1152"),
+ ("1152x2688 (9:21)", "1152x2688"),
# 1080p
("1920x1088 (16:9)", "1920x1088"),
("1088x1920 (9:16)", "1088x1920"),
@@ -8588,7 +8629,8 @@ group_thresholds = {
"540p": 960 * 544,
"720p": 1024 * 1024,
"1080p": 1920 * 1088,
- "1440p": 9999 * 9999
+ "1440p": 2560 * 1440,
+ "2160p": 3840 * 2176,
}
def categorize_resolution(resolution_str):
@@ -8598,7 +8640,7 @@ def categorize_resolution(resolution_str):
for group in group_thresholds.keys():
if pixel_count <= group_thresholds[group]:
return group
- return "1440p"
+ return next(reversed(group_thresholds))
def group_resolutions(model_def, resolutions, selected_resolution):
@@ -8913,6 +8955,8 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
image_prompt_type_endcheckbox = gr.Checkbox( value =False, show_label= False, visible= False , scale= 1)
image_start_row, image_start, image_start_extra = get_image_gallery(label= "Images as starting points for new Videos in the Generation Queue" + (" (None for Black Frames)" if model_def.get("black_frame", False) else ''), value = ui_defaults.get("image_start", None), visible= "S" in image_prompt_type_value )
video_source = gr.Video(label= "Video to Continue", height = gallery_height, visible= "V" in image_prompt_type_value, value= ui_defaults.get("video_source", None), elem_id="video_input")
+ input_video_strength_label = model_def.get("input_video_strength", "")
+ input_video_strength = gr.Slider(0, 1, value=ui_get("input_video_strength", 1.0), step=0.01, label=input_video_strength_label, visible = len(input_video_strength_label) and any_letters(image_prompt_type_value, "SVL"), show_reset_button= False)
image_end_row, image_end, image_end_extra = get_image_gallery(label= get_image_end_label(ui_get("multi_prompts_gen_type")), value = ui_defaults.get("image_end", None), visible= any_letters(image_prompt_type_value, "SVL") and ("E" in image_prompt_type_value) )
if model_mode_choices is None or image_mode_value not in model_modes_visibility:
model_mode = gr.Dropdown(value=None, label="model mode", visible=False, allow_custom_value= True)
@@ -9893,7 +9937,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
audio_prompt_type_remux.change(fn=refresh_audio_prompt_type_remux, inputs=[state, audio_prompt_type, audio_prompt_type_remux], outputs=[audio_prompt_type])
remove_background_sound.change(fn=refresh_remove_background_sound, inputs=[state, audio_prompt_type, remove_background_sound], outputs=[audio_prompt_type])
audio_prompt_type_sources.change(fn=refresh_audio_prompt_type_sources, inputs=[state, audio_prompt_type, audio_prompt_type_sources], outputs=[audio_prompt_type, audio_guide, audio_guide2, speakers_locations_row, remove_background_sound, audio_guide_row])
- image_prompt_type_radio.change(fn=refresh_image_prompt_type_radio, inputs=[state, image_prompt_type, image_prompt_type_radio], outputs=[image_prompt_type, image_start_row, image_end_row, video_source, keep_frames_video_source, image_prompt_type_endcheckbox], show_progress="hidden" )
+ image_prompt_type_radio.change(fn=refresh_image_prompt_type_radio, inputs=[state, image_prompt_type, image_prompt_type_radio], outputs=[image_prompt_type, image_start_row, image_end_row, video_source, input_video_strength, keep_frames_video_source, image_prompt_type_endcheckbox], show_progress="hidden" )
image_prompt_type_endcheckbox.change(fn=refresh_image_prompt_type_endcheckbox, inputs=[state, image_prompt_type, image_prompt_type_radio, image_prompt_type_endcheckbox], outputs=[image_prompt_type, image_end_row] )
video_prompt_type_image_refs.input(fn=refresh_video_prompt_type_image_refs, inputs = [state, video_prompt_type, video_prompt_type_image_refs,image_mode], outputs = [video_prompt_type, image_refs_row, remove_background_images_ref, image_refs_relative_size, frames_positions,video_guide_outpainting_col], show_progress="hidden")
video_prompt_type_video_guide.input(fn=refresh_video_prompt_type_video_guide, inputs = [state, gr.State(""), video_prompt_type, video_prompt_type_video_guide, image_mode, image_mask_guide, image_guide, image_mask], outputs = [video_prompt_type, video_guide, image_guide, keep_frames_video_guide, denoising_strength, masking_strength, video_guide_outpainting_col, video_prompt_type_video_mask, video_mask, image_mask, image_mask_guide, mask_expand, image_refs_row, video_prompt_type_video_custom_dropbox, video_prompt_type_video_custom_checkbox], show_progress="hidden")