dagloop5 commited on
Commit
0df7722
·
verified ·
1 Parent(s): 4b5cf9a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +901 -0
app.py ADDED
@@ -0,0 +1,901 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Installation and Setup
3
+ # =============================================================================
4
+ import os
5
+ import subprocess
6
+ import sys
7
+
8
+ os.environ["TORCH_COMPILE_DISABLE"] = "1"
9
+ os.environ["TORCHDYNAMO_DISABLE"] = "1"
10
+
11
+ subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
12
+
13
+ LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
14
+ LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
15
+ LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2"
16
+
17
+ if not os.path.exists(LTX_REPO_DIR):
18
+ print(f"Cloning {LTX_REPO_URL}...")
19
+ subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
20
+ subprocess.run(["git", "checkout", LTX_COMMIT], cwd=LTX_REPO_DIR, check=True)
21
+
22
+ print("Installing ltx-core and ltx-pipelines from cloned repo...")
23
+ subprocess.run(
24
+ [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
25
+ os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
26
+ "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
27
+ check=True,
28
+ )
29
+
30
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
31
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
32
+
33
+ # =============================================================================
34
+ # Imports
35
+ # =============================================================================
36
+ import logging
37
+ import random
38
+ import tempfile
39
+ from pathlib import Path
40
+ import gc
41
+ import hashlib
42
+
43
+ import torch
44
+ torch._dynamo.config.suppress_errors = True
45
+ torch._dynamo.config.disable = True
46
+
47
+ import spaces
48
+ import gradio as gr
49
+ import numpy as np
50
+ from huggingface_hub import hf_hub_download, snapshot_download
51
+ from safetensors.torch import load_file, save_file
52
+
53
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
54
+ from ltx_core.model.audio_vae import decode_audio as vae_decode_audio
55
+ from ltx_core.model.video_vae import decode_video as vae_decode_video
56
+ from ltx_core.model.upsampler import upsample_video
57
+ from ltx_core.quantization import QuantizationPolicy
58
+ from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
59
+ from ltx_core.components.guiders import MultiModalGuider, MultiModalGuiderParams
60
+ from ltx_core.components.noisers import GaussianNoiser
61
+ from ltx_core.components.diffusion_steps import Res2sDiffusionStep
62
+ from ltx_core.components.schedulers import LTX2Scheduler
63
+ from ltx_core.types import Audio, LatentState, VideoPixelShape, AudioLatentShape
64
+ from ltx_core.tools import VideoLatentShape
65
+
66
+ from ltx_pipelines.ti2vid_two_stages_hq import TI2VidTwoStagesHQPipeline
67
+ from ltx_pipelines.utils.args import ImageConditioningInput
68
+ from ltx_pipelines.utils.constants import LTX_2_3_HQ_PARAMS, STAGE_2_DISTILLED_SIGMA_VALUES
69
+ from ltx_pipelines.utils.media_io import encode_video
70
+ from ltx_pipelines.utils.helpers import (
71
+ assert_resolution,
72
+ cleanup_memory,
73
+ combined_image_conditionings,
74
+ encode_prompts,
75
+ res2s_audio_video_denoising_loop,
76
+ multi_modal_guider_denoising_func,
77
+ simple_denoising_func,
78
+ denoise_audio_video,
79
+ )
80
+
81
+ # Patch xformers
82
+ try:
83
+ from ltx_core.model.transformer import attention as _attn_mod
84
+ from xformers.ops import memory_efficient_attention as _mea
85
+ _attn_mod.memory_efficient_attention = _mea
86
+ print("[ATTN] xformers patch applied")
87
+ except Exception as e:
88
+ print(f"[ATTN] xformers patch failed: {e}")
89
+
90
+ logging.getLogger().setLevel(logging.INFO)
91
+
92
+ MAX_SEED = np.iinfo(np.int32).max
93
+ DEFAULT_PROMPT = (
94
+ "A majestic eagle soaring over mountain peaks at sunset, "
95
+ "wings spread wide against the orange sky, feathers catching the light, "
96
+ "wind currents visible in the motion blur, cinematic slow motion, 4K quality"
97
+ )
98
+ DEFAULT_NEGATIVE_PROMPT = (
99
+ "worst quality, inconsistent motion, blurry, jittery, distorted, "
100
+ "deformed, artifacts, text, watermark, logo, frame, border, "
101
+ "low resolution, pixelated, unnatural, fake, CGI, cartoon"
102
+ )
103
+ DEFAULT_FRAME_RATE = 24.0
104
+ MIN_DIM, MAX_DIM, STEP = 256, 1280, 64
105
+ MIN_FRAMES, MAX_FRAMES = 9, 257
106
+
107
+ # Resolution presets with high/low tiers
108
+ RESOLUTIONS = {
109
+ "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
110
+ "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
111
+ }
112
+
113
+ LTX_MODEL_REPO = "Lightricks/LTX-2.3"
114
+ GEMMA_REPO = "Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
115
+
116
+ # =============================================================================
117
+ # Custom HQ Pipeline with LoRA Cache Support
118
+ # =============================================================================
119
+
120
+ class HQPipelineWithCachedLoRA(TI2VidTwoStagesHQPipeline):
121
+ """TI2VidTwoStagesHQPipeline with support for cached LoRA state."""
122
+
123
+ def __init__(self, *args, **kwargs):
124
+ super().__init__(*args, **kwargs)
125
+ self._cached_state_stage1 = None
126
+ self._cached_state_stage2 = None
127
+
128
+ def apply_cached_lora_state(self, state_dict_stage1, state_dict_stage2=None):
129
+ self._cached_state_stage1 = state_dict_stage1
130
+ self._cached_state_stage2 = state_dict_stage2 if state_dict_stage2 else state_dict_stage1
131
+
132
+ @torch.inference_mode()
133
+ def __call__( # noqa: PLR0913
134
+ self,
135
+ prompt: str,
136
+ negative_prompt: str,
137
+ seed: int,
138
+ height: int,
139
+ width: int,
140
+ num_frames: int,
141
+ frame_rate: float,
142
+ num_inference_steps: int,
143
+ video_guider_params: MultiModalGuiderParams,
144
+ audio_guider_params: MultiModalGuiderParams,
145
+ images: list,
146
+ tiling_config: TilingConfig | None = None,
147
+ enhance_prompt: bool = False,
148
+ ):
149
+ assert_resolution(height=height, width=width, is_two_stage=True)
150
+
151
+ device = self.device
152
+ dtype = self.dtype
153
+ generator = torch.Generator(device=device).manual_seed(seed)
154
+ noiser = GaussianNoiser(generator=generator)
155
+
156
+ # Apply cached LoRA state if available
157
+ if self._cached_state_stage1 is not None:
158
+ print("[LoRA] Applying cached state to stage 1 transformer...")
159
+ t1 = self.stage_1_model_ledger.transformer()
160
+ with torch.no_grad():
161
+ t1.load_state_dict(self._cached_state_stage1, strict=False)
162
+
163
+ if self._cached_state_stage2 is not None:
164
+ print("[LoRA] Applying cached state to stage 2 transformer...")
165
+ t2 = self.stage_2_model_ledger.transformer()
166
+ with torch.no_grad():
167
+ t2.load_state_dict(self._cached_state_stage2, strict=False)
168
+
169
+ ctx_p, ctx_n = encode_prompts(
170
+ [prompt, negative_prompt],
171
+ self.stage_1_model_ledger,
172
+ enhance_first_prompt=enhance_prompt,
173
+ enhance_prompt_image=images[0][0] if len(images) > 0 else None,
174
+ enhance_prompt_seed=seed,
175
+ )
176
+
177
+ v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encoding
178
+ v_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding
179
+
180
+ stage_1_output_shape = VideoPixelShape(
181
+ batch=1, frames=num_frames,
182
+ width=width // 2, height=height // 2, fps=frame_rate
183
+ )
184
+
185
+ video_encoder = self.stage_1_model_ledger.video_encoder()
186
+ stage_1_conditionings = combined_image_conditionings(
187
+ images=images,
188
+ height=stage_1_output_shape.height,
189
+ width=stage_1_output_shape.width,
190
+ video_encoder=video_encoder,
191
+ dtype=dtype,
192
+ device=device,
193
+ )
194
+ torch.cuda.synchronize()
195
+ del video_encoder
196
+ cleanup_memory()
197
+
198
+ transformer = self.stage_1_model_ledger.transformer()
199
+
200
+ empty_latent = torch.empty(VideoLatentShape.from_pixel_shape(stage_1_output_shape).to_torch_shape())
201
+ stepper = Res2sDiffusionStep()
202
+ sigmas = (
203
+ LTX2Scheduler()
204
+ .execute(latent=empty_latent, steps=num_inference_steps)
205
+ .to(dtype=torch.float32, device=device)
206
+ )
207
+
208
+ def first_stage_denoising_loop(sigmas, video_state, audio_state, stepper):
209
+ return res2s_audio_video_denoising_loop(
210
+ sigmas=sigmas,
211
+ video_state=video_state,
212
+ audio_state=audio_state,
213
+ stepper=stepper,
214
+ denoise_fn=multi_modal_guider_denoising_func(
215
+ video_guider=MultiModalGuider(params=video_guider_params, negative_context=v_context_n),
216
+ audio_guider=MultiModalGuider(params=audio_guider_params, negative_context=a_context_n),
217
+ v_context=v_context_p,
218
+ a_context=a_context_p,
219
+ transformer=transformer,
220
+ ),
221
+ )
222
+
223
+ video_state, audio_state = denoise_audio_video(
224
+ output_shape=stage_1_output_shape,
225
+ conditionings=stage_1_conditionings,
226
+ noiser=noiser,
227
+ sigmas=sigmas,
228
+ stepper=stepper,
229
+ denoising_loop_fn=first_stage_denoising_loop,
230
+ components=self.pipeline_components,
231
+ dtype=dtype,
232
+ device=device,
233
+ )
234
+
235
+ torch.cuda.synchronize()
236
+ del transformer
237
+ cleanup_memory()
238
+
239
+ video_encoder = self.stage_1_model_ledger.video_encoder()
240
+ upscaled_video_latent = upsample_video(
241
+ latent=video_state.latent[:1],
242
+ video_encoder=video_encoder,
243
+ upsampler=self.stage_2_model_ledger.spatial_upsampler(),
244
+ )
245
+
246
+ stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
247
+ stage_2_conditionings = combined_image_conditionings(
248
+ images=images,
249
+ height=stage_2_output_shape.height,
250
+ width=stage_2_output_shape.width,
251
+ video_encoder=video_encoder,
252
+ dtype=dtype,
253
+ device=device,
254
+ )
255
+ torch.cuda.synchronize()
256
+ del video_encoder
257
+ cleanup_memory()
258
+
259
+ transformer = self.stage_2_model_ledger.transformer()
260
+ distilled_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=device)
261
+
262
+ def second_stage_denoising_loop(sigmas, video_state, audio_state, stepper):
263
+ return res2s_audio_video_denoising_loop(
264
+ sigmas=sigmas,
265
+ video_state=video_state,
266
+ audio_state=audio_state,
267
+ stepper=stepper,
268
+ denoise_fn=simple_denoising_func(
269
+ video_context=v_context_p,
270
+ audio_context=a_context_p,
271
+ transformer=transformer,
272
+ ),
273
+ )
274
+
275
+ video_state, audio_state = denoise_audio_video(
276
+ output_shape=stage_2_output_shape,
277
+ conditionings=stage_2_conditionings,
278
+ noiser=noiser,
279
+ sigmas=distilled_sigmas,
280
+ stepper=stepper,
281
+ denoising_loop_fn=second_stage_denoising_loop,
282
+ components=self.pipeline_components,
283
+ dtype=dtype,
284
+ device=device,
285
+ noise_scale=distilled_sigmas[0],
286
+ initial_video_latent=upscaled_video_latent,
287
+ initial_audio_latent=audio_state.latent,
288
+ )
289
+
290
+ torch.cuda.synchronize()
291
+ del transformer
292
+ cleanup_memory()
293
+
294
+ decoded_video = vae_decode_video(
295
+ video_state.latent, self.stage_2_model_ledger.video_decoder(), tiling_config, generator
296
+ )
297
+ decoded_audio = vae_decode_audio(
298
+ audio_state.latent, self.stage_2_model_ledger.audio_decoder(), self.stage_2_model_ledger.vocoder()
299
+ )
300
+
301
+ return decoded_video, decoded_audio
302
+
303
+
304
+ # =============================================================================
305
+ # Model Download
306
+ # =============================================================================
307
+
308
+ print("=" * 80)
309
+ print("Downloading LTX-2.3 HQ models...")
310
+ print("=" * 80)
311
+
312
+ checkpoint_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-dev.safetensors")
313
+ spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
314
+ distilled_lora_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-22b-distilled-lora-384.safetensors")
315
+ gemma_root = snapshot_download(repo_id=GEMMA_REPO)
316
+
317
+ print(f"Dev checkpoint: {checkpoint_path}")
318
+ print(f"Spatial upsampler: {spatial_upsampler_path}")
319
+ print(f"Distilled LoRA: {distilled_lora_path}")
320
+ print(f"Gemma root: {gemma_root}")
321
+
322
+ # =============================================================================
323
+ # Download Custom LoRAs
324
+ # =============================================================================
325
+
326
+ LORA_REPO = "dagloop5/LoRA"
327
+
328
+ print("=" * 80)
329
+ print("Downloading custom LoRA adapters...")
330
+ print("=" * 80)
331
+
332
+ pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
333
+ general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_reasoning_I2V_V3.safetensors")
334
+ motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="motion_helper.safetensors")
335
+ dreamlay_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="DR34ML4Y_LTXXX_PREVIEW_RC1.safetensors")
336
+ mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Furry Hyper Masturbation - LTX-2 I2V v1.safetensors")
337
+ dramatic_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2.3 - Orgasm.safetensors")
338
+ fluid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="cr3ampi3_animation_i2v_ltx2_v1.0.safetensors")
339
+ liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors")
340
+ demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors")
341
+ voice_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="hentai_voice_ltx23.safetensors")
342
+ realism_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="FurryenhancerLTX2.3V1.215.safetensors")
343
+ transition_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2_takerpov_lora_v1.2.safetensors")
344
+
345
+ print(f"All 12 custom LoRAs downloaded + distilled LoRA")
346
+ print("=" * 80)
347
+
348
+ # =============================================================================
349
+ # Pipeline Initialization
350
+ # =============================================================================
351
+
352
+ print("Initializing HQ Pipeline...")
353
+
354
+ pipeline = HQPipelineWithCachedLoRA(
355
+ checkpoint_path=checkpoint_path,
356
+ distilled_lora=[
357
+ LoraPathStrengthAndSDOps(path=distilled_lora_path, strength=1.0, sd_ops=LTXV_LORA_COMFY_RENAMING_MAP)
358
+ ],
359
+ distilled_lora_strength_stage_1=0.25,
360
+ distilled_lora_strength_stage_2=0.50,
361
+ spatial_upsampler_path=spatial_upsampler_path,
362
+ gemma_root=gemma_root,
363
+ loras=(), # LoRAs will be applied via cached state
364
+ quantization=QuantizationPolicy.fp8_cast(),
365
+ )
366
+
367
+ print("Pipeline initialized!")
368
+ print("=" * 80)
369
+
370
+ # =============================================================================
371
+ # ZeroGPU Tensor Preloading - Adapted for Two Ledgers
372
+ # =============================================================================
373
+
374
+ print("Preloading all models for ZeroGPU tensor packing...")
375
+
376
+ # ===== Stage 1 Model Ledger =====
377
+ print(" Preloading Stage 1 models...")
378
+ ledger1 = pipeline.stage_1_model_ledger
379
+
380
+ _orig_transformer_factory1 = ledger1.transformer
381
+ _orig_video_encoder_factory1 = ledger1.video_encoder
382
+ _orig_video_decoder_factory1 = ledger1.video_decoder
383
+ _orig_audio_decoder_factory1 = ledger1.audio_decoder
384
+ _orig_vocoder_factory1 = ledger1.vocoder
385
+ _orig_spatial_upsampler_factory1 = ledger1.spatial_upsampler
386
+ _orig_text_encoder_factory1 = ledger1.text_encoder
387
+ _orig_embeddings_processor_factory1 = ledger1.embeddings_processor
388
+
389
+ _transformer1 = _orig_transformer_factory1()
390
+ _video_encoder1 = _orig_video_encoder_factory1()
391
+ _video_decoder1 = _orig_video_decoder_factory1()
392
+ _audio_decoder1 = _orig_audio_decoder_factory1()
393
+ _vocoder1 = _orig_vocoder_factory1()
394
+ _spatial_upsampler1 = _orig_spatial_upsampler_factory1()
395
+ _text_encoder1 = _orig_text_encoder_factory1()
396
+ _embeddings_processor1 = _orig_embeddings_processor_factory1()
397
+
398
+ ledger1.transformer = lambda: _transformer1
399
+ ledger1.video_encoder = lambda: _video_encoder1
400
+ ledger1.video_decoder = lambda: _video_decoder1
401
+ ledger1.audio_decoder = lambda: _audio_decoder1
402
+ ledger1.vocoder = lambda: _vocoder1
403
+ ledger1.spatial_upsampler = lambda: _spatial_upsampler1
404
+ ledger1.text_encoder = lambda: _text_encoder1
405
+ ledger1.embeddings_processor = lambda: _embeddings_processor1
406
+
407
+ print(" Stage 1 models preloaded")
408
+
409
+ # ===== Stage 2 Model Ledger =====
410
+ print(" Preloading Stage 2 models...")
411
+ ledger2 = pipeline.stage_2_model_ledger
412
+
413
+ _orig_transformer_factory2 = ledger2.transformer
414
+ _orig_video_encoder_factory2 = ledger2.video_encoder
415
+ _orig_video_decoder_factory2 = ledger2.video_decoder
416
+ _orig_audio_decoder_factory2 = ledger2.audio_decoder
417
+ _orig_vocoder_factory2 = ledger2.vocoder
418
+ _orig_spatial_upsampler_factory2 = ledger2.spatial_upsampler
419
+ _orig_text_encoder_factory2 = ledger2.text_encoder
420
+ _orig_embeddings_processor_factory2 = ledger2.embeddings_processor
421
+
422
+ _transformer2 = _orig_transformer_factory2()
423
+ _video_encoder2 = _orig_video_encoder_factory2()
424
+ _video_decoder2 = _orig_video_decoder_factory2()
425
+ _audio_decoder2 = _orig_audio_decoder_factory2()
426
+ _vocoder2 = _orig_vocoder_factory2()
427
+ _spatial_upsampler2 = _orig_spatial_upsampler_factory2()
428
+ _text_encoder2 = _orig_text_encoder_factory2()
429
+ _embeddings_processor2 = _orig_embeddings_processor_factory2()
430
+
431
+ ledger2.transformer = lambda: _transformer2
432
+ ledger2.video_encoder = lambda: _video_encoder2
433
+ ledger2.video_decoder = lambda: _video_decoder2
434
+ ledger2.audio_decoder = lambda: _audio_decoder2
435
+ ledger2.vocoder = lambda: _vocoder2
436
+ ledger2.spatial_upsampler = lambda: _spatial_upsampler2
437
+ ledger2.text_encoder = lambda: _text_encoder2
438
+ ledger2.embeddings_processor = lambda: _embeddings_processor2
439
+
440
+ print(" Stage 2 models preloaded")
441
+
442
+ print("All models preloaded for ZeroGPU tensor packing!")
443
+ print("=" * 80)
444
+ print("Pipeline ready!")
445
+ print("=" * 80)
446
+
447
+ # =============================================================================
448
+ # LoRA Cache Functions
449
+ # =============================================================================
450
+
451
+ LORA_CACHE_DIR = Path("lora_cache")
452
+ LORA_CACHE_DIR.mkdir(exist_ok=True)
453
+
454
+ def prepare_lora_cache(
455
+ distilled_strength: float,
456
+ pose_strength: float, general_strength: float, motion_strength: float,
457
+ dreamlay_strength: float, mself_strength: float, dramatic_strength: float,
458
+ fluid_strength: float, liquid_strength: float, demopose_strength: float,
459
+ voice_strength: float, realism_strength: float, transition_strength: float,
460
+ progress=gr.Progress(track_tqdm=True),
461
+ ):
462
+ """Build cached LoRA state for both stages."""
463
+ global pipeline
464
+
465
+ progress(0.05, desc="Preparing LoRA cache...")
466
+
467
+ # Create key for cache (include distilled strength)
468
+ key_str = f"{checkpoint_path}:{distilled_strength}:{pose_strength}:{general_strength}:{motion_strength}:{dreamlay_strength}:{mself_strength}:{dramatic_strength}:{fluid_strength}:{liquid_strength}:{demopose_strength}:{voice_strength}:{realism_strength}:{transition_strength}"
469
+ key = hashlib.sha256(key_str.encode()).hexdigest()
470
+
471
+ cache_path_stage1 = LORA_CACHE_DIR / f"{key}_stage1.safetensors"
472
+ cache_path_stage2 = LORA_CACHE_DIR / f"{key}_stage2.safetensors"
473
+
474
+ if cache_path_stage1.exists() and cache_path_stage2.exists():
475
+ progress(0.20, desc="Loading cached LoRA state...")
476
+ state_stage1 = load_file(str(cache_path_stage1))
477
+ state_stage2 = load_file(str(cache_path_stage2))
478
+ pipeline.apply_cached_lora_state(state_stage1, state_stage2)
479
+ return f"Loaded cached LoRA state: {cache_path_stage1.name}"
480
+
481
+ # Build LoRA list (distilled + 12 custom)
482
+ entries = [
483
+ (distilled_lora_path, distilled_strength),
484
+ (pose_lora_path, pose_strength),
485
+ (general_lora_path, general_strength),
486
+ (motion_lora_path, motion_strength),
487
+ (dreamlay_lora_path, dreamlay_strength),
488
+ (mself_lora_path, mself_strength),
489
+ (dramatic_lora_path, dramatic_strength),
490
+ (fluid_lora_path, fluid_strength),
491
+ (liquid_lora_path, liquid_strength),
492
+ (demopose_lora_path, demopose_strength),
493
+ (voice_lora_path, voice_strength),
494
+ (realism_lora_path, realism_strength),
495
+ (transition_lora_path, transition_strength),
496
+ ]
497
+
498
+ loras = [
499
+ LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP)
500
+ for path, strength in entries
501
+ if path is not None and float(strength) != 0.0
502
+ ]
503
+
504
+ progress(0.35, desc="Building stage 1 fused state (CPU)...")
505
+ tmp_ledger1 = pipeline.stage_1_model_ledger.__class__(
506
+ dtype=torch.bfloat16,
507
+ device=torch.device("cpu"),
508
+ checkpoint_path=str(checkpoint_path),
509
+ spatial_upsampler_path=str(spatial_upsampler_path),
510
+ gemma_root_path=str(gemma_root),
511
+ loras=tuple(loras),
512
+ quantization=None,
513
+ )
514
+ transformer1 = tmp_ledger1.transformer()
515
+ state_stage1 = {k: v.detach().cpu().contiguous() for k, v in transformer1.state_dict().items()}
516
+ save_file(state_stage1, str(cache_path_stage1))
517
+
518
+ del transformer1, tmp_ledger1
519
+ gc.collect()
520
+
521
+ progress(0.65, desc="Building stage 2 fused state (CPU)...")
522
+
523
+ tmp_ledger2 = pipeline.stage_2_model_ledger.__class__(
524
+ dtype=torch.bfloat16,
525
+ device=torch.device("cpu"),
526
+ checkpoint_path=str(checkpoint_path),
527
+ spatial_upsampler_path=str(spatial_upsampler_path),
528
+ gemma_root_path=str(gemma_root),
529
+ loras=tuple(loras), # Same loras for stage 2
530
+ quantization=None,
531
+ )
532
+ transformer2 = tmp_ledger2.transformer()
533
+ state_stage2 = {k: v.detach().cpu().contiguous() for k, v in transformer2.state_dict().items()}
534
+ save_file(state_stage2, str(cache_path_stage2))
535
+
536
+ del transformer2, tmp_ledger2
537
+ gc.collect()
538
+
539
+ progress(0.90, desc="Applying LoRA state to pipeline...")
540
+ pipeline.apply_cached_lora_state(state_stage1, state_stage2)
541
+
542
+ progress(1.0, desc="Done!")
543
+ return f"Built and cached LoRA state: {cache_path_stage1.name}"
544
+
545
+
546
+ # =============================================================================
547
+ # Helper Functions
548
+ # =============================================================================
549
+
550
+ def log_memory(tag: str):
551
+ if torch.cuda.is_available():
552
+ allocated = torch.cuda.memory_allocated() / 1024**3
553
+ peak = torch.cuda.max_memory_allocated() / 1024**3
554
+ free, total = torch.cuda.mem_get_info()
555
+ print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
556
+
557
+
558
+ def calculate_frames(duration: float, frame_rate: float = DEFAULT_FRAME_RATE) -> int:
559
+ ideal_frames = int(duration * frame_rate)
560
+ ideal_frames = max(ideal_frames, MIN_FRAMES)
561
+ k = round((ideal_frames - 1) / 8)
562
+ frames = k * 8 + 1
563
+ return min(frames, MAX_FRAMES)
564
+
565
+
566
+ def validate_resolution(height: int, width: int) -> tuple[int, int]:
567
+ height = round(height / STEP) * STEP
568
+ width = round(width / STEP) * STEP
569
+ height = max(MIN_DIM, min(height, MAX_DIM))
570
+ width = max(MIN_DIM, min(width, MAX_DIM))
571
+ return height, width
572
+
573
+
574
+ def detect_aspect_ratio(image) -> str:
575
+ if image is None:
576
+ return "16:9"
577
+ if hasattr(image, "size"):
578
+ w, h = image.size
579
+ elif hasattr(image, "shape"):
580
+ h, w = image.shape[:2]
581
+ else:
582
+ return "16:9"
583
+ ratio = w / h
584
+ candidates = {"16:9": 16/9, "9:16": 9/16, "1:1": 1.0}
585
+ return min(candidates, key=lambda k: abs(ratio - candidates[k]))
586
+
587
+
588
+ def on_image_upload(first_image, last_image, high_res):
589
+ ref_image = first_image if first_image is not None else last_image
590
+ aspect = detect_aspect_ratio(ref_image)
591
+ tier = "high" if high_res else "low"
592
+ w, h = RESOLUTIONS[tier][aspect]
593
+ return gr.update(value=w), gr.update(value=h)
594
+
595
+
596
+ def on_highres_toggle(first_image, last_image, high_res):
597
+ ref_image = first_image if first_image is not None else last_image
598
+ aspect = detect_aspect_ratio(ref_image)
599
+ tier = "high" if high_res else "low"
600
+ w, h = RESOLUTIONS[tier][aspect]
601
+ return gr.update(value=w), gr.update(value=h)
602
+
603
+
604
+ def get_duration(
605
+ prompt, negative_prompt, first_image, last_image,
606
+ duration, seed, randomize_seed, height, width, enhance_prompt,
607
+ video_cfg_scale, video_stg_scale, video_rescale_scale, video_a2v_scale,
608
+ audio_cfg_scale, audio_stg_scale, audio_rescale_scale, audio_v2a_scale,
609
+ gpu_duration,
610
+ progress=None,
611
+ ) -> int:
612
+ return int(gpu_duration)
613
+
614
+
615
+ @spaces.GPU(duration=get_duration)
616
+ @torch.inference_mode()
617
+ def generate_video(
618
+ prompt: str,
619
+ negative_prompt: str,
620
+ first_image,
621
+ last_image,
622
+ duration: float,
623
+ seed: int,
624
+ randomize_seed: bool,
625
+ height: int,
626
+ width: int,
627
+ enhance_prompt: bool,
628
+ video_cfg_scale: float,
629
+ video_stg_scale: float,
630
+ video_rescale_scale: float,
631
+ video_a2v_scale: float,
632
+ audio_cfg_scale: float,
633
+ audio_stg_scale: float,
634
+ audio_rescale_scale: float,
635
+ audio_v2a_scale: float,
636
+ progress=gr.Progress(track_tqdm=True),
637
+ ):
638
+ try:
639
+ torch.cuda.reset_peak_memory_stats()
640
+ log_memory("start")
641
+
642
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
643
+ print(f"Using seed: {current_seed}")
644
+
645
+ height, width = validate_resolution(int(height), int(width))
646
+ print(f"Resolution: {width}x{height}")
647
+
648
+ num_frames = calculate_frames(duration, DEFAULT_FRAME_RATE)
649
+ print(f"Frames: {num_frames} ({duration}s @ {DEFAULT_FRAME_RATE}fps)")
650
+
651
+ images = []
652
+ output_dir = Path("outputs")
653
+ output_dir.mkdir(exist_ok=True)
654
+
655
+ if first_image is not None:
656
+ temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
657
+ if hasattr(first_image, "save"):
658
+ first_image.save(temp_first_path)
659
+ else:
660
+ import shutil
661
+ shutil.copy(first_image, temp_first_path)
662
+ images.append((str(temp_first_path), 1.0))
663
+
664
+ if last_image is not None:
665
+ temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
666
+ if hasattr(last_image, "save"):
667
+ last_image.save(temp_last_path)
668
+ else:
669
+ import shutil
670
+ shutil.copy(last_image, temp_last_path)
671
+ images.append((str(temp_last_path), 1.0))
672
+
673
+ tiling_config = TilingConfig.default()
674
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
675
+
676
+ video_guider_params = MultiModalGuiderParams(
677
+ cfg_scale=video_cfg_scale,
678
+ stg_scale=video_stg_scale,
679
+ rescale_scale=video_rescale_scale,
680
+ modality_scale=video_a2v_scale,
681
+ skip_step=0,
682
+ stg_blocks=[],
683
+ )
684
+
685
+ audio_guider_params = MultiModalGuiderParams(
686
+ cfg_scale=audio_cfg_scale,
687
+ stg_scale=audio_stg_scale,
688
+ rescale_scale=audio_rescale_scale,
689
+ modality_scale=audio_v2a_scale,
690
+ skip_step=0,
691
+ stg_blocks=[],
692
+ )
693
+
694
+ log_memory("before pipeline call")
695
+
696
+ video, audio = pipeline(
697
+ prompt=prompt,
698
+ negative_prompt=negative_prompt,
699
+ seed=current_seed,
700
+ height=height,
701
+ width=width,
702
+ num_frames=num_frames,
703
+ frame_rate=DEFAULT_FRAME_RATE,
704
+ num_inference_steps=LTX_2_3_HQ_PARAMS.num_inference_steps,
705
+ video_guider_params=video_guider_params,
706
+ audio_guider_params=audio_guider_params,
707
+ images=images,
708
+ tiling_config=tiling_config,
709
+ enhance_prompt=enhance_prompt,
710
+ )
711
+
712
+ log_memory("after pipeline call")
713
+
714
+ output_path = tempfile.mktemp(suffix=".mp4")
715
+ encode_video(
716
+ video=video,
717
+ fps=DEFAULT_FRAME_RATE,
718
+ audio=audio,
719
+ output_path=output_path,
720
+ video_chunks_number=video_chunks_number,
721
+ )
722
+
723
+ log_memory("after encode_video")
724
+ return str(output_path), current_seed
725
+
726
+ except Exception as e:
727
+ import traceback
728
+ log_memory("on error")
729
+ print(f"Error: {str(e)}\n{traceback.format_exc()}")
730
+ return None, current_seed
731
+
732
+
733
+ # =============================================================================
734
+ # Gradio UI
735
+ # =============================================================================
736
+
737
+ css = """
738
+ .fillable {max-width: 1200px !important}
739
+ .progress-text {color: white}
740
+ """
741
+
742
+ with gr.Blocks(title="LTX-2.3 Two-Stage HQ with LoRA Cache") as demo:
743
+ gr.Markdown("# LTX-2.3 Two-Stage HQ Video Generation with LoRA Cache")
744
+ gr.Markdown(
745
+ "High-quality text/image-to-video with cached LoRA state + CFG guidance. "
746
+ "[[Model]](https://huggingface.co/Lightricks/LTX-2.3)"
747
+ )
748
+
749
+ with gr.Row():
750
+ # LEFT SIDE: Input Controls
751
+ with gr.Column():
752
+ with gr.Row():
753
+ first_image = gr.Image(label="First Frame (Optional)", type="pil")
754
+ last_image = gr.Image(label="Last Frame (Optional)", type="pil")
755
+
756
+ prompt = gr.Textbox(
757
+ label="Prompt",
758
+ value=DEFAULT_PROMPT,
759
+ lines=3,
760
+ )
761
+
762
+ negative_prompt = gr.Textbox(
763
+ label="Negative Prompt",
764
+ value=DEFAULT_NEGATIVE_PROMPT,
765
+ lines=2,
766
+ )
767
+
768
+ duration = gr.Slider(
769
+ label="Duration (seconds)",
770
+ minimum=0.5, maximum=8.0, value=2.0, step=0.1,
771
+ )
772
+
773
+ with gr.Row():
774
+ seed = gr.Number(label="Seed", value=42, precision=0, minimum=0, maximum=MAX_SEED)
775
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
776
+
777
+ with gr.Row():
778
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
779
+ high_res = gr.Checkbox(label="High Resolution", value=True)
780
+
781
+ with gr.Row():
782
+ width = gr.Number(label="Width", value=1536, precision=0)
783
+ height = gr.Number(label="Height", value=1024, precision=0)
784
+
785
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
786
+
787
+ with gr.Accordion("Advanced Settings", open=False):
788
+ gr.Markdown("### Video Guidance Parameters")
789
+
790
+ with gr.Row():
791
+ video_cfg_scale = gr.Slider(
792
+ label="Video CFG Scale", minimum=1.0, maximum=10.0,
793
+ value=LTX_2_3_HQ_PARAMS.video_guider_params.cfg_scale, step=0.1
794
+ )
795
+ video_stg_scale = gr.Slider(
796
+ label="Video STG Scale", minimum=0.0, maximum=2.0, value=0.0, step=0.1
797
+ )
798
+
799
+ with gr.Row():
800
+ video_rescale_scale = gr.Slider(
801
+ label="Video Rescale", minimum=0.0, maximum=2.0, value=0.45, step=0.1
802
+ )
803
+ video_a2v_scale = gr.Slider(
804
+ label="A2V Scale", minimum=0.0, maximum=5.0, value=3.0, step=0.1
805
+ )
806
+
807
+ gr.Markdown("### Audio Guidance Parameters")
808
+
809
+ with gr.Row():
810
+ audio_cfg_scale = gr.Slider(
811
+ label="Audio CFG Scale", minimum=1.0, maximum=15.0,
812
+ value=LTX_2_3_HQ_PARAMS.audio_guider_params.cfg_scale, step=0.1
813
+ )
814
+ audio_stg_scale = gr.Slider(
815
+ label="Audio STG Scale", minimum=0.0, maximum=2.0, value=0.0, step=0.1
816
+ )
817
+
818
+ with gr.Row():
819
+ audio_rescale_scale = gr.Slider(
820
+ label="Audio Rescale", minimum=0.0, maximum=2.0, value=1.0, step=0.1
821
+ )
822
+ audio_v2a_scale = gr.Slider(
823
+ label="V2A Scale", minimum=0.0, maximum=5.0, value=3.0, step=0.1
824
+ )
825
+
826
+ # RIGHT SIDE: Output and LoRA
827
+ with gr.Column():
828
+ output_video = gr.Video(label="Generated Video", autoplay=True)
829
+
830
+ gpu_duration = gr.Slider(
831
+ label="ZeroGPU duration (seconds)",
832
+ minimum=30.0, maximum=240.0, value=90.0, step=1.0,
833
+ info="Increase for longer videos, higher resolution, or LoRA usage"
834
+ )
835
+
836
+ gr.Markdown("### LoRA Adapter Strengths")
837
+ gr.Markdown("Set to 0 to disable, then click 'Prepare LoRA Cache'")
838
+
839
+ with gr.Row():
840
+ distilled_strength = gr.Slider(label="Distilled LoRA", minimum=0.0, maximum=1.5, value=0.0, step=0.01)
841
+ pose_strength = gr.Slider(label="Anthro Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
842
+
843
+ with gr.Row():
844
+ general_strength = gr.Slider(label="Reasoning Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
845
+ motion_strength = gr.Slider(label="Anthro Posing", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
846
+
847
+ with gr.Row():
848
+ dreamlay_strength = gr.Slider(label="Dreamlay", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
849
+ mself_strength = gr.Slider(label="Mself", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
850
+
851
+ with gr.Row():
852
+ dramatic_strength = gr.Slider(label="Dramatic", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
853
+ fluid_strength = gr.Slider(label="Fluid Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
854
+
855
+ with gr.Row():
856
+ liquid_strength = gr.Slider(label="Liquid Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
857
+ demopose_strength = gr.Slider(label="Audio Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
858
+
859
+ with gr.Row():
860
+ voice_strength = gr.Slider(label="Voice Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
861
+ realism_strength = gr.Slider(label="Anthro Realism", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
862
+
863
+ with gr.Row():
864
+ transition_strength = gr.Slider(label="POV", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
865
+ gr.Markdown("") # Spacer for alignment
866
+
867
+ prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
868
+ lora_status = gr.Textbox(
869
+ label="LoRA Cache Status",
870
+ value="No LoRA state prepared yet.",
871
+ interactive=False,
872
+ )
873
+
874
+ # Event handlers
875
+ first_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
876
+ last_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
877
+ high_res.change(fn=on_highres_toggle, inputs=[first_image, last_image, high_res], outputs=[width, height])
878
+
879
+ prepare_lora_btn.click(
880
+ fn=prepare_lora_cache,
881
+ inputs=[distilled_strength, pose_strength, general_strength, motion_strength, dreamlay_strength,
882
+ mself_strength, dramatic_strength, fluid_strength, liquid_strength,
883
+ demopose_strength, voice_strength, realism_strength, transition_strength],
884
+ outputs=[lora_status],
885
+ )
886
+
887
+ generate_btn.click(
888
+ fn=generate_video,
889
+ inputs=[
890
+ prompt, negative_prompt, first_image, last_image, duration,
891
+ seed, randomize_seed, height, width, enhance_prompt,
892
+ video_cfg_scale, video_stg_scale, video_rescale_scale, video_a2v_scale,
893
+ audio_cfg_scale, audio_stg_scale, audio_rescale_scale, audio_v2a_scale,
894
+ gpu_duration,
895
+ ],
896
+ outputs=[output_video, seed],
897
+ )
898
+
899
+
900
+ if __name__ == "__main__":
901
+ demo.queue().launch(theme=gr.themes.Citrus(), css=css, mcp_server=True)