improvements + fixes

#1
by linoyts HF Staff - opened
.gitattributes CHANGED
@@ -36,3 +36,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  astronaut.jpg filter=lfs diff=lfs merge=lfs -text
37
  kill_bill.jpeg filter=lfs diff=lfs merge=lfs -text
38
  cat_selfie.JPG filter=lfs diff=lfs merge=lfs -text
 
 
36
  astronaut.jpg filter=lfs diff=lfs merge=lfs -text
37
  kill_bill.jpeg filter=lfs diff=lfs merge=lfs -text
38
  cat_selfie.JPG filter=lfs diff=lfs merge=lfs -text
39
+ wednesday.png filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -8,10 +8,14 @@ sys.path.insert(0, str(current_dir / "packages" / "ltx-core" / "src"))
8
 
9
  import spaces
10
  import gradio as gr
 
11
  import numpy as np
12
  import random
 
13
  from typing import Optional
 
14
  from huggingface_hub import hf_hub_download
 
15
  from ltx_pipelines.distilled import DistilledPipeline
16
  from ltx_core.tiling import TilingConfig
17
  from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
@@ -31,11 +35,13 @@ DEFAULT_PROMPT = "An astronaut hatches from a fragile egg on the surface of the
31
 
32
  # HuggingFace Hub defaults
33
  DEFAULT_REPO_ID = "Lightricks/LTX-2"
34
- DEFAULT_GEMMA_REPO_ID = "google/gemma-3-12b-it-qat-q4_0-unquantized"
35
  DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev-fp8.safetensors"
36
  DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"
37
  DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"
38
 
 
 
 
39
  def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):
40
  """Download from HuggingFace Hub or use local checkpoint."""
41
  if repo_id is None and filename is None:
@@ -66,7 +72,7 @@ print(f"Initializing pipeline with:")
66
  print(f" checkpoint_path={checkpoint_path}")
67
  print(f" distilled_lora_path={distilled_lora_path}")
68
  print(f" spatial_upsampler_path={spatial_upsampler_path}")
69
- print(f" gemma_root={DEFAULT_GEMMA_REPO_ID}")
70
 
71
  # Load distilled LoRA as a regular LoRA
72
  loras = [
@@ -77,15 +83,26 @@ loras = [
77
  )
78
  ]
79
 
 
 
80
  pipeline = DistilledPipeline(
81
  checkpoint_path=checkpoint_path,
82
  spatial_upsampler_path=spatial_upsampler_path,
83
- gemma_root=DEFAULT_GEMMA_REPO_ID,
84
  loras=loras,
85
  fp8transformer=True,
86
  local_files_only=False,
87
  )
88
 
 
 
 
 
 
 
 
 
 
89
  print("=" * 80)
90
  print("Pipeline fully loaded and ready!")
91
  print("=" * 80)
@@ -95,6 +112,7 @@ def generate_video(
95
  input_image,
96
  prompt: str,
97
  duration: float,
 
98
  seed: int = 42,
99
  randomize_seed: bool = True,
100
  height: int = DEFAULT_HEIGHT,
@@ -113,20 +131,59 @@ def generate_video(
113
  # Create output directory if it doesn't exist
114
  output_dir = Path("outputs")
115
  output_dir.mkdir(exist_ok=True)
116
- output_path = output_dir / f"video_{seed}.mp4"
117
 
118
  # Handle image input
119
  images = []
 
 
120
  if input_image is not None:
121
  # Save uploaded image temporarily
122
- temp_image_path = output_dir / f"temp_input_{seed}.jpg"
123
  if hasattr(input_image, 'save'):
124
  input_image.save(temp_image_path)
125
  else:
126
  # If it's a file path already
127
- temp_image_path = input_image
128
  # Format: (image_path, frame_idx, strength)
129
  images = [(str(temp_image_path), 0, 1.0)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  # Run inference - progress automatically tracks tqdm from pipeline
132
  pipeline(
@@ -139,6 +196,8 @@ def generate_video(
139
  frame_rate=frame_rate,
140
  images=images,
141
  tiling_config=TilingConfig.default(),
 
 
142
  )
143
 
144
  return str(output_path), current_seed
@@ -168,14 +227,18 @@ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
168
  lines=3,
169
  placeholder="Describe the motion and animation you want..."
170
  )
171
-
172
- duration = gr.Slider(
173
- label="Duration (seconds)",
174
- minimum=1.0,
175
- maximum=10.0,
176
- value=3.0,
177
- step=0.1
178
- )
 
 
 
 
179
 
180
  generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
181
 
@@ -214,6 +277,7 @@ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
214
  input_image,
215
  prompt,
216
  duration,
 
217
  seed,
218
  randomize_seed,
219
  height,
@@ -225,15 +289,20 @@ with gr.Blocks(title="LTX-2 Video Distilled 🎥🔈") as demo:
225
  # Add example
226
  gr.Examples(
227
  examples=[
228
- [
229
- "astronaut.jpg",
230
- "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.",
231
- 3.0,
232
- ],
233
  [
234
  "kill_bill.jpeg",
235
  "A low, subsonic drone pulses as Uma Thurman's character, Beatrix Kiddo, holds her razor-sharp katana blade steady in the cinematic lighting. A faint electrical hum fills the silence. Suddenly, accompanied by a deep metallic groan, the polished steel begins to soften and distort, like heated metal starting to lose its structural integrity. Discordant strings swell as the blade's perfect edge slowly warps and droops, molten steel beginning to flow downward in silvery rivulets while maintaining its metallic sheen—each drip producing a wet, viscous stretching sound. The transformation starts subtly at first—a slight bend in the blade—then accelerates as the metal becomes increasingly fluid, the groaning intensifying. The camera holds steady on her face as her piercing eyes gradually narrow, not with lethal focus, but with confusion and growing alarm as she watches her weapon dissolve before her eyes. She whispers under her breath, voice flat with disbelief: 'Wait, what?' Her heartbeat rises in the mix—thump... thump-thump—as her breathing quickens slightly while she witnesses this impossible transformation. Sharp violin stabs punctuate each breath. The melting intensifies, the katana's perfect form becoming increasingly abstract, dripping like liquid mercury from her grip. Molten droplets fall to the ground with soft, bell-like pings. Unintelligible whispers fade in and out as her expression shifts from calm readiness to bewilderment and concern, her heartbeat now pounding like a war drum, as her legendary instrument of vengeance literally liquefies in her hands, leaving her defenseless and disoriented. All sound cuts to silence—then a single devastating bass drop as the final droplet falls, leaving only her unsteady breathing in the dark.",
236
  5.0,
 
 
 
 
 
 
 
 
 
 
237
  ]
238
 
239
  ],
 
8
 
9
  import spaces
10
  import gradio as gr
11
+ from gradio_client import Client, handle_file
12
  import numpy as np
13
  import random
14
+ import torch
15
  from typing import Optional
16
+ from pathlib import Path
17
  from huggingface_hub import hf_hub_download
18
+ from gradio_client import Client
19
  from ltx_pipelines.distilled import DistilledPipeline
20
  from ltx_core.tiling import TilingConfig
21
  from ltx_core.loader.primitives import LoraPathStrengthAndSDOps
 
35
 
36
  # HuggingFace Hub defaults
37
  DEFAULT_REPO_ID = "Lightricks/LTX-2"
 
38
  DEFAULT_CHECKPOINT_FILENAME = "ltx-2-19b-dev-fp8.safetensors"
39
  DEFAULT_DISTILLED_LORA_FILENAME = "ltx-2-19b-distilled-lora-384.safetensors"
40
  DEFAULT_SPATIAL_UPSAMPLER_FILENAME = "ltx-2-spatial-upscaler-x2-1.0.safetensors"
41
 
42
+ # Text encoder space URL
43
+ TEXT_ENCODER_SPACE = "linoyts/gemma-text-encoder"
44
+
45
  def get_hub_or_local_checkpoint(repo_id: Optional[str] = None, filename: Optional[str] = None):
46
  """Download from HuggingFace Hub or use local checkpoint."""
47
  if repo_id is None and filename is None:
 
72
  print(f" checkpoint_path={checkpoint_path}")
73
  print(f" distilled_lora_path={distilled_lora_path}")
74
  print(f" spatial_upsampler_path={spatial_upsampler_path}")
75
+ print(f" text_encoder_space={TEXT_ENCODER_SPACE}")
76
 
77
  # Load distilled LoRA as a regular LoRA
78
  loras = [
 
83
  )
84
  ]
85
 
86
+ # Initialize pipeline WITHOUT text encoder (gemma_root=None)
87
+ # Text encoding will be done by external space
88
  pipeline = DistilledPipeline(
89
  checkpoint_path=checkpoint_path,
90
  spatial_upsampler_path=spatial_upsampler_path,
91
+ gemma_root=None, # No text encoder in this space
92
  loras=loras,
93
  fp8transformer=True,
94
  local_files_only=False,
95
  )
96
 
97
+ # Initialize text encoder client
98
+ print(f"Connecting to text encoder space: {TEXT_ENCODER_SPACE}")
99
+ try:
100
+ text_encoder_client = Client(TEXT_ENCODER_SPACE)
101
+ print("✓ Text encoder client connected!")
102
+ except Exception as e:
103
+ print(f"⚠ Warning: Could not connect to text encoder space: {e}")
104
+ text_encoder_client = None
105
+
106
  print("=" * 80)
107
  print("Pipeline fully loaded and ready!")
108
  print("=" * 80)
 
112
  input_image,
113
  prompt: str,
114
  duration: float,
115
+ enhance_prompt: bool = True,
116
  seed: int = 42,
117
  randomize_seed: bool = True,
118
  height: int = DEFAULT_HEIGHT,
 
131
  # Create output directory if it doesn't exist
132
  output_dir = Path("outputs")
133
  output_dir.mkdir(exist_ok=True)
134
+ output_path = output_dir / f"video_{current_seed}.mp4"
135
 
136
  # Handle image input
137
  images = []
138
+ temp_image_path = None # Initialize to None
139
+
140
  if input_image is not None:
141
  # Save uploaded image temporarily
142
+ temp_image_path = output_dir / f"temp_input_{current_seed}.jpg"
143
  if hasattr(input_image, 'save'):
144
  input_image.save(temp_image_path)
145
  else:
146
  # If it's a file path already
147
+ temp_image_path = Path(input_image)
148
  # Format: (image_path, frame_idx, strength)
149
  images = [(str(temp_image_path), 0, 1.0)]
150
+
151
+ # Get embeddings from text encoder space
152
+ print(f"Encoding prompt: {prompt}")
153
+
154
+ if text_encoder_client is None:
155
+ raise RuntimeError(
156
+ f"Text encoder client not connected. Please ensure the text encoder space "
157
+ f"({TEXT_ENCODER_SPACE}) is running and accessible."
158
+ )
159
+
160
+ try:
161
+ # Prepare image for upload if it exists
162
+ image_input = None
163
+ if temp_image_path is not None:
164
+ image_input = handle_file(str(temp_image_path))
165
+
166
+ result = text_encoder_client.predict(
167
+ prompt=prompt,
168
+ enhance_prompt=enhance_prompt,
169
+ input_image=image_input,
170
+ seed=current_seed,
171
+ negative_prompt="",
172
+ api_name="/encode_prompt"
173
+ )
174
+ embedding_path = result[0] # Path to .pt file
175
+ print(f"Embeddings received from: {embedding_path}")
176
+
177
+ # Load embeddings
178
+ embeddings = torch.load(embedding_path)
179
+ video_context = embeddings['video_context']
180
+ audio_context = embeddings['audio_context']
181
+ print("✓ Embeddings loaded successfully")
182
+ except Exception as e:
183
+ raise RuntimeError(
184
+ f"Failed to get embeddings from text encoder space: {e}\n"
185
+ f"Please ensure {TEXT_ENCODER_SPACE} is running properly."
186
+ )
187
 
188
  # Run inference - progress automatically tracks tqdm from pipeline
189
  pipeline(
 
196
  frame_rate=frame_rate,
197
  images=images,
198
  tiling_config=TilingConfig.default(),
199
+ video_context=video_context,
200
+ audio_context=audio_context,
201
  )
202
 
203
  return str(output_path), current_seed
 
227
  lines=3,
228
  placeholder="Describe the motion and animation you want..."
229
  )
230
+ with gr.Row():
231
+ duration = gr.Slider(
232
+ label="Duration (seconds)",
233
+ minimum=1.0,
234
+ maximum=10.0,
235
+ value=3.0,
236
+ step=0.1
237
+ )
238
+ enhance_prompt = gr.Checkbox(
239
+ label="Enhance Prompt",
240
+ value=True
241
+ )
242
 
243
  generate_btn = gr.Button("Generate Video", variant="primary", size="lg")
244
 
 
277
  input_image,
278
  prompt,
279
  duration,
280
+ enhance_prompt,
281
  seed,
282
  randomize_seed,
283
  height,
 
289
  # Add example
290
  gr.Examples(
291
  examples=[
 
 
 
 
 
292
  [
293
  "kill_bill.jpeg",
294
  "A low, subsonic drone pulses as Uma Thurman's character, Beatrix Kiddo, holds her razor-sharp katana blade steady in the cinematic lighting. A faint electrical hum fills the silence. Suddenly, accompanied by a deep metallic groan, the polished steel begins to soften and distort, like heated metal starting to lose its structural integrity. Discordant strings swell as the blade's perfect edge slowly warps and droops, molten steel beginning to flow downward in silvery rivulets while maintaining its metallic sheen—each drip producing a wet, viscous stretching sound. The transformation starts subtly at first—a slight bend in the blade—then accelerates as the metal becomes increasingly fluid, the groaning intensifying. The camera holds steady on her face as her piercing eyes gradually narrow, not with lethal focus, but with confusion and growing alarm as she watches her weapon dissolve before her eyes. She whispers under her breath, voice flat with disbelief: 'Wait, what?' Her heartbeat rises in the mix—thump... thump-thump—as her breathing quickens slightly while she witnesses this impossible transformation. Sharp violin stabs punctuate each breath. The melting intensifies, the katana's perfect form becoming increasingly abstract, dripping like liquid mercury from her grip. Molten droplets fall to the ground with soft, bell-like pings. Unintelligible whispers fade in and out as her expression shifts from calm readiness to bewilderment and concern, her heartbeat now pounding like a war drum, as her legendary instrument of vengeance literally liquefies in her hands, leaving her defenseless and disoriented. All sound cuts to silence—then a single devastating bass drop as the final droplet falls, leaving only her unsteady breathing in the dark.",
295
  5.0,
296
+ ],
297
+ [
298
+ "wednesday.png",
299
+ "A cinematic close-up of Wednesday Addams frozen mid-dance on a dark, blue-lit ballroom floor as students move indistinctly behind her, their footsteps and muffled music reduced to a distant, underwater thrum; the audio foregrounds her steady breathing and the faint rustle of fabric as she slowly raises one arm, never breaking eye contact with the camera, then after a deliberately long silence she speaks in a flat, dry, perfectly controlled voice, “I don’t dance… I vibe code,” each word crisp and unemotional, followed by an abrupt cutoff of her voice as the background sound swells slightly, reinforcing the deadpan humor, with precise lip sync, minimal facial movement, stark gothic lighting, and cinematic realism.",
300
+ 5.0,
301
+ ],
302
+ [
303
+ "astronaut.jpg",
304
+ "An astronaut hatches from a fragile egg on the surface of the Moon, the shell cracking and peeling apart in gentle low-gravity motion. Fine lunar dust lifts and drifts outward with each movement, floating in slow arcs before settling back onto the ground. The astronaut pushes free in a deliberate, weightless motion, small fragments of the egg tumbling and spinning through the air. In the background, the deep darkness of space subtly shifts as stars glide with the camera's movement, emphasizing vast depth and scale. The camera performs a smooth, cinematic slow push-in, with natural parallax between the foreground dust, the astronaut, and the distant starfield. Ultra-realistic detail, physically accurate low-gravity motion, cinematic lighting, and a breath-taking, movie-like shot.",
305
+ 3.0,
306
  ]
307
 
308
  ],
packages/ltx-pipelines/src/ltx_pipelines/distilled.py CHANGED
@@ -64,6 +64,10 @@ class DistilledPipeline:
64
  device=device,
65
  )
66
 
 
 
 
 
67
  @torch.inference_mode()
68
  def __call__(
69
  self,
@@ -76,23 +80,37 @@ class DistilledPipeline:
76
  frame_rate: float,
77
  images: list[tuple[str, int, float]],
78
  tiling_config: TilingConfig | None = None,
 
 
79
  ) -> None:
80
  generator = torch.Generator(device=self.device).manual_seed(seed)
81
  noiser = GaussianNoiser(generator=generator)
82
  stepper = EulerDiffusionStep()
83
  dtype = torch.bfloat16
84
 
85
- text_encoder = self.model_ledger.text_encoder()
86
- context_p = encode_text(text_encoder, prompts=[prompt])[0]
87
- video_context, audio_context = context_p
 
 
88
 
89
- torch.cuda.synchronize()
90
- del text_encoder
91
- utils.cleanup_memory()
 
 
 
 
92
 
93
  # Stage 1: Initial low resolution video generation.
94
- video_encoder = self.model_ledger.video_encoder()
95
- transformer = self.model_ledger.transformer()
 
 
 
 
 
 
96
  stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device)
97
 
98
  def denoising_loop(
@@ -168,9 +186,9 @@ class DistilledPipeline:
168
  )
169
 
170
  torch.cuda.synchronize()
171
- del transformer
172
- del video_encoder
173
- utils.cleanup_memory()
174
 
175
  decoded_video = vae_decode_video(video_state, self.model_ledger.video_decoder(), tiling_config)
176
 
@@ -214,4 +232,4 @@ def main() -> None:
214
 
215
 
216
  if __name__ == "__main__":
217
- main()
 
64
  device=device,
65
  )
