nexusbert commited on
Commit
fa5cffc
Β·
1 Parent(s): d0386d4

Rewrite app.py for current LTX-2 API

Browse files
Files changed (1) hide show
  1. app.py +17 -225
app.py CHANGED
@@ -2,14 +2,14 @@ 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
 
@@ -40,7 +40,6 @@ torch._dynamo.config.disable = True
40
  try:
41
  import spaces
42
  except ImportError:
43
- # Running locally, not on HF Spaces β€” provide a no-op decorator
44
  class _FakeSpaces:
45
  @staticmethod
46
  def GPU(duration=0):
@@ -53,35 +52,19 @@ import gradio as gr
53
  import numpy as np
54
  from huggingface_hub import hf_hub_download, snapshot_download
55
 
56
- from ltx_core.components.diffusion_steps import EulerDiffusionStep
57
- from ltx_core.components.noisers import GaussianNoiser
58
- from ltx_core.model.audio_vae import encode_audio as vae_encode_audio
59
- from ltx_core.model.upsampler import upsample_video
60
  from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
61
  from ltx_core.quantization import QuantizationPolicy
62
- from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape
63
  from ltx_pipelines.distilled import DistilledPipeline
64
- from ltx_pipelines.utils import euler_denoising_loop
65
  from ltx_pipelines.utils.args import ImageConditioningInput
66
- from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
67
- from ltx_pipelines.utils.helpers import (
68
- cleanup_memory,
69
- combined_image_conditionings,
70
- denoise_video_only,
71
- encode_prompts,
72
- simple_denoising_func,
73
- )
74
- from ltx_pipelines.utils.media_io import decode_audio_from_file, encode_video
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
 
@@ -94,179 +77,15 @@ DEFAULT_PROMPT = (
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)},
100
  "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
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
- if audio_path is None:
122
- return super().__call__(
123
- prompt=prompt,
124
- seed=seed,
125
- height=height,
126
- width=width,
127
- num_frames=num_frames,
128
- frame_rate=frame_rate,
129
- images=images,
130
- tiling_config=tiling_config,
131
- enhance_prompt=enhance_prompt,
132
- )
133
-
134
- generator = torch.Generator(device=self.device).manual_seed(seed)
135
- noiser = GaussianNoiser(generator=generator)
136
- stepper = EulerDiffusionStep()
137
- dtype = torch.bfloat16
138
-
139
- (ctx_p,) = encode_prompts(
140
- [prompt],
141
- self.model_ledger,
142
- enhance_first_prompt=enhance_prompt,
143
- enhance_prompt_image=images[0].path if len(images) > 0 else None,
144
- )
145
- video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding
146
-
147
- video_duration = num_frames / frame_rate
148
- decoded_audio = decode_audio_from_file(audio_path, self.device, 0.0, video_duration)
149
- if decoded_audio is None:
150
- raise ValueError(f"Could not extract audio stream from {audio_path}")
151
-
152
- encoded_audio_latent = vae_encode_audio(decoded_audio, self.model_ledger.audio_encoder())
153
- audio_shape = AudioLatentShape.from_duration(batch=1, duration=video_duration, channels=8, mel_bins=16)
154
- expected_frames = audio_shape.frames
155
- actual_frames = encoded_audio_latent.shape[2]
156
-
157
- if actual_frames > expected_frames:
158
- encoded_audio_latent = encoded_audio_latent[:, :, :expected_frames, :]
159
- elif actual_frames < expected_frames:
160
- pad = torch.zeros(
161
- encoded_audio_latent.shape[0],
162
- encoded_audio_latent.shape[1],
163
- expected_frames - actual_frames,
164
- encoded_audio_latent.shape[3],
165
- device=encoded_audio_latent.device,
166
- dtype=encoded_audio_latent.dtype,
167
- )
168
- encoded_audio_latent = torch.cat([encoded_audio_latent, pad], dim=2)
169
-
170
- video_encoder = self.model_ledger.video_encoder()
171
- transformer = self.model_ledger.transformer()
172
- stage_1_sigmas = torch.tensor(DISTILLED_SIGMA_VALUES, device=self.device)
173
-
174
- def denoising_loop(sigmas, video_state, audio_state, stepper):
175
- return euler_denoising_loop(
176
- sigmas=sigmas,
177
- video_state=video_state,
178
- audio_state=audio_state,
179
- stepper=stepper,
180
- denoise_fn=simple_denoising_func(
181
- video_context=video_context,
182
- audio_context=audio_context,
183
- transformer=transformer,
184
- ),
185
- )
186
-
187
- stage_1_output_shape = VideoPixelShape(
188
- batch=1,
189
- frames=num_frames,
190
- width=width // 2,
191
- height=height // 2,
192
- fps=frame_rate,
193
- )
194
- stage_1_conditionings = combined_image_conditionings(
195
- images=images,
196
- height=stage_1_output_shape.height,
197
- width=stage_1_output_shape.width,
198
- video_encoder=video_encoder,
199
- dtype=dtype,
200
- device=self.device,
201
- )
202
- video_state = denoise_video_only(
203
- output_shape=stage_1_output_shape,
204
- conditionings=stage_1_conditionings,
205
- noiser=noiser,
206
- sigmas=stage_1_sigmas,
207
- stepper=stepper,
208
- denoising_loop_fn=denoising_loop,
209
- components=self.pipeline_components,
210
- dtype=dtype,
211
- device=self.device,
212
- initial_audio_latent=encoded_audio_latent,
213
- )
214
-
215
- torch.cuda.synchronize()
216
- cleanup_memory()
217
-
218
- upscaled_video_latent = upsample_video(
219
- latent=video_state.latent[:1],
220
- video_encoder=video_encoder,
221
- upsampler=self.model_ledger.spatial_upsampler(),
222
- )
223
- stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES, device=self.device)
224
- stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)
225
- stage_2_conditionings = combined_image_conditionings(
226
- images=images,
227
- height=stage_2_output_shape.height,
228
- width=stage_2_output_shape.width,
229
- video_encoder=video_encoder,
230
- dtype=dtype,
231
- device=self.device,
232
- )
233
- video_state = denoise_video_only(
234
- output_shape=stage_2_output_shape,
235
- conditionings=stage_2_conditionings,
236
- noiser=noiser,
237
- sigmas=stage_2_sigmas,
238
- stepper=stepper,
239
- denoising_loop_fn=denoising_loop,
240
- components=self.pipeline_components,
241
- dtype=dtype,
242
- device=self.device,
243
- noise_scale=stage_2_sigmas[0],
244
- initial_video_latent=upscaled_video_latent,
245
- initial_audio_latent=encoded_audio_latent,
246
- )
247
-
248
- torch.cuda.synchronize()
249
- del transformer
250
- del video_encoder
251
- cleanup_memory()
252
-
253
- decoded_video = self.model_ledger.video_decoder().decode_video(
254
- video_state.latent,
255
- tiling_config,
256
- generator,
257
- )
258
- original_audio = Audio(
259
- waveform=decoded_audio.waveform.squeeze(0),
260
- sampling_rate=decoded_audio.sampling_rate,
261
- )
262
- return decoded_video, original_audio
263
-
264
-
265
- # Model repos
266
  LTX_MODEL_REPO = "diffusers-internal-dev/ltx-23"
