Spaces:
Runtime error
Runtime error
Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652import osimport subprocessimport sys
# Disable torch.compile / dynamo before any torch importos.environ["TORCH_COMPILE_DISABLE"] = "1"os.environ["TORCHDYNAMO_DISABLE"] = "1"
# Install xformers for memory-efficient attentionsubprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
# Clone LTX-2 repo and install packagesLTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
if not os.path.exists(LTX_REPO_DIR): print(f"Cloning {LTX_REPO_URL}...") subprocess.run(["git", "clone", "--depth", "1", LTX_REPO_URL, 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 loggingimport randomimport tempfilefrom pathlib import Path
import torchtorch._dynamo.config.suppress_errors = Truetorch._dynamo.config.disable = True
import spacesimport gradio as grimport numpy as npfrom huggingface_hub import hf_hub_download, snapshot_download
from ltx_core.components.diffusion_steps import EulerDiffusionStepfrom ltx_core.components.noisers import GaussianNoiserfrom ltx_core.model.audio_vae import encode_audio as vae_encode_audiofrom ltx_core.model.upsampler import upsample_videofrom ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video# >>> ADD these imports (place immediately after your video_vae import)from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAPfrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.types import Audio, AudioLatentShape, VideoPixelShapefrom ltx_pipelines.distilled import DistilledPipelinefrom ltx_pipelines.utils import euler_denoising_loopfrom ltx_pipelines.utils.args import ImageConditioningInputfrom ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUESfrom ltx_pipelines.utils.helpers import ( cleanup_memory, combined_image_conditionings, denoise_video_only, encode_prompts, simple_denoising_func,)from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
# Force-patch xformers attention into the LTX attention module.from ltx_core.model.transformer import attention as _attn_modprint(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}")
logging.getLogger().setLevel(logging.INFO)
MAX_SEED = np.iinfo(np.int32).maxDEFAULT_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
# Resolution presets: (width, height)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)},}
class LTX23DistilledA2VPipeline(DistilledPipeline): """DistilledPipeline with optional audio conditioning."""
def __call__( self, prompt: str, seed: int, height: int, width: int, num_frames: int, frame_rate: float, images: list[ImageConditioningInput], audio_path: str | None = None, tiling_config: TilingConfig | None = None, enhance_prompt: bool = False, ): # Standard path when no audio input is provided. print(prompt) if audio_path is None: return super().__call__( prompt=prompt, seed=seed, height=height, width=width, num_frames=num_frames, frame_rate=frame_rate, images=images, tiling_config=tiling_config, enhance_prompt=enhance_prompt, )
generator = torch.Generator(device=self.device).manual_seed(seed) noiser = GaussianNoiser(generator=generator) stepper = EulerDiffusionStep() dtype = torch.bfloat16
(ctx_p,) = encode_prompts( [prompt], self.model_ledger, enhance_first_prompt=enhance_prompt, enhance_prompt_image=images[0].path if len(images) > 0 else None, ) video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
video_duration = num_frames / frame_rate decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration) if decoded_audio is None: raise ValueError(f"Could not extract audio stream from {audio_path}")
encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder()) audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16) expected_frames = audio_shape.frames actual_frames = encoded_audio_latent.shape[2]
if actual_frames > expected_frames: encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :] elif actual_frames < expected_frames: pad = torch.zeros( encoded_audio_latent.shape[0], encoded_audio_latent.shape[1], expected_frames - actual_frames, encoded_audio_latent.shape[3], device=encoded_audio_latent.device, dtype=encoded_audio_latent.dtype, ) encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
video_encoder = self.model_ledger.video_encoder() transformer = self.model_ledger.transformer() stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
def denoising_loop(sigmas, video_state, audio_state, stepper): return euler_denoising_loop( sigmas=sigmas, video_state=video_state, audio_state=audio_state, stepper=stepper, denoise_fn=simple_denoising_func( video_context=video_context, audio_context=audio_context, transformer=transformer, ), )
stage_1_output_shape = VideoPixelShape( batch=1, frames=num_frames, width=width // 2, height=height // 2, fps=frame_rate, ) stage_1_conditionings = combined_image_conditionings( images=images, height=stage_1_output_shape.height, width=stage_1_output_shape.width, video_encoder=video_encoder, dtype=dtype, device=self.device, ) video_state = denoise_video_only( output_shape=stage_1_output_shape, conditionings=stage_1_conditionings, noiser=noiser, sigmas=stage_1_sigmas, stepper=stepper, denoising_loop_fn=denoising_loop, components=self.pipeline_components, dtype=dtype, device=self.device, initial_audio_latent=encoded_audio_latent, )
torch.cuda.synchronize() cleanup_memory()
upscaled_video_latent = upsample_video( latent=video_state.latent[:1], video_encoder=video_encoder, upsampler=self.model_ledger.spatial_upsampler(), ) stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device) stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate) stage_2_conditionings = combined_image_conditionings( images=images, height=stage_2_output_shape.height, width=stage_2_output_shape.width, video_encoder=video_encoder, dtype=dtype, device=self.device, ) video_state = denoise_video_only( output_shape=stage_2_output_shape, conditionings=stage_2_conditionings, noiser=noiser, sigmas=stage_2_sigmas, stepper=stepper, denoising_loop_fn=denoising_loop, components=self.pipeline_components, dtype=dtype, device=self.device, noise_scale=stage_2_sigmas[0], initial_video_latent=upscaled_video_latent, initial_audio_latent=encoded_audio_latent, )
torch.cuda.synchronize() del transformer del video_encoder cleanup_memory()
decoded_video = vae_decode_video( video_state.latent, self.model_ledger.video_decoder(), tiling_config, generator, ) original_audio = Audio( waveform=decoded_audio.waveform.squeeze(0), sampling_rate=decoded_audio.sampling_rate, ) return decoded_video, original_audio
# Model reposLTX_MODEL_REPO = "Lightricks/LTX-2.3"GEMMA_REPO ="rahul7star/gemma-3-12b-it-heretic"
# Download model checkpointsprint("=" * 80)print("Downloading LTX-2.3 distilled model + Gemma...")print("=" * 80)
checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled.safetensors")spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")gemma_root = snapshot_download(repo_id=GEMMA_REPO)
# >>> ADD: download and prepare LoRA descriptorprint("Downloading LoRA for this Space (dagloop5/LoRA:LoRA2.safetensors)...")lora_path = hf_hub_download(repo_id="dagloop5/LoRA", filename="LoRA2.safetensors")# Create a descriptor object that the LTX loader expects.# initial strength is set to 1.0; we'll mutate `.strength` at runtime from the UI slider.lora_descriptor = LoraPathStrengthAndSDOps(lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)
print(f"LoRA: {lora_path}")
print(f"Checkpoint: {checkpoint_path}")print(f"Spatial upsampler: {spatial_upsampler_path}")print(f"Gemma root: {gemma_root}")
# Initialize pipeline WITH text encoder and optional audio supportpipeline = LTX23DistilledA2VPipeline( distilled_checkpoint_path=checkpoint_path, spatial_upsampler_path=spatial_upsampler_path, gemma_root=gemma_root, loras=[lora_descriptor], quantization=QuantizationPolicy.fp8_cast(),)
# Preload all models for ZeroGPU tensor packing.# >>> REPLACE the "Preload all models" block with this one:print("Preloading models (pinning decoders/encoders but leaving transformer dynamic)...")ledger = pipeline.model_ledger
# NOTE: do NOT call ledger.transformer() here. We keep the transformer's construction dynamic# so that changes to lora_descriptor.strength (made at runtime) are applied when the transformer# is built. We DO preload other components that are safe to pin._video_encoder = ledger.video_encoder()_video_decoder = ledger.video_decoder()_audio_encoder = ledger.audio_encoder()_audio_decoder = ledger.audio_decoder()_vocoder = ledger.vocoder()_spatial_upsampler = ledger.spatial_upsampler()_text_encoder = ledger.text_encoder()_embeddings_processor = ledger.gemma_embeddings_processor()
# Replace ledger methods to return the pinned objects for those components.# Intentionally do NOT override ledger.transformer so transformer is built when needed.ledger.video_encoder = lambda: _video_encoderledger.video_decoder = lambda: _video_decoderledger.audio_encoder = lambda: _audio_encoderledger.audio_decoder = lambda: _audio_decoderledger.vocoder = lambda: _vocoderledger.spatial_upsampler = lambda: _spatial_upsamplerledger.text_encoder = lambda: _text_encoderledger.gemma_embeddings_processor = lambda: _embeddings_processor
print("Selected models pinned. Transformer remains dynamic to reflect runtime LoRA strength.")print("Preload complete.")
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: 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(first_image, last_image, high_res): ref_image = first_image if first_image is not None else last_image aspect = detect_aspect_ratio(ref_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(first_image, last_image, high_res): ref_image = first_image if first_image is not None else last_image aspect = detect_aspect_ratio(ref_image) tier = "high" if high_res else "low" w, h = RESOLUTIONS[tier][aspect] return gr.update(value=w), gr.update(value=h)
@spaces.GPU(duration=75)@torch.inference_mode()def generate_video( first_image, last_image, input_audio, prompt: str, duration: float, enhance_prompt: bool = True, seed: int = 42, randomize_seed: bool = True, height: int = 1024, width: int = 1536, lora_strength: float = 1.0, progress=gr.Progress(track_tqdm=True),): try: global pipeline # <<< ADD THIS LINE HERE (VERY TOP of try block) 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 = [] output_dir = Path("outputs") output_dir.mkdir(exist_ok=True)
if first_image is not None: temp_first_path = output_dir / f"temp_first_{current_seed}.jpg" if hasattr(first_image, "save"): first_image.save(temp_first_path) else: temp_first_path = Path(first_image) images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
if last_image is not None: temp_last_path = output_dir / f"temp_last_{current_seed}.jpg" if hasattr(last_image, "save"): last_image.save(temp_last_path) else: temp_last_path = Path(last_image) images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
tiling_config = TilingConfig.default() video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
# >>> RUNTIME LoRA application (robust, multi-fallback) # We cannot rely on mutating the original descriptor (some implementations are immutable), # so create a fresh runtime descriptor and try multiple ways to install it. runtime_strength = float(lora_strength) replaced = False
# 1) Try simple approach: build a new LoraPathStrengthAndSDOps runtime_lora = LoraPathStrengthAndSDOps(lora_path, runtime_strength, LTXV_LORA_COMFY_RENAMING_MAP) print(f"[LoRA] attempting to apply runtime LoRA (strength={runtime_strength})")
# Try a few likely places to replace the descriptor used by the pipeline/ledger. try: # common attribute on pipeline if hasattr(pipeline, "loras"): try: pipeline.loras = [runtime_lora] replaced = True print("[LoRA] replaced pipeline.loras") except Exception as e: print(f"[LoRA] pipeline.loras assignment failed: {e}") except Exception: pass
try: # common attribute on the model ledger if hasattr(pipeline, "model_ledger") and hasattr(pipeline.model_ledger, "loras"): try: pipeline.model_ledger.loras = [runtime_lora] replaced = True print("[LoRA] replaced pipeline.model_ledger.loras") except Exception as e: print(f"[LoRA] pipeline.model_ledger.loras assignment failed: {e}") except Exception: pass
try: # some internals use a private _loras list if hasattr(pipeline, "model_ledger") and hasattr(pipeline.model_ledger, "_loras"): try: pipeline.model_ledger._loras = [runtime_lora] replaced = True print("[LoRA] replaced pipeline.model_ledger._loras") except Exception as e: print(f"[LoRA] pipeline.model_ledger._loras assignment failed: {e}") except Exception: pass
# 2) If we succeeded replacing the descriptor in-place, clear transformer cache so it will rebuild if replaced: try: if hasattr(pipeline.model_ledger, "_transformer"): pipeline.model_ledger._transformer = None # also clear potential caches named similar to 'transformer_cache' if present if hasattr(pipeline.model_ledger, "transformer_cache"): try: pipeline.model_ledger.transformer_cache = {} except Exception: pass print("[LoRA] in-place descriptor replacement done; transformer cache cleared") except Exception as e: print(f"[LoRA] replacement succeeded but cache clearing failed: {e}")
# 3) FINAL FALLBACK - if none of the in-place replacements worked, rebuild the pipeline if not replaced: print("[LoRA] in-place replacement FAILED; rebuilding pipeline with runtime LoRA (this is slow)") try: # Rebuild pipeline object with the new LoRA descriptor # NOTE: this replaces the global `pipeline`. We must declare global to reassign it. pipeline = LTX23DistilledA2VPipeline( distilled_checkpoint_path=checkpoint_path, spatial_upsampler_path=spatial_upsampler_path, gemma_root=gemma_root, loras=[runtime_lora], quantization=QuantizationPolicy.fp8_cast(), )
# After rebuilding, we *do not* re-run the original module-level preloads here, # because re-pinning may be complex; the rebuilt pipeline will construct its # own ledger as part of the first call. This is slower but reliable. # Clear any transformer caches if they exist on the new ledger as well. try: if hasattr(pipeline.model_ledger, "_transformer"): pipeline.model_ledger._transformer = None except Exception: pass
print("[LoRA] pipeline rebuilt with runtime LoRA") except Exception as e: print(f"[LoRA] pipeline rebuild FAILED: {e}")
# Finally, log memory then proceed 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, audio_path=input_audio, 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
with gr.Blocks(title="LTX-2.3 Heretic Distilled") as demo: gr.Markdown("# LTX-2.3 F2LF:Heretic with Fast Audio-Video Generation with Frame Conditioning")
with gr.Row(): with gr.Column(): with gr.Row(): first_image = gr.Image(label="First Frame (Optional)", type="pil") last_image = gr.Image(label="Last Frame (Optional)", type="pil") input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath") 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...", ) duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
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.Row(): enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False) high_res = gr.Checkbox(label="High Resolution", value=True) # >>> MOVE slider OUTSIDE the row lora_strength = gr.Slider( label="LoRA Strength", info="Scale for the LoRA weights (0.0 = off). Set near 1.0 for full effect.", minimum=0.0, maximum=2.0, value=1.0, step=0.01, )
with gr.Column(): output_video = gr.Video(label="Generated Video", autoplay=False)
gr.Examples( examples=[ [ None, "pinkknit.jpg", None, "The camera falls downward through darkness as if dropped into a tunnel. " "As it slows, five friends wearing pink knitted hats and sunglasses lean " "over and look down toward the camera with curious expressions. The lens " "has a strong fisheye effect, creating a circular frame around them. They " "crowd together closely, forming a symmetrical cluster while staring " "directly into the lens.", 3.0, False, 42, True, 1024, 1024, 1.0, ], ], inputs=[ first_image, last_image, input_audio, prompt, duration, enhance_prompt, seed, randomize_seed, height, width, lora_strength ], )
first_image.change( fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height], )
last_image.change( fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height], )
high_res.change( fn=on_highres_toggle, inputs=[first_image, last_image, high_res], outputs=[width, height], )
generate_btn.click( fn=generate_video, inputs=[ first_image, last_image, input_audio, prompt, duration, enhance_prompt, seed, randomize_seed, height, width, lora_strength ], outputs=[output_video, seed], )
css = """.fillable{max-width: 1200px !important}"""
if __name__ == "__main__": demo.launch(theme=gr.themes.Citrus(), css=css)app.pyAdded+652