| import os |
| import subprocess |
| import sys |
|
|
| |
| os.environ["TORCH_COMPILE_DISABLE"] = "1" |
| os.environ["TORCHDYNAMO_DISABLE"] = "1" |
|
|
| |
| subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False) |
|
|
| |
| LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git" |
| LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2") |
| LTX_COMMIT_SHA = "ae855f8538843825f9015a419cf4ba5edaf5eec2" |
|
|
| if not os.path.exists(LTX_REPO_DIR): |
| print(f"Cloning {LTX_REPO_URL}...") |
| os.makedirs(LTX_REPO_DIR) |
| subprocess.run(["git", "init", LTX_REPO_DIR], check=True) |
| subprocess.run(["git", "remote", "add", "origin", LTX_REPO_URL], cwd=LTX_REPO_DIR, check=True) |
| subprocess.run(["git", "fetch", "--depth", "1", "origin", LTX_COMMIT_SHA], cwd=LTX_REPO_DIR, check=True) |
| subprocess.run(["git", "checkout", LTX_COMMIT_SHA], cwd=LTX_REPO_DIR, check=True) |
|
|
|
|
| print("Installing ltx-core and ltx-pipelines from cloned repo...") |
| subprocess.run( |
| [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e", |
| os.path.join(LTX_REPO_DIR, "packages", "ltx-core"), |
| "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")], |
| check=True, |
| ) |
|
|
| sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src")) |
| sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src")) |
|
|
| import logging |
| import random |
| import tempfile |
| from pathlib import Path |
|
|
| import torch |
| torch._dynamo.config.suppress_errors = True |
| torch._dynamo.config.disable = True |
|
|
| import spaces |
| import gradio as gr |
| import numpy as np |
| from huggingface_hub import hf_hub_download, snapshot_download |
|
|
| from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number |
| from ltx_core.quantization import QuantizationPolicy |
| from ltx_pipelines.distilled import DistilledPipeline |
| from ltx_pipelines.utils.args import ImageConditioningInput |
| from ltx_pipelines.utils.media_io import encode_video |
|
|
| |
| from ltx_core.model.transformer import attention as _attn_mod |
| print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}") |
| try: |
| from xformers.ops import memory_efficient_attention as _mea |
| _attn_mod.memory_efficient_attention = _mea |
| print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}") |
| except Exception as e: |
| print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}") |
|
|
| |
| |
| |
| |
| try: |
| from xformers.ops.fmha import _set_use_fa3 |
| _set_use_fa3(False) |
| print("[ATTN] xformers FA3 dispatch disabled (Blackwell-incompatible)") |
| except Exception as e: |
| print(f"[ATTN] FA3 disable FAILED: {type(e).__name__}: {e}") |
|
|
| |
| |
| |
| |
| import json |
| import struct |
|
|
| from ltx_core.loader.primitives import StateDict |
| from ltx_core.loader.sft_loader import SafetensorsStateDictLoader |
|
|
| _SAFETENSORS_DTYPE_MAP = { |
| "F64": torch.float64, |
| "F32": torch.float32, |
| "F16": torch.float16, |
| "BF16": torch.bfloat16, |
| "F8_E5M2": torch.float8_e5m2, |
| "F8_E4M3": torch.float8_e4m3fn, |
| "I64": torch.int64, |
| "I32": torch.int32, |
| "I16": torch.int16, |
| "I8": torch.int8, |
| "U8": torch.uint8, |
| "BOOL": torch.bool, |
| } |
|
|
|
|
| def _patched_load(self, path, sd_ops, device=None): |
| sd = {} |
| size = 0 |
| dtype = set() |
| device = device or torch.device("cpu") |
| model_paths = path if isinstance(path, list) else [path] |
| for shard_path in model_paths: |
| with open(shard_path, "rb") as f: |
| header_len = struct.unpack("<Q", f.read(8))[0] |
| header = json.loads(f.read(header_len).decode("utf-8")) |
| data_base = 8 + header_len |
| for name, meta in header.items(): |
| if name == "__metadata__": |
| continue |
| expected_name = name if sd_ops is None else sd_ops.apply_to_key(name) |
| if expected_name is None: |
| continue |
| start, end = meta["data_offsets"] |
| f.seek(data_base + start) |
| buf = f.read(end - start) |
| t = torch.frombuffer( |
| bytearray(buf), dtype=_SAFETENSORS_DTYPE_MAP[meta["dtype"]] |
| ).reshape(meta["shape"]) |
| t = t.to(device=device, non_blocking=True, copy=False) |
| kvs = ( |
| ((expected_name, t),) |
| if sd_ops is None |
| else sd_ops.apply_to_key_value(expected_name, t) |
| ) |
| for key, v in kvs: |
| size += v.nbytes |
| dtype.add(v.dtype) |
| sd[key] = v |
| return StateDict(sd=sd, device=device, size=size, dtype=dtype) |
|
|
|
|
| SafetensorsStateDictLoader.load = _patched_load |
| print("[FUSE-PATCH] SafetensorsStateDictLoader.load replaced (chunked-read)") |
|
|
| logging.getLogger().setLevel(logging.INFO) |
|
|
| MAX_SEED = np.iinfo(np.int32).max |
| DEFAULT_PROMPT = ( |
| "An astronaut hatches from a fragile egg on the surface of the Moon, " |
| "the shell cracking and peeling apart in gentle low-gravity motion. " |
| "Fine lunar dust lifts and drifts outward with each movement, floating " |
| "in slow arcs before settling back onto the ground." |
| ) |
| DEFAULT_FRAME_RATE = 24.0 |
|
|
| |
| RESOLUTIONS = { |
| "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)}, |
| "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)}, |
| } |
|
|
| LTX_REPO_ID = "Lightricks/LTX-2.3" |
| |
| |
| GEMMA_REPO_ID = "Lightricks/gemma-3-12b-it-qat-q4_0-unquantized" |
|
|
| DISTILLED_FILENAME = "ltx-2.3-22b-distilled-1.1.safetensors" |
| UPSCALER_FILENAME = "ltx-2.3-spatial-upscaler-x2-1.1.safetensors" |
|
|
| |
| distilled_checkpoint_path = hf_hub_download(repo_id=LTX_REPO_ID, filename=DISTILLED_FILENAME) |
| spatial_upsampler_path = hf_hub_download(repo_id=LTX_REPO_ID, filename=UPSCALER_FILENAME) |
| gemma_root = snapshot_download(repo_id=GEMMA_REPO_ID) |
|
|
| |
| pipeline = DistilledPipeline( |
| distilled_checkpoint_path=distilled_checkpoint_path, |
| spatial_upsampler_path=spatial_upsampler_path, |
| gemma_root=gemma_root, |
| loras=[], |
| quantization=QuantizationPolicy.fp8_cast(), |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
| print("Preloading all models (including Gemma)...") |
| ledger = pipeline.model_ledger |
| _text_encoder = ledger.text_encoder() |
| |
| |
| |
| |
| |
| from torchao.quantization import quantize_ as _quantize_, Int8WeightOnlyConfig as _Int8 |
| _quantize_(_text_encoder, _Int8()) |
| print("[QUANT] Gemma text encoder quantized to int8") |
| _embeddings_processor = ledger.gemma_embeddings_processor() |
| _transformer = ledger.transformer() |
| _video_encoder = ledger.video_encoder() |
| _video_decoder = ledger.video_decoder() |
| _audio_decoder = ledger.audio_decoder() |
| _vocoder = ledger.vocoder() |
| _spatial_upsampler = ledger.spatial_upsampler() |
|
|
| ledger.transformer = lambda: _transformer |
| ledger.video_encoder = lambda: _video_encoder |
| ledger.video_decoder = lambda: _video_decoder |
| ledger.audio_decoder = lambda: _audio_decoder |
| ledger.vocoder = lambda: _vocoder |
| ledger.spatial_upsampler = lambda: _spatial_upsampler |
| ledger.text_encoder = lambda: _text_encoder |
| ledger.gemma_embeddings_processor = lambda: _embeddings_processor |
| print("All models preloaded (including Gemma text encoder)!") |
|
|
| print("=" * 80) |
| print("Pipeline ready!") |
| print("=" * 80) |
|
|
|
|
| def log_memory(tag: str): |
| if torch.cuda.is_available(): |
| allocated = torch.cuda.memory_allocated() / 1024**3 |
| peak = torch.cuda.max_memory_allocated() / 1024**3 |
| free, total = torch.cuda.mem_get_info() |
| print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB") |
|
|
|
|
| def detect_aspect_ratio(image) -> str: |
| """Detect the closest aspect ratio (16:9, 9:16, or 1:1) from an image.""" |
| if image is None: |
| return "16:9" |
| if hasattr(image, "size"): |
| w, h = image.size |
| elif hasattr(image, "shape"): |
| h, w = image.shape[:2] |
| else: |
| return "16:9" |
| ratio = w / h |
| candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0} |
| return min(candidates, key=lambda k: abs(ratio - candidates[k])) |
|
|
|
|
| def on_image_upload(image, high_res): |
| """Auto-set resolution when image is uploaded.""" |
| aspect = detect_aspect_ratio(image) |
| tier = "high" if high_res else "low" |
| w, h = RESOLUTIONS[tier][aspect] |
| return gr.update(value=w), gr.update(value=h) |
|
|
|
|
| def on_highres_toggle(image, high_res): |
| """Update resolution when high-res toggle changes.""" |
| aspect = detect_aspect_ratio(image) |
| tier = "high" if high_res else "low" |
| w, h = RESOLUTIONS[tier][aspect] |
| return gr.update(value=w), gr.update(value=h) |
|
|
|
|
| def _gpu_duration(input_image, prompt, duration, enhance_prompt=True, seed=10, |
| randomize_seed=True, height=1024, width=1536, *args, **kwargs): |
| |
| |
| |
| |
| |
| frames = int(float(duration) * DEFAULT_FRAME_RATE) + 1 |
| frames = ((frames - 1 + 7) // 8) * 8 + 1 |
| mpx_frames = int(height) * int(width) * frames / 1e6 |
| return int(min(110, max(20, 15 + 0.55 * mpx_frames))) |
|
|
| @spaces.GPU(duration=_gpu_duration) |
| @torch.inference_mode() |
| def generate_video( |
| input_image, |
| prompt: str, |
| duration: float, |
| enhance_prompt: bool = True, |
| seed: int = 42, |
| randomize_seed: bool = True, |
| height: int = 1024, |
| width: int = 1536, |
| progress=gr.Progress(track_tqdm=True), |
| ): |
| try: |
| torch.cuda.reset_peak_memory_stats() |
| log_memory("start") |
|
|
| current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed) |
|
|
| frame_rate = DEFAULT_FRAME_RATE |
| num_frames = int(duration * frame_rate) + 1 |
| num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1 |
|
|
| print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}") |
|
|
| images = [] |
| if input_image is not None: |
| output_dir = Path("outputs") |
| output_dir.mkdir(exist_ok=True) |
| temp_image_path = output_dir / f"temp_input_{current_seed}.jpg" |
| if hasattr(input_image, "save"): |
| input_image.save(temp_image_path) |
| else: |
| temp_image_path = Path(input_image) |
| images = [ImageConditioningInput(path=str(temp_image_path), frame_idx=0, strength=1.0)] |
|
|
| tiling_config = TilingConfig.default() |
| video_chunks_number = get_video_chunks_number(num_frames, tiling_config) |
|
|
| log_memory("before pipeline call") |
|
|
| video, audio = pipeline( |
| prompt=prompt, |
| seed=current_seed, |
| height=int(height), |
| width=int(width), |
| num_frames=num_frames, |
| frame_rate=frame_rate, |
| images=images, |
| tiling_config=tiling_config, |
| enhance_prompt=enhance_prompt, |
| ) |
|
|
| log_memory("after pipeline call") |
|
|
| output_path = tempfile.mktemp(suffix=".mp4") |
| encode_video( |
| video=video, |
| fps=frame_rate, |
| audio=audio, |
| output_path=output_path, |
| video_chunks_number=video_chunks_number, |
| ) |
|
|
| log_memory("after encode_video") |
| return str(output_path), current_seed |
|
|
| except Exception as e: |
| import traceback |
| log_memory("on error") |
| print(f"Error: {str(e)}\n{traceback.format_exc()}") |
| return None, current_seed |
|
|
|
|
| UPSAMPLER_THEME = gr.themes.Soft( |
| primary_hue=gr.themes.colors.indigo, |
| secondary_hue=gr.themes.colors.purple, |
| neutral_hue=gr.themes.colors.slate, |
| ).set( |
| button_primary_background_fill="linear-gradient(135deg, #6366f1, #a855f7)", |
| button_primary_background_fill_hover="linear-gradient(135deg, #5457e5, #9333ea)", |
| button_primary_text_color="#ffffff", |
| button_primary_border_color="*primary_500", |
| ) |
| UPSAMPLER_CSS = """ |
| footer{display:none !important} |
| .gradio-container{max-width:1000px !important; margin:0 auto !important} |
| h1,h2,h3{font-family:system-ui,-apple-system,'Segoe UI',sans-serif} |
| """ |
| _header = """<div style="max-width:760px;margin:0 auto;text-align:center;padding:20px 16px 2px;font-family:system-ui,-apple-system,'Segoe UI',sans-serif"> |
| <h1 style="font-size:1.7rem;font-weight:700;margin:0 0 6px;letter-spacing:-.02em">LTX 2.3 22B Distilled</h1> |
| <p style="font-size:1rem;line-height:1.5;opacity:.6;margin:0">Fast video with synchronized audio from a text prompt or an image.</p> |
| </div>""" |
| _footer = """<div style="max-width:640px;margin:2rem auto .4rem;text-align:center;font-family:system-ui,-apple-system,'Segoe UI',sans-serif"> |
| <p style="font-size:.85rem;line-height:1.6;opacity:.5;margin:0 0 10px">LTX 2.3 by Lightricks is one of the fastest open text-to-video models, generating HD clips with synchronized audio from a written prompt or a single image. Dialogue, sound effects, and camera motion come out of a single pass, so a finished video with sound takes well under a minute on this space.</p> |
| <p style="font-size:.85rem;line-height:1.6;opacity:.65;margin:0">Maintained by <a href="https://upsampler.com" target="_blank" rel="noopener" style="color:#8b7cf6;font-weight:600;text-decoration:none">Upsampler</a>. Check out the <a href="https://upsampler.com/free-video-generator-no-signup" target="_blank" rel="noopener" style="color:#8b7cf6;font-weight:600;text-decoration:none">free AI video generator</a>, no sign-up required.</p> |
| </div>""" |
|
|
| with gr.Blocks(title="LTX 2.3 - Text or Image to Video") as demo: |
| gr.HTML(_header) |
|
|
| with gr.Row(): |
| with gr.Column(): |
| input_image = gr.Image(label="Input Image (Optional)", type="pil") |
| prompt = gr.Textbox( |
| label="Prompt", |
| info="for best results - make it as elaborate as possible", |
| value="Make this image come alive with cinematic motion, smooth animation", |
| lines=3, |
| placeholder="Describe the motion and animation you want...", |
| ) |
| |
| with gr.Row(): |
| duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1) |
| with gr.Column(): |
| enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False) |
| high_res = gr.Checkbox(label="High Resolution", value=True) |
|
|
| generate_btn = gr.Button("Generate Video", variant="primary", size="lg") |
|
|
| with gr.Accordion("Advanced Settings", open=False): |
| seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1) |
| randomize_seed = gr.Checkbox(label="Randomize Seed", value=True) |
| with gr.Row(): |
| width = gr.Number(label="Width", value=1536, precision=0) |
| height = gr.Number(label="Height", value=1024, precision=0) |
|
|
| with gr.Column(): |
| output_video = gr.Video(label="Generated Video", autoplay=True) |
|
|
| |
| input_image.change( |
| fn=on_image_upload, |
| inputs=[input_image, high_res], |
| outputs=[width, height], |
| ) |
|
|
| |
| high_res.change( |
| fn=on_highres_toggle, |
| inputs=[input_image, high_res], |
| outputs=[width, height], |
| ) |
|
|
| generate_btn.click( |
| fn=generate_video, |
| inputs=[ |
| input_image, prompt, duration, enhance_prompt, |
| seed, randomize_seed, height, width, |
| ], |
| outputs=[output_video, seed], |
| ) |
|
|
| gr.HTML(_footer) |
|
|
|
|
| css = """ |
| .fillable{max-width: 1200px !important} |
| .progress-text {color: white} |
| """ |
|
|
| if __name__ == "__main__": |
| demo.launch(theme=UPSAMPLER_THEME, css=UPSAMPLER_CSS + css, ssr_mode=False, show_error=True) |
|
|
|
|