66
 
67
+ # Cached models to avoid reloading
68
+ self._video_encoder = None
69
+ self._transformer = None
70
+
71
  @torch.inference_mode()
72
  def __call__(
73
  self,
 
80
  frame_rate: float,
81
  images: list[tuple[str, int, float]],
82
  tiling_config: TilingConfig | None = None,
83
+ video_context: torch.Tensor | None = None,
84
+ audio_context: torch.Tensor | None = None,
85
  ) -> None:
86
  generator = torch.Generator(device=self.device).manual_seed(seed)
87
  noiser = GaussianNoiser(generator=generator)
88
  stepper = EulerDiffusionStep()
89
  dtype = torch.bfloat16
90
 
91
+ # Use pre-computed embeddings if provided, otherwise encode text
92
+ if video_context is None or audio_context is None:
93
+ text_encoder = self.model_ledger.text_encoder()
94
+ context_p = encode_text(text_encoder, prompts=[prompt])[0]
95
+ video_context, audio_context = context_p
96
 
97
+ torch.cuda.synchronize()
98
+ del text_encoder
99
+ utils.cleanup_memory()
100
+ else:
101
+ # Move pre-computed embeddings to device if needed
102
+ video_context = video_context.to(self.device)
103
+ audio_context = audio_context.to(self.device)
104
 
105
  # Stage 1: Initial low resolution video generation.
106
+ # Load models only if not already cached
107
+ if self._video_encoder is None:
108
+ self._video_encoder = self.model_ledger.video_encoder()
109
+ video_encoder = self._video_encoder
110
+
111
+ if self._transformer is None:
112
+ self._transformer = self.model_ledger.transformer()
113
+ transformer = self._transformer
114
  stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device)
115
 
116
  def denoising_loop(
 
186
  )
187
 
188
  torch.cuda.synchronize()
189
+ # del transformer
190
+ # del video_encoder
191
+ # utils.cleanup_memory()
192
 
193
  decoded_video = vae_decode_video(video_state, self.model_ledger.video_decoder(), tiling_config)
194
 
 
232
 
233
 
234
  if __name__ == "__main__":
235
+ main()
wednesday.png ADDED

Git LFS Details

  • SHA256: 27193cae97c24a31ab574a21fc3c598627c28ab60edb0c60209acdb8071cf1ea
  • Pointer size: 132 Bytes
  • Size of remote file: 1.36 MB