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