duongsd's picture
Default 1280x704 (720p)
8faed75 verified
Raw History Blame Contribute Delete
15.2 kB
import os
# ZeroGPU's MIG slice trips an NVML assert in torch's native caching allocator
# ("NVML_SUCCESS == r INTERNAL ASSERT FAILED"); cudaMallocAsync is NVML-safe. Must be set before
# torch initializes its allocator. torch 2.9 renamed the variable and warns on the old name, so set both.
os.environ.setdefault("PYTORCH_ALLOC_CONF", "backend:cudaMallocAsync")
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "backend:cudaMallocAsync")
import hashlib
import random
import tempfile
import time
from collections import OrderedDict
import gradio as gr
import PIL.Image
import spaces
import torch
from gradio_client import Client, handle_file
from huggingface_hub import snapshot_download
from diffusers import (
LTX2ImageToVideoPipeline,
LTX2LatentUpsamplePipeline,
LTX2Pipeline,
LTX2VideoDiffusionDecodePipeline,
LTX2VideoDiffusionDecoderModel,
)
from diffusers.models.autoencoders.ltx2_diffusion_decoder import (
LTX2VideoVaeNeighborhoodNattenProcessor,
)
from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel
from diffusers.pipelines.ltx2.utils import (
DEFAULT_NEGATIVE_PROMPT,
DISTILLED_SIGMA_VALUES,
STAGE_2_DISTILLED_SIGMA_VALUES,
)
from diffusers.utils import encode_video
HF_TOKEN = os.environ.get("HF_TOKEN")
# Lightricks' own diffusers pack. Verified equivalent to the internal mirror it replaces: same 4090
# transformer keys, byte-identical sampled tensors, identical transformer/scheduler/latent_upsampler
# configs — only the sharding differs (4 shards -> 8). Its `model_index.json` additionally lists
# `diffusion_decoder`, which `LTX2Pipeline` does not take; diffusers drops it with a warning
# ("not expected and will be ignored"), and the decoder is loaded from its subfolder below regardless.
# Gated (auto-approve): the Space's HF_TOKEN must have accepted the license or from_pretrained 403s.
MODEL_ID = os.environ.get("LTX25_MODEL_ID", "Lightricks/LTX-2.5-Diffusers")
MAX_SEED = 2**31 - 1
FRAME_RATE = 24.0
def frames_from_duration(seconds: float) -> int:
"""Snap a duration in seconds to the VAE's 8k+1 frame grid at 24 fps (2 s -> 49 frames)."""
return max(25, int(round(float(seconds) * FRAME_RATE)) // 8 * 8 + 1)
# Auto length. The LTX-2.5 checkpoints ship a duration head, so the model can pick the clip length from the
# prompt instead of taking it from the slider. Capped below the head's own 20s default: the ZeroGPU
# reservation has to cover the worst case (the prediction only exists once the connectors have run, i.e.
# already inside the GPU call), so the ceiling is what every auto run costs a visitor's quota.
AUTO_MAX_SECONDS = 15.0
AUTO_MAX_FRAMES = int(AUTO_MAX_SECONDS * FRAME_RATE) // 8 * 8 + 1 # 361, on the VAE's 8k+1 grid
# ---------------------------------------------------------------------------------------------
# THE RECIPE — the exported constants from diffusers.pipelines.ltx2.utils, already trimmed of the
# reference's trailing 0.0 (`set_timesteps(sigmas=...)` appends its own terminal zero).
# Note the spacing is deliberately non-uniform: five values packed near 1.0, then three large jumps.
# ---------------------------------------------------------------------------------------------
STAGE_1_SIGMAS = DISTILLED_SIGMA_VALUES
STAGE_2_SIGMAS = STAGE_2_DISTILLED_SIGMA_VALUES
# Unguided in both stages: the reference uses SimpleDenoiser throughout for the distilled model.
GUIDANCE_SCALE = 1.0
AUDIO_GUIDANCE_SCALE = 1.0
def load_conditioning_image(path: str, width: int | None = None, height: int | None = None) -> PIL.Image.Image:
"""Load a conditioning image and (when a target size is given) cover-resize and center-crop to
exactly ``width``x``height`` — so the pipeline's own resize is an identity and never distorts the
aspect ratio. The training-matched H.264 CRF re-compression now lives in the pipeline itself
(`image_crf`, auto-resolved to 18 for LTX-2.5), applied to the image we hand it."""
img = PIL.Image.open(path).convert("RGB")
if width and height:
scale = max(width / img.width, height / img.height)
img = img.resize((round(img.width * scale), round(img.height * scale)), PIL.Image.LANCZOS)
left, top = (img.width - width) // 2, (img.height - height) // 2
img = img.crop((left, top, left + width, top + height))
return img
# Image-to-video sizing: the smaller side is pinned here and the longer side follows the input
# image's aspect ratio on the two-stage /64 grid.
I2V_SHORT_SIDE = 832
MAX_SIDE = 1536
def dims_for_image(image_w: int, image_h: int) -> tuple[int, int]:
"""Closest valid (height, width) to an uploaded image: smaller side fixed at ``I2V_SHORT_SIDE``,
longer side the aspect-matched multiple of 64, capped at the slider maximum."""
if image_w >= image_h:
height = I2V_SHORT_SIDE
width = min(MAX_SIDE, max(I2V_SHORT_SIDE, round(I2V_SHORT_SIDE * image_w / image_h / 64) * 64))
else:
width = I2V_SHORT_SIDE
height = min(MAX_SIDE, max(I2V_SHORT_SIDE, round(I2V_SHORT_SIDE * image_h / image_w / 64) * 64))
return height, width
print("[ltx25-diffusers] loading LTX-2.5 distilled (transformer + gemma4 + conv VAE + audio)...", flush=True)
# Module scope + .to("cuda") is the ZeroGPU pattern: weights placed on cuda at import are packed to
# disk by the backend and streamed into VRAM on the first @spaces.GPU entry. Loading inside the
# decorated call instead spends the whole allocation on ~60 GB of I/O; leaving them on the CPU gets
# the container OOM-killed, since transformer + encoder + connectors is ~68 GB of RAM.
# Snapshot first, without `transformer_full/`. `from_pretrained` builds its allow-patterns from every
# model-like file in the repo rather than from `model_index.json`, so it pulls BOTH DiTs -- 76 GB of
# transformer instead of 38 -- and fills the disk. Passing `ignore_patterns` to `from_pretrained` does
# not help: it is discarded before the download call.
MODEL_DIR = snapshot_download(
MODEL_ID, ignore_patterns=["transformer_full/*"], token=HF_TOKEN, max_workers=8
)
pipe = LTX2Pipeline.from_pretrained(MODEL_DIR, dtype=torch.bfloat16)
# LTX-2.5's own decoder. It is NOT the pipeline's `vae`: encoding still goes through the convolutional
# AutoencoderKLLTX2Video (which is also what the latent upsampler needs), and this drives pixel decode.
diffusion_decoder = LTX2VideoDiffusionDecoderModel.from_pretrained(
MODEL_DIR, subfolder="diffusion_decoder", dtype=torch.bfloat16
)
# The default processor builds a FlexAttention BlockMask; uncompiled that materialises the full score
# matrix, so NATTEN's fused kernels are the practical choice at video resolutions — and they are what
# the reference decoder calls. Fetched from the Hub (`shi-labs/natten`) via the `kernels` package.
diffusion_decoder.set_attn_processor(LTX2VideoVaeNeighborhoodNattenProcessor())
# Overlapping-tile decode: peak memory bounded by the tile size, not the video size.
diffusion_decoder.enable_tiling()
# ltx-2.3-spatial-upscaler-x2-1.1, converted to diffusers format. There is no 2.5-era upscaler; the
# partner README says to use the 2.3 one, and the distilled recipe requires it.
latent_upsampler = LTX2LatentUpsamplerModel.from_pretrained(
MODEL_DIR, subfolder="latent_upsampler", dtype=torch.bfloat16
)
pipe.to("cuda")
diffusion_decoder.to("cuda")
latent_upsampler.to("cuda")
# The conv decoder is the fallback for large outputs, and untiled it OOMs there: stage 2 decodes at
# double the stage-1 resolution, which asked for >100 GB at 1088x1920. The reference script tiles too.
pipe.vae.enable_tiling()
AUDIO_SR = pipe.vocoder.config.output_sampling_rate
# Every auxiliary pipeline below wraps the SAME already-loaded component objects — no second copy of
# the 22B transformer or the 12B encoder.
decode_pipe = LTX2VideoDiffusionDecodePipeline(
diffusion_decoder=diffusion_decoder, scheduler=pipe.scheduler
)
upsample_pipe = LTX2LatentUpsamplePipeline(vae=pipe.vae, latent_upsampler=latent_upsampler)
from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2ConditionPipeline, LTX2VideoCondition
# Keyframe (first/last frame) pipeline wrapping the SAME loaded components: no second copy of weights.
_comp = {k: v for k, v in pipe.components.items()
if k in ("scheduler", "vae", "audio_vae", "text_encoder", "tokenizer", "connectors", "transformer",
"vocoder", "audio_scheduler", "processor", "prompt_enhancer", "duration_head")}
pipe_cond = LTX2ConditionPipeline(**_comp)
print(f"[flf] ready (components: {sorted(_comp)})", flush=True)
MAX_SECONDS = 10.0
def _duration(prompt, negative_prompt, first_path, last_path, loop, height, width, num_frames, seed,
decoder, *args) -> int:
px = int(height) * int(width) * int(num_frames)
decode = 25 if decoder == "diffusion" else 10
return int(min(300, max(60, 40 + px / 1_200_000 + decode)))
@spaces.GPU(duration=_duration, size="xlarge")
def generate(prompt, negative_prompt, first_path, last_path, loop, height, width, num_frames, seed,
decoder, progress=gr.Progress(track_tqdm=True)):
height, width, num_frames = int(height), int(width), int(num_frames)
if height % 64 or width % 64:
raise gr.Error(f"Height and width must be divisible by 64 (got {height}x{width}).")
generator = torch.Generator("cuda").manual_seed(int(seed))
def conds(w, h):
c = []
if first_path:
first = load_conditioning_image(first_path, w, h)
c.append(LTX2VideoCondition(frames=first, index=0, strength=1.0))
if loop:
c.append(LTX2VideoCondition(frames=first, index=-1, strength=1.0))
if last_path and not loop:
c.append(LTX2VideoCondition(frames=load_conditioning_image(last_path, w, h), index=-1, strength=1.0))
return c
shared = dict(
prompt=prompt,
negative_prompt=negative_prompt or DEFAULT_NEGATIVE_PROMPT,
frame_rate=FRAME_RATE, guidance_scale=1.0, audio_guidance_scale=1.0,
stg_scale=0.0, audio_stg_scale=0.0, modality_scale=1.0, audio_modality_scale=1.0,
guidance_rescale=0.0, audio_guidance_rescale=0.0, spatio_temporal_guidance_blocks=None,
generator=generator, return_dict=False,
)
t0 = time.time()
print(f"[gen] stage 1 @ {width // 2}x{height // 2}x{num_frames}", flush=True)
s1_latents, s1_audio = pipe_cond(
conditions=conds(width // 2, height // 2), height=height // 2, width=width // 2,
num_frames=num_frames, sigmas=STAGE_1_SIGMAS, output_type="latent", **shared)
num_frames = (s1_latents.shape[2] - 1) * pipe.vae_temporal_compression_ratio + 1
up = upsample_pipe(latents=s1_latents, output_type="latent", return_dict=False)[0]
print(f"[gen] stage 2 @ {width}x{height}x{num_frames}", flush=True)
want_latents = decoder == "diffusion"
s2 = pipe_cond(
conditions=conds(width, height), height=height, width=width, num_frames=num_frames,
sigmas=STAGE_2_SIGMAS, latents=up, audio_latents=s1_audio, noise_scale=STAGE_2_SIGMAS[0],
output_type="latent" if want_latents else "np", **shared)
if want_latents:
vl, al = s2
video = decode_pipe(vl, generator=generator, denormalize=False, output_type="np", return_dict=False)[0]
mel = pipe.audio_vae.decode(al.to(pipe.audio_vae.dtype), return_dict=False)[0]
audio = pipe.vocoder(mel)
else:
video, audio = s2
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as fh:
path = fh.name
kw = dict(audio=audio[0].float().cpu(), audio_sample_rate=AUDIO_SR) if audio is not None else {}
encode_video(video[0], fps=FRAME_RATE, output_path=path, **kw)
print(f"[gen] done in {time.time() - t0:.1f}s", flush=True)
return path, num_frames
def run(first_image, last_image, loop, prompt, negative_prompt, duration_s, width, height, seed,
randomize_seed, decoder):
if not first_image and not last_image:
raise gr.Error("Upload at least a first image.")
if not first_image:
first_image, last_image = None, last_image
if randomize_seed:
seed = random.randint(0, MAX_SEED)
nf = frames_from_duration(duration_s)
video, frames = generate(prompt, negative_prompt, first_image, last_image, bool(loop),
height, width, nf, seed, decoder)
return video, seed, f"{frames} frames ({frames / FRAME_RATE:.2f}s)"
with gr.Blocks(title="LTX-2.5 First/Last Frame") as demo:
gr.Markdown("# LTX-2.5 · First / Last Frame (keyframe) video\n"
"LTX-2.5 distilled 22B, two-stage (8 + 3 steps), via diffusers `LTX2ConditionPipeline`. "
"Tick **Seamless loop** to use the first image as the last frame too.")
with gr.Row():
with gr.Column():
with gr.Row():
first_image = gr.Image(label="First frame", type="filepath")
last_image = gr.Image(label="Last frame (optional)", type="filepath")
loop = gr.Checkbox(label="Seamless loop (last frame = first frame)", value=False)
prompt = gr.Textbox(label="Prompt", lines=4)
duration = gr.Slider(1.0, MAX_SECONDS, value=5.0, step=0.5, label="Duration (s, 24 fps)")
with gr.Accordion("Settings", open=False):
negative_prompt = gr.Textbox(label="Negative prompt", value=DEFAULT_NEGATIVE_PROMPT, lines=2,
info="Little effect: the distilled model runs without CFG.")
with gr.Row():
width = gr.Slider(512, MAX_SIDE, value=1280, step=64, label="Width")
height = gr.Slider(512, MAX_SIDE, value=704, step=64, label="Height")
gr.Number(value=11, interactive=False, label="Steps (fixed by distillation: 8 + 3)")
decoder = gr.Radio(["conv", "diffusion"], value="conv", label="Video decoder")
with gr.Row():
seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed")
randomize_seed = gr.Checkbox(value=False, label="Randomize seed")
go = gr.Button("Generate", variant="primary")
with gr.Column():
out_video = gr.Video(label="Result", autoplay=True)
used_seed = gr.Number(label="Seed used", interactive=False)
used_length = gr.Textbox(label="Length generated", interactive=False)
def set_dims(path):
if not path:
return gr.update(), gr.update()
with PIL.Image.open(path) as im:
w, h = im.size
if w >= h:
hh = 704; ww = min(MAX_SIDE, max(512, round(704 * w / h / 64) * 64))
else:
ww = 704; hh = min(MAX_SIDE, max(512, round(704 * h / w / 64) * 64))
return hh, ww
first_image.upload(set_dims, inputs=first_image, outputs=[height, width])
go.click(run, [first_image, last_image, loop, prompt, negative_prompt, duration, width, height, seed,
randomize_seed, decoder], [out_video, used_seed, used_length], api_name="generate")
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus())