Spaces:
Running
on
Zero
Running
on
Zero
up
Browse files- app.py +46 -23
- optimization.py +26 -24
- optimization_utils.py +13 -10
app.py
CHANGED
@@ -1,6 +1,9 @@
|
|
1 |
# PyTorch 2.8 (temporary hack)
|
2 |
import os
|
3 |
-
|
|
|
|
|
|
|
4 |
|
5 |
# Actual demo code
|
6 |
import spaces
|
@@ -25,14 +28,14 @@ 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(
|
35 |
-
prompt=
|
36 |
height=LANDSCAPE_HEIGHT,
|
37 |
width=LANDSCAPE_WIDTH,
|
38 |
num_frames=MAX_FRAMES_MODEL,
|
@@ -64,6 +67,7 @@ def resize_image_landscape(image: Image.Image) -> Image.Image:
|
|
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,
|
@@ -82,6 +86,7 @@ def get_duration(
|
|
82 |
else:
|
83 |
return 60
|
84 |
|
|
|
85 |
@spaces.GPU(duration=get_duration)
|
86 |
def generate_video(
|
87 |
input_image,
|
@@ -96,15 +101,15 @@ def generate_video(
|
|
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.
|
@@ -117,15 +122,15 @@ def generate_video(
|
|
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)
|
@@ -135,7 +140,7 @@ def generate_video(
|
|
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)
|
@@ -161,39 +166,57 @@ def generate_video(
|
|
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(
|
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(
|
|
|
|
|
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,
|
185 |
-
|
186 |
-
|
|
|
|
|
|
|
|
|
|
|
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],
|
|
|
|
|
|
|
196 |
)
|
197 |
|
198 |
if __name__ == "__main__":
|
199 |
-
demo.queue().launch(mcp_server=True)
|
|
|
1 |
# PyTorch 2.8 (temporary hack)
|
2 |
import os
|
3 |
+
|
4 |
+
os.system(
|
5 |
+
'pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces'
|
6 |
+
)
|
7 |
|
8 |
# Actual demo code
|
9 |
import spaces
|
|
|
28 |
MIN_FRAMES_MODEL = 8
|
29 |
MAX_FRAMES_MODEL = 96
|
30 |
|
31 |
+
MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)
|
32 |
+
MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)
|
33 |
|
34 |
pipe = LTXConditionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16).to("cuda")
|
35 |
optimize_pipeline_(
|
36 |
pipe,
|
37 |
+
image=Image.new("RGB", (LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT)),
|
38 |
+
prompt="prompt",
|
39 |
height=LANDSCAPE_HEIGHT,
|
40 |
width=LANDSCAPE_WIDTH,
|
41 |
num_frames=MAX_FRAMES_MODEL,
|
|
|
67 |
image = image.crop((0, top, width, top + new_height))
|
68 |
return image.resize((LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT), Image.LANCZOS)
|
69 |
|
70 |
+
|
71 |
def get_duration(
|
72 |
input_image,
|
73 |
prompt,
|
|
|
86 |
else:
|
87 |
return 60
|
88 |
|
89 |
+
|
90 |
@spaces.GPU(duration=get_duration)
|
91 |
def generate_video(
|
92 |
input_image,
|
|
|
101 |
):
|
102 |
"""
|
103 |
Generate a video from an input image using the LTX distilled model.
|
104 |
+
|
105 |
This function takes an input image and generates a video animation based on the provided
|
106 |
prompt and parameters. It uses the LTX 13B Distilled Image-to-Video model for fast generation
|
107 |
in 4-8 steps.
|
108 |
+
|
109 |
Args:
|
110 |
input_image (PIL.Image): The input image to animate. Will be resized to target dimensions.
|
111 |
prompt (str): Text prompt describing the desired animation or motion.
|
112 |
+
negative_prompt (str, optional): Negative prompt to avoid unwanted elements.
|
113 |
Defaults to default_negative_prompt (contains unwanted visual artifacts).
|
114 |
duration_seconds (float, optional): Duration of the generated video in seconds.
|
115 |
Defaults to 2. Clamped between MIN_FRAMES_MODEL/FIXED_FPS and MAX_FRAMES_MODEL/FIXED_FPS.
|
|
|
122 |
randomize_seed (bool, optional): Whether to use a random seed instead of the provided seed.
|
123 |
Defaults to False.
|
124 |
progress (gr.Progress, optional): Gradio progress tracker. Defaults to gr.Progress(track_tqdm=True).
|
125 |
+
|
126 |
Returns:
|
127 |
tuple: A tuple containing:
|
128 |
- video_path (str): Path to the generated video file (.mp4)
|
129 |
- current_seed (int): The seed used for generation (useful when randomize_seed=True)
|
130 |
+
|
131 |
Raises:
|
132 |
gr.Error: If input_image is None (no image uploaded).
|
133 |
+
|
134 |
Note:
|
135 |
- The function automatically resizes the input image to the target dimensions
|
136 |
- Frame count is calculated as duration_seconds * FIXED_FPS (24)
|
|
|
140 |
"""
|
141 |
if input_image is None:
|
142 |
raise gr.Error("Please upload an input image.")
|
143 |
+
|
144 |
num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
|
145 |
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
146 |
resized_image = resize_image(input_image)
|
|
|
166 |
|
167 |
return video_path, current_seed
|
168 |
|
169 |
+
|
170 |
with gr.Blocks() as demo:
|
171 |
gr.Markdown("# Fast few-steps LTX 0.9.8 I2V (13B)")
|
172 |
with gr.Row():
|
173 |
with gr.Column():
|
174 |
input_image_component = gr.Image(type="pil", label="Input Image (auto-resized to target H/W)")
|
175 |
prompt_input = gr.Textbox(label="Prompt", value=default_prompt_i2v)
|
176 |
+
duration_seconds_input = gr.Slider(
|
177 |
+
minimum=MIN_DURATION,
|
178 |
+
maximum=MAX_DURATION,
|
179 |
+
step=0.1,
|
180 |
+
value=MAX_DURATION,
|
181 |
+
label="Duration (seconds)",
|
182 |
+
info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.",
|
183 |
+
)
|
184 |
+
|
185 |
with gr.Accordion("Advanced Settings", open=False):
|
186 |
negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
|
187 |
seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
|
188 |
randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
|
189 |
+
steps_slider = gr.Slider(minimum=1, maximum=10, step=1, value=8, label="Inference Steps")
|
190 |
+
guidance_scale_input = gr.Slider(
|
191 |
+
minimum=1.0, maximum=20.0, step=0.5, value=1.0, label="Guidance Scale", visible=False
|
192 |
+
)
|
193 |
|
194 |
generate_button = gr.Button("Generate Video", variant="primary")
|
195 |
with gr.Column():
|
196 |
video_output = gr.Video(label="Generated Video", autoplay=True, interactive=False)
|
197 |
+
|
198 |
ui_inputs = [
|
199 |
+
input_image_component,
|
200 |
+
prompt_input,
|
201 |
+
negative_prompt_input,
|
202 |
+
duration_seconds_input,
|
203 |
+
guidance_scale_input,
|
204 |
+
steps_slider,
|
205 |
+
seed_input,
|
206 |
+
randomize_seed_checkbox,
|
207 |
]
|
208 |
generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
|
209 |
|
210 |
gr.Examples(
|
211 |
+
examples=[
|
212 |
["peng.png", "a penguin playfully dancing in the snow, Antarctica"],
|
213 |
["forg.jpg", "the frog jumps around"],
|
214 |
],
|
215 |
+
inputs=[input_image_component, prompt_input],
|
216 |
+
outputs=[video_output, seed_input],
|
217 |
+
fn=generate_video,
|
218 |
+
cache_examples="lazy",
|
219 |
)
|
220 |
|
221 |
if __name__ == "__main__":
|
222 |
+
demo.queue().launch(mcp_server=True)
|
optimization.py
CHANGED
@@ -16,50 +16,50 @@ from optimization_utils import capture_component_call
|
|
16 |
from optimization_utils import aoti_compile
|
17 |
|
18 |
|
19 |
-
P = ParamSpec(
|
20 |
|
21 |
|
22 |
# Sequence packing in LTX is a bit of a pain.
|
23 |
# See: https://github.com/huggingface/diffusers/blob/c052791b5fe29ce8a308bf63dda97aa205b729be/src/diffusers/pipelines/ltx/pipeline_ltx.py#L420
|
24 |
-
TRANSFORMER_NUM_FRAMES_DIM = torch.export.Dim(
|
25 |
|
26 |
TRANSFORMER_DYNAMIC_SHAPES = {
|
27 |
-
|
28 |
}
|
29 |
|
30 |
INDUCTOR_CONFIGS = {
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
}
|
38 |
TRANSFORMER_SPATIAL_PATCH_SIZE = 1
|
39 |
TRANSFORMER_TEMPORAL_PATCH_SIZE = 1
|
40 |
VAE_SPATIAL_COMPRESSION_RATIO = 32
|
41 |
VAE_TEMPORAL_COMPRESSION_RATIO = 8
|
42 |
|
|
|
43 |
def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
44 |
num_frames = kwargs.get("num_frames")
|
45 |
height = kwargs.get("height")
|
46 |
-
width =
|
47 |
latent_num_frames = (num_frames - 1) // VAE_TEMPORAL_COMPRESSION_RATIO + 1
|
48 |
latent_height = height // VAE_SPATIAL_COMPRESSION_RATIO
|
49 |
-
latent_width = width //VAE_SPATIAL_COMPRESSION_RATIO
|
50 |
|
51 |
@spaces.GPU(duration=1500)
|
52 |
def compile_transformer():
|
53 |
-
|
54 |
-
with capture_component_call(pipeline, 'transformer') as call:
|
55 |
pipeline(*args, **kwargs)
|
56 |
-
|
57 |
dynamic_shapes = tree_map_only((torch.Tensor, bool), lambda t: None, call.kwargs)
|
58 |
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
59 |
|
60 |
quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())
|
61 |
-
|
62 |
-
hidden_states: torch.Tensor = call.kwargs[
|
63 |
unpacked_hidden_states = LTXConditionPipeline._unpack_latents(
|
64 |
hidden_states,
|
65 |
latent_num_frames,
|
@@ -68,7 +68,7 @@ def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kw
|
|
68 |
TRANSFORMER_SPATIAL_PATCH_SIZE,
|
69 |
TRANSFORMER_TEMPORAL_PATCH_SIZE,
|
70 |
)
|
71 |
-
unpacked_hidden_states_transposed =
|
72 |
if unpacked_hidden_states.shape[-1] > hidden_states.shape[-2]:
|
73 |
hidden_states_landscape = unpacked_hidden_states
|
74 |
hidden_states_portrait = unpacked_hidden_states_transposed
|
@@ -86,27 +86,29 @@ def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kw
|
|
86 |
exported_landscape = torch.export.export(
|
87 |
mod=pipeline.transformer,
|
88 |
args=call.args,
|
89 |
-
kwargs=call.kwargs | {
|
90 |
dynamic_shapes=dynamic_shapes,
|
91 |
)
|
92 |
-
|
93 |
exported_portrait = torch.export.export(
|
94 |
mod=pipeline.transformer,
|
95 |
args=call.args,
|
96 |
-
kwargs=call.kwargs | {
|
97 |
dynamic_shapes=dynamic_shapes,
|
98 |
)
|
99 |
|
100 |
compiled_landscape = aoti_compile(exported_landscape, INDUCTOR_CONFIGS)
|
101 |
compiled_portrait = aoti_compile(exported_portrait, INDUCTOR_CONFIGS)
|
102 |
-
compiled_portrait.weights =
|
|
|
|
|
103 |
|
104 |
return compiled_landscape, compiled_portrait
|
105 |
|
106 |
compiled_landscape, compiled_portrait = compile_transformer()
|
107 |
|
108 |
def combined_transformer(*args, **kwargs):
|
109 |
-
hidden_states: torch.Tensor = kwargs[
|
110 |
unpacked_hidden_states = LTXConditionPipeline._unpack_latents(
|
111 |
hidden_states,
|
112 |
latent_num_frames,
|
@@ -123,5 +125,5 @@ def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kw
|
|
123 |
transformer_config = pipeline.transformer.config
|
124 |
transformer_dtype = pipeline.transformer.dtype
|
125 |
pipeline.transformer = combined_transformer
|
126 |
-
pipeline.transformer.config = transformer_config
|
127 |
-
pipeline.transformer.dtype = transformer_dtype
|
|
|
16 |
from optimization_utils import aoti_compile
|
17 |
|
18 |
|
19 |
+
P = ParamSpec("P")
|
20 |
|
21 |
|
22 |
# Sequence packing in LTX is a bit of a pain.
|
23 |
# See: https://github.com/huggingface/diffusers/blob/c052791b5fe29ce8a308bf63dda97aa205b729be/src/diffusers/pipelines/ltx/pipeline_ltx.py#L420
|
24 |
+
TRANSFORMER_NUM_FRAMES_DIM = torch.export.Dim("seq_len", min=4680, max=6000)
|
25 |
|
26 |
TRANSFORMER_DYNAMIC_SHAPES = {
|
27 |
+
"hidden_states": {1: TRANSFORMER_NUM_FRAMES_DIM},
|
28 |
}
|
29 |
|
30 |
INDUCTOR_CONFIGS = {
|
31 |
+
"conv_1x1_as_mm": True,
|
32 |
+
"epilogue_fusion": False,
|
33 |
+
"coordinate_descent_tuning": True,
|
34 |
+
"coordinate_descent_check_all_directions": True,
|
35 |
+
"max_autotune": True,
|
36 |
+
"triton.cudagraphs": True,
|
37 |
}
|
38 |
TRANSFORMER_SPATIAL_PATCH_SIZE = 1
|
39 |
TRANSFORMER_TEMPORAL_PATCH_SIZE = 1
|
40 |
VAE_SPATIAL_COMPRESSION_RATIO = 32
|
41 |
VAE_TEMPORAL_COMPRESSION_RATIO = 8
|
42 |
|
43 |
+
|
44 |
def optimize_pipeline_(pipeline: Callable[P, Any], *args: P.args, **kwargs: P.kwargs):
|
45 |
num_frames = kwargs.get("num_frames")
|
46 |
height = kwargs.get("height")
|
47 |
+
width = kwargs.get("width")
|
48 |
latent_num_frames = (num_frames - 1) // VAE_TEMPORAL_COMPRESSION_RATIO + 1
|
49 |
latent_height = height // VAE_SPATIAL_COMPRESSION_RATIO
|
50 |
+
latent_width = width // VAE_SPATIAL_COMPRESSION_RATIO
|
51 |
|
52 |
@spaces.GPU(duration=1500)
|
53 |
def compile_transformer():
|
54 |
+
with capture_component_call(pipeline, "transformer") as call:
|
|
|
55 |
pipeline(*args, **kwargs)
|
56 |
+
|
57 |
dynamic_shapes = tree_map_only((torch.Tensor, bool), lambda t: None, call.kwargs)
|
58 |
dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
|
59 |
|
60 |
quantize_(pipeline.transformer, Float8DynamicActivationFloat8WeightConfig())
|
61 |
+
|
62 |
+
hidden_states: torch.Tensor = call.kwargs["hidden_states"]
|
63 |
unpacked_hidden_states = LTXConditionPipeline._unpack_latents(
|
64 |
hidden_states,
|
65 |
latent_num_frames,
|
|
|
68 |
TRANSFORMER_SPATIAL_PATCH_SIZE,
|
69 |
TRANSFORMER_TEMPORAL_PATCH_SIZE,
|
70 |
)
|
71 |
+
unpacked_hidden_states_transposed = unpacked_hidden_states.transpose(-1, -2).contiguous()
|
72 |
if unpacked_hidden_states.shape[-1] > hidden_states.shape[-2]:
|
73 |
hidden_states_landscape = unpacked_hidden_states
|
74 |
hidden_states_portrait = unpacked_hidden_states_transposed
|
|
|
86 |
exported_landscape = torch.export.export(
|
87 |
mod=pipeline.transformer,
|
88 |
args=call.args,
|
89 |
+
kwargs=call.kwargs | {"hidden_states": hidden_states_landscape},
|
90 |
dynamic_shapes=dynamic_shapes,
|
91 |
)
|
92 |
+
|
93 |
exported_portrait = torch.export.export(
|
94 |
mod=pipeline.transformer,
|
95 |
args=call.args,
|
96 |
+
kwargs=call.kwargs | {"hidden_states": hidden_states_portrait},
|
97 |
dynamic_shapes=dynamic_shapes,
|
98 |
)
|
99 |
|
100 |
compiled_landscape = aoti_compile(exported_landscape, INDUCTOR_CONFIGS)
|
101 |
compiled_portrait = aoti_compile(exported_portrait, INDUCTOR_CONFIGS)
|
102 |
+
compiled_portrait.weights = (
|
103 |
+
compiled_landscape.weights
|
104 |
+
) # Avoid weights duplication when serializing back to main process
|
105 |
|
106 |
return compiled_landscape, compiled_portrait
|
107 |
|
108 |
compiled_landscape, compiled_portrait = compile_transformer()
|
109 |
|
110 |
def combined_transformer(*args, **kwargs):
|
111 |
+
hidden_states: torch.Tensor = kwargs["hidden_states"]
|
112 |
unpacked_hidden_states = LTXConditionPipeline._unpack_latents(
|
113 |
hidden_states,
|
114 |
latent_num_frames,
|
|
|
125 |
transformer_config = pipeline.transformer.config
|
126 |
transformer_dtype = pipeline.transformer.dtype
|
127 |
pipeline.transformer = combined_transformer
|
128 |
+
pipeline.transformer.config = transformer_config # pyright: ignore[reportAttributeAccessIssue]
|
129 |
+
pipeline.transformer.dtype = transformer_dtype # pyright: ignore[reportAttributeAccessIssue]
|
optimization_utils.py
CHANGED
@@ -1,6 +1,7 @@
|
|
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
|
@@ -15,22 +16,23 @@ from torch.export.pt2_archive._package_weights import Weights
|
|
15 |
|
16 |
|
17 |
INDUCTOR_CONFIGS_OVERRIDES = {
|
18 |
-
|
19 |
-
|
20 |
-
|
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(
|
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=
|
34 |
constants_map[name] = tensor_.copy_(tensor).detach().share_memory_()
|
35 |
return ZeroGPUWeights, (constants_map, True)
|
36 |
|
@@ -39,13 +41,15 @@ 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(
|
|
|
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 |
|
@@ -62,7 +66,7 @@ def aoti_compile(
|
|
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 |
|
@@ -71,9 +75,8 @@ def aoti_compile(
|
|
71 |
def capture_component_call(
|
72 |
pipeline: Any,
|
73 |
component_name: str,
|
74 |
-
component_method=
|
75 |
):
|
76 |
-
|
77 |
class CapturedCallException(Exception):
|
78 |
def __init__(self, *args, **kwargs):
|
79 |
super().__init__()
|
@@ -96,4 +99,4 @@ def capture_component_call(
|
|
96 |
yield captured_call
|
97 |
except CapturedCallException as e:
|
98 |
captured_call.args = e.args
|
99 |
-
captured_call.kwargs = e.kwargs
|
|
|
1 |
"""
|
2 |
Taken from https://huggingface.co/spaces/cbensimon/wan2-1-fast/
|
3 |
"""
|
4 |
+
|
5 |
import contextlib
|
6 |
from contextvars import ContextVar
|
7 |
from io import BytesIO
|
|
|
16 |
|
17 |
|
18 |
INDUCTOR_CONFIGS_OVERRIDES = {
|
19 |
+
"aot_inductor.package_constants_in_so": False,
|
20 |
+
"aot_inductor.package_constants_on_disk": True,
|
21 |
+
"aot_inductor.package": True,
|
22 |
}
|
23 |
|
24 |
|
25 |
class ZeroGPUWeights:
|
26 |
def __init__(self, constants_map: dict[str, torch.Tensor], to_cuda: bool = False):
|
27 |
if to_cuda:
|
28 |
+
self.constants_map = {name: tensor.to("cuda") for name, tensor in constants_map.items()}
|
29 |
else:
|
30 |
self.constants_map = constants_map
|
31 |
+
|
32 |
def __reduce__(self):
|
33 |
constants_map: dict[str, torch.Tensor] = {}
|
34 |
for name, tensor in self.constants_map.items():
|
35 |
+
tensor_ = torch.empty_like(tensor, device="cpu").pin_memory()
|
36 |
constants_map[name] = tensor_.copy_(tensor).detach().share_memory_()
|
37 |
return ZeroGPUWeights, (constants_map, True)
|
38 |
|
|
|
41 |
def __init__(self, archive_file: torch.types.FileLike, weights: ZeroGPUWeights):
|
42 |
self.archive_file = archive_file
|
43 |
self.weights = weights
|
44 |
+
self.compiled_model: ContextVar[AOTICompiledModel | None] = ContextVar("compiled_model", default=None)
|
45 |
+
|
46 |
def __call__(self, *args, **kwargs):
|
47 |
if (compiled_model := self.compiled_model.get()) is None:
|
48 |
compiled_model = cast(AOTICompiledModel, torch._inductor.aoti_load_package(self.archive_file))
|
49 |
compiled_model.load_constants(self.weights.constants_map, check_full_update=True, user_managed=True)
|
50 |
self.compiled_model.set(compiled_model)
|
51 |
return compiled_model(*args, **kwargs)
|
52 |
+
|
53 |
def __reduce__(self):
|
54 |
return ZeroGPUCompiledModel, (self.archive_file, self.weights)
|
55 |
|
|
|
66 |
archive_file = BytesIO()
|
67 |
files: list[str | Weights] = [file for file in artifacts if isinstance(file, str)]
|
68 |
package_aoti(archive_file, files)
|
69 |
+
(weights,) = (artifact for artifact in artifacts if isinstance(artifact, Weights))
|
70 |
zerogpu_weights = ZeroGPUWeights({name: weights.get_weight(name)[0] for name in weights})
|
71 |
return ZeroGPUCompiledModel(archive_file, zerogpu_weights)
|
72 |
|
|
|
75 |
def capture_component_call(
|
76 |
pipeline: Any,
|
77 |
component_name: str,
|
78 |
+
component_method="forward",
|
79 |
):
|
|
|
80 |
class CapturedCallException(Exception):
|
81 |
def __init__(self, *args, **kwargs):
|
82 |
super().__init__()
|
|
|
99 |
yield captured_call
|
100 |
except CapturedCallException as e:
|
101 |
captured_call.args = e.args
|
102 |
+
captured_call.kwargs = e.kwargs
|