[Model] Add LTX-2.5 support (#6070)

Signed-off-by: lishunyang12 <lishunyang12@163.com>
This commit is contained in:
SYLAR authored and GitHub committed 2026-08-15 18:27:23 +08:00
1 parent f39b8684eb
commit ce6ab0ca46
47 files changed
+4558 -218

No files matched your search

+142 -9
View File
@@ -42,6 +42,7 @@ class LTXForwardContext:
original_audio_num_frames: int
padded_audio_num_frames: int
timesteps: torch.Tensor
sampler: str
audio_scheduler: Any
video_audio_step_adapter: Any
@@ -88,6 +89,11 @@ class LTXDenoisePipeline(Protocol):
LTXDenoiseStep = Callable[[int, torch.Tensor, LTXAVState], LTXAVState]
LTX_ANCESTRAL_ETA = 1.0
LTX_ANCESTRAL_S_NOISE = 1.0
LTX_ANCESTRAL_NOISE_SEED_OFFSET = 10000
LTX_OFFICIAL_DEFAULT_SEED = 10
class LTXDenoiseExecutor:
"""Run the one shared LTX denoise loop.
@@ -138,6 +144,9 @@ class LTXVideoAudioStepAdapter:
latent_width: int,
*,
image_conditioned: bool,
sampler: str = "euler",
generator: torch.Generator | list[torch.Generator] | None = None,
conditioning_mask: torch.Tensor | None = None,
) -> None:
self._pipeline = pipeline
self._audio_scheduler = audio_scheduler
@@ -145,11 +154,27 @@ class LTXVideoAudioStepAdapter:
self._latent_height = latent_height
self._latent_width = latent_width
self._image_conditioned = image_conditioned
self._sampler = sampler
self._conditioning_mask = conditioning_mask
self._ancestral_generators = (
_make_ancestral_generators(generator, pipeline.device) if sampler == "euler_ancestral" else None
)
self._step_index = 0
def step(self, noise_pred, t, latents, return_dict=False, generator=None):
del t, return_dict, generator
if self._image_conditioned:
if self._sampler == "euler_ancestral":
video_out = _ancestral_euler_step_from_velocity(
latents[0],
noise_pred[0],
self._pipeline.scheduler.sigmas,
self._step_index,
self._ancestral_generators,
)
if self._conditioning_mask is not None:
mask = self._conditioning_mask.unsqueeze(-1).to(video_out.dtype)
video_out = torch.lerp(video_out, latents[0], mask)
elif self._image_conditioned:
video_out = self._pipeline._step_video_latents_i2v(
noise_pred[0],
latents[0],
@@ -165,17 +190,96 @@ class LTXVideoAudioStepAdapter:
self._pipeline.scheduler.sigmas,
self._step_index,
)
audio_out = euler_step_from_velocity(
latents[1],
noise_pred[1],
self._audio_scheduler.sigmas,
self._step_index,
)
if self._sampler == "euler_ancestral":
audio_out = _ancestral_euler_step_from_velocity(
latents[1],
noise_pred[1],
self._audio_scheduler.sigmas,
self._step_index,
self._ancestral_generators,
)
else:
audio_out = euler_step_from_velocity(
latents[1],
noise_pred[1],
self._audio_scheduler.sigmas,
self._step_index,
)
self._step_index += 1
return ((video_out, audio_out),)
def _official_ltx_sigmas(scheduler: Any, steps: int, device: torch.device) -> torch.Tensor:
def _make_ancestral_generators(
generator: torch.Generator | list[torch.Generator] | None,
device: torch.device,
) -> torch.Generator | list[torch.Generator]:
"""Create the official independent ``seed + 10000`` noise stream."""
def _offset(source: torch.Generator | None) -> torch.Generator:
seed = LTX_OFFICIAL_DEFAULT_SEED if source is None else source.initial_seed()
return torch.Generator(device=device).manual_seed(seed + LTX_ANCESTRAL_NOISE_SEED_OFFSET)
if isinstance(generator, list):
return [_offset(item) for item in generator]
return _offset(generator)
def _randn_like_with_generators(
sample: torch.Tensor,
generators: torch.Generator | list[torch.Generator],
) -> torch.Tensor:
if not isinstance(generators, list):
return torch.randn(sample.shape, generator=generators, dtype=sample.dtype, device=sample.device)
if len(generators) != sample.shape[0]:
raise ValueError(
f"LTX ancestral sampling received {len(generators)} generators for batch size {sample.shape[0]}."
)
return torch.cat(
[
torch.randn((1, *sample.shape[1:]), generator=item, dtype=sample.dtype, device=sample.device)
for item in generators
]
)
def _ancestral_euler_step_from_velocity(
sample: torch.Tensor,
velocity: torch.Tensor,
sigmas: torch.Tensor,
step_index: int,
generators: torch.Generator | list[torch.Generator] | None,
) -> torch.Tensor:
"""Apply the official LTX-2.5 rectified-flow ancestral Euler step."""
sigma = sigmas[step_index].to(torch.float32)
sigma_next = sigmas[step_index + 1].to(torch.float32)
# Official X0Model materializes the denoised prediction in the model
# dtype before the ancestral step promotes it back to float32.
denoised_model_dtype = (sample.float() - velocity.float() * sigma).to(sample.dtype)
denoised = denoised_model_dtype.float()
if sigma_next == 0:
return denoised.to(sample.dtype)
if generators is None:
raise ValueError("LTX ancestral Euler sampling requires a noise generator.")
downstep_ratio = 1.0 + (sigma_next / sigma - 1.0) * LTX_ANCESTRAL_ETA
sigma_down = sigma_next * downstep_ratio
sigma_down_ratio = sigma_down / sigma
x_next = sigma_down_ratio * sample.float() + (1.0 - sigma_down_ratio) * denoised
alpha_next = 1.0 - sigma_next
alpha_down = 1.0 - sigma_down
renoise_coeff = (sigma_next**2 - sigma_down**2 * alpha_next**2 / alpha_down**2).clamp(min=0).sqrt()
noise = _randn_like_with_generators(sample, generators)
x_next = (alpha_next / alpha_down) * x_next + noise.float() * LTX_ANCESTRAL_S_NOISE * renoise_coeff
result = x_next.to(sample.dtype)
return result
def _official_ltx_sigmas(
scheduler: Any,
steps: int,
device: torch.device,
) -> torch.Tensor:
"""Build the official LTX one-stage sigma schedule in torch fp32."""
config = scheduler.config
base_anchor = config.get("base_image_seq_len", 1024)
@@ -185,7 +289,8 @@ def _official_ltx_sigmas(scheduler: Any, steps: int, device: torch.device) -> to
sigmas = torch.linspace(1.0, 0.0, steps + 1)
slope = (max_shift - base_shift) / (max_anchor - base_anchor)
# Official LTX2 one-stage intentionally uses the max sequence anchor, so the shift stays at max_shift.
# Official LTX one-stage pipelines omit the latent when constructing
# this schedule, so the shift stays at the max sequence anchor.
sigma_shift = max_anchor * slope + (base_shift - slope * base_anchor)
exp_shift = math.exp(sigma_shift)
sigmas = torch.where(sigmas != 0, exp_shift / (exp_shift + (1 / sigmas - 1)), 0)
@@ -224,6 +329,9 @@ def prepare_scheduler_stage(
latent_width: int,
use_official_sigma_schedule: bool,
image_conditioned: bool = False,
sampler: str = "euler",
generator: torch.Generator | list[torch.Generator] | None = None,
conditioning_mask: torch.Tensor | None = None,
) -> tuple[Any, Any, torch.Tensor]:
if sigmas is not None and timesteps is not None:
raise ValueError("Only one of `sigmas` or `timesteps` may be provided.")
@@ -236,6 +344,9 @@ def prepare_scheduler_stage(
latent_height,
latent_width,
image_conditioned=image_conditioned,
sampler=sampler,
generator=generator,
conditioning_mask=conditioning_mask,
)
if sigmas is not None:
scheduler_sigmas = torch.as_tensor(sigmas, dtype=torch.float32, device=device)
@@ -302,6 +413,20 @@ def prepare_rope_coords_stage(
return video_coords, audio_coords
def _first_frame_keyframes_mask(reference: torch.Tensor, latent_num_frames: int) -> torch.Tensor:
"""Mark the first causal latent frame, matching official LTX-2.5."""
if latent_num_frames <= 0:
raise ValueError(f"LTX latent frame count must be positive, got {latent_num_frames}.")
tokens_per_frame, remainder = divmod(reference.shape[1], latent_num_frames)
if remainder:
raise ValueError(
f"LTX video token count {reference.shape[1]} is not divisible by {latent_num_frames} latent frames."
)
mask = reference.new_zeros((reference.shape[0], reference.shape[1], 1))
mask[:, :tokens_per_frame] = 1
return mask
def build_transformer_kwargs(
pipeline: Any,
forward_ctx: LTXForwardContext,
@@ -317,9 +442,13 @@ def build_transformer_kwargs(
attention_kwargs: dict[str, Any] | None = None,
) -> dict[str, Any]:
del encoder_attention_mask, audio_encoder_attention_mask
keyframes_mask = None
if getattr(pipeline.transformer.config, "use_keyframes_abs_pos_embedding", False):
keyframes_mask = _first_frame_keyframes_mask(hidden_states, forward_ctx.latent_num_frames)
return {
"hidden_states": hidden_states,
"audio_hidden_states": audio_hidden_states,
"keyframes_mask": keyframes_mask,
"encoder_hidden_states": encoder_hidden_states,
"audio_encoder_hidden_states": audio_encoder_hidden_states,
**pipeline._denoise_timestep_kwargs(
@@ -426,6 +555,9 @@ class LTXPhaseExecutor:
latent_width=latent_width,
use_official_sigma_schedule=phase_recipe.use_official_sigma_schedule,
image_conditioned=conditioning_mask is not None,
sampler=phase_recipe.sampler,
generator=request_inputs.generator,
conditioning_mask=conditioning_mask,
)
forward_ctx = LTXForwardContext(
req=req,
@@ -441,6 +573,7 @@ class LTXPhaseExecutor:
original_audio_num_frames=original_audio_num_frames,
padded_audio_num_frames=padded_audio_num_frames,
timesteps=timesteps_tensor,
sampler=phase_recipe.sampler,
audio_scheduler=audio_scheduler,
video_audio_step_adapter=video_audio_step_adapter,
)