267
  GEMMA_REPO = "google/gemma-3-12b-it-qat-q4_0-unquantized"
268
 
269
- # Download model checkpoints
270
  print("=" * 80)
271
  print("Downloading LTX-2.3 distilled model + Gemma...")
272
  print("=" * 80)
@@ -279,8 +98,8 @@ print(f"Checkpoint: {checkpoint_path}")
279
  print(f"Spatial upsampler: {spatial_upsampler_path}")
280
  print(f"Gemma root: {gemma_root}")
281
 
282
- # Initialize pipeline WITH text encoder and optional audio support
283
- pipeline = LTX23DistilledA2VPipeline(
284
  distilled_checkpoint_path=checkpoint_path,
285
  spatial_upsampler_path=spatial_upsampler_path,
286
  gemma_root=gemma_root,
@@ -288,30 +107,6 @@ pipeline = LTX23DistilledA2VPipeline(
288
  quantization=QuantizationPolicy.fp8_cast(),
289
  )
290
 
291
- # Preload all models for ZeroGPU tensor packing.
292
- print("Preloading all models (including Gemma and audio components)...")
293
- ledger = pipeline.model_ledger
294
- _transformer = ledger.transformer()
295
- _video_encoder = ledger.video_encoder()
296
- _video_decoder = ledger.video_decoder()
297
- _audio_encoder = ledger.audio_encoder()
298
- _audio_decoder = ledger.audio_decoder()
299
- _vocoder = ledger.vocoder()
300
- _spatial_upsampler = ledger.spatial_upsampler()
301
- _text_encoder = ledger.text_encoder()
302
- _embeddings_processor = ledger.gemma_embeddings_processor()
303
-
304
- ledger.transformer = lambda: _transformer
305
- ledger.video_encoder = lambda: _video_encoder
306
- ledger.video_decoder = lambda: _video_decoder
307
- ledger.audio_encoder = lambda: _audio_encoder
308
- ledger.audio_decoder = lambda: _audio_decoder
309
- ledger.vocoder = lambda: _vocoder
310
- ledger.spatial_upsampler = lambda: _spatial_upsampler
311
- ledger.text_encoder = lambda: _text_encoder
312
- ledger.gemma_embeddings_processor = lambda: _embeddings_processor
313
- print("All models preloaded (including Gemma text encoder and audio encoder)!")
314
-
315
  print("=" * 80)
316
  print("Pipeline ready!")
317
  print("=" * 80)
@@ -360,7 +155,6 @@ def on_highres_toggle(first_image, last_image, high_res):
360
  def generate_video(
361
  first_image,
362
  last_image,
363
- input_audio,
364
  prompt: str,
365
  duration: float,
366
  enhance_prompt: bool = True,
@@ -371,7 +165,8 @@ def generate_video(
371
  progress=gr.Progress(track_tqdm=True),
372
  ):
373
  try:
374
- torch.cuda.reset_peak_memory_stats()
 
375
  log_memory("start")
376
 
377
  current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
@@ -415,7 +210,6 @@ def generate_video(
415
  num_frames=num_frames,
416
  frame_rate=frame_rate,
417
  images=images,
418
- audio_path=input_audio,
419
  tiling_config=tiling_config,
420
  enhance_prompt=enhance_prompt,
421
  )
@@ -441,10 +235,11 @@ def generate_video(
441
  return None, current_seed
442
 
443
 
 
444
  with gr.Blocks(title="LTX-2.3 Distilled") as demo:
445
  gr.Markdown("# LTX-2.3 F2LF: Fast Audio-Video Generation with Frame Conditioning")
446
  gr.Markdown(
447
- "Fast and high quality video + audio generation with first and last frame conditioning and optional audio input "
448
  "[[model]](https://huggingface.co/Lightricks/LTX-2.3) "
449
  "[[code]](https://github.com/Lightricks/LTX-2)"
450
  )
@@ -454,7 +249,6 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
454
  with gr.Row():
455
  first_image = gr.Image(label="First Frame (Optional)", type="pil")
456
  last_image = gr.Image(label="Last Frame (Optional)", type="pil")
457
- input_audio = gr.Audio(label="Audio Input (Optional)", type="filepath")
458
  prompt = gr.Textbox(
459
  label="Prompt",
460
  info="for best results - make it as elaborate as possible",
@@ -463,7 +257,6 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
463
  placeholder="Describe the motion and animation you want...",
464
  )
465
  duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
466
-
467
 
468
  generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
469
 
@@ -485,7 +278,6 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
485
  [
486
  None,
487
  "pinkknit.jpg",
488
- None,
489
  "The camera falls downward through darkness as if dropped into a tunnel. "
490
  "As it slows, five friends wearing pink knitted hats and sunglasses lean "
491
  "over and look down toward the camera with curious expressions. The lens "
@@ -501,7 +293,7 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
501
  ],
502
  ],
503
  inputs=[
504
- first_image, last_image, input_audio, prompt, duration,
505
  enhance_prompt, seed, randomize_seed, height, width,
506
  ],
507
  )
@@ -527,7 +319,7 @@ with gr.Blocks(title="LTX-2.3 Distilled") as demo:
527
  generate_btn.click(
528
  fn=generate_video,
529
  inputs=[
530
- first_image, last_image, input_audio, prompt, duration, enhance_prompt,
531
  seed, randomize_seed, height, width,
532
  ],
533
  outputs=[output_video, seed],
 
2
  import subprocess
3
  import sys
4
 
 
5
  os.environ["TORCH_COMPILE_DISABLE"] = "1"
6
  os.environ["TORCHDYNAMO_DISABLE"] = "1"
7
 
8
+ subprocess.run(
9
+ [sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"],
10
+ check=False,
11
+ )
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
 
 
40
  try:
41
  import spaces
42
  except ImportError:
 
43
  class _FakeSpaces:
44
  @staticmethod
45
  def GPU(duration=0):
 
52
  import numpy as np
53
  from huggingface_hub import hf_hub_download, snapshot_download
54
 
 
 
 
 
55
  from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
56
  from ltx_core.quantization import QuantizationPolicy
 
57
  from ltx_pipelines.distilled import DistilledPipeline
 
58
  from ltx_pipelines.utils.args import ImageConditioningInput
59
+ from ltx_pipelines.utils.media_io import encode_video
 
 
 
 
 
 
 
 
60
 
 
 
 
61
  try:
62
+ from ltx_core.model.transformer import attention as _attn_mod
63
  from xformers.ops import memory_efficient_attention as _mea
64
  _attn_mod.memory_efficient_attention = _mea
65
+ print("[ATTN] xformers memory_efficient_attention patched successfully")
66
  except Exception as e:
67
+ print(f"[ATTN] xformers patch skipped: {type(e).__name__}: {e}")
68
 
69
  logging.getLogger().setLevel(logging.INFO)
70
 
 
77
  )
78
  DEFAULT_FRAME_RATE = 24.0
79
 
 
80
  RESOLUTIONS = {
81
  "high": {"16:9": (1536, 1024), "9:16": (1024, 1536), "1:1": (1024, 1024)},
82
  "low": {"16:9": (768, 512), "9:16": (512, 768), "1:1": (768, 768)},
83
  }
84
 
85
+ # ── Model download ──────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  LTX_MODEL_REPO = "diffusers-internal-dev/ltx-23"
87
  GEMMA_REPO = "google/gemma-3-12b-it-qat-q4_0-unquantized"
88
 
 
89
  print("=" * 80)
90
  print("Downloading LTX-2.3 distilled model + Gemma...")
91
  print("=" * 80)
 
98
  print(f"Spatial upsampler: {spatial_upsampler_path}")
99
  print(f"Gemma root: {gemma_root}")
100
 
101
+ # ── Pipeline init ───────────────────────────────────────────────────────────
102
+ pipeline = DistilledPipeline(
103
  distilled_checkpoint_path=checkpoint_path,
104
  spatial_upsampler_path=spatial_upsampler_path,
105
  gemma_root=gemma_root,
 
107
  quantization=QuantizationPolicy.fp8_cast(),
108
  )
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  print("=" * 80)
111
  print("Pipeline ready!")
112
  print("=" * 80)
 
155
  def generate_video(
156
  first_image,
157
  last_image,
 
158
  prompt: str,
159
  duration: float,
160
  enhance_prompt: bool = True,
 
165
  progress=gr.Progress(track_tqdm=True),
166
  ):
167
  try:
168
+ if torch.cuda.is_available():
169
+ torch.cuda.reset_peak_memory_stats()
170
  log_memory("start")
171
 
172
  current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
 
210
  num_frames=num_frames,
211
  frame_rate=frame_rate,
212
  images=images,
 
213
  tiling_config=tiling_config,
214
  enhance_prompt=enhance_prompt,
215
  )
 
235
  return None, current_seed
236
 
237
 
238
+ # ── Gradio UI ───────────────────────────────────────────────────────────────
239
  with gr.Blocks(title="LTX-2.3 Distilled") as demo:
240
  gr.Markdown("# LTX-2.3 F2LF: Fast Audio-Video Generation with Frame Conditioning")
241
  gr.Markdown(
242
+ "Fast and high quality video + audio generation with first and last frame conditioning "
243
  "[[model]](https://huggingface.co/Lightricks/LTX-2.3) "
244
  "[[code]](https://github.com/Lightricks/LTX-2)"
245
  )
 
249
  with gr.Row():
250
  first_image = gr.Image(label="First Frame (Optional)", type="pil")
251
  last_image = gr.Image(label="Last Frame (Optional)", type="pil")
 
252
  prompt = gr.Textbox(
253
  label="Prompt",
254
  info="for best results - make it as elaborate as possible",
 
257
  placeholder="Describe the motion and animation you want...",
258
  )
259
  duration = gr.Slider(label="Duration (seconds)", minimum=1.0, maximum=10.0, value=3.0, step=0.1)
 
260
 
261
  generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
262
 
 
278
  [
279
  None,
280
  "pinkknit.jpg",
 
281
  "The camera falls downward through darkness as if dropped into a tunnel. "
282
  "As it slows, five friends wearing pink knitted hats and sunglasses lean "
283
  "over and look down toward the camera with curious expressions. The lens "
 
293
  ],
294
  ],
295
  inputs=[
296
+ first_image, last_image, prompt, duration,
297
  enhance_prompt, seed, randomize_seed, height, width,
298
  ],
299
  )
 
319
  generate_btn.click(
320
  fn=generate_video,
321
  inputs=[
322
+ first_image, last_image, prompt, duration, enhance_prompt,
323
  seed, randomize_seed, height, width,
324
  ],
325
  outputs=[output_video, seed],