dagloop5 commited on
Commit
f3665d7
·
verified ·
1 Parent(s): 621332b

Upload app(16).py

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