dagloop5 commited on
Commit
a8764e5
·
verified ·
1 Parent(s): d9e6377

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +857 -0
app.py ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+
5
+ # Disable torch.compile / dynamo before any torch import
6
+ os.environ["TORCH_COMPILE_DISABLE"] = "1"
7
+ os.environ["TORCHDYNAMO_DISABLE"] = "1"
8
+
9
+ # Install xformers for memory-efficient attention
10
+ subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
11
+
12
+ # Clone LTX-2 repo and install packages
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
+
16
+ LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2" # known working commit with decode_video
17
+
18
+ if not os.path.exists(LTX_REPO_DIR):
19
+ print(f"Cloning {LTX_REPO_URL}...")
20
+ subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
21
+ subprocess.run(["git", "checkout", LTX_COMMIT], cwd=LTX_REPO_DIR, check=True)
22
+
23
+ print("Installing ltx-core and ltx-pipelines from cloned repo...")
24
+ subprocess.run(
25
+ [sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps", "-e",
26
+ os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
27
+ "-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")],
28
+ check=True,
29
+ )
30
+
31
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
32
+ sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
33
+
34
+ import logging
35
+ import random
36
+ import tempfile
37
+ from pathlib import Path
38
+ import gc
39
+ import hashlib
40
+
41
+ import torch
42
+ torch._dynamo.config.suppress_errors = True
43
+ torch._dynamo.config.disable = True
44
+
45
+ import spaces
46
+ import gradio as gr
47
+ import numpy as np
48
+ from huggingface_hub import hf_hub_download, snapshot_download
49
+ from safetensors.torch import load_file, save_file
50
+
51
+ from ltx_core.components.diffusion_steps import EulerDiffusionStep
52
+ from ltx_core.components.noisers import GaussianNoiser
53
+ from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
54
+ from ltx_core.model.upsampler import upsample_video
55
+ from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
56
+ from ltx_core.quantization import QuantizationPolicy
57
+ from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
58
+ from ltx_pipelines.distilled import DistilledPipeline
59
+ from ltx_pipelines.utils import euler_denoising_loop
60
+ from ltx_pipelines.utils.args import ImageConditioningInput
61
+ from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
62
+ from ltx_pipelines.utils.helpers import (
63
+ cleanup_memory,
64
+ combined_image_conditionings,
65
+ denoise_video_only,
66
+ encode_prompts,
67
+ simple_denoising_func,
68
+ )
69
+ from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
70
+ from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
71
+ from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
72
+
73
+ # Force-patch xformers attention into the LTX attention module.
74
+ from ltx_core.model.transformer import attention as _attn_mod
75
+ print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
76
+ try:
77
+ from xformers.ops import memory_efficient_attention as _mea
78
+ _attn_mod.memory_efficient_attention = _mea
79
+ print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
80
+ except Exception as e:
81
+ print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
82
+
83
+ logging.getLogger().setLevel(logging.INFO)
84
+
85
+ MAX_SEED = np.iinfo(np.int32).max
86
+ DEFAULT_PROMPT = (
87
+ "An astronaut hatches from a fragile egg on the surface of the Moon, "
88
+ "the shell cracking and peeling apart in gentle low-gravity motion. "
89
+ "Fine lunar dust lifts and drifts outward with each movement, floating "
90
+ "in slow arcs before settling back onto the ground."
91
+ )
92
+ DEFAULT_FRAME_RATE = 24.0
93
+
94
+ # Resolution presets: (width, height)
95
+ RESOLUTIONS = {
96
+ "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024), "9:7": (1408, 1088), "7:9": (1088, 1408), "19:13": (1472, 1008), "13:19": (1008, 1472)},
97
+ "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768), "9:7": (704, 544), "7:9": (544, 704), "19:13": (736, 504), "13:19": (504, 736)},
98
+ }
99
+
100
+
101
+ class LTX23DistilledA2VPipeline(DistilledPipeline):
102
+ """DistilledPipeline with optional audio conditioning."""
103
+
104
+ def __call__(
105
+ self,
106
+ prompt: str,
107
+ seed: int,
108
+ height: int,
109
+ width: int,
110
+ num_frames: int,
111
+ frame_rate: float,
112
+ images: list[ImageConditioningInput],
113
+ audio_path: str | None = None,
114
+ tiling_config: TilingConfig | None = None,
115
+ enhance_prompt: bool = False,
116
+ ):
117
+ # Standard path when no audio input is provided.
118
+ print(prompt)
119
+ if audio_path is None:
120
+ return super().__call__(
121
+ prompt=prompt,
122
+ seed=seed,
123
+ height=height,
124
+ width=width,
125
+ num_frames=num_frames,
126
+ frame_rate=frame_rate,
127
+ images=images,
128
+ tiling_config=tiling_config,
129
+ enhance_prompt=enhance_prompt,
130
+ )
131
+
132
+ generator = torch.Generator(device=self.device).manual_seed(seed)
133
+ noiser = GaussianNoiser(generator=generator)
134
+ stepper = EulerDiffusionStep()
135
+ dtype = torch.bfloat16
136
+
137
+ (ctx_p,) = encode_prompts(
138
+ [prompt],
139
+ self.model_ledger,
140
+ enhance_first_prompt=enhance_prompt,
141
+ enhance_prompt_image=images[0].path if len(images) > 0 else None,
142
+ )
143
+ video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
144
+
145
+ video_duration = num_frames / frame_rate
146
+ decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
147
+ if decoded_audio is None:
148
+ raise ValueError(f"Could not extract audio stream from {audio_path}")
149
+
150
+ encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
151
+ audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
152
+ expected_frames = audio_shape.frames
153
+ actual_frames = encoded_audio_latent.shape[2]
154
+
155
+ if actual_frames > expected_frames:
156
+ encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
157
+ elif actual_frames < expected_frames:
158
+ pad = torch.zeros(
159
+ encoded_audio_latent.shape[0],
160
+ encoded_audio_latent.shape[1],
161
+ expected_frames - actual_frames,
162
+ encoded_audio_latent.shape[3],
163
+ device=encoded_audio_latent.device,
164
+ dtype=encoded_audio_latent.dtype,
165
+ )
166
+ encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
167
+
168
+ video_encoder = self.model_ledger.video_encoder()
169
+ transformer = self.model_ledger.transformer()
170
+ stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
171
+
172
+ def denoising_loop(sigmas, video_state, audio_state, stepper):
173
+ return euler_denoising_loop(
174
+ sigmas=sigmas,
175
+ video_state=video_state,
176
+ audio_state=audio_state,
177
+ stepper=stepper,
178
+ denoise_fn=simple_denoising_func(
179
+ video_context=video_context,
180
+ audio_context=audio_context,
181
+ transformer=transformer,
182
+ ),
183
+ )
184
+
185
+ stage_1_output_shape = VideoPixelShape(
186
+ batch=1,
187
+ frames=num_frames,
188
+ width=width // 2,
189
+ height=height // 2,
190
+ fps=frame_rate,
191
+ )
192
+ stage_1_conditionings = combined_image_conditionings(
193
+ images=images,
194
+ height=stage_1_output_shape.height,
195
+ width=stage_1_output_shape.width,
196
+ video_encoder=video_encoder,
197
+ dtype=dtype,
198
+ device=self.device,
199
+ )
200
+ video_state = denoise_video_only(
201
+ output_shape=stage_1_output_shape,
202
+ conditionings=stage_1_conditionings,
203
+ noiser=noiser,
204
+ sigmas=stage_1_sigmas,
205
+ stepper=stepper,
206
+ denoising_loop_fn=denoising_loop,
207
+ components=self.pipeline_components,
208
+ dtype=dtype,
209
+ device=self.device,
210
+ initial_audio_latent=encoded_audio_latent,
211
+ )
212
+
213
+ torch.cuda.synchronize()
214
+ cleanup_memory()
215
+
216
+ upscaled_video_latent = upsample_video(
217
+ latent=video_state.latent[:1],
218
+ video_encoder=video_encoder,
219
+ upsampler=self.model_ledger.spatial_upsampler(),
220
+ )
221
+ stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
222
+ stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
223
+ stage_2_conditionings = combined_image_conditionings(
224
+ images=images,
225
+ height=stage_2_output_shape.height,
226
+ width=stage_2_output_shape.width,
227
+ video_encoder=video_encoder,
228
+ dtype=dtype,
229
+ device=self.device,
230
+ )
231
+ video_state = denoise_video_only(
232
+ output_shape=stage_2_output_shape,
233
+ conditionings=stage_2_conditionings,
234
+ noiser=noiser,
235
+ sigmas=stage_2_sigmas,
236
+ stepper=stepper,
237
+ denoising_loop_fn=denoising_loop,
238
+ components=self.pipeline_components,
239
+ dtype=dtype,
240
+ device=self.device,
241
+ noise_scale=stage_2_sigmas[0],
242
+ initial_video_latent=upscaled_video_latent,
243
+ initial_audio_latent=encoded_audio_latent,
244
+ )
245
+
246
+ torch.cuda.synchronize()
247
+ del transformer
248
+ del video_encoder
249
+ cleanup_memory()
250
+
251
+ decoded_video = vae_decode_video(
252
+ video_state.latent,
253
+ self.model_ledger.video_decoder(),
254
+ tiling_config,
255
+ generator,
256
+ )
257
+ original_audio = Audio(
258
+ waveform=decoded_audio.waveform.squeeze(0),
259
+ sampling_rate=decoded_audio.sampling_rate,
260
+ )
261
+ return decoded_video, original_audio
262
+
263
+
264
+ # Model repos
265
+ LTX_MODEL_REPO = "Lightricks/LTX-2.3"
266
+ GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
267
+
268
+
269
+ # Download model checkpoints
270
+ print("=" * 80)
271
+ print("Downloading LTX-2.3 distilled model + Gemma...")
272
+ print("=" * 80)
273
+
274
+ # LoRA cache directory and currently-applied key
275
+ LORA_CACHE_DIR = Path("lora_cache")
276
+ LORA_CACHE_DIR.mkdir(exist_ok=True)
277
+ current_lora_key: str | None = None
278
+
279
+ PENDING_LORA_KEY: str | None = None
280
+ PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
281
+ PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
282
+
283
+ weights_dir = Path("weights")
284
+ weights_dir.mkdir(exist_ok=True)
285
+ checkpoint_path = hf_hub_download(
286
+ repo_id=LTX_MODEL_REPO,
287
+ filename="ltx-2.3-22b-distilled.safetensors",
288
+ local_dir=str(weights_dir),
289
+ local_dir_use_symlinks=False,
290
+ )
291
+ spatial_upsampler_path = hf_hub_download(repo_id=LTX_MODEL_REPO, filename="ltx-2.3-spatial-upscaler-x2-1.0.safetensors")
292
+ gemma_root = snapshot_download(repo_id=GEMMA_REPO)
293
+
294
+ # ---- Insert block (LoRA downloads) between lines 268 and 269 ----
295
+ # LoRA repo + download the requested LoRA adapters
296
+ LORA_REPO = "dagloop5/LoRA"
297
+
298
+ print("=" * 80)
299
+ print("Downloading LoRA adapters from dagloop5/LoRA...")
300
+ print("=" * 80)
301
+ pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
302
+ general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Reasoning_V1.safetensors")
303
+ motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="motion_helper.safetensors")
304
+ dreamlay_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="DR34ML4Y_LTXXX_PREVIEW_RC1.safetensors") # m15510n4ry, bl0wj0b, d0ubl3_bj, d0gg1e, c0wg1rl
305
+ mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Furry Hyper Masturbation - LTX-2 I2V v1.safetensors") # Hyperfap
306
+ dramatic_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2.3 - Orgasm.safetensors") # "[He | She] is having am orgasm." (am or an?)
307
+ fluid_lora_path = hf_hub_download(repo_id="valiantcat/LTX-2.3-Transition-LORA", filename="ltx2.3-transition.safetensors") # cr3ampi3 animation., missionary animation, doggystyle bouncy animation, double penetration animation
308
+ liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors") # wet dr1pp
309
+ demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors") # skin slapping against skin
310
+
311
+ print(f"Pose LoRA: {pose_lora_path}")
312
+ print(f"General LoRA: {general_lora_path}")
313
+ print(f"Motion LoRA: {motion_lora_path}")
314
+ print(f"Dreamlay LoRA: {dreamlay_lora_path}")
315
+ print(f"Mself LoRA: {mself_lora_path}")
316
+ print(f"Dramatic LoRA: {dramatic_lora_path}")
317
+ print(f"Fluid LoRA: {fluid_lora_path}")
318
+ print(f"Liquid LoRA: {liquid_lora_path}")
319
+ print(f"Demopose LoRA: {demopose_lora_path}")
320
+ # ----------------------------------------------------------------
321
+
322
+ print(f"Checkpoint: {checkpoint_path}")
323
+ print(f"Spatial upsampler: {spatial_upsampler_path}")
324
+ print(f"Gemma root: {gemma_root}")
325
+
326
+ # Initialize pipeline WITH text encoder and optional audio support
327
+ # ---- Replace block (pipeline init) lines 275-281 ----
328
+ pipeline = LTX23DistilledA2VPipeline(
329
+ distilled_checkpoint_path=checkpoint_path,
330
+ spatial_upsampler_path=spatial_upsampler_path,
331
+ gemma_root=gemma_root,
332
+ loras=[],
333
+ quantization=QuantizationPolicy.fp8_cast(), # keep FP8 quantization unchanged
334
+ )
335
+ # ----------------------------------------------------------------
336
+
337
+ def _make_lora_key(pose_strength: float, general_strength: float, motion_strength: float, dreamlay_strength: float, mself_strength: float, dramatic_strength: float, fluid_strength: float, liquid_strength: float, demopose_strength: float) -> tuple[str, str]:
338
+ rp = round(float(pose_strength), 2)
339
+ rg = round(float(general_strength), 2)
340
+ rm = round(float(motion_strength), 2)
341
+ rd = round(float(dreamlay_strength), 2)
342
+ rs = round(float(mself_strength), 2)
343
+ rr = round(float(dramatic_strength), 2)
344
+ rf = round(float(fluid_strength), 2)
345
+ rl = round(float(liquid_strength), 2)
346
+ ro = round(float(demopose_strength), 2)
347
+ key_str = f"{pose_lora_path}:{rp}|{general_lora_path}:{rg}|{motion_lora_path}:{rm}|{dreamlay_lora_path}:{rd}|{mself_lora_path}:{rs}|{dramatic_lora_path}:{rr}|{fluid_lora_path}:{rf}|{liquid_lora_path}:{rl}|{demopose_lora_path}:{ro}"
348
+ key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
349
+ return key, key_str
350
+
351
+
352
+ def prepare_lora_cache(
353
+ pose_strength: float,
354
+ general_strength: float,
355
+ motion_strength: float,
356
+ dreamlay_strength: float,
357
+ mself_strength: float,
358
+ dramatic_strength: float,
359
+ fluid_strength: float,
360
+ liquid_strength: float,
361
+ demopose_strength: float,
362
+ progress=gr.Progress(track_tqdm=True),
363
+ ):
364
+ """
365
+ CPU-only step:
366
+ - checks cache
367
+ - loads cached fused transformer state_dict, or
368
+ - builds fused transformer on CPU and saves it
369
+ The resulting state_dict is stored in memory and can be applied later.
370
+ """
371
+ global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
372
+
373
+ ledger = pipeline.model_ledger
374
+ key, _ = _make_lora_key(pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength)
375
+ cache_path = LORA_CACHE_DIR / f"{key}.safetensors"
376
+
377
+ progress(0.05, desc="Preparing LoRA state")
378
+ if cache_path.exists():
379
+ try:
380
+ progress(0.20, desc="Loading cached fused state")
381
+ state = load_file(str(cache_path))
382
+ PENDING_LORA_KEY = key
383
+ PENDING_LORA_STATE = state
384
+ PENDING_LORA_STATUS = f"Loaded cached LoRA state: {cache_path.name}"
385
+ return PENDING_LORA_STATUS
386
+ except Exception as e:
387
+ print(f"[LoRA] Cache load failed: {type(e).__name__}: {e}")
388
+
389
+ entries = [
390
+ (pose_lora_path, round(float(pose_strength), 2)),
391
+ (general_lora_path, round(float(general_strength), 2)),
392
+ (motion_lora_path, round(float(motion_strength), 2)),
393
+ (dreamlay_lora_path, round(float(dreamlay_strength), 2)),
394
+ (mself_lora_path, round(float(mself_strength), 2)),
395
+ (dramatic_lora_path, round(float(dramatic_strength), 2)),
396
+ (fluid_lora_path, round(float(fluid_strength), 2)),
397
+ (liquid_lora_path, round(float(liquid_strength), 2)),
398
+ (demopose_lora_path, round(float(demopose_strength), 2)),
399
+ ]
400
+ loras_for_builder = [
401
+ LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP)
402
+ for path, strength in entries
403
+ if path is not None and float(strength) != 0.0
404
+ ]
405
+
406
+ if not loras_for_builder:
407
+ PENDING_LORA_KEY = None
408
+ PENDING_LORA_STATE = None
409
+ PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
410
+ return PENDING_LORA_STATUS
411
+
412
+ tmp_ledger = None
413
+ new_transformer_cpu = None
414
+ try:
415
+ progress(0.35, desc="Building fused CPU transformer")
416
+ tmp_ledger = pipeline.model_ledger.__class__(
417
+ dtype=ledger.dtype,
418
+ device=torch.device("cpu"),
419
+ checkpoint_path=str(checkpoint_path),
420
+ spatial_upsampler_path=str(spatial_upsampler_path),
421
+ gemma_root_path=str(gemma_root),
422
+ loras=tuple(loras_for_builder),
423
+ quantization=getattr(ledger, "quantization", None),
424
+ )
425
+ new_transformer_cpu = tmp_ledger.transformer()
426
+
427
+ progress(0.70, desc="Extracting fused state_dict")
428
+ state = {
429
+ k: v.detach().cpu().contiguous()
430
+ for k, v in new_transformer_cpu.state_dict().items()
431
+ }
432
+ save_file(state, str(cache_path))
433
+
434
+ PENDING_LORA_KEY = key
435
+ PENDING_LORA_STATE = state
436
+ PENDING_LORA_STATUS = f"Built and cached LoRA state: {cache_path.name}"
437
+ return PENDING_LORA_STATUS
438
+
439
+ except Exception as e:
440
+ import traceback
441
+ print(f"[LoRA] Prepare failed: {type(e).__name__}: {e}")
442
+ print(traceback.format_exc())
443
+ PENDING_LORA_KEY = None
444
+ PENDING_LORA_STATE = None
445
+ PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
446
+ return PENDING_LORA_STATUS
447
+
448
+ finally:
449
+ try:
450
+ del new_transformer_cpu
451
+ except Exception:
452
+ pass
453
+ try:
454
+ del tmp_ledger
455
+ except Exception:
456
+ pass
457
+ gc.collect()
458
+
459
+
460
+ def apply_prepared_lora_state_to_pipeline():
461
+ """
462
+ Fast step: copy the already prepared CPU state into the live transformer.
463
+ This is the only part that should remain near generation time.
464
+ """
465
+ global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE
466
+
467
+ if PENDING_LORA_STATE is None or PENDING_LORA_KEY is None:
468
+ print("[LoRA] No prepared LoRA state available; skipping.")
469
+ return False
470
+
471
+ if current_lora_key == PENDING_LORA_KEY:
472
+ print("[LoRA] Prepared LoRA state already active; skipping.")
473
+ return True
474
+
475
+ existing_transformer = _transformer
476
+ with torch.no_grad():
477
+ missing, unexpected = existing_transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
478
+ if missing or unexpected:
479
+ print(f"[LoRA] load_state_dict mismatch: missing={len(missing)}, unexpected={len(unexpected)}")
480
+
481
+ current_lora_key = PENDING_LORA_KEY
482
+ print("[LoRA] Prepared LoRA state applied to the pipeline.")
483
+ return True
484
+
485
+ # ---- REPLACE PRELOAD BLOCK START ----
486
+ # Preload all models for ZeroGPU tensor packing.
487
+ print("Preloading all models (including Gemma and audio components)...")
488
+ ledger = pipeline.model_ledger
489
+
490
+ # Save the original factory methods so we can rebuild individual components later.
491
+ # These are bound callables on ledger that will call the builder when invoked.
492
+ _orig_transformer_factory = ledger.transformer
493
+ _orig_video_encoder_factory = ledger.video_encoder
494
+ _orig_video_decoder_factory = ledger.video_decoder
495
+ _orig_audio_encoder_factory = ledger.audio_encoder
496
+ _orig_audio_decoder_factory = ledger.audio_decoder
497
+ _orig_vocoder_factory = ledger.vocoder
498
+ _orig_spatial_upsampler_factory = ledger.spatial_upsampler
499
+ _orig_text_encoder_factory = ledger.text_encoder
500
+ _orig_gemma_embeddings_factory = ledger.gemma_embeddings_processor
501
+
502
+ # Call the original factories once to create the cached instances we will serve by default.
503
+ _transformer = _orig_transformer_factory()
504
+ _video_encoder = _orig_video_encoder_factory()
505
+ _video_decoder = _orig_video_decoder_factory()
506
+ _audio_encoder = _orig_audio_encoder_factory()
507
+ _audio_decoder = _orig_audio_decoder_factory()
508
+ _vocoder = _orig_vocoder_factory()
509
+ _spatial_upsampler = _orig_spatial_upsampler_factory()
510
+ _text_encoder = _orig_text_encoder_factory()
511
+ _embeddings_processor = _orig_gemma_embeddings_factory()
512
+
513
+ # Replace ledger methods with lightweight lambdas that return the cached instances.
514
+ # We keep the original factories above so we can call them later to rebuild components.
515
+ ledger.transformer = lambda: _transformer
516
+ ledger.video_encoder = lambda: _video_encoder
517
+ ledger.video_decoder = lambda: _video_decoder
518
+ ledger.audio_encoder = lambda: _audio_encoder
519
+ ledger.audio_decoder = lambda: _audio_decoder
520
+ ledger.vocoder = lambda: _vocoder
521
+ ledger.spatial_upsampler = lambda: _spatial_upsampler
522
+ ledger.text_encoder = lambda: _text_encoder
523
+ ledger.gemma_embeddings_processor = lambda: _embeddings_processor
524
+
525
+ print("All models preloaded (including Gemma text encoder and audio encoder)!")
526
+ # ---- REPLACE PRELOAD BLOCK END ----
527
+
528
+ print("=" * 80)
529
+ print("Pipeline ready!")
530
+ print("=" * 80)
531
+
532
+
533
+ def log_memory(tag: str):
534
+ if torch.cuda.is_available():
535
+ allocated = torch.cuda.memory_allocated() / 1024**3
536
+ peak = torch.cuda.max_memory_allocated() / 1024**3
537
+ free, total = torch.cuda.mem_get_info()
538
+ print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
539
+
540
+
541
+ def detect_aspect_ratio(image) -> str:
542
+ if image is None:
543
+ return "16:9"
544
+ if hasattr(image, "size"):
545
+ w, h = image.size
546
+ elif hasattr(image, "shape"):
547
+ h, w = image.shape[:2]
548
+ else:
549
+ return "16:9"
550
+ ratio = w / h
551
+ candidates = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0}
552
+ return min(candidates, key=lambda k: abs(ratio - candidates[k]))
553
+
554
+
555
+ def on_image_upload(first_image, last_image, high_res):
556
+ ref_image = first_image if first_image is not None else last_image
557
+ aspect = detect_aspect_ratio(ref_image)
558
+ tier = "high" if high_res else "low"
559
+ w, h = RESOLUTIONS[tier][aspect]
560
+ return gr.update(value=w), gr.update(value=h)
561
+
562
+
563
+ def on_highres_toggle(first_image, last_image, high_res):
564
+ ref_image = first_image if first_image is not None else last_image
565
+ aspect = detect_aspect_ratio(ref_image)
566
+ tier = "high" if high_res else "low"
567
+ w, h = RESOLUTIONS[tier][aspect]
568
+ return gr.update(value=w), gr.update(value=h)
569
+
570
+
571
+ def get_gpu_duration(
572
+ first_image,
573
+ last_image,
574
+ input_audio,
575
+ prompt: str,
576
+ duration: float,
577
+ gpu_duration: float,
578
+ enhance_prompt: bool = True,
579
+ seed: int = 42,
580
+ randomize_seed: bool = True,
581
+ height: int = 1024,
582
+ width: int = 1536,
583
+ pose_strength: float = 0.0,
584
+ general_strength: float = 0.0,
585
+ motion_strength: float = 0.0,
586
+ dreamlay_strength: float = 0.0,
587
+ mself_strength: float = 0.0,
588
+ dramatic_strength: float = 0.0,
589
+ fluid_strength: float = 0.0,
590
+ liquid_strength: float = 0.0,
591
+ demopose_strength: float = 0.0,
592
+ progress=None,
593
+ ):
594
+ return int(gpu_duration)
595
+
596
+ @spaces.GPU(duration=get_gpu_duration)
597
+ @torch.inference_mode()
598
+ def generate_video(
599
+ first_image,
600
+ last_image,
601
+ input_audio,
602
+ prompt: str,
603
+ duration: float,
604
+ gpu_duration: float,
605
+ enhance_prompt: bool = True,
606
+ seed: int = 42,
607
+ randomize_seed: bool = True,
608
+ height: int = 1024,
609
+ width: int = 1536,
610
+ pose_strength: float = 0.0,
611
+ general_strength: float = 0.0,
612
+ motion_strength: float = 0.0,
613
+ dreamlay_strength: float = 0.0,
614
+ mself_strength: float = 0.0,
615
+ dramatic_strength: float = 0.0,
616
+ fluid_strength: float = 0.0,
617
+ liquid_strength: float = 0.0,
618
+ demopose_strength: float = 0.0,
619
+ progress=gr.Progress(track_tqdm=True),
620
+ ):
621
+ try:
622
+ torch.cuda.reset_peak_memory_stats()
623
+ log_memory("start")
624
+
625
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
626
+
627
+ frame_rate = DEFAULT_FRAME_RATE
628
+ num_frames = int(duration * frame_rate) + 1
629
+ num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
630
+
631
+ print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
632
+
633
+ images = []
634
+ output_dir = Path("outputs")
635
+ output_dir.mkdir(exist_ok=True)
636
+
637
+ if first_image is not None:
638
+ temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
639
+ if hasattr(first_image, "save"):
640
+ first_image.save(temp_first_path)
641
+ else:
642
+ temp_first_path = Path(first_image)
643
+ images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
644
+
645
+ if last_image is not None:
646
+ temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
647
+ if hasattr(last_image, "save"):
648
+ last_image.save(temp_last_path)
649
+ else:
650
+ temp_last_path = Path(last_image)
651
+ images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
652
+
653
+ tiling_config = TilingConfig.default()
654
+ video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
655
+
656
+ log_memory("before pipeline call")
657
+
658
+ apply_prepared_lora_state_to_pipeline()
659
+
660
+ video, audio = pipeline(
661
+ prompt=prompt,
662
+ seed=current_seed,
663
+ height=int(height),
664
+ width=int(width),
665
+ num_frames=num_frames,
666
+ frame_rate=frame_rate,
667
+ images=images,
668
+ audio_path=input_audio,
669
+ tiling_config=tiling_config,
670
+ enhance_prompt=enhance_prompt,
671
+ )
672
+
673
+ log_memory("after pipeline call")
674
+
675
+ output_path = tempfile.mktemp(suffix=".mp4")
676
+ encode_video(
677
+ video=video,
678
+ fps=frame_rate,
679
+ audio=audio,
680
+ output_path=output_path,
681
+ video_chunks_number=video_chunks_number,
682
+ )
683
+
684
+ log_memory("after encode_video")
685
+ return str(output_path), current_seed
686
+
687
+ except Exception as e:
688
+ import traceback
689
+ log_memory("on error")
690
+ print(f"Error: {str(e)}\n{traceback.format_exc()}")
691
+ return None, current_seed
692
+
693
+
694
+ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
695
+ gr.Markdown("# LTX-2.3 F2LF with Fast Audio-Video Generation with Frame Conditioning")
696
+
697
+
698
+ with gr.Row():
699
+ with gr.Column():
700
+ with gr.Row():
701
+ first_image = gr.Image(label="First Frame (Optional)", type="pil")
702
+ last_image = gr.Image(label="Last Frame (Optional)", type="pil")
703
+ input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
704
+ prompt = gr.Textbox(
705
+ label="Prompt",
706
+ info="for best results - make it as elaborate as possible",
707
+ value="Make this image come alive with cinematic motion, smooth animation",
708
+ lines=3,
709
+ placeholder="Describe the motion and animation you want...",
710
+ )
711
+ duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=30.0, value=10.0, step=0.1)
712
+
713
+
714
+ generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
715
+
716
+ with gr.Accordion("Advanced Settings", open=False):
717
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, value=10, step=1)
718
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
719
+ with gr.Row():
720
+ width = gr.Number(label="Width", value=1536, precision=0)
721
+ height = gr.Number(label="Height", value=1024, precision=0)
722
+ with gr.Row():
723
+ enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
724
+ high_res = gr.Checkbox(label="High Resolution", value=True)
725
+ with gr.Column():
726
+ gr.Markdown("### LoRA adapter strengths (set to 0 to disable)")
727
+ pose_strength = gr.Slider(
728
+ label="Anthro Enhancer strength",
729
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
730
+ )
731
+ general_strength = gr.Slider(
732
+ label="Reasoning Enhancer strength",
733
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
734
+ )
735
+ motion_strength = gr.Slider(
736
+ label="Anthro Posing Helper strength",
737
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
738
+ )
739
+ dreamlay_strength = gr.Slider(
740
+ label="Dreamlay strength",
741
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
742
+ )
743
+ mself_strength = gr.Slider(
744
+ label="Mself strength",
745
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
746
+ )
747
+ dramatic_strength = gr.Slider(
748
+ label="Dramatic strength",
749
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
750
+ )
751
+ fluid_strength = gr.Slider(
752
+ label="Fluid Helper strength",
753
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
754
+ )
755
+ liquid_strength = gr.Slider(
756
+ label="Liquid Helper strength",
757
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
758
+ )
759
+ demopose_strength = gr.Slider(
760
+ label="Demopose Helper strength",
761
+ minimum=0.0, maximum=2.0, value=0.0, step=0.01
762
+ )
763
+ prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
764
+ lora_status = gr.Textbox(
765
+ label="LoRA Cache Status",
766
+ value="No LoRA state prepared yet.",
767
+ interactive=False,
768
+ )
769
+
770
+ with gr.Column():
771
+ output_video = gr.Video(label="Generated Video", autoplay=False)
772
+ gpu_duration = gr.Slider(
773
+ label="ZeroGPU duration (seconds)",
774
+ minimum=40.0,
775
+ maximum=240.0,
776
+ value=85.0,
777
+ step=1.0,
778
+ )
779
+
780
+ gr.Examples(
781
+ examples=[
782
+ [
783
+ None,
784
+ "pinkknit.jpg",
785
+ None,
786
+ "The camera falls downward through darkness as if dropped into a tunnel. "
787
+ "As it slows, five friends wearing pink knitted hats and sunglasses lean "
788
+ "over and look down toward the camera with curious expressions. The lens "
789
+ "has a strong fisheye effect, creating a circular frame around them. They "
790
+ "crowd together closely, forming a symmetrical cluster while staring "
791
+ "directly into the lens.",
792
+ 3.0,
793
+ 80.0,
794
+ False,
795
+ 42,
796
+ True,
797
+ 1024,
798
+ 1024,
799
+ 0.0, # pose_strength (example)
800
+ 0.0, # general_strength (example)
801
+ 0.0, # motion_strength (example)
802
+ 0.0,
803
+ 0.0,
804
+ 0.0,
805
+ 0.0,
806
+ 0.0,
807
+ 0.0,
808
+ ],
809
+ ],
810
+ inputs=[
811
+ first_image, last_image, input_audio, prompt, duration, gpu_duration,
812
+ enhance_prompt, seed, randomize_seed, height, width,
813
+ pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength,
814
+ ],
815
+ )
816
+
817
+ first_image.change(
818
+ fn=on_image_upload,
819
+ inputs=[first_image, last_image, high_res],
820
+ outputs=[width, height],
821
+ )
822
+
823
+ last_image.change(
824
+ fn=on_image_upload,
825
+ inputs=[first_image, last_image, high_res],
826
+ outputs=[width, height],
827
+ )
828
+
829
+ high_res.change(
830
+ fn=on_highres_toggle,
831
+ inputs=[first_image, last_image, high_res],
832
+ outputs=[width, height],
833
+ )
834
+
835
+ prepare_lora_btn.click(
836
+ fn=prepare_lora_cache,
837
+ inputs=[pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength],
838
+ outputs=[lora_status],
839
+ )
840
+
841
+ generate_btn.click(
842
+ fn=generate_video,
843
+ inputs=[
844
+ first_image, last_image, input_audio, prompt, duration, gpu_duration, enhance_prompt,
845
+ seed, randomize_seed, height, width,
846
+ pose_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength,
847
+ ],
848
+ outputs=[output_video, seed],
849
+ )
850
+
851
+
852
+ css = """
853
+ .fillable{max-width: 1200px !important}
854
+ """
855
+
856
+ if __name__ == "__main__":
857
+ demo.launch(theme=gr.themes.Citrus(), css=css)