dagloop5 commited on
Commit
3146f01
·
verified ·
1 Parent(s): b5194ca

Delete app(draft3).py

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