Consulawtech commited on
Commit
305aa30
ยท
verified ยท
1 Parent(s): 51b43e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -45
app.py CHANGED
@@ -3,7 +3,6 @@ import spaces
3
  import torch
4
  import os
5
  from diffusers import FluxPipeline
6
- from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
7
  from PIL import Image
8
  import time
9
  import gc
@@ -12,75 +11,49 @@ import gc
12
  # CONFIGURATION
13
  # ============================================
14
  MODEL_ID = "black-forest-labs/FLUX.1-dev" # Fastest real-time capable model
15
- USE_AOTI = True # Ahead-of-Time compilation for 1.3-1.8x speedup
16
- USE_QUANTIZATION = True # FP8 quantization for H200
17
- QUANTIZATION_CONFIG = Float8DynamicActivationFloat8WeightConfig if USE_QUANTIZATION else None
18
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
19
  DTYPE = torch.bfloat16 if DEVICE == "cuda" else torch.float32
20
 
21
  # ============================================
22
- # MODEL LOADING WITH OPTIMIZATION
23
  # ============================================
24
  class OptimizedFluxPipeline:
25
- """Memory-efficient pipeline with AOTI compilation support"""
26
 
27
  def __init__(self):
28
  self.pipe = None
29
- self.compiled_transformer = None
30
  self.is_loaded = False
31
 
32
  def load(self):
33
- """Load model with quantization and optional AOTI compilation"""
34
  if self.is_loaded:
35
  return
36
 
37
  print(f"Loading {MODEL_ID} on {DEVICE} with {DTYPE}...")
38
 
39
- # Base pipeline loading
40
  self.pipe = FluxPipeline.from_pretrained(
41
  MODEL_ID,
42
  torch_dtype=DTYPE,
43
  variant="bf16" if DTYPE == torch.bfloat16 else None,
44
- use_safetensors=True
 
45
  )
46
 
47
  # Move to device
48
  self.pipe.to(DEVICE)
49
 
50
- # Apply quantization if enabled and on CUDA
51
- if USE_QUANTIZATION and DEVICE == "cuda":
52
- try:
53
- print("Applying FP8 quantization for H200 acceleration...")
54
- # Quantize transformer component (heaviest part)
55
- quantize_(self.pipe.transformer, QUANTIZATION_CONFIG())
56
- print("โœ… Quantization applied successfully")
57
- except Exception as e:
58
- print(f"โš ๏ธ Quantization failed: {e}. Proceeding without quantization.")
59
 
60
- # Apply AOTI compilation if enabled
61
- if USE_AOTI and DEVICE == "cuda":
62
- try:
63
- self._apply_aot_compilation()
64
- except Exception as e:
65
- print(f"โš ๏ธ AOTI compilation failed: {e}. Using standard pipeline.")
66
 
67
  self.is_loaded = True
68
- print("โœ… Model ready for real-time inference!")
69
-
70
- def _apply_aot_compilation(self):
71
- """Apply Ahead-of-Time compilation for faster inference"""
72
- print("Applying AOTI compilation for 1.3-1.8x speedup...")
73
-
74
- try:
75
- # Simple compilation approach
76
- self.pipe.transformer = torch.compile(
77
- self.pipe.transformer,
78
- mode="reduce-overhead",
79
- fullgraph=False
80
- )
81
- print("โœ… AOTI compilation complete!")
82
- except Exception as e:
83
- print(f"โš ๏ธ Compilation failed: {e}")
84
 
85
  def generate(self, prompt, negative_prompt="", guidance_scale=3.5, num_inference_steps=28, seed=None, progress=None):
86
  """Generate image from prompt with interactive parameters"""
@@ -118,8 +91,6 @@ class OptimizedFluxPipeline:
118
 
119
  def cleanup(self):
120
  """Free memory when not in use"""
121
- if hasattr(self, 'compiled_transformer') and self.compiled_transformer:
122
- del self.compiled_transformer
123
  if self.pipe:
124
  del self.pipe
125
  gc.collect()
@@ -211,8 +182,7 @@ with gr.Blocks(css=custom_css, title="Real-Time Flux Diffusion", theme=gr.themes
211
  ### Powered by FLUX.1-dev on ZeroGPU H200
212
 
213
  **Features:**
214
- - โšก 1.3-1.8x faster with AOTI compilation
215
- - ๐Ÿ”ฅ FP8 quantization for H200 acceleration
216
  - ๐ŸŽฎ Real-time parameter adjustment
217
  - ๐Ÿ†“ ZeroGPU optimized (free tier + PRO priority)
218
  """)
 
3
  import torch
4
  import os
5
  from diffusers import FluxPipeline
 
6
  from PIL import Image
7
  import time
8
  import gc
 
11
  # CONFIGURATION
12
  # ============================================
13
  MODEL_ID = "black-forest-labs/FLUX.1-dev" # Fastest real-time capable model
14
+ USE_AOTI = False # Disable AOTI for now due to compatibility issues
15
+ USE_QUANTIZATION = False # Disable quantization for now
 
16
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
17
  DTYPE = torch.bfloat16 if DEVICE == "cuda" else torch.float32
18
 
19
  # ============================================
20
+ # MODEL LOADING
21
  # ============================================
22
  class OptimizedFluxPipeline:
23
+ """Memory-efficient pipeline"""
24
 
25
  def __init__(self):
26
  self.pipe = None
 
27
  self.is_loaded = False
28
 
29
  def load(self):
30
+ """Load model with basic optimizations"""
31
  if self.is_loaded:
32
  return
33
 
34
  print(f"Loading {MODEL_ID} on {DEVICE} with {DTYPE}...")
35
 
36
+ # Base pipeline loading with memory optimizations
37
  self.pipe = FluxPipeline.from_pretrained(
38
  MODEL_ID,
39
  torch_dtype=DTYPE,
40
  variant="bf16" if DTYPE == torch.bfloat16 else None,
41
+ use_safetensors=True,
42
+ low_cpu_mem_usage=True
43
  )
44
 
45
  # Move to device
46
  self.pipe.to(DEVICE)
47
 
48
+ # Enable memory efficient attention if available
49
+ if hasattr(self.pipe, "enable_attention_slicing"):
50
+ self.pipe.enable_attention_slicing()
 
 
 
 
 
 
51
 
52
+ if hasattr(self.pipe, "enable_vae_slicing"):
53
+ self.pipe.enable_vae_slicing()
 
 
 
 
54
 
55
  self.is_loaded = True
56
+ print("โœ… Model ready for inference!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  def generate(self, prompt, negative_prompt="", guidance_scale=3.5, num_inference_steps=28, seed=None, progress=None):
59
  """Generate image from prompt with interactive parameters"""
 
91
 
92
  def cleanup(self):
93
  """Free memory when not in use"""
 
 
94
  if self.pipe:
95
  del self.pipe
96
  gc.collect()
 
182
  ### Powered by FLUX.1-dev on ZeroGPU H200
183
 
184
  **Features:**
185
+ - ๐Ÿš€ Optimized for ZeroGPU with memory-efficient attention
 
186
  - ๐ŸŽฎ Real-time parameter adjustment
187
  - ๐Ÿ†“ ZeroGPU optimized (free tier + PRO priority)
188
  """)