Spaces:
Running
on
A100
Running
on
A100
Commit
·
5cd8eab
1
Parent(s):
d67e4c8
zerogpu
Browse files- app.py +20 -34
- demo_zerogpu.py +233 -0
- docs_for_ai_coding_bots/spaces/zero-gpu.md +103 -0
- requirements.txt +1 -0
app.py
CHANGED
@@ -21,6 +21,7 @@ import torchvision.transforms as transforms
|
|
21 |
from loguru import logger
|
22 |
from huggingface_hub import hf_hub_download
|
23 |
import tempfile
|
|
|
24 |
|
25 |
from hymm_sp.sample_inference import HunyuanVideoSampler
|
26 |
from hymm_sp.data_kits.data_tools import save_videos_grid
|
@@ -63,7 +64,7 @@ def create_args():
|
|
63 |
args.use_linear_quadratic_schedule = False
|
64 |
args.linear_schedule_end = 0.25
|
65 |
args.use_deepcache = False
|
66 |
-
args.cpu_offload =
|
67 |
args.use_sage = True
|
68 |
args.save_path = './results/'
|
69 |
args.save_path_suffix = ''
|
@@ -117,8 +118,6 @@ def create_args():
|
|
117 |
|
118 |
return args
|
119 |
|
120 |
-
logger.info("Initializing Hunyuan-GameCraft model...")
|
121 |
-
|
122 |
# Define all required model files
|
123 |
required_files = [
|
124 |
"gamecraft_models/mp_rank_00_model_states_distill.pt",
|
@@ -182,11 +181,13 @@ for file_path in text_encoder_files:
|
|
182 |
# Continue anyway as some files might be optional
|
183 |
|
184 |
logger.info("All required model files are ready")
|
|
|
185 |
|
186 |
args = create_args()
|
187 |
logger.info(f"Created args, val_disable_autocast: {hasattr(args, 'val_disable_autocast')} = {getattr(args, 'val_disable_autocast', 'NOT SET')}")
|
188 |
-
|
189 |
-
|
|
|
190 |
logger.info(f"Loading model to device: {model_device}")
|
191 |
hunyuan_video_sampler = HunyuanVideoSampler.from_pretrained(
|
192 |
args.ckpt,
|
@@ -197,28 +198,10 @@ logger.info(f"After from_pretrained, sampler.args has val_disable_autocast: {has
|
|
197 |
args = hunyuan_video_sampler.args
|
198 |
logger.info(f"After reassigning args, val_disable_autocast: {hasattr(args, 'val_disable_autocast')} = {getattr(args, 'val_disable_autocast', 'NOT SET')}")
|
199 |
|
200 |
-
|
201 |
-
|
202 |
-
onload_device = torch.device("cuda")
|
203 |
-
apply_group_offloading(
|
204 |
-
hunyuan_video_sampler.pipeline.transformer,
|
205 |
-
onload_device=onload_device,
|
206 |
-
offload_type="block_level",
|
207 |
-
num_blocks_per_group=1
|
208 |
-
)
|
209 |
-
logger.info("Enabled CPU offloading for transformer blocks")
|
210 |
-
else:
|
211 |
-
# Ensure all model components are on GPU when not using CPU offload
|
212 |
-
hunyuan_video_sampler.pipeline.transformer.to('cuda')
|
213 |
-
hunyuan_video_sampler.vae.to('cuda')
|
214 |
-
if hunyuan_video_sampler.text_encoder:
|
215 |
-
hunyuan_video_sampler.text_encoder.model.to('cuda')
|
216 |
-
if hunyuan_video_sampler.text_encoder_2:
|
217 |
-
hunyuan_video_sampler.text_encoder_2.model.to('cuda')
|
218 |
-
logger.info("Model components moved to GPU")
|
219 |
-
|
220 |
-
logger.info("Model loaded successfully!")
|
221 |
|
|
|
222 |
def generate_video(
|
223 |
input_image,
|
224 |
prompt,
|
@@ -236,6 +219,16 @@ def generate_video(
|
|
236 |
if input_image is None:
|
237 |
return None, "Please upload an image first!"
|
238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
239 |
action_list = action_sequence.lower().replace(" ", "").split(",") if action_sequence else ["w"]
|
240 |
speed_list = [float(s.strip()) for s in action_speeds.split(",")] if action_speeds else [0.2]
|
241 |
|
@@ -274,10 +267,6 @@ def generate_video(
|
|
274 |
progress(0.2, desc="Encoding image...")
|
275 |
|
276 |
with torch.autocast(device_type="cuda", dtype=torch.float16, enabled=True):
|
277 |
-
if args.cpu_offload:
|
278 |
-
hunyuan_video_sampler.vae.quant_conv.to('cuda')
|
279 |
-
hunyuan_video_sampler.vae.encoder.to('cuda')
|
280 |
-
|
281 |
hunyuan_video_sampler.pipeline.vae.enable_tiling()
|
282 |
|
283 |
raw_last_latents = hunyuan_video_sampler.vae.encode(
|
@@ -287,9 +276,6 @@ def generate_video(
|
|
287 |
raw_ref_latents = raw_last_latents.clone()
|
288 |
|
289 |
hunyuan_video_sampler.pipeline.vae.disable_tiling()
|
290 |
-
if args.cpu_offload:
|
291 |
-
hunyuan_video_sampler.vae.quant_conv.to('cpu')
|
292 |
-
hunyuan_video_sampler.vae.encoder.to('cpu')
|
293 |
|
294 |
ref_images = [raw_ref_image]
|
295 |
last_latents = raw_last_latents
|
@@ -329,7 +315,7 @@ def generate_video(
|
|
329 |
use_linear_quadratic_schedule=args.use_linear_quadratic_schedule,
|
330 |
linear_schedule_end=args.linear_schedule_end,
|
331 |
use_deepcache=args.use_deepcache,
|
332 |
-
cpu_offload=
|
333 |
ref_images=ref_images,
|
334 |
output_dir=None,
|
335 |
return_latents=True,
|
|
|
21 |
from loguru import logger
|
22 |
from huggingface_hub import hf_hub_download
|
23 |
import tempfile
|
24 |
+
import spaces
|
25 |
|
26 |
from hymm_sp.sample_inference import HunyuanVideoSampler
|
27 |
from hymm_sp.data_kits.data_tools import save_videos_grid
|
|
|
64 |
args.use_linear_quadratic_schedule = False
|
65 |
args.linear_schedule_end = 0.25
|
66 |
args.use_deepcache = False
|
67 |
+
args.cpu_offload = False # Always False for ZeroGPU compatibility
|
68 |
args.use_sage = True
|
69 |
args.save_path = './results/'
|
70 |
args.save_path_suffix = ''
|
|
|
118 |
|
119 |
return args
|
120 |
|
|
|
|
|
121 |
# Define all required model files
|
122 |
required_files = [
|
123 |
"gamecraft_models/mp_rank_00_model_states_distill.pt",
|
|
|
181 |
# Continue anyway as some files might be optional
|
182 |
|
183 |
logger.info("All required model files are ready")
|
184 |
+
logger.info("Initializing Hunyuan-GameCraft model...")
|
185 |
|
186 |
args = create_args()
|
187 |
logger.info(f"Created args, val_disable_autocast: {hasattr(args, 'val_disable_autocast')} = {getattr(args, 'val_disable_autocast', 'NOT SET')}")
|
188 |
+
|
189 |
+
# For ZeroGPU, always load model to CPU initially (it will be moved to GPU during inference)
|
190 |
+
model_device = torch.device("cpu")
|
191 |
logger.info(f"Loading model to device: {model_device}")
|
192 |
hunyuan_video_sampler = HunyuanVideoSampler.from_pretrained(
|
193 |
args.ckpt,
|
|
|
198 |
args = hunyuan_video_sampler.args
|
199 |
logger.info(f"After reassigning args, val_disable_autocast: {hasattr(args, 'val_disable_autocast')} = {getattr(args, 'val_disable_autocast', 'NOT SET')}")
|
200 |
|
201 |
+
# Don't apply CPU offloading for ZeroGPU - the model stays on CPU until needed
|
202 |
+
logger.info("Model loaded successfully on CPU, will be moved to GPU during inference")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
|
204 |
+
@spaces.GPU(duration=120)
|
205 |
def generate_video(
|
206 |
input_image,
|
207 |
prompt,
|
|
|
219 |
if input_image is None:
|
220 |
return None, "Please upload an image first!"
|
221 |
|
222 |
+
# Move model components to GPU for ZeroGPU inference
|
223 |
+
logger.info("Moving model components to GPU...")
|
224 |
+
hunyuan_video_sampler.pipeline.transformer.to('cuda')
|
225 |
+
hunyuan_video_sampler.vae.to('cuda')
|
226 |
+
if hunyuan_video_sampler.text_encoder:
|
227 |
+
hunyuan_video_sampler.text_encoder.model.to('cuda')
|
228 |
+
if hunyuan_video_sampler.text_encoder_2:
|
229 |
+
hunyuan_video_sampler.text_encoder_2.model.to('cuda')
|
230 |
+
logger.info("Model components moved to GPU")
|
231 |
+
|
232 |
action_list = action_sequence.lower().replace(" ", "").split(",") if action_sequence else ["w"]
|
233 |
speed_list = [float(s.strip()) for s in action_speeds.split(",")] if action_speeds else [0.2]
|
234 |
|
|
|
267 |
progress(0.2, desc="Encoding image...")
|
268 |
|
269 |
with torch.autocast(device_type="cuda", dtype=torch.float16, enabled=True):
|
|
|
|
|
|
|
|
|
270 |
hunyuan_video_sampler.pipeline.vae.enable_tiling()
|
271 |
|
272 |
raw_last_latents = hunyuan_video_sampler.vae.encode(
|
|
|
276 |
raw_ref_latents = raw_last_latents.clone()
|
277 |
|
278 |
hunyuan_video_sampler.pipeline.vae.disable_tiling()
|
|
|
|
|
|
|
279 |
|
280 |
ref_images = [raw_ref_image]
|
281 |
last_latents = raw_last_latents
|
|
|
315 |
use_linear_quadratic_schedule=args.use_linear_quadratic_schedule,
|
316 |
linear_schedule_end=args.linear_schedule_end,
|
317 |
use_deepcache=args.use_deepcache,
|
318 |
+
cpu_offload=False, # Always False for ZeroGPU
|
319 |
ref_images=ref_images,
|
320 |
output_dir=None,
|
321 |
return_latents=True,
|
demo_zerogpu.py
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
|
9 |
+
from diffusers.models.transformers.transformer_wan import WanTransformer3DModel
|
10 |
+
from diffusers.utils.export_utils import export_to_video
|
11 |
+
import gradio as gr
|
12 |
+
import tempfile
|
13 |
+
import numpy as np
|
14 |
+
from PIL import Image
|
15 |
+
import random
|
16 |
+
import gc
|
17 |
+
from optimization import optimize_pipeline_
|
18 |
+
|
19 |
+
|
20 |
+
MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
|
21 |
+
|
22 |
+
LANDSCAPE_WIDTH = 832
|
23 |
+
LANDSCAPE_HEIGHT = 480
|
24 |
+
MAX_SEED = np.iinfo(np.int32).max
|
25 |
+
|
26 |
+
FIXED_FPS = 16
|
27 |
+
MIN_FRAMES_MODEL = 8
|
28 |
+
MAX_FRAMES_MODEL = 81
|
29 |
+
|
30 |
+
MIN_DURATION = round(MIN_FRAMES_MODEL/FIXED_FPS,1)
|
31 |
+
MAX_DURATION = round(MAX_FRAMES_MODEL/FIXED_FPS,1)
|
32 |
+
|
33 |
+
|
34 |
+
pipe = WanImageToVideoPipeline.from_pretrained(MODEL_ID,
|
35 |
+
transformer=WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',
|
36 |
+
subfolder='transformer',
|
37 |
+
torch_dtype=torch.bfloat16,
|
38 |
+
device_map='cuda',
|
39 |
+
),
|
40 |
+
transformer_2=WanTransformer3DModel.from_pretrained('cbensimon/Wan2.2-I2V-A14B-bf16-Diffusers',
|
41 |
+
subfolder='transformer_2',
|
42 |
+
torch_dtype=torch.bfloat16,
|
43 |
+
device_map='cuda',
|
44 |
+
),
|
45 |
+
torch_dtype=torch.bfloat16,
|
46 |
+
).to('cuda')
|
47 |
+
|
48 |
+
for i in range(3):
|
49 |
+
gc.collect()
|
50 |
+
torch.cuda.synchronize()
|
51 |
+
torch.cuda.empty_cache()
|
52 |
+
|
53 |
+
optimize_pipeline_(pipe,
|
54 |
+
image=Image.new('RGB', (LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT)),
|
55 |
+
prompt='prompt',
|
56 |
+
height=LANDSCAPE_HEIGHT,
|
57 |
+
width=LANDSCAPE_WIDTH,
|
58 |
+
num_frames=MAX_FRAMES_MODEL,
|
59 |
+
)
|
60 |
+
|
61 |
+
|
62 |
+
default_prompt_i2v = "make this image come alive, cinematic motion, smooth animation"
|
63 |
+
default_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
|
64 |
+
|
65 |
+
|
66 |
+
def resize_image(image: Image.Image) -> Image.Image:
|
67 |
+
if image.height > image.width:
|
68 |
+
transposed = image.transpose(Image.Transpose.ROTATE_90)
|
69 |
+
resized = resize_image_landscape(transposed)
|
70 |
+
return resized.transpose(Image.Transpose.ROTATE_270)
|
71 |
+
return resize_image_landscape(image)
|
72 |
+
|
73 |
+
|
74 |
+
def resize_image_landscape(image: Image.Image) -> Image.Image:
|
75 |
+
target_aspect = LANDSCAPE_WIDTH / LANDSCAPE_HEIGHT
|
76 |
+
width, height = image.size
|
77 |
+
in_aspect = width / height
|
78 |
+
if in_aspect > target_aspect:
|
79 |
+
new_width = round(height * target_aspect)
|
80 |
+
left = (width - new_width) // 2
|
81 |
+
image = image.crop((left, 0, left + new_width, height))
|
82 |
+
else:
|
83 |
+
new_height = round(width / target_aspect)
|
84 |
+
top = (height - new_height) // 2
|
85 |
+
image = image.crop((0, top, width, top + new_height))
|
86 |
+
return image.resize((LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT), Image.LANCZOS)
|
87 |
+
|
88 |
+
def get_duration(
|
89 |
+
input_image,
|
90 |
+
prompt,
|
91 |
+
steps,
|
92 |
+
negative_prompt,
|
93 |
+
duration_seconds,
|
94 |
+
guidance_scale,
|
95 |
+
guidance_scale_2,
|
96 |
+
seed,
|
97 |
+
randomize_seed,
|
98 |
+
progress,
|
99 |
+
):
|
100 |
+
return int(steps) * 15
|
101 |
+
|
102 |
+
@spaces.GPU(duration=get_duration)
|
103 |
+
def generate_video(
|
104 |
+
input_image,
|
105 |
+
prompt,
|
106 |
+
steps = 4,
|
107 |
+
negative_prompt=default_negative_prompt,
|
108 |
+
duration_seconds = MAX_DURATION,
|
109 |
+
guidance_scale = 1,
|
110 |
+
guidance_scale_2 = 1,
|
111 |
+
seed = 42,
|
112 |
+
randomize_seed = False,
|
113 |
+
progress=gr.Progress(track_tqdm=True),
|
114 |
+
):
|
115 |
+
"""
|
116 |
+
Generate a video from an input image using the Wan 2.2 14B I2V model with Lightning LoRA.
|
117 |
+
|
118 |
+
This function takes an input image and generates a video animation based on the provided
|
119 |
+
prompt and parameters. It uses an FP8 qunatized Wan 2.2 14B Image-to-Video model in with Lightning LoRA
|
120 |
+
for fast generation in 4-8 steps.
|
121 |
+
|
122 |
+
Args:
|
123 |
+
input_image (PIL.Image): The input image to animate. Will be resized to target dimensions.
|
124 |
+
prompt (str): Text prompt describing the desired animation or motion.
|
125 |
+
steps (int, optional): Number of inference steps. More steps = higher quality but slower.
|
126 |
+
Defaults to 4. Range: 1-30.
|
127 |
+
negative_prompt (str, optional): Negative prompt to avoid unwanted elements.
|
128 |
+
Defaults to default_negative_prompt (contains unwanted visual artifacts).
|
129 |
+
duration_seconds (float, optional): Duration of the generated video in seconds.
|
130 |
+
Defaults to 2. Clamped between MIN_FRAMES_MODEL/FIXED_FPS and MAX_FRAMES_MODEL/FIXED_FPS.
|
131 |
+
guidance_scale (float, optional): Controls adherence to the prompt. Higher values = more adherence.
|
132 |
+
Defaults to 1.0. Range: 0.0-20.0.
|
133 |
+
guidance_scale_2 (float, optional): Controls adherence to the prompt. Higher values = more adherence.
|
134 |
+
Defaults to 1.0. Range: 0.0-20.0.
|
135 |
+
seed (int, optional): Random seed for reproducible results. Defaults to 42.
|
136 |
+
Range: 0 to MAX_SEED (2147483647).
|
137 |
+
randomize_seed (bool, optional): Whether to use a random seed instead of the provided seed.
|
138 |
+
Defaults to False.
|
139 |
+
progress (gr.Progress, optional): Gradio progress tracker. Defaults to gr.Progress(track_tqdm=True).
|
140 |
+
|
141 |
+
Returns:
|
142 |
+
tuple: A tuple containing:
|
143 |
+
- video_path (str): Path to the generated video file (.mp4)
|
144 |
+
- current_seed (int): The seed used for generation (useful when randomize_seed=True)
|
145 |
+
|
146 |
+
Raises:
|
147 |
+
gr.Error: If input_image is None (no image uploaded).
|
148 |
+
|
149 |
+
Note:
|
150 |
+
- The function automatically resizes the input image to the target dimensions
|
151 |
+
- Frame count is calculated as duration_seconds * FIXED_FPS (24)
|
152 |
+
- Output dimensions are adjusted to be multiples of MOD_VALUE (32)
|
153 |
+
- The function uses GPU acceleration via the @spaces.GPU decorator
|
154 |
+
- Generation time varies based on steps and duration (see get_duration function)
|
155 |
+
"""
|
156 |
+
if input_image is None:
|
157 |
+
raise gr.Error("Please upload an input image.")
|
158 |
+
|
159 |
+
num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
|
160 |
+
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
161 |
+
resized_image = resize_image(input_image)
|
162 |
+
|
163 |
+
output_frames_list = pipe(
|
164 |
+
image=resized_image,
|
165 |
+
prompt=prompt,
|
166 |
+
negative_prompt=negative_prompt,
|
167 |
+
height=resized_image.height,
|
168 |
+
width=resized_image.width,
|
169 |
+
num_frames=num_frames,
|
170 |
+
guidance_scale=float(guidance_scale),
|
171 |
+
guidance_scale_2=float(guidance_scale_2),
|
172 |
+
num_inference_steps=int(steps),
|
173 |
+
generator=torch.Generator(device="cuda").manual_seed(current_seed),
|
174 |
+
).frames[0]
|
175 |
+
|
176 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
|
177 |
+
video_path = tmpfile.name
|
178 |
+
|
179 |
+
export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
|
180 |
+
|
181 |
+
return video_path, current_seed
|
182 |
+
|
183 |
+
with gr.Blocks() as demo:
|
184 |
+
gr.Markdown("# Fast 4 steps Wan 2.2 I2V (14B) with Lightning LoRA")
|
185 |
+
gr.Markdown("run Wan 2.2 in just 4-8 steps, with [Lightning LoRA](https://huggingface.co/Kijai/WanVideo_comfy/tree/main/Wan22-Lightning), fp8 quantization & AoT compilation - compatible with 🧨 diffusers and ZeroGPU⚡️")
|
186 |
+
with gr.Row():
|
187 |
+
with gr.Column():
|
188 |
+
input_image_component = gr.Image(type="pil", label="Input Image (auto-resized to target H/W)")
|
189 |
+
prompt_input = gr.Textbox(label="Prompt", value=default_prompt_i2v)
|
190 |
+
duration_seconds_input = gr.Slider(minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=3.5, label="Duration (seconds)", info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps.")
|
191 |
+
|
192 |
+
with gr.Accordion("Advanced Settings", open=False):
|
193 |
+
negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
|
194 |
+
seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
|
195 |
+
randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
|
196 |
+
steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=6, label="Inference Steps")
|
197 |
+
guidance_scale_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale - high noise stage")
|
198 |
+
guidance_scale_2_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale 2 - low noise stage")
|
199 |
+
|
200 |
+
generate_button = gr.Button("Generate Video", variant="primary")
|
201 |
+
with gr.Column():
|
202 |
+
video_output = gr.Video(label="Generated Video", autoplay=True, interactive=False)
|
203 |
+
|
204 |
+
ui_inputs = [
|
205 |
+
input_image_component, prompt_input, steps_slider,
|
206 |
+
negative_prompt_input, duration_seconds_input,
|
207 |
+
guidance_scale_input, guidance_scale_2_input, seed_input, randomize_seed_checkbox
|
208 |
+
]
|
209 |
+
generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
|
210 |
+
|
211 |
+
gr.Examples(
|
212 |
+
examples=[
|
213 |
+
[
|
214 |
+
"wan_i2v_input.JPG",
|
215 |
+
"POV selfie video, white cat with sunglasses standing on surfboard, relaxed smile, tropical beach behind (clear water, green hills, blue sky with clouds). Surfboard tips, cat falls into ocean, camera plunges underwater with bubbles and sunlight beams. Brief underwater view of cat’s face, then cat resurfaces, still filming selfie, playful summer vacation mood.",
|
216 |
+
4,
|
217 |
+
],
|
218 |
+
[
|
219 |
+
"wan22_input_2.jpg",
|
220 |
+
"A sleek lunar vehicle glides into view from left to right, kicking up moon dust as astronauts in white spacesuits hop aboard with characteristic lunar bouncing movements. In the distant background, a VTOL craft descends straight down and lands silently on the surface. Throughout the entire scene, ethereal aurora borealis ribbons dance across the star-filled sky, casting shimmering curtains of green, blue, and purple light that bathe the lunar landscape in an otherworldly, magical glow.",
|
221 |
+
4,
|
222 |
+
],
|
223 |
+
[
|
224 |
+
"kill_bill.jpeg",
|
225 |
+
"Uma Thurman's character, Beatrix Kiddo, holds her razor-sharp katana blade steady in the cinematic lighting. Suddenly, the polished steel begins to soften and distort, like heated metal starting to lose its structural integrity. The blade's perfect edge slowly warps and droops, molten steel beginning to flow downward in silvery rivulets while maintaining its metallic sheen. The transformation starts subtly at first - a slight bend in the blade - then accelerates as the metal becomes increasingly fluid. 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. Her breathing quickens slightly as she witnesses this impossible transformation. 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 metallic impacts. Her expression shifts from calm readiness to bewilderment and concern as her legendary instrument of vengeance literally liquefies in her hands, leaving her defenseless and disoriented.",
|
226 |
+
6,
|
227 |
+
],
|
228 |
+
],
|
229 |
+
inputs=[input_image_component, prompt_input, steps_slider], outputs=[video_output, seed_input], fn=generate_video, cache_examples="lazy"
|
230 |
+
)
|
231 |
+
|
232 |
+
if __name__ == "__main__":
|
233 |
+
demo.queue().launch(mcp_server=True)
|
docs_for_ai_coding_bots/spaces/zero-gpu.md
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[](#spaces-zerogpu-dynamic-gpu-allocation-for-spaces)Spaces ZeroGPU: Dynamic GPU Allocation for Spaces
|
2 |
+
======================================================================================================
|
3 |
+
|
4 |
+

|
5 |
+
|
6 |
+
ZeroGPU is a shared infrastructure that optimizes GPU usage for AI models and demos on Hugging Face Spaces. It dynamically allocates and releases NVIDIA H200 GPUs as needed, offering:
|
7 |
+
|
8 |
+
1. **Free GPU Access**: Enables cost-effective GPU usage for Spaces.
|
9 |
+
2. **Multi-GPU Support**: Allows Spaces to leverage multiple GPUs concurrently on a single application.
|
10 |
+
|
11 |
+
Unlike traditional single-GPU allocations, ZeroGPU’s efficient system lowers barriers for developers, researchers, and organizations to deploy AI models by maximizing resource utilization and power efficiency.
|
12 |
+
|
13 |
+
[](#using-and-hosting-zerogpu-spaces)Using and hosting ZeroGPU Spaces
|
14 |
+
---------------------------------------------------------------------
|
15 |
+
|
16 |
+
* **Using existing ZeroGPU Spaces**
|
17 |
+
* ZeroGPU Spaces are available to use for free to all users. (Visit [the curated list](https://huggingface.co/spaces/enzostvs/zero-gpu-spaces)).
|
18 |
+
* [PRO users](https://huggingface.co/subscribe/pro) get x5 more daily usage quota and highest priority in GPU queues when using any ZeroGPU Spaces.
|
19 |
+
* **Hosting your own ZeroGPU Spaces**
|
20 |
+
* Personal accounts: [Subscribe to PRO](https://huggingface.co/settings/billing/subscription) to access ZeroGPU in the hardware options when creating a new Gradio SDK Space.
|
21 |
+
* Organizations: [Subscribe to the Enterprise Hub](https://huggingface.co/enterprise) to enable ZeroGPU Spaces for all organization members.
|
22 |
+
|
23 |
+
[](#technical-specifications)Technical Specifications
|
24 |
+
-----------------------------------------------------
|
25 |
+
|
26 |
+
* **GPU Type**: Nvidia H200 slice
|
27 |
+
* **Available VRAM**: 70GB per workload
|
28 |
+
|
29 |
+
[](#compatibility)Compatibility
|
30 |
+
-------------------------------
|
31 |
+
|
32 |
+
ZeroGPU Spaces are designed to be compatible with most PyTorch-based GPU Spaces. While compatibility is enhanced for high-level Hugging Face libraries like `transformers` and `diffusers`, users should be aware that:
|
33 |
+
|
34 |
+
* Currently, ZeroGPU Spaces are exclusively compatible with the **Gradio SDK**.
|
35 |
+
* ZeroGPU Spaces may have limited compatibility compared to standard GPU Spaces.
|
36 |
+
* Unexpected issues may arise in some scenarios.
|
37 |
+
|
38 |
+
### [](#supported-versions)Supported Versions
|
39 |
+
|
40 |
+
* Gradio: 4+
|
41 |
+
* PyTorch: 2.1.2, 2.2.2, 2.4.0, 2.5.1 (Note: 2.3.x is not supported due to a [PyTorch bug](https://github.com/pytorch/pytorch/issues/122085))
|
42 |
+
* Python: 3.10.13
|
43 |
+
|
44 |
+
[](#getting-started-with-zerogpu)Getting started with ZeroGPU
|
45 |
+
-------------------------------------------------------------
|
46 |
+
|
47 |
+
To utilize ZeroGPU in your Space, follow these steps:
|
48 |
+
|
49 |
+
1. Make sure the ZeroGPU hardware is selected in your Space settings.
|
50 |
+
2. Import the `spaces` module.
|
51 |
+
3. Decorate GPU-dependent functions with `@spaces.GPU`.
|
52 |
+
|
53 |
+
This decoration process allows the Space to request a GPU when the function is called and release it upon completion.
|
54 |
+
|
55 |
+
### [](#example-usage)Example Usage
|
56 |
+
|
57 |
+
Copied
|
58 |
+
|
59 |
+
import spaces
|
60 |
+
from diffusers import DiffusionPipeline
|
61 |
+
|
62 |
+
pipe = DiffusionPipeline.from\_pretrained(...)
|
63 |
+
pipe.to('cuda')
|
64 |
+
|
65 |
+
@spaces.GPU
|
66 |
+
def generate(prompt):
|
67 |
+
return pipe(prompt).images
|
68 |
+
|
69 |
+
gr.Interface(
|
70 |
+
fn=generate,
|
71 |
+
inputs=gr.Text(),
|
72 |
+
outputs=gr.Gallery(),
|
73 |
+
).launch()
|
74 |
+
|
75 |
+
Note: The `@spaces.GPU` decorator is designed to be effect-free in non-ZeroGPU environments, ensuring compatibility across different setups.
|
76 |
+
|
77 |
+
[](#duration-management)Duration Management
|
78 |
+
-------------------------------------------
|
79 |
+
|
80 |
+
For functions expected to exceed the default 60-second of GPU runtime, you can specify a custom duration:
|
81 |
+
|
82 |
+
Copied
|
83 |
+
|
84 |
+
@spaces.GPU(duration=120)
|
85 |
+
def generate(prompt):
|
86 |
+
return pipe(prompt).images
|
87 |
+
|
88 |
+
This sets the maximum function runtime to 120 seconds. Specifying shorter durations for quicker functions will improve queue priority for Space visitors.
|
89 |
+
|
90 |
+
[](#hosting-limitations)Hosting Limitations
|
91 |
+
-------------------------------------------
|
92 |
+
|
93 |
+
* **Personal accounts ([PRO subscribers](https://huggingface.co/subscribe/pro))**: Maximum of 10 ZeroGPU Spaces.
|
94 |
+
* **Organization accounts ([Enterprise Hub](https://huggingface.co/enterprise))**: Maximum of 50 ZeroGPU Spaces.
|
95 |
+
|
96 |
+
By leveraging ZeroGPU, developers can create more efficient and scalable Spaces, maximizing GPU utilization while minimizing costs.
|
97 |
+
|
98 |
+
[](#feedback)Feedback
|
99 |
+
---------------------
|
100 |
+
|
101 |
+
You can share your feedback on Spaces ZeroGPU directly on the HF Hub: [https://huggingface.co/spaces/zero-gpu-explorers/README/discussions](https://huggingface.co/spaces/zero-gpu-explorers/README/discussions)
|
102 |
+
|
103 |
+
[< \> Update on GitHub](https://github.com/huggingface/hub-docs/blob/main/docs/hub/spaces-zerogpu.md)
|
requirements.txt
CHANGED
@@ -85,3 +85,4 @@ wheel==0.45.1
|
|
85 |
zipp==3.23.0
|
86 |
gradio==5.42.0
|
87 |
sageattention==1.0.6
|
|
|
|
85 |
zipp==3.23.0
|
86 |
gradio==5.42.0
|
87 |
sageattention==1.0.6
|
88 |
+
spaces
|