Spaces:
Sleeping
Sleeping
File size: 8,704 Bytes
f5267ae 2a414d5 f5267ae 2a414d5 f5267ae | 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 | import copy
import gradio as gr
import numpy as np
import random
import pickle
import torch
import os
import sys
import spaces
from huggingface_hub import hf_hub_download, snapshot_download
from diffusers import FluxPipeline
from diffusers.models import FluxTransformer2DModel
from diffusers.utils import SAFETENSORS_WEIGHTS_NAME
from diffusers.loaders.lora_base import LORA_WEIGHT_NAME_SAFE
from safetensors.torch import load_file
# Import essential classes for unpickling pruned models
from utils import SparsityLinear, SkipConnection, AttentionSkipConnection
# Create a simple mock module for pickle imports
class MockModule:
def __init__(self):
# Add all the classes that pickle might need
self.SparsityLinear = SparsityLinear
self.SkipConnection = SkipConnection
self.AttentionSkipConnection = AttentionSkipConnection
# Self-reference for nested imports
self.utils = self
# Register the mock module for all sdib import paths
mock = MockModule()
sys.modules['sdib'] = mock
sys.modules['sdib.utils'] = mock
sys.modules['sdib.utils.utils'] = mock
################################################################################
################################################################################
# Configuration
PRUNING_RATIOS = [25, 30]
device = "cuda" if torch.cuda.is_available() else "cpu"
MAX_SEED = np.iinfo(np.int32).max
dtype = torch.bfloat16
print("π Loading base Flux dev pipeline...")
base_pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
torch_dtype=dtype
)
print("β
Base Flux dev pipeline loaded!")
# Global storage for all models
pruned_models = {}
print("π₯ Preloading all pruned models...")
for ratio in PRUNING_RATIOS:
try:
print(f"Loading {ratio}% pruned model...")
model_file = hf_hub_download(
repo_id="LWZ19/ecodiff_flux_prune",
filename=f"dev/pruned_model_{ratio}.pkl"
)
with open(model_file, "rb") as f:
pruned_model = pickle.load(f)
pruned_model.to("cpu")
pruned_model.to(dtype)
pruned_models[ratio] = pruned_model
print(f"β
{ratio}% pruned model loaded!")
except Exception as e:
print(f"β Failed to load {ratio}% pruned model: {e}")
pruned_models[ratio] = None
print("π₯ Preloading all LoRA weights...")
for ratio in PRUNING_RATIOS:
try:
lora_repo_path = snapshot_download(
repo_id="LWZ19/ecodiff_flux_retrain_weights",
allow_patterns=[f"dev/lora/prune_{ratio}/*"]
)
lora_weights = load_file(os.path.join(lora_repo_path, "dev", "lora", f"prune_{ratio}", LORA_WEIGHT_NAME_SAFE))
print("β
LoRA checkpoint loaded!")
# Temporarily set the pruned model as transformer
base_pipe.transformer = pruned_models[ratio]
# Load and merge LoRA weights
base_pipe.load_lora_weights(lora_weights)
base_pipe.fuse_lora()
base_pipe.unload_lora_weights()
# Store the merged model back
pruned_models[ratio] = base_pipe.transformer
print(f"β
LoRA merged with {ratio}% pruned model!")
except Exception as e:
print(f"β Failed to load LoRA checkpoint: {e}")
# Model state
base_pipe.transformer = pruned_models[25].to(device)
current_ratio = 25
def load_model(ratio):
"""Apply specified model to the pipeline with optional LoRA"""
global current_ratio
try:
# Switch to new pruned model if different ratio
if current_ratio != ratio:
base_pipe.transformer = pruned_models[ratio].to(device)
current_ratio = ratio
return f"β
Ready with {ratio}% pruned Flux.1 [dev] + LoRA retrained"
except Exception as e:
return f"β Failed to apply weights: {str(e)}"
@spaces.GPU(duration=80)
def generate_image(
ratio,
prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
progress=gr.Progress(track_tqdm=True),
):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
try:
# Apply model configuration
status = load_model(ratio)
if "β" in status:
return None, seed, status
# Move pipeline to GPU for generation
base_pipe.to(device)
generator = torch.Generator(device).manual_seed(seed)
# Generate image using base pipeline (already configured with pruned model)
image = base_pipe(
prompt=prompt,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
width=width,
height=height,
generator=generator,
).images[0]
# Clean up GPU memory
torch.cuda.empty_cache() if torch.cuda.is_available() else None
result_status = f"β
Generated with {ratio}% pruned Flux.1 [dev] + LoRA retrained"
return image, seed, result_status
except Exception as e:
error_status = f"β Generation failed: {str(e)}\nPlease retry after a few minutes."
return None, seed, error_status
examples = [
"A clock tower floating in a sea of clouds",
"A cozy library with a roaring fireplace",
"A cat playing football",
"A magical forest with glowing mushrooms",
"An astronaut riding a rainbow unicorn",
]
css = """
#col-container {
margin: 0 auto;
max-width: 720px;
}
"""
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("# EcoDiff Flux.1 [dev]: Memory-Efficient Diffusion")
gr.Markdown("Generate images using pruned Flux.1 [dev] models with 25% and 30% pruning ratios, both LoRA retrained.")
with gr.Row():
prompt = gr.Text(
label="Prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
container=False,
)
with gr.Row():
ratio = gr.Dropdown(
choices=PRUNING_RATIOS,
value=25,
label="Pruning Ratio (%)",
info="Select pruning ratio",
scale=1
)
generate_button = gr.Button("Generate", variant="primary")
result = gr.Image(label="Result", show_label=False)
status_display = gr.Textbox(label="Status", interactive=False)
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width = gr.Slider(
label="Width",
minimum=512,
maximum=2048,
step=32,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=512,
maximum=2048,
step=32,
value=1024,
)
with gr.Row():
guidance_scale = gr.Slider(
label="Guidance scale",
minimum=1.0,
maximum=10.0,
step=0.1,
value=3.5,
)
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=50,
step=1,
value=50,
)
gr.Examples(examples=examples, inputs=[prompt])
gr.Markdown("""
### About EcoDiff Flux.1 [dev] Unified
This space showcases pruned Flux.1 [dev] models using learnable pruning techniques with LoRA fine-tuning.
- **Base Model**: Flux.1 [dev]
- **Pruning Ratios**: 25% and 30% of parameters removed
- **LoRA Enhancement**: Both models are retrained with LoRA weights for improved quality
""")
generate_button.click(
fn=generate_image,
inputs=[
ratio,
prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
],
outputs=[result, seed, status_display],
)
if __name__ == "__main__":
demo.launch()
|