hyperman12's picture
Upload 9 files
be6ad40 verified
Raw History Blame Contribute Delete
17.3 kB
import gradio as gr
import numpy as np
import random
import threading
from queue import Queue
import spaces
from diffusers import DiffusionPipeline
import torch
# Multi-GPU Setup with Dynamic Memory Allocation
model_repo_id = "stabilityai/stable-diffusion-3.5-large"
torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
# Memory optimization settings
ENABLE_CPU_OFFLOAD = True # Reduces VRAM: 16GB β†’ 6GB (slower but fits more)
ENABLE_ATTENTION_SLICING = True # Reduces VRAM for large images
ENABLE_VAE_SLICING = True # Further memory reduction
TARGET_VRAM_USAGE = 0.90 # Use 90% of available VRAM (leave 10% buffer)
# Estimate VRAM usage per model based on settings
if ENABLE_CPU_OFFLOAD:
VRAM_PER_MODEL_GB = 6.0 # With CPU offload
else:
VRAM_PER_MODEL_GB = 16.0 # Without offload (full model in VRAM)
# Detect available GPUs
num_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0
print(f"πŸ”₯ Detected {num_gpus} GPU(s)")
# Dynamically calculate how many models fit per GPU
gpu_info = []
total_models = 0
if num_gpus > 0:
print(f"\n{'='*70}")
print("πŸ“Š Analyzing GPU Memory Capacity...")
print(f"{'='*70}")
for gpu_id in range(num_gpus):
# Get GPU properties
props = torch.cuda.get_device_properties(gpu_id)
total_vram_gb = props.total_memory / (1024**3) # Convert to GB
# Calculate usable VRAM (90% to leave buffer)
usable_vram_gb = total_vram_gb * TARGET_VRAM_USAGE
# Calculate how many models fit
models_per_gpu = int(usable_vram_gb / VRAM_PER_MODEL_GB)
models_per_gpu = max(1, models_per_gpu) # At least 1 model per GPU
gpu_info.append({
'gpu_id': gpu_id,
'name': props.name,
'total_vram_gb': total_vram_gb,
'usable_vram_gb': usable_vram_gb,
'models_to_load': models_per_gpu,
'estimated_usage_gb': models_per_gpu * VRAM_PER_MODEL_GB
})
total_models += models_per_gpu
print(f"GPU {gpu_id}: {props.name}")
print(f" Total VRAM: {total_vram_gb:.1f} GB")
print(f" Usable VRAM (90%): {usable_vram_gb:.1f} GB")
print(f" VRAM per model: {VRAM_PER_MODEL_GB:.1f} GB")
print(f" Models to load: {models_per_gpu}")
print(f" Est. VRAM usage: {models_per_gpu * VRAM_PER_MODEL_GB:.1f} GB ({(models_per_gpu * VRAM_PER_MODEL_GB / total_vram_gb * 100):.1f}%)")
print()
print(f"{'='*70}")
print(f"🎯 Total Models Across All GPUs: {total_models}")
print(f"⚑ Maximum Concurrent Users: {total_models}")
print(f"{'='*70}\n")
# Load models dynamically based on calculated capacity
pipes = []
model_to_gpu_map = {} # Track which GPU each model is on
if num_gpus > 0:
model_counter = 0
for gpu_data in gpu_info:
gpu_id = gpu_data['gpu_id']
models_to_load = gpu_data['models_to_load']
for model_idx in range(models_to_load):
print(f"πŸ“₯ Loading model {model_counter} on GPU {gpu_id} (instance {model_idx+1}/{models_to_load})...")
pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
pipe = pipe.to(f"cuda:{gpu_id}")
# Apply memory optimizations
if ENABLE_CPU_OFFLOAD:
pipe.enable_model_cpu_offload(gpu_id=gpu_id)
print(f" βœ“ CPU offload enabled (saves ~10GB VRAM)")
if ENABLE_ATTENTION_SLICING:
pipe.enable_attention_slicing(slice_size="auto")
print(f" βœ“ Attention slicing enabled (saves ~1-2GB VRAM)")
if ENABLE_VAE_SLICING:
pipe.enable_vae_slicing()
print(f" βœ“ VAE slicing enabled (saves ~0.5-1GB VRAM)")
pipes.append(pipe)
model_to_gpu_map[model_counter] = gpu_id
print(f"βœ… Model {model_counter} ready on GPU {gpu_id}!")
model_counter += 1
# Optional: Clear cache between loads
torch.cuda.empty_cache()
else:
# Fallback to CPU
print("⚠️ No GPU detected, using CPU (will be slow)")
pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch.float32)
pipes.append(pipe)
model_to_gpu_map[0] = -1 # -1 for CPU
print(f"\n{'='*70}")
print(f"βœ… All {len(pipes)} models loaded successfully!")
print(f"{'='*70}\n")
# GPU assignment queue - round-robin across GPUs
gpu_lock = threading.Lock()
current_gpu = 0
def get_next_gpu():
"""Round-robin GPU assignment"""
global current_gpu
with gpu_lock:
gpu_id = current_gpu
current_gpu = (current_gpu + 1) % len(pipes)
return gpu_id
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
@spaces.GPU(duration=65)
def infer(
prompt,
negative_prompt="",
seed=42,
randomize_seed=False,
width=1024,
height=1024,
guidance_scale=4.5,
num_inference_steps=40,
progress=gr.Progress(track_tqdm=True),
):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# Get next available model instance (round-robin across all instances)
model_id = get_next_gpu()
pipe = pipes[model_id]
# Get the GPU this model is on
gpu_id = model_to_gpu_map.get(model_id, 0)
device = f"cuda:{gpu_id}" if gpu_id >= 0 else "cpu"
print(f"🎨 Generating with model {model_id} on GPU {gpu_id}...")
generator = torch.Generator(device=device).manual_seed(seed)
image = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
width=width,
height=height,
generator=generator,
).images[0]
print(f"βœ… Model {model_id} (GPU {gpu_id}) completed!")
return image, seed
return image, seed
examples = [
"A serene mountain landscape at sunset with crystal clear lake reflections, photorealistic, 8k quality",
"Modern minimalist office space with floor-to-ceiling windows, natural lighting, architectural photography",
"Portrait of a woman in elegant evening dress, studio lighting, fashion photography, high detail",
"Futuristic city skyline at night with neon lights, cyberpunk aesthetic, ultra detailed",
"Cozy coffee shop interior with warm ambient lighting, bokeh effect, professional photography",
]
css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
#main-container {
max-width: 1400px;
margin: 0 auto;
padding: 2rem;
background: #ffffff;
}
.header-section {
text-align: center;
padding: 2rem 0;
border-bottom: 1px solid #e5e7eb;
margin-bottom: 2rem;
}
.header-section h1 {
font-size: 2.5rem;
font-weight: 700;
color: #111827;
margin-bottom: 0.5rem;
letter-spacing: -0.025em;
}
.header-section p {
font-size: 1.125rem;
color: #6b7280;
font-weight: 400;
}
.input-section {
background: #f9fafb;
padding: 2rem;
border-radius: 12px;
border: 1px solid #e5e7eb;
margin-bottom: 1.5rem;
}
.output-section {
background: #ffffff;
padding: 1.5rem;
border-radius: 12px;
border: 1px solid #e5e7eb;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}
button.primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
border: none !important;
color: white !important;
font-weight: 600 !important;
padding: 0.75rem 2rem !important;
border-radius: 8px !important;
font-size: 1rem !important;
transition: all 0.3s ease !important;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important;
}
button.primary:hover {
transform: translateY(-2px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1) !important;
}
.accordion {
background: #ffffff !important;
border: 1px solid #e5e7eb !important;
border-radius: 8px !important;
margin-top: 1rem;
}
label {
font-weight: 500 !important;
color: #374151 !important;
font-size: 0.875rem !important;
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 0.5rem !important;
}
input, textarea {
border: 1px solid #d1d5db !important;
border-radius: 8px !important;
padding: 0.75rem !important;
font-size: 1rem !important;
transition: border-color 0.2s ease !important;
}
input:focus, textarea:focus {
border-color: #667eea !important;
outline: none !important;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1) !important;
}
.slider {
margin: 1rem 0;
}
.examples {
margin-top: 2rem;
padding-top: 2rem;
border-top: 1px solid #e5e7eb;
}
.footer {
text-align: center;
padding: 2rem 0;
color: #9ca3af;
font-size: 0.875rem;
margin-top: 3rem;
border-top: 1px solid #e5e7eb;
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
"""
with gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate")) as demo:
with gr.Column(elem_id="main-container"):
# Header
with gr.Row(elem_classes="header-section"):
memory_mode = "Dynamic Optimized" if ENABLE_CPU_OFFLOAD else "High Performance"
total_vram = sum(g['total_vram_gb'] for g in gpu_info) if gpu_info else 0
used_vram = sum(g['estimated_usage_gb'] for g in gpu_info) if gpu_info else 0
efficiency = (used_vram / total_vram * 100) if total_vram > 0 else 0
gr.HTML(f"""
<div>
<h1>🎨 Stable Diffusion 3.5 Large</h1>
<p>Professional AI Image Generation - 8B Parameter Model</p>
<p style="font-size: 0.9rem; color: #10b981; font-weight: 600; margin-top: 0.5rem;">
πŸš€ {num_gpus} GPU(s) | {len(pipes)} Models | {total_vram:.0f}GB Total | {used_vram:.0f}GB Used ({efficiency:.0f}%) | Up to {len(pipes)} Concurrent
</p>
</div>
""")
# Main content in two columns
with gr.Row():
# Left column - Input
with gr.Column(scale=1):
with gr.Group(elem_classes="input-section"):
prompt = gr.Textbox(
label="✍️ Your Prompt",
placeholder="Describe the image you want to create in detail...",
lines=4,
max_lines=8,
)
run_button = gr.Button(
"πŸš€ Generate Image",
variant="primary",
size="lg",
elem_classes="primary"
)
# Advanced Settings
with gr.Accordion("βš™οΈ Advanced Settings", open=False, elem_classes="accordion"):
negative_prompt = gr.Textbox(
label="🚫 Negative Prompt",
placeholder="What to avoid in the image...",
lines=2,
value="blurry, low quality, distorted, artifacts"
)
with gr.Row():
width = gr.Slider(
label="Width (px)",
minimum=512,
maximum=MAX_IMAGE_SIZE,
step=64,
value=1024,
)
height = gr.Slider(
label="Height (px)",
minimum=512,
maximum=MAX_IMAGE_SIZE,
step=64,
value=1024,
)
with gr.Row():
guidance_scale = gr.Slider(
label="Guidance Scale",
minimum=1.0,
maximum=15.0,
step=0.5,
value=4.5,
info="Higher = more adherence to prompt"
)
num_inference_steps = gr.Slider(
label="Quality Steps",
minimum=20,
maximum=75,
step=5,
value=40,
info="More steps = higher quality"
)
with gr.Row():
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=42,
info="For reproducible results"
)
randomize_seed = gr.Checkbox(
label="🎲 Randomize Seed",
value=True
)
# Right column - Output
with gr.Column(scale=1):
with gr.Group(elem_classes="output-section"):
result = gr.Image(
label="Generated Image",
show_label=True,
height=600,
show_download_button=True,
show_share_button=True
)
seed_output = gr.Number(
label="Used Seed",
interactive=False,
info="Save this to reproduce the exact image"
)
# Example prompts
with gr.Row(elem_classes="examples"):
gr.Examples(
examples=examples,
inputs=[prompt],
outputs=[result, seed_output],
fn=infer,
cache_examples=False,
label="πŸ’‘ Example Prompts - Click to try"
)
# Footer
gr.HTML("""
<div class="footer">
<p>Powered by Stable Diffusion 3.5 Large | Built with Gradio</p>
<p style="margin-top: 0.5rem; font-size: 0.75rem;">Model by Stability AI β€’ Interface by Gradio</p>
</div>
""")
# Event handlers
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[
prompt,
negative_prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
],
outputs=[result, seed_output],
)
if __name__ == "__main__":
# Multi-instance queue configuration
concurrent_limit = len(pipes) # Process as many as we have model instances
memory_mode = "Memory Optimized" if ENABLE_CPU_OFFLOAD else "High Performance"
print(f"\n{'='*70}")
print(f"πŸš€ Starting Multi-GPU Server with Memory Optimization")
print(f"{'='*70}")
print(f"πŸ“Š GPUs Available: {num_gpus}")
print(f"πŸ”§ Model Instances: {len(pipes)}")
print(f"πŸ’Ύ Memory Mode: {memory_mode}")
print(f"⚑ Concurrent Generations: {concurrent_limit}")
if ENABLE_CPU_OFFLOAD:
print(f"οΏ½ VRAM per instance: ~6GB (vs ~16GB without offload)")
print(f"⏱️ Speed: ~30% slower, but {MAX_MODELS_PER_GPU}x more concurrent users")
print(f"οΏ½πŸ“ˆ Theoretical Max Throughput: {concurrent_limit * 60 / 40:.1f} images/minute")
print(f"{'='*70}\n")
demo.queue(
max_size=100, # Larger queue for more users
default_concurrency_limit=concurrent_limit, # Process N requests simultaneously
api_open=False
)
demo.launch(
share=True, # Creates a public URL
server_name="0.0.0.0",
server_port=7860,
show_error=True,
max_threads=concurrent_limit * 3, # More threads for handling connections
)