sayakpaul HF Staff commited on
Commit
3fc0a22
·
1 Parent(s): d91b213
__pycache__/app.cpython-310.pyc ADDED
Binary file (7.66 kB). View file
 
__pycache__/optimization.cpython-310.pyc ADDED
Binary file (2.61 kB). View file
 
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PyTorch 2.8 (temporary hack)
2
+ import os
3
+ os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces')
4
+
5
+ # Actual demo code
6
+ import spaces
7
+ import torch
8
+ from diffusers import LTXConditionPipeline
9
+ from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition
10
+ from diffusers.utils import export_to_video, load_video
11
+ import gradio as gr
12
+ import tempfile
13
+ import numpy as np
14
+ from PIL import Image
15
+ import random
16
+ from optimization import optimize_pipeline_
17
+
18
+ MODEL_ID = "Lightricks/LTX-Video-0.9.8-13B-distilled"
19
+
20
+ LANDSCAPE_WIDTH = 832
21
+ LANDSCAPE_HEIGHT = 480
22
+ MAX_SEED = np.iinfo(np.int32).max
23
+
24
+ FIXED_FPS = 24
25
+ MIN_FRAMES_MODEL = 8
26
+ MAX_FRAMES_MODEL = 96
27
+
28
+ MIN_DURATION = round(MIN_FRAMES_MODEL/FIXED_FPS,1)
29
+ MAX_DURATION = round(MAX_FRAMES_MODEL/FIXED_FPS,1)
30
+
31
+ pipe = LTXConditionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16).to("cuda")
32
+ optimize_pipeline_(
33
+ pipe,
34
+ image=Image.new('RGB', (LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT)),
35
+ prompt='prompt',
36
+ height=LANDSCAPE_HEIGHT,
37
+ width=LANDSCAPE_WIDTH,
38
+ num_frames=MAX_FRAMES_MODEL,
39
+ )
40
+
41
+ default_prompt_i2v = "make this image come alive, cinematic motion, smooth animation"
42
+ default_negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards, watermark, text, signature"
43
+
44
+
45
+ def resize_image(image: Image.Image) -> Image.Image:
46
+ if image.height > image.width:
47
+ transposed = image.transpose(Image.Transpose.ROTATE_90)
48
+ resized = resize_image_landscape(transposed)
49
+ return resized.transpose(Image.Transpose.ROTATE_270)
50
+ return resize_image_landscape(image)
51
+
52
+
53
+ def resize_image_landscape(image: Image.Image) -> Image.Image:
54
+ target_aspect = LANDSCAPE_WIDTH / LANDSCAPE_HEIGHT
55
+ width, height = image.size
56
+ in_aspect = width / height
57
+ if in_aspect > target_aspect:
58
+ new_width = round(height * target_aspect)
59
+ left = (width - new_width) // 2
60
+ image = image.crop((left, 0, left + new_width, height))
61
+ else:
62
+ new_height = round(width / target_aspect)
63
+ top = (height - new_height) // 2
64
+ image = image.crop((0, top, width, top + new_height))
65
+ return image.resize((LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT), Image.LANCZOS)
66
+
67
+ def get_duration(
68
+ input_image,
69
+ prompt,
70
+ negative_prompt,
71
+ duration_seconds,
72
+ guidance_scale,
73
+ steps,
74
+ seed,
75
+ randomize_seed,
76
+ progress,
77
+ ):
78
+ if steps > 4 and duration_seconds > 2:
79
+ return 90
80
+ elif steps > 4 or duration_seconds > 2:
81
+ return 75
82
+ else:
83
+ return 60
84
+
85
+ @spaces.GPU(duration=get_duration)
86
+ def generate_video(
87
+ input_image,
88
+ prompt,
89
+ negative_prompt=default_negative_prompt,
90
+ duration_seconds=MAX_DURATION,
91
+ guidance_scale=3.0,
92
+ steps=8,
93
+ seed=42,
94
+ randomize_seed=False,
95
+ progress=gr.Progress(track_tqdm=True),
96
+ ):
97
+ """
98
+ Generate a video from an input image using the LTX distilled model.
99
+
100
+ This function takes an input image and generates a video animation based on the provided
101
+ prompt and parameters. It uses the LTX 13B Distilled Image-to-Video model for fast generation
102
+ in 4-8 steps.
103
+
104
+ Args:
105
+ input_image (PIL.Image): The input image to animate. Will be resized to target dimensions.
106
+ prompt (str): Text prompt describing the desired animation or motion.
107
+ negative_prompt (str, optional): Negative prompt to avoid unwanted elements.
108
+ Defaults to default_negative_prompt (contains unwanted visual artifacts).
109
+ duration_seconds (float, optional): Duration of the generated video in seconds.
110
+ Defaults to 2. Clamped between MIN_FRAMES_MODEL/FIXED_FPS and MAX_FRAMES_MODEL/FIXED_FPS.
111
+ guidance_scale (float, optional): Controls adherence to the prompt. Higher values = more adherence.
112
+ Defaults to 1.0. Range: 0.0-20.0.
113
+ steps (int, optional): Number of inference steps. More steps = higher quality but slower.
114
+ Defaults to 4. Range: 1-30.
115
+ seed (int, optional): Random seed for reproducible results. Defaults to 42.
116
+ Range: 0 to MAX_SEED (2147483647).
117
+ randomize_seed (bool, optional): Whether to use a random seed instead of the provided seed.
118
+ Defaults to False.
119
+ progress (gr.Progress, optional): Gradio progress tracker. Defaults to gr.Progress(track_tqdm=True).
120
+
121
+ Returns:
122
+ tuple: A tuple containing:
123
+ - video_path (str): Path to the generated video file (.mp4)
124
+ - current_seed (int): The seed used for generation (useful when randomize_seed=True)
125
+
126
+ Raises:
127
+ gr.Error: If input_image is None (no image uploaded).
128
+
129
+ Note:
130
+ - The function automatically resizes the input image to the target dimensions
131
+ - Frame count is calculated as duration_seconds * FIXED_FPS (24)
132
+ - Output dimensions are adjusted to be multiples of MOD_VALUE (32)
133
+ - The function uses GPU acceleration via the @spaces.GPU decorator
134
+ - Generation time varies based on steps and duration (see get_duration function)
135
+ """
136
+ if input_image is None:
137
+ raise gr.Error("Please upload an input image.")
138
+
139
+ num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
140
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
141
+ resized_image = resize_image(input_image)
142
+
143
+ video = load_video(export_to_video([resized_image]))
144
+ condition1 = LTXVideoCondition(video=video, frame_index=0)
145
+ output_frames_list = pipe(
146
+ conditions=[condition1],
147
+ prompt=prompt,
148
+ negative_prompt=negative_prompt,
149
+ height=resized_image.height,
150
+ width=resized_image.width,
151
+ num_frames=num_frames,
152
+ guidance_scale=float(guidance_scale),
153
+ num_inference_steps=int(steps),
154
+ generator=torch.Generator(device="cuda").manual_seed(current_seed),
155
+ ).frames[0]
156
+
157
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
158
+ video_path = tmpfile.name
159
+
160
+ export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
161
+
162
+ return video_path, current_seed
163
+
164
+ with gr.Blocks() as demo:
165
+ gr.Markdown("# Fast few-steps LTX 0.9.8 I2V (13B)")
166
+ with gr.Row():
167
+ with gr.Column():
168
+ input_image_component = gr.Image(type="pil", label="Input Image (auto-resized to target H/W)")
169
+ prompt_input = gr.Textbox(label="Prompt", value=default_prompt_i2v)
170
+ duration_seconds_input = gr.Slider(minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=MAX_DURATION, label="Duration (seconds)", info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.")
171
+
172
+ with gr.Accordion("Advanced Settings", open=False):
173
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
174
+ seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
175
+ randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
176
+ steps_slider = gr.Slider(minimum=1, maximum=10, step=1, value=8, label="Inference Steps")
177
+ guidance_scale_input = gr.Slider(minimum=0.0, maximum=20.0, step=0.5, value=3.0, label="Guidance Scale", visible=False)
178
+
179
+ generate_button = gr.Button("Generate Video", variant="primary")
180
+ with gr.Column():
181
+ video_output = gr.Video(label="Generated Video", autoplay=True, interactive=False)
182
+
183
+ ui_inputs = [
184
+ input_image_component, prompt_input,
185
+ negative_prompt_input, duration_seconds_input,
186
+ guidance_scale_input, steps_slider, seed_input, randomize_seed_checkbox
187
+ ]
188
+ generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
189
+
190
+ gr.Examples(
191
+ examples=[
192
+ ["peng.png", "a penguin playfully dancing in the snow, Antarctica"],
193
+ ["forg.jpg", "the frog jumps around"],
194
+ ],
195
+ inputs=[input_image_component, prompt_input], outputs=[video_output, seed_input], fn=generate_video, cache_examples="lazy"
196
+ )
197
+
198
+ if __name__ == "__main__":
199
+ demo.queue().launch(mcp_server=True)
optimization.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Taken from https://huggingface.co/spaces/cbensimon/wan2-1-fast/
3
+ """
4
+
5
+ from typing import Any
6
+ from typing import Callable
7
+ from typing import ParamSpec
8
+
9
+ import spaces
10
+ import torch
11
+ from torch.utils._pytree import tree_map_only
12
+ from torchao.quantization import quantize_
13
+ from torchao.quantization import Float8DynamicActivationFloat8WeightConfig
14
+
15
+ from optimization_utils import capture_component_call
16
+ from optimization_utils import aoti_compile
17
+
18
+
19
+ P = ParamSpec('P')
20
+
21
+
22
+ TRANSFORMER_NUM_FRAMES_DIM = torch.export.Dim('num_frames', min=3, max=21)
23
+
24
+ TRANSFORMER_DYNAMIC_SHAPES = {
25
+ 'hidden_states': {2: TRANSFORMER_NUM_FRAMES_DIM},
26
+ }
27
+
28
+ INDUCTOR_CONFIGS = {
29
+ 'conv_1x1_as_mm': True,
30
+ 'epilogue_fusion': False,
31
+ 'coordinate_descent_tuning': True,
32
+ 'coordinate_descent_check_all_directions': True,
33
+ 'max_autotune': True,
34
+ 'triton.cudagraphs': True,
35
+ }
36
+
37
+
38
+ def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
39
+
40
+ @spaces.GPU(duration=1500)
41
+ def compile_transformer():
42
+
43
+ with capture_component_call(pipeline, 'transformer') as call:
44
+ pipeline(*args, **kwargs)
45
+
46
+ dynamic_shapes = tree_map_only((torch.Tensor, bool), lambda t: None, call.kwargs)
47
+ dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
48
+
49
+ quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())
50
+
51
+ hidden_states: torch.Tensor = call.kwargs['hidden_states']
52
+ hidden_states_transposed = hidden_states.transpose(-1, -2).contiguous()
53
+ if hidden_states.shape[-1] > hidden_states.shape[-2]:
54
+ hidden_states_landscape = hidden_states
55
+ hidden_states_portrait = hidden_states_transposed
56
+ else:
57
+ hidden_states_landscape = hidden_states_transposed
58
+ hidden_states_portrait = hidden_states
59
+
60
+ exported_landscape = torch.export.export(
61
+ mod=pipeline.transformer,
62
+ args=call.args,
63
+ kwargs=call.kwargs | {'hidden_states': hidden_states_landscape},
64
+ dynamic_shapes=dynamic_shapes,
65
+ )
66
+
67
+ exported_portrait = torch.export.export(
68
+ mod=pipeline.transformer,
69
+ args=call.args,
70
+ kwargs=call.kwargs | {'hidden_states': hidden_states_portrait},
71
+ dynamic_shapes=dynamic_shapes,
72
+ )
73
+
74
+ compiled_landscape = aoti_compile(exported_landscape, INDUCTOR_CONFIGS)
75
+ compiled_portrait = aoti_compile(exported_portrait, INDUCTOR_CONFIGS)
76
+ compiled_portrait.weights = compiled_landscape.weights # Avoid weights duplication when serializing back to main process
77
+
78
+ return compiled_landscape, compiled_portrait
79
+
80
+ compiled_landscape, compiled_portrait = compile_transformer()
81
+
82
+ def combined_transformer(*args, **kwargs):
83
+ hidden_states: torch.Tensor = kwargs['hidden_states']
84
+ if hidden_states.shape[-1] > hidden_states.shape[-2]:
85
+ return compiled_landscape(*args, **kwargs)
86
+ else:
87
+ return compiled_portrait(*args, **kwargs)
88
+
89
+ transformer_config = pipeline.transformer.config
90
+ transformer_dtype = pipeline.transformer.dtype
91
+ pipeline.transformer = combined_transformer
92
+ pipeline.transformer.config = transformer_config # pyright: ignore[reportAttributeAccessIssue]
93
+ pipeline.transformer.dtype = transformer_dtype # pyright: ignore[reportAttributeAccessIssue]
optimization_utils.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Taken from https://huggingface.co/spaces/cbensimon/wan2-1-fast/
3
+ """
4
+ import contextlib
5
+ from contextvars import ContextVar
6
+ from io import BytesIO
7
+ from typing import Any
8
+ from typing import cast
9
+ from unittest.mock import patch
10
+
11
+ import torch
12
+ from torch._inductor.package.package import package_aoti
13
+ from torch.export.pt2_archive._package import AOTICompiledModel
14
+ from torch.export.pt2_archive._package_weights import Weights
15
+
16
+
17
+ INDUCTOR_CONFIGS_OVERRIDES = {
18
+ 'aot_inductor.package_constants_in_so': False,
19
+ 'aot_inductor.package_constants_on_disk': True,
20
+ 'aot_inductor.package': True,
21
+ }
22
+
23
+
24
+ class ZeroGPUWeights:
25
+ def __init__(self, constants_map: dict[str, torch.Tensor], to_cuda: bool = False):
26
+ if to_cuda:
27
+ self.constants_map = {name: tensor.to('cuda') for name, tensor in constants_map.items()}
28
+ else:
29
+ self.constants_map = constants_map
30
+ def __reduce__(self):
31
+ constants_map: dict[str, torch.Tensor] = {}
32
+ for name, tensor in self.constants_map.items():
33
+ tensor_ = torch.empty_like(tensor, device='cpu').pin_memory()
34
+ constants_map[name] = tensor_.copy_(tensor).detach().share_memory_()
35
+ return ZeroGPUWeights, (constants_map, True)
36
+
37
+
38
+ class ZeroGPUCompiledModel:
39
+ def __init__(self, archive_file: torch.types.FileLike, weights: ZeroGPUWeights):
40
+ self.archive_file = archive_file
41
+ self.weights = weights
42
+ self.compiled_model: ContextVar[AOTICompiledModel | None] = ContextVar('compiled_model', default=None)
43
+ def __call__(self, *args, **kwargs):
44
+ if (compiled_model := self.compiled_model.get()) is None:
45
+ compiled_model = cast(AOTICompiledModel, torch._inductor.aoti_load_package(self.archive_file))
46
+ compiled_model.load_constants(self.weights.constants_map, check_full_update=True, user_managed=True)
47
+ self.compiled_model.set(compiled_model)
48
+ return compiled_model(*args, **kwargs)
49
+ def __reduce__(self):
50
+ return ZeroGPUCompiledModel, (self.archive_file, self.weights)
51
+
52
+
53
+ def aoti_compile(
54
+ exported_program: torch.export.ExportedProgram,
55
+ inductor_configs: dict[str, Any] | None = None,
56
+ ):
57
+ inductor_configs = (inductor_configs or {}) | INDUCTOR_CONFIGS_OVERRIDES
58
+ gm = cast(torch.fx.GraphModule, exported_program.module())
59
+ assert exported_program.example_inputs is not None
60
+ args, kwargs = exported_program.example_inputs
61
+ artifacts = torch._inductor.aot_compile(gm, args, kwargs, options=inductor_configs)
62
+ archive_file = BytesIO()
63
+ files: list[str | Weights] = [file for file in artifacts if isinstance(file, str)]
64
+ package_aoti(archive_file, files)
65
+ weights, = (artifact for artifact in artifacts if isinstance(artifact, Weights))
66
+ zerogpu_weights = ZeroGPUWeights({name: weights.get_weight(name)[0] for name in weights})
67
+ return ZeroGPUCompiledModel(archive_file, zerogpu_weights)
68
+
69
+
70
+ @contextlib.contextmanager
71
+ def capture_component_call(
72
+ pipeline: Any,
73
+ component_name: str,
74
+ component_method='forward',
75
+ ):
76
+
77
+ class CapturedCallException(Exception):
78
+ def __init__(self, *args, **kwargs):
79
+ super().__init__()
80
+ self.args = args
81
+ self.kwargs = kwargs
82
+
83
+ class CapturedCall:
84
+ def __init__(self):
85
+ self.args: tuple[Any, ...] = ()
86
+ self.kwargs: dict[str, Any] = {}
87
+
88
+ component = getattr(pipeline, component_name)
89
+ captured_call = CapturedCall()
90
+
91
+ def capture_call(*args, **kwargs):
92
+ raise CapturedCallException(*args, **kwargs)
93
+
94
+ with patch.object(component, component_method, new=capture_call):
95
+ try:
96
+ yield captured_call
97
+ except CapturedCallException as e:
98
+ captured_call.args = e.args
99
+ captured_call.kwargs = e.kwargs