dagloop5 commited on
Commit
a83c40e
·
verified ·
1 Parent(s): d45398c

Delete app(10wip).py

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