dagloop5 commited on
Commit
f47c107
·
verified ·
1 Parent(s): adac5dc

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -978
app.py DELETED
@@ -1,978 +0,0 @@
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
- # Clone LTX-2 repo and install packages
10
- LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
11
- LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
12
-
13
- LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2" # known working commit with decode_video
14
-
15
- if not os.path.exists(LTX_REPO_DIR):
16
- print(f"Cloning {LTX_REPO_URL}...")
17
- subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
18
- subprocess.run(["git", "checkout", LTX_COMMIT], cwd=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
- from safetensors.torch import load_file, save_file
47
- from safetensors import safe_open
48
- import json
49
- import requests
50
-
51
- from ltx_core.components.diffusion_steps import EulerDiffusionStep
52
- from ltx_core.components.guiders import MultiModalGuider, MultiModalGuiderParams
53
- from ltx_core.components.noisers import GaussianNoiser
54
- from ltx_core.components.protocols import DiffusionStepProtocol
55
- from ltx_core.components.schedulers import LTX2Scheduler
56
- from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
57
- from ltx_core.model.audio_vae import decode_audio as vae_decode_audio
58
- from ltx_core.model.upsampler import upsample_video
59
- from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as vae_decode_video
60
- from ltx_core.quantization import QuantizationPolicy
61
- from ltx_core.types import Audio, AudioLatentShape, VideoLatentShape, VideoPixelShape
62
- from ltx_pipelines.distilled import DistilledPipeline
63
- from ltx_pipelines.utils import (
64
- res2s_audio_video_denoising_loop,
65
- euler_denoising_loop,
66
- cleanup_memory,
67
- encode_prompts,
68
- denoise_audio_video,
69
- )
70
- from ltx_pipelines.utils.args import ImageConditioningInput
71
- from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMA_VALUES
72
- from ltx_pipelines.utils.helpers import (
73
- combined_image_conditionings,
74
- denoise_video_only,
75
- simple_denoising_func,
76
- multi_modal_guider_denoising_func,
77
- )
78
- from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
79
- from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
80
- from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP
81
-
82
- from ltx_core.model.transformer import attention as _attn_mod
83
-
84
- print(f"[ATTN] Before patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
85
- try:
86
- from xformers.ops import memory_efficient_attention as _mea
87
- from xformers.ops.fmha import cutlass
88
-
89
- def _cutlass_memory_efficient_attention(*args, **kwargs):
90
- # Force CUTLASS and avoid FlashAttention paths that are crashing.
91
- kwargs["op"] = (cutlass.FwOp, cutlass.BwOp)
92
- return _mea(*args, **kwargs)
93
-
94
- _attn_mod.memory_efficient_attention = _cutlass_memory_efficient_attention
95
- print(f"[ATTN] After patch: memory_efficient_attention={_attn_mod.memory_efficient_attention}")
96
- except Exception as e:
97
- print(f"[ATTN] xformers patch FAILED: {type(e).__name__}: {e}")
98
-
99
- logging.getLogger().setLevel(logging.INFO)
100
-
101
- MAX_SEED = np.iinfo(np.int32).max
102
- DEFAULT_PROMPT = (
103
- "An astronaut hatches from a fragile egg on the surface of the Moon, "
104
- "the shell cracking and peeling apart in gentle low-gravity motion. "
105
- "Fine lunar dust lifts and drifts outward with each movement, floating "
106
- "in slow arcs before settling back onto the ground."
107
- )
108
-
109
- DEFAULT_FRAME_RATE = 24.0
110
-
111
- # Resolution presets: (width, height)
112
- RESOLUTIONS = {
113
- "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768),
114
- "4:3": (768, 576), "3:4": (576, 768), "21:9": (768, 384)},
115
- "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024),
116
- "4:3": (1536, 1152), "3:4": (1152, 1536), "21:9": (1536, 768)},
117
- }
118
-
119
- class LTX23DistilledA2VPipeline:
120
- """Standalone pipeline with optional audio conditioning — no parent class."""
121
-
122
- def __init__(
123
- self,
124
- distilled_checkpoint_path: str,
125
- spatial_upsampler_path: str,
126
- gemma_root: str,
127
- loras: tuple,
128
- quantization: QuantizationPolicy | None = None,
129
- ):
130
- from ltx_pipelines.utils import ModelLedger, denoise_audio_video
131
- from ltx_pipelines.utils.types import PipelineComponents
132
-
133
- self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
134
- self.dtype = torch.bfloat16
135
-
136
- self.model_ledger = ModelLedger(
137
- dtype=self.dtype,
138
- device=self.device,
139
- checkpoint_path=distilled_checkpoint_path,
140
- gemma_root_path=gemma_root,
141
- spatial_upsampler_path=spatial_upsampler_path,
142
- loras=loras,
143
- quantization=quantization,
144
- )
145
-
146
- self.pipeline_components = PipelineComponents(
147
- dtype=self.dtype,
148
- device=self.device,
149
- )
150
-
151
- def __call__(
152
- self,
153
- prompt: str,
154
- seed: int,
155
- height: int,
156
- width: int,
157
- num_frames: int,
158
- frame_rate: float,
159
- video_guider_params: MultiModalGuiderParams,
160
- audio_guider_params: MultiModalGuiderParams,
161
- images: list[ImageConditioningInput],
162
- num_inference_steps: int = 8,
163
- audio_path: str | None = None,
164
- tiling_config: TilingConfig | None = None,
165
- enhance_prompt: bool = False,
166
- ):
167
- print(prompt)
168
-
169
- generator = torch.Generator(device=self.device).manual_seed(seed)
170
- noiser = GaussianNoiser(generator=generator)
171
- stepper = EulerDiffusionStep()
172
- dtype = torch.bfloat16
173
-
174
- ctx_p = encode_prompts(
175
- [prompt],
176
- self.model_ledger,
177
- enhance_first_prompt=enhance_prompt,
178
- enhance_prompt_image=images[0].path if len(images) > 0 else None,
179
- )[0]
180
- v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encoding
181
-
182
- # ── Audio encoding (only for conditioning, not output generation) ──
183
- encoded_audio_latent = None
184
- decoded_audio = None
185
- if audio_path is not None:
186
- video_duration = num_frames / frame_rate
187
- decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
188
- if decoded_audio is None:
189
- raise ValueError(f"Could not extract audio stream from {audio_path}")
190
-
191
- encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
192
- audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
193
- expected_frames = audio_shape.frames
194
- actual_frames = encoded_audio_latent.shape[2]
195
-
196
- if actual_frames > expected_frames:
197
- encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
198
- elif actual_frames < expected_frames:
199
- pad = torch.zeros(
200
- encoded_audio_latent.shape[0],
201
- encoded_audio_latent.shape[1],
202
- expected_frames - actual_frames,
203
- encoded_audio_latent.shape[3],
204
- device=encoded_audio_latent.device,
205
- dtype=encoded_audio_latent.dtype,
206
- )
207
- encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
208
-
209
- video_encoder = self.model_ledger.video_encoder()
210
- transformer = self.model_ledger.transformer()
211
-
212
- # Stage 1: Generate sigmas using LTX2Scheduler with user-specified steps
213
- empty_latent = torch.empty(VideoLatentShape.from_pixel_shape(
214
- VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
215
- ).to_torch_shape())
216
- stage_1_sigmas = (
217
- LTX2Scheduler()
218
- .execute(latent=empty_latent, steps=num_inference_steps)
219
- .to(dtype=torch.float32, device=self.device)
220
- )
221
-
222
- def stage1_denoising_loop(sigmas: torch.Tensor, video_state, audio_state, stepper: DiffusionStepProtocol):
223
- return euler_denoising_loop(
224
- sigmas=sigmas,
225
- video_state=video_state,
226
- audio_state=audio_state,
227
- stepper=stepper,
228
- denoise_fn=multi_modal_guider_denoising_func(
229
- video_guider=MultiModalGuider(
230
- params=video_guider_params,
231
- ),
232
- audio_guider=MultiModalGuider(
233
- params=audio_guider_params,
234
- ),
235
- v_context=v_context_p,
236
- a_context=a_context_p,
237
- transformer=transformer,
238
- ),
239
- )
240
-
241
- # ── Stage 1: Half resolution ──
242
- stage_1_output_shape = VideoPixelShape(
243
- batch=1,
244
- frames=num_frames,
245
- width=width,
246
- height=height,
247
- fps=frame_rate,
248
- )
249
- stage_1_conditionings = combined_image_conditionings(
250
- images=images,
251
- height=stage_1_output_shape.height,
252
- width=stage_1_output_shape.width,
253
- video_encoder=video_encoder,
254
- dtype=dtype,
255
- device=self.device,
256
- )
257
-
258
- # Use denoise_audio_video so audio is ALWAYS generated
259
- from ltx_pipelines.utils import denoise_audio_video
260
- video_state, audio_state = denoise_audio_video(
261
- output_shape=stage_1_output_shape,
262
- conditionings=stage_1_conditionings,
263
- noiser=noiser,
264
- sigmas=stage_1_sigmas,
265
- stepper=stepper,
266
- denoising_loop_fn=stage1_denoising_loop,
267
- components=self.pipeline_components,
268
- dtype=dtype,
269
- device=self.device,
270
- initial_audio_latent=encoded_audio_latent,
271
- )
272
-
273
- torch.cuda.synchronize()
274
- cleanup_memory()
275
-
276
- # ── Decode both video and audio ──
277
- decoded_video = vae_decode_video(
278
- video_state.latent,
279
- self.model_ledger.video_decoder(),
280
- tiling_config,
281
- generator,
282
- )
283
- decoded_audio_output = vae_decode_audio(
284
- audio_state.latent,
285
- self.model_ledger.audio_decoder(),
286
- self.model_ledger.vocoder(),
287
- )
288
-
289
- return decoded_video, decoded_audio_output
290
-
291
- # Model repos
292
- LTX_MODEL_REPO = "SulphurAI/Sulphur-2-base"
293
- GEMMA_REPO ="Lightricks/gemma-3-12b-it-qat-q4_0-unquantized"
294
-
295
- # Download model checkpoints
296
- print("=" * 80)
297
- print("Downloading LTX-2.3 distilled model + Gemma...")
298
- print("=" * 80)
299
-
300
- # LoRA cache directory and currently-applied key
301
- LORA_CACHE_DIR = Path("lora_cache")
302
- LORA_CACHE_DIR.mkdir(exist_ok=True)
303
- current_lora_key: str | None = None
304
-
305
- PENDING_LORA_KEY: str | None = None
306
- PENDING_LORA_STATE: dict[str, torch.Tensor] | None = None
307
- PENDING_LORA_STATUS: str = "No LoRA state prepared yet."
308
-
309
- weights_dir = Path("weights")
310
- weights_dir.mkdir(exist_ok=True)
311
- checkpoint_path = hf_hub_download(
312
- repo_id=LTX_MODEL_REPO,
313
- filename="sulphur_distil_bf16.safetensors",
314
- local_dir=str(weights_dir),
315
- local_dir_use_symlinks=False,
316
- )
317
- spatial_upsampler_path = hf_hub_download(repo_id="Lightricks/LTX-2.3", filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors")
318
- gemma_root = snapshot_download(repo_id=GEMMA_REPO)
319
-
320
-
321
- LORA_REPO = "dagloop5/LoRA"
322
-
323
- print("=" * 80)
324
- print("Downloading LoRA adapters from dagloop5/LoRA...")
325
- print("=" * 80)
326
- pose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2_3_NSFW_furry_concat_v2.safetensors")
327
- twod_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_2d_NSFW_motion_enhancer.safetensors") # 2d style animation
328
- general_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_reasoning_I2V_V3.safetensors")
329
- motion_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Sulphur_LTX 2.3_better _NSFW_motion.safetensors")
330
- dreamlay_lora_path = hf_hub_download(repo_id="lynaNSFW/DR34ML4Y_AIO_NSFW_LTX23", filename="DR34ML4Y_LTXXX_V2.safetensors") # m15510n4ry, bl0wj0b, d0ubl3_bj, d0gg1e, c0wg1rl
331
- mself_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Furry Hyper Masturbation - LTX-2 I2V v1.safetensors") # Hyperfap
332
- 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?)
333
- fluid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="Cr3ampi3_animation_sulphur-2_i2v_v1.0.safetensors") # cr3ampi3 animation
334
- liquid_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="liquid_wet_dr1pp_ltx2_v1.0_scaled.safetensors") # wet dr1pp
335
- demopose_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="clapping-cheeks-audio-v001-alpha.safetensors")
336
- voice_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="hentai_voice_ltx23.safetensors")
337
- realism_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="FurryenhancerLTX2.3V4.094fused.safetensors")
338
- transition_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX-2_takerpov_lora_v1.2.safetensors") # takerpov1, taker pov
339
- physics_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Physics_V2_000002000.safetensors")
340
- reasoning_lora_path = hf_hub_download(repo_id="LiconStudio/Ltx2.3-VBVR-lora-I2V", filename="Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors")
341
- twostep_lora_path = hf_hub_download(repo_id=LORA_REPO, filename="LTX2.3_Multi_step_video_reasoning_V0.1.safetensors")
342
-
343
- print(f"Pose LoRA: {pose_lora_path}")
344
- print(f"twod LoRA: {twod_lora_path}")
345
- print(f"General LoRA: {general_lora_path}")
346
- print(f"Motion LoRA: {motion_lora_path}")
347
- print(f"Dreamlay LoRA: {dreamlay_lora_path}")
348
- print(f"Mself LoRA: {mself_lora_path}")
349
- print(f"Dramatic LoRA: {dramatic_lora_path}")
350
- print(f"Fluid LoRA: {fluid_lora_path}")
351
- print(f"Liquid LoRA: {liquid_lora_path}")
352
- print(f"Demopose LoRA: {demopose_lora_path}")
353
- print(f"Voice LoRA: {voice_lora_path}")
354
- print(f"Realism LoRA: {realism_lora_path}")
355
- print(f"Transition LoRA: {transition_lora_path}")
356
- print(f"Physics LoRA: {physics_lora_path}")
357
- print(f"Reasoning LoRA: {reasoning_lora_path}")
358
- print(f"Twostep LoRA: {twostep_lora_path}")
359
-
360
- print(f"Checkpoint: {checkpoint_path}")
361
- print(f"Spatial upsampler: {spatial_upsampler_path}")
362
- print(f"[Gemma] Root ready: {gemma_root}")
363
-
364
- pipeline = LTX23DistilledA2VPipeline(
365
- distilled_checkpoint_path=checkpoint_path,
366
- spatial_upsampler_path=spatial_upsampler_path,
367
- gemma_root=gemma_root,
368
- loras=[],
369
- quantization=QuantizationPolicy.fp8_cast(),
370
- )
371
-
372
- def _make_lora_key(pose_strength: float, twod_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, physics_strength: float, reasoning_strength: float, twostep_strength: float) -> tuple[str, str]:
373
- rp = round(float(pose_strength), 2)
374
- ra = round(float(twod_strength), 2)
375
- rg = round(float(general_strength), 2)
376
- rm = round(float(motion_strength), 2)
377
- rd = round(float(dreamlay_strength), 2)
378
- rs = round(float(mself_strength), 2)
379
- rr = round(float(dramatic_strength), 2)
380
- rf = round(float(fluid_strength), 2)
381
- rl = round(float(liquid_strength), 2)
382
- ro = round(float(demopose_strength), 2)
383
- rv = round(float(voice_strength), 2)
384
- re = round(float(realism_strength), 2)
385
- rt = round(float(transition_strength), 2)
386
- ry = round(float(physics_strength), 2)
387
- ri = round(float(reasoning_strength), 2)
388
- rw = round(float(twostep_strength), 2)
389
- key_str = f"{pose_lora_path}:{rp}|{twod_lora_path}:{ra}|{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}|{physics_lora_path}:{ry}|{reasoning_lora_path}:{ri}|{twostep_lora_path}:{rw}"
390
- key = hashlib.sha256(key_str.encode("utf-8")).hexdigest()
391
- return key, key_str
392
-
393
-
394
- def prepare_lora_cache(
395
- pose_strength: float,
396
- twod_strength: float,
397
- general_strength: float,
398
- motion_strength: float,
399
- dreamlay_strength: float,
400
- mself_strength: float,
401
- dramatic_strength: float,
402
- fluid_strength: float,
403
- liquid_strength: float,
404
- demopose_strength: float,
405
- voice_strength: float,
406
- realism_strength: float,
407
- transition_strength: float,
408
- physics_strength: float,
409
- reasoning_strength: float,
410
- twostep_strength: float,
411
- progress=gr.Progress(track_tqdm=True),
412
- ):
413
- """
414
- CPU-only step:
415
- - checks cache
416
- - loads cached fused transformer state_dict, or
417
- - builds fused transformer on CPU and saves it
418
- The resulting state_dict is stored in memory and can be applied later.
419
- """
420
- global PENDING_LORA_KEY, PENDING_LORA_STATE, PENDING_LORA_STATUS
421
-
422
- ledger = pipeline.model_ledger
423
- key, _ = _make_lora_key(pose_strength, twod_strength, general_strength, motion_strength, dreamlay_strength, mself_strength, dramatic_strength, fluid_strength, liquid_strength, demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength)
424
- cache_path = LORA_CACHE_DIR / f"{key}.safetensors"
425
-
426
- progress(0.05, desc="Preparing LoRA state")
427
- if cache_path.exists():
428
- try:
429
- progress(0.20, desc="Loading cached fused state")
430
- state = load_file(str(cache_path))
431
- PENDING_LORA_KEY = key
432
- PENDING_LORA_STATE = state
433
- PENDING_LORA_STATUS = f"Loaded cached LoRA state: {cache_path.name}"
434
- return PENDING_LORA_STATUS
435
- except Exception as e:
436
- print(f"[LoRA] Cache load failed: {type(e).__name__}: {e}")
437
-
438
- entries = [
439
- (pose_lora_path, round(float(pose_strength), 2)),
440
- (twod_lora_path, round(float(twod_strength), 2)),
441
- (general_lora_path, round(float(general_strength), 2)),
442
- (motion_lora_path, round(float(motion_strength), 2)),
443
- (dreamlay_lora_path, round(float(dreamlay_strength), 2)),
444
- (mself_lora_path, round(float(mself_strength), 2)),
445
- (dramatic_lora_path, round(float(dramatic_strength), 2)),
446
- (fluid_lora_path, round(float(fluid_strength), 2)),
447
- (liquid_lora_path, round(float(liquid_strength), 2)),
448
- (demopose_lora_path, round(float(demopose_strength), 2)),
449
- (voice_lora_path, round(float(voice_strength), 2)),
450
- (realism_lora_path, round(float(realism_strength), 2)),
451
- (transition_lora_path, round(float(transition_strength), 2)),
452
- (physics_lora_path, round(float(physics_strength), 2)),
453
- (reasoning_lora_path, round(float(reasoning_strength), 2)),
454
- (twostep_lora_path, round(float(twostep_strength), 2)),
455
- ]
456
- loras_for_builder = [
457
- LoraPathStrengthAndSDOps(path, strength, LTXV_LORA_COMFY_RENAMING_MAP)
458
- for path, strength in entries
459
- if path is not None and float(strength) != 0.0
460
- ]
461
-
462
- if not loras_for_builder:
463
- PENDING_LORA_KEY = None
464
- PENDING_LORA_STATE = None
465
- PENDING_LORA_STATUS = "No non-zero LoRA strengths selected; nothing to prepare."
466
- return PENDING_LORA_STATUS
467
-
468
- tmp_ledger = None
469
- new_transformer_cpu = None
470
- try:
471
- progress(0.35, desc="Building fused CPU transformer")
472
- tmp_ledger = pipeline.model_ledger.__class__(
473
- dtype=ledger.dtype,
474
- device=torch.device("cpu"),
475
- checkpoint_path=str(checkpoint_path),
476
- spatial_upsampler_path=str(spatial_upsampler_path),
477
- gemma_root_path=str(gemma_root),
478
- loras=tuple(loras_for_builder),
479
- quantization=getattr(ledger, "quantization", None),
480
- )
481
- new_transformer_cpu = tmp_ledger.transformer()
482
-
483
- progress(0.70, desc="Extracting fused state_dict")
484
- state = {
485
- k: v.detach().cpu().contiguous()
486
- for k, v in new_transformer_cpu.state_dict().items()
487
- }
488
- save_file(state, str(cache_path))
489
-
490
- PENDING_LORA_KEY = key
491
- PENDING_LORA_STATE = state
492
- PENDING_LORA_STATUS = f"Built and cached LoRA state: {cache_path.name}"
493
- return PENDING_LORA_STATUS
494
-
495
- except Exception as e:
496
- import traceback
497
- print(f"[LoRA] Prepare failed: {type(e).__name__}: {e}")
498
- print(traceback.format_exc())
499
- PENDING_LORA_KEY = None
500
- PENDING_LORA_STATE = None
501
- PENDING_LORA_STATUS = f"LoRA prepare failed: {type(e).__name__}: {e}"
502
- return PENDING_LORA_STATUS
503
-
504
- finally:
505
- try:
506
- del new_transformer_cpu
507
- except Exception:
508
- pass
509
- try:
510
- del tmp_ledger
511
- except Exception:
512
- pass
513
- gc.collect()
514
-
515
-
516
- def apply_prepared_lora_state_to_pipeline():
517
- """
518
- Fast step: copy the already prepared CPU state into the live transformer.
519
- This is the only part that should remain near generation time.
520
- """
521
- global current_lora_key, PENDING_LORA_KEY, PENDING_LORA_STATE
522
-
523
- if PENDING_LORA_STATE is None or PENDING_LORA_KEY is None:
524
- print("[LoRA] No prepared LoRA state available; skipping.")
525
- return False
526
-
527
- if current_lora_key == PENDING_LORA_KEY:
528
- print("[LoRA] Prepared LoRA state already active; skipping.")
529
- return True
530
-
531
- existing_transformer = _transformer
532
- with torch.no_grad():
533
- missing, unexpected = existing_transformer.load_state_dict(PENDING_LORA_STATE, strict=False)
534
- if missing or unexpected:
535
- print(f"[LoRA] load_state_dict mismatch: missing={len(missing)}, unexpected={len(unexpected)}")
536
-
537
- current_lora_key = PENDING_LORA_KEY
538
- print("[LoRA] Prepared LoRA state applied to the pipeline.")
539
- return True
540
-
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
- def log_memory(tag: str):
588
- if torch.cuda.is_available():
589
- allocated = torch.cuda.memory_allocated() / 1024**3
590
- peak = torch.cuda.max_memory_allocated() / 1024**3
591
- free, total = torch.cuda.mem_get_info()
592
- print(f"[VRAM {tag}] allocated={allocated:.2f}GB peak={peak:.2f}GB free={free / 1024**3:.2f}GB total={total / 1024**3:.2f}GB")
593
-
594
-
595
- def detect_aspect_ratio(image) -> str:
596
- if image is None:
597
- return "16:9"
598
- if hasattr(image, "size"):
599
- w, h = image.size
600
- elif hasattr(image, "shape"):
601
- h, w = image.shape[:2]
602
- else:
603
- return "16:9"
604
- ratio = w / h
605
- candidates = {
606
- "16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0,
607
- "4:3": 4 / 3, "3:4": 3 / 4, "21:9": 21 / 9,
608
- }
609
- return min(candidates, key=lambda k: abs(ratio - candidates[k]))
610
-
611
-
612
- def on_image_upload(first_image, last_image, high_res):
613
- ref_image = first_image if first_image is not None else last_image
614
- aspect = detect_aspect_ratio(ref_image)
615
- tier = "high" if high_res else "low"
616
- w, h = RESOLUTIONS[tier][aspect]
617
- return gr.update(value=w), gr.update(value=h)
618
-
619
-
620
- def on_highres_toggle(first_image, last_image, high_res):
621
- ref_image = first_image if first_image is not None else last_image
622
- aspect = detect_aspect_ratio(ref_image)
623
- tier = "high" if high_res else "low"
624
- w, h = RESOLUTIONS[tier][aspect]
625
- return gr.update(value=w), gr.update(value=h)
626
-
627
- def get_gpu_duration(
628
- first_image,
629
- last_image,
630
- input_audio,
631
- prompt: str,
632
- duration: float,
633
- gpu_duration: float,
634
- enhance_prompt: bool = True,
635
- seed: int = 42,
636
- randomize_seed: bool = True,
637
- height: int = 1024,
638
- width: int = 1536,
639
- video_cfg_scale: float = 1.0,
640
- video_stg_scale: float = 0.0,
641
- video_rescale_scale: float = 0.45,
642
- video_a2v_scale: float = 3.0,
643
- audio_cfg_scale: float = 1.0,
644
- audio_stg_scale: float = 0.0,
645
- audio_rescale_scale: float = 1.0,
646
- audio_v2a_scale: float = 3.0,
647
- pose_strength: float = 0.0,
648
- twod_strength: float = 0.0,
649
- general_strength: float = 0.0,
650
- motion_strength: float = 0.0,
651
- dreamlay_strength: float = 0.0,
652
- mself_strength: float = 0.0,
653
- dramatic_strength: float = 0.0,
654
- fluid_strength: float = 0.0,
655
- liquid_strength: float = 0.0,
656
- demopose_strength: float = 0.0,
657
- voice_strength: float = 0.0,
658
- realism_strength: float = 0.0,
659
- transition_strength: float = 0.0,
660
- physics_strength: float = 0.0,
661
- reasoning_strength: float = 0.0,
662
- twostep_strength: float = 0.0,
663
- num_inference_steps: int = 8,
664
- progress=None,
665
- ):
666
- return int(gpu_duration)
667
-
668
- @spaces.GPU(duration=get_gpu_duration)
669
- @torch.inference_mode()
670
- def generate_video(
671
- first_image,
672
- last_image,
673
- input_audio,
674
- prompt: str,
675
- duration: float,
676
- gpu_duration: float,
677
- enhance_prompt: bool = True,
678
- seed: int = 42,
679
- randomize_seed: bool = True,
680
- height: int = 1024,
681
- width: int = 1536,
682
- video_cfg_scale: float = 1.0,
683
- video_stg_scale: float = 0.0,
684
- video_rescale_scale: float = 0.45,
685
- video_a2v_scale: float = 3.0,
686
- audio_cfg_scale: float = 1.0,
687
- audio_stg_scale: float = 0.0,
688
- audio_rescale_scale: float = 1.0,
689
- audio_v2a_scale: float = 3.0,
690
- pose_strength: float = 0.0,
691
- twod_strength: float = 0.0,
692
- general_strength: float = 0.0,
693
- motion_strength: float = 0.0,
694
- dreamlay_strength: float = 0.0,
695
- mself_strength: float = 0.0,
696
- dramatic_strength: float = 0.0,
697
- fluid_strength: float = 0.0,
698
- liquid_strength: float = 0.0,
699
- demopose_strength: float = 0.0,
700
- voice_strength: float = 0.0,
701
- realism_strength: float = 0.0,
702
- transition_strength: float = 0.0,
703
- physics_strength: float = 0.0,
704
- reasoning_strength: float = 0.0,
705
- twostep_strength: float = 0.0,
706
- num_inference_steps: int = 8,
707
- progress=gr.Progress(track_tqdm=True),
708
- ):
709
- try:
710
- torch.cuda.reset_peak_memory_stats()
711
- log_memory("start")
712
-
713
- current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
714
-
715
- frame_rate = DEFAULT_FRAME_RATE
716
- num_frames = int(duration * frame_rate) + 1
717
- num_frames = ((num_frames - 1 + 7) // 8) * 8 + 1
718
-
719
- print(f"Generating: {height}x{width}, {num_frames} frames ({duration}s), seed={current_seed}")
720
-
721
- images = []
722
- output_dir = Path("outputs")
723
- output_dir.mkdir(exist_ok=True)
724
-
725
- if first_image is not None:
726
- temp_first_path = output_dir / f"temp_first_{current_seed}.jpg"
727
- if hasattr(first_image, "save"):
728
- first_image.save(temp_first_path)
729
- else:
730
- temp_first_path = Path(first_image)
731
- images.append(ImageConditioningInput(path=str(temp_first_path), frame_idx=0, strength=1.0))
732
-
733
- if last_image is not None:
734
- temp_last_path = output_dir / f"temp_last_{current_seed}.jpg"
735
- if hasattr(last_image, "save"):
736
- last_image.save(temp_last_path)
737
- else:
738
- temp_last_path = Path(last_image)
739
- images.append(ImageConditioningInput(path=str(temp_last_path), frame_idx=num_frames - 1, strength=1.0))
740
-
741
- tiling_config = TilingConfig.default()
742
- video_chunks_number = get_video_chunks_number(num_frames, tiling_config)
743
-
744
- video_guider_params = MultiModalGuiderParams(
745
- cfg_scale=video_cfg_scale,
746
- stg_scale=video_stg_scale,
747
- rescale_scale=video_rescale_scale,
748
- modality_scale=video_a2v_scale,
749
- skip_step=0,
750
- stg_blocks=[],
751
- )
752
-
753
- audio_guider_params = MultiModalGuiderParams(
754
- cfg_scale=audio_cfg_scale,
755
- stg_scale=audio_stg_scale,
756
- rescale_scale=audio_rescale_scale,
757
- modality_scale=audio_v2a_scale,
758
- skip_step=0,
759
- stg_blocks=[],
760
- )
761
-
762
- log_memory("before pipeline call")
763
-
764
- apply_prepared_lora_state_to_pipeline()
765
-
766
- video, audio = pipeline(
767
- prompt=prompt,
768
- seed=current_seed,
769
- height=int(height),
770
- width=int(width),
771
- num_frames=num_frames,
772
- frame_rate=frame_rate,
773
- video_guider_params=video_guider_params,
774
- audio_guider_params=audio_guider_params,
775
- images=images,
776
- num_inference_steps=num_inference_steps,
777
- audio_path=input_audio,
778
- tiling_config=tiling_config,
779
- enhance_prompt=enhance_prompt,
780
- )
781
-
782
- log_memory("after pipeline call")
783
-
784
- output_path = tempfile.mktemp(suffix=".mp4")
785
- encode_video(
786
- video=video,
787
- fps=frame_rate,
788
- audio=audio,
789
- output_path=output_path,
790
- video_chunks_number=video_chunks_number,
791
- )
792
-
793
- log_memory("after encode_video")
794
- return str(output_path), current_seed
795
-
796
- except Exception as e:
797
- import traceback
798
- log_memory("on error")
799
- print(f"Error: {str(e)}\n{traceback.format_exc()}")
800
- return None, current_seed
801
-
802
- # =============================================================================
803
- # Gradio UI
804
- # =============================================================================
805
-
806
- css = """
807
- .fillable {max-width: 1200px !important}
808
- .progress-text {color: black}
809
- """
810
-
811
- with gr.Blocks(title="LTX-2.3 Distilled with LoRAs, Negative Prompting, and Advanced Settings") as demo:
812
- gr.Markdown("# LTX-2.3 Two-Stage HQ Video Generation")
813
- gr.Markdown(
814
- "High-quality text/image-to-video with cached LoRA state + CFG guidance. "
815
- "[[Model]](https://huggingface.co/Lightricks/LTX-2.3)"
816
- )
817
-
818
- with gr.Row():
819
- # LEFT SIDE: Input Controls
820
- with gr.Column():
821
- with gr.Row():
822
- first_image = gr.Image(label="First Frame (Optional)", type="pil")
823
- last_image = gr.Image(label="Last Frame (Optional)", type="pil")
824
-
825
- prompt = gr.Textbox(
826
- label="Prompt",
827
- value="Make this image come alive with cinematic motion, smooth animation",
828
- lines=3,
829
- placeholder="Describe the motion and animation you want...",
830
- )
831
-
832
- duration = gr.Slider(
833
- label="Duration (seconds)",
834
- minimum=1.0, maximum=30.0, value=10.0, step=0.1,
835
- )
836
-
837
- with gr.Row():
838
- seed = gr.Number(label="Seed", value=42, precision=0, minimum=0, maximum=MAX_SEED)
839
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
840
-
841
- with gr.Row():
842
- high_res = gr.Checkbox(label="High Resolution", value=True)
843
- enhance_prompt = gr.Checkbox(label="Enhance Prompt", value=False)
844
-
845
- with gr.Row():
846
- width = gr.Number(label="Width", value=1536, precision=0)
847
- height = gr.Number(label="Height", value=1024, precision=0)
848
-
849
- with gr.Row():
850
- num_inference_steps = gr.Slider(
851
- label="Inference Steps",
852
- minimum=2, maximum=16, value=8, step=1,
853
- info="Higher = more quality but slower"
854
- )
855
-
856
- generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
857
-
858
- with gr.Accordion("Advanced Settings", open=False):
859
- gr.Markdown("### Video Guidance Parameters")
860
-
861
- with gr.Row():
862
- video_cfg_scale = gr.Slider(
863
- label="Video CFG Scale", minimum=1.0, maximum=10.0, value=1.0, step=0.1
864
- )
865
- video_stg_scale = gr.Slider(
866
- label="Video STG Scale", minimum=0.0, maximum=2.0, value=0.0, step=0.1
867
- )
868
-
869
- with gr.Row():
870
- video_rescale_scale = gr.Slider(
871
- label="Video Rescale", minimum=0.0, maximum=2.0, value=0.45, step=0.1
872
- )
873
- video_a2v_scale = gr.Slider(
874
- label="A2V Scale", minimum=0.0, maximum=5.0, value=3.0, step=0.1
875
- )
876
-
877
- gr.Markdown("### Audio Guidance Parameters")
878
-
879
- with gr.Row():
880
- audio_cfg_scale = gr.Slider(
881
- label="Audio CFG Scale", minimum=1.0, maximum=15.0, value=1.0, step=0.1
882
- )
883
- audio_stg_scale = gr.Slider(
884
- label="Audio STG Scale", minimum=0.0, maximum=2.0, value=0.0, step=0.1
885
- )
886
-
887
- with gr.Row():
888
- audio_rescale_scale = gr.Slider(
889
- label="Audio Rescale", minimum=0.0, maximum=2.0, value=1.0, step=0.1
890
- )
891
- audio_v2a_scale = gr.Slider(
892
- label="V2A Scale", minimum=0.0, maximum=5.0, value=3.0, step=0.1
893
- )
894
- with gr.Row():
895
- input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
896
-
897
- # RIGHT SIDE: Output and LoRA
898
- with gr.Column():
899
- output_video = gr.Video(label="Generated Video", autoplay=False)
900
-
901
- gpu_duration = gr.Slider(
902
- label="ZeroGPU duration (seconds)",
903
- minimum=30.0, maximum=240.0, value=90.0, step=1.0,
904
- info="Increase for longer videos, higher resolution, or LoRA usage"
905
- )
906
-
907
- gr.Markdown("### LoRA Adapter Strengths")
908
- gr.Markdown("Set to 0 to disable, then click 'Prepare LoRA Cache'")
909
-
910
- with gr.Row():
911
- pose_strength = gr.Slider(label="Anthro Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
912
- twod_strength = gr.Slider(label="2D Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
913
-
914
- with gr.Row():
915
- general_strength = gr.Slider(label="Reasoning Enhancer", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
916
- motion_strength = gr.Slider(label="Anthro Posing", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
917
-
918
- with gr.Row():
919
- dreamlay_strength = gr.Slider(label="Dreamlay", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
920
- mself_strength = gr.Slider(label="Mself", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
921
-
922
- with gr.Row():
923
- dramatic_strength = gr.Slider(label="Dramatic", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
924
- fluid_strength = gr.Slider(label="Fluid Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
925
-
926
- with gr.Row():
927
- liquid_strength = gr.Slider(label="Liquid Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
928
- demopose_strength = gr.Slider(label="Audio Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
929
-
930
- with gr.Row():
931
- voice_strength = gr.Slider(label="Voice Helper", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
932
- realism_strength = gr.Slider(label="Anthro Realism", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
933
-
934
- with gr.Row():
935
- transition_strength = gr.Slider(label="POV", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
936
- physics_strength = gr.Slider(label="Physics", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
937
- with gr.Row():
938
- reasoning_strength = gr.Slider(label="Official Reasoning", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
939
- twostep_strength = gr.Slider(label="Two Step Reasoning", minimum=0.0, maximum=2.0, value=0.0, step=0.01)
940
-
941
- prepare_lora_btn = gr.Button("Prepare / Load LoRA Cache", variant="secondary")
942
- lora_status = gr.Textbox(
943
- label="LoRA Cache Status",
944
- value="No LoRA state prepared yet.",
945
- interactive=False,
946
- )
947
-
948
- # Event handlers
949
- first_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
950
- last_image.change(fn=on_image_upload, inputs=[first_image, last_image, high_res], outputs=[width, height])
951
- high_res.change(fn=on_highres_toggle, inputs=[first_image, last_image, high_res], outputs=[width, height])
952
-
953
- prepare_lora_btn.click(
954
- fn=prepare_lora_cache,
955
- inputs=[pose_strength, twod_strength, general_strength, motion_strength, dreamlay_strength,
956
- mself_strength, dramatic_strength, fluid_strength, liquid_strength,
957
- demopose_strength, voice_strength, realism_strength, transition_strength, physics_strength, reasoning_strength, twostep_strength],
958
- outputs=[lora_status],
959
- )
960
-
961
- generate_btn.click(
962
- fn=generate_video,
963
- inputs=[
964
- first_image, last_image, input_audio, prompt, duration, gpu_duration,
965
- enhance_prompt, seed, randomize_seed, height, width,
966
- video_cfg_scale, video_stg_scale, video_rescale_scale, video_a2v_scale,
967
- audio_cfg_scale, audio_stg_scale, audio_rescale_scale, audio_v2a_scale,
968
- pose_strength, twod_strength, general_strength, motion_strength,
969
- dreamlay_strength, mself_strength, dramatic_strength, fluid_strength,
970
- liquid_strength, demopose_strength, voice_strength, realism_strength,
971
- transition_strength, physics_strength, reasoning_strength, twostep_strength, num_inference_steps,
972
- ],
973
- outputs=[output_video, seed],
974
- )
975
-
976
-
977
- if __name__ == "__main__":
978
- demo.queue().launch(theme=gr.themes.Citrus(), css=css, mcp_server=False)