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
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
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
    )