Spaces:
Running
on
Zero
Running
on
Zero
init
Browse files- app.py +127 -103
- live_preview_helpers.py +166 -0
- requirements.txt +4 -4
app.py
CHANGED
@@ -1,49 +1,98 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
import numpy as np
|
3 |
import random
|
4 |
-
|
5 |
from diffusers import DiffusionPipeline
|
6 |
import torch
|
|
|
|
|
|
|
|
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
9 |
-
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
torch_dtype = torch.float32
|
15 |
|
16 |
-
|
17 |
-
pipe = pipe.to(device)
|
18 |
|
19 |
-
|
20 |
-
MAX_IMAGE_SIZE = 1024
|
21 |
|
22 |
-
|
23 |
-
def
|
|
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
)
|
|
|
|
|
|
|
|
|
39 |
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
-
examples = [
|
43 |
-
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
44 |
-
"An astronaut riding a green horse",
|
45 |
-
"A delicious ceviche cheesecake slice",
|
46 |
-
]
|
47 |
|
48 |
css="""
|
49 |
#col-container {
|
@@ -56,87 +105,62 @@ with gr.Blocks(css=css) as demo:
|
|
56 |
|
57 |
with gr.Column(elem_id="col-container"):
|
58 |
gr.Markdown(f"""
|
59 |
-
#
|
60 |
""")
|
61 |
|
62 |
-
with gr.
|
63 |
-
|
64 |
-
prompt = gr.Text(
|
65 |
-
label="Prompt",
|
66 |
-
show_label=False,
|
67 |
-
max_lines=1,
|
68 |
-
placeholder="Enter your prompt",
|
69 |
-
container=False,
|
70 |
-
)
|
71 |
-
|
72 |
-
run_button = gr.Button("Run", scale=0)
|
73 |
-
|
74 |
-
result = gr.Image(label="Result", show_label=False)
|
75 |
-
|
76 |
-
with gr.Accordion("Advanced Settings", open=False):
|
77 |
-
|
78 |
-
negative_prompt = gr.Text(
|
79 |
-
label="Negative prompt",
|
80 |
-
max_lines=1,
|
81 |
-
placeholder="Enter a negative prompt",
|
82 |
-
visible=False,
|
83 |
-
)
|
84 |
-
|
85 |
-
seed = gr.Slider(
|
86 |
-
label="Seed",
|
87 |
-
minimum=0,
|
88 |
-
maximum=MAX_SEED,
|
89 |
-
step=1,
|
90 |
-
value=0,
|
91 |
-
)
|
92 |
-
|
93 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
94 |
-
|
95 |
with gr.Row():
|
96 |
|
97 |
-
|
98 |
-
label="
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
)
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
)
|
112 |
-
|
113 |
-
with gr.Row():
|
114 |
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
)
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
gr.on(
|
136 |
triggers=[run_button.click, prompt.submit],
|
137 |
-
fn =
|
138 |
-
inputs = [prompt,
|
139 |
-
outputs
|
140 |
)
|
141 |
|
142 |
demo.queue().launch()
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
import numpy as np
|
4 |
import random
|
5 |
+
import spaces
|
6 |
from diffusers import DiffusionPipeline
|
7 |
import torch
|
8 |
+
import json
|
9 |
+
import logging
|
10 |
+
from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
|
11 |
+
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
|
12 |
|
13 |
+
from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
|
14 |
+
import copy
|
15 |
+
import random
|
16 |
+
import time
|
17 |
+
|
18 |
+
|
19 |
+
# init
|
20 |
+
dtype = torch.bfloat16
|
21 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
22 |
+
base_model = "black-forest-labs/FLUX.1-dev"
|
23 |
|
24 |
+
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
|
25 |
+
good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
|
26 |
+
pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
|
|
|
27 |
|
28 |
+
MAX_SEED = 2**32-1
|
|
|
29 |
|
30 |
+
pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
|
|
|
31 |
|
32 |
+
class calculateDuration:
|
33 |
+
def __init__(self, activity_name=""):
|
34 |
+
self.activity_name = activity_name
|
35 |
|
36 |
+
def __enter__(self):
|
37 |
+
self.start_time = time.time()
|
38 |
+
return self
|
39 |
+
|
40 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
41 |
+
self.end_time = time.time()
|
42 |
+
self.elapsed_time = self.end_time - self.start_time
|
43 |
+
if self.activity_name:
|
44 |
+
print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
|
45 |
+
else:
|
46 |
+
print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
|
47 |
+
|
48 |
+
|
49 |
+
@spaces.GPU(duration=70)
|
50 |
+
def generate_image(prompt, steps, seed, cfg_scale, width, height, lora_scale, progress):
|
51 |
+
pipe.to("cuda")
|
52 |
+
generator = torch.Generator(device="cuda").manual_seed(seed)
|
53 |
+
with calculateDuration("Generating image"):
|
54 |
+
# Generate image
|
55 |
+
for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
|
56 |
+
prompt=prompt,
|
57 |
+
num_inference_steps=steps,
|
58 |
+
guidance_scale=cfg_scale,
|
59 |
+
width=width,
|
60 |
+
height=height,
|
61 |
+
generator=generator,
|
62 |
+
joint_attention_kwargs={"scale": lora_scale},
|
63 |
+
output_type="pil",
|
64 |
+
good_vae=good_vae,
|
65 |
+
):
|
66 |
+
yield img
|
67 |
+
|
68 |
+
|
69 |
+
def run_lora(prompt, cfg_scale, steps, lora_repo, lora_name, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
|
70 |
|
71 |
+
with calculateDuration("Unloading LoRA"):
|
72 |
+
pipe.unload_lora_weights()
|
73 |
+
|
74 |
+
# Load LoRA weights
|
75 |
+
with calculateDuration(f"Loading LoRA weights for {lora_repo} {lora_name}"):
|
76 |
+
pipe.load_lora_weights(lora_repo, weight_name=lora_name)
|
77 |
+
|
78 |
+
# Set random seed for reproducibility
|
79 |
+
with calculateDuration("Randomizing seed"):
|
80 |
+
if randomize_seed:
|
81 |
+
seed = random.randint(0, MAX_SEED)
|
82 |
+
|
83 |
+
image_generator = generate_image(prompt, steps, seed, cfg_scale, width, height, lora_scale, progress)
|
84 |
|
85 |
+
# Consume the generator to get the final image
|
86 |
+
final_image = None
|
87 |
+
step_counter = 0
|
88 |
+
for image in image_generator:
|
89 |
+
step_counter+=1
|
90 |
+
final_image = image
|
91 |
+
progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
|
92 |
+
yield image, seed, gr.update(value=progress_bar, visible=True)
|
93 |
+
|
94 |
+
yield final_image, seed, gr.update(value=progress_bar, visible=False)
|
95 |
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
css="""
|
98 |
#col-container {
|
|
|
105 |
|
106 |
with gr.Column(elem_id="col-container"):
|
107 |
gr.Markdown(f"""
|
108 |
+
# Simple flux with lora
|
109 |
""")
|
110 |
|
111 |
+
with gr.Column():
|
112 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
with gr.Row():
|
114 |
|
115 |
+
prompt = gr.Text(
|
116 |
+
label="Prompt",
|
117 |
+
show_label=False,
|
118 |
+
max_lines=1,
|
119 |
+
placeholder="Enter your prompt",
|
120 |
+
container=False,
|
121 |
)
|
122 |
|
123 |
+
lora_repo = gr.Text(
|
124 |
+
label="Repo",
|
125 |
+
max_lines=1,
|
126 |
+
placeholder="Enter a lora repo",
|
127 |
+
visible=False,
|
128 |
+
)
|
|
|
|
|
|
|
129 |
|
130 |
+
lora_name = gr.Text(
|
131 |
+
label="Weights",
|
132 |
+
max_lines=1,
|
133 |
+
placeholder="Enter a lora weights",
|
134 |
+
visible=False,
|
135 |
+
)
|
136 |
+
run_button = gr.Button("Run", scale=0)
|
137 |
+
|
138 |
+
with gr.Accordion("Advanced Settings", open=False):
|
139 |
+
|
140 |
+
with gr.Row():
|
141 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
|
142 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
143 |
+
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
|
144 |
+
|
145 |
+
with gr.Row():
|
146 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
|
147 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
|
148 |
+
|
149 |
+
with gr.Row():
|
150 |
+
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
|
151 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
|
152 |
+
|
153 |
+
|
154 |
+
|
155 |
+
with gr.Row():
|
156 |
+
progress_bar = gr.Markdown(elem_id="progress",visible=False)
|
157 |
+
result = gr.Image(label="Result", show_label=False)
|
158 |
+
|
159 |
gr.on(
|
160 |
triggers=[run_button.click, prompt.submit],
|
161 |
+
fn = run_lora,
|
162 |
+
inputs = [prompt, cfg_scale, steps, lora_repo, lora_name, randomize_seed, seed, width, height, lora_scale],
|
163 |
+
outputs=[result, seed, progress_bar]
|
164 |
)
|
165 |
|
166 |
demo.queue().launch()
|
live_preview_helpers.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
from diffusers import FluxPipeline, AutoencoderTiny, FlowMatchEulerDiscreteScheduler
|
4 |
+
from typing import Any, Dict, List, Optional, Union
|
5 |
+
|
6 |
+
# Helper functions
|
7 |
+
def calculate_shift(
|
8 |
+
image_seq_len,
|
9 |
+
base_seq_len: int = 256,
|
10 |
+
max_seq_len: int = 4096,
|
11 |
+
base_shift: float = 0.5,
|
12 |
+
max_shift: float = 1.16,
|
13 |
+
):
|
14 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
15 |
+
b = base_shift - m * base_seq_len
|
16 |
+
mu = image_seq_len * m + b
|
17 |
+
return mu
|
18 |
+
|
19 |
+
def retrieve_timesteps(
|
20 |
+
scheduler,
|
21 |
+
num_inference_steps: Optional[int] = None,
|
22 |
+
device: Optional[Union[str, torch.device]] = None,
|
23 |
+
timesteps: Optional[List[int]] = None,
|
24 |
+
sigmas: Optional[List[float]] = None,
|
25 |
+
**kwargs,
|
26 |
+
):
|
27 |
+
if timesteps is not None and sigmas is not None:
|
28 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
29 |
+
if timesteps is not None:
|
30 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
31 |
+
timesteps = scheduler.timesteps
|
32 |
+
num_inference_steps = len(timesteps)
|
33 |
+
elif sigmas is not None:
|
34 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
35 |
+
timesteps = scheduler.timesteps
|
36 |
+
num_inference_steps = len(timesteps)
|
37 |
+
else:
|
38 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
39 |
+
timesteps = scheduler.timesteps
|
40 |
+
return timesteps, num_inference_steps
|
41 |
+
|
42 |
+
# FLUX pipeline function
|
43 |
+
@torch.inference_mode()
|
44 |
+
def flux_pipe_call_that_returns_an_iterable_of_images(
|
45 |
+
self,
|
46 |
+
prompt: Union[str, List[str]] = None,
|
47 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
48 |
+
height: Optional[int] = None,
|
49 |
+
width: Optional[int] = None,
|
50 |
+
num_inference_steps: int = 28,
|
51 |
+
timesteps: List[int] = None,
|
52 |
+
guidance_scale: float = 3.5,
|
53 |
+
num_images_per_prompt: Optional[int] = 1,
|
54 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
55 |
+
latents: Optional[torch.FloatTensor] = None,
|
56 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
57 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
58 |
+
output_type: Optional[str] = "pil",
|
59 |
+
return_dict: bool = True,
|
60 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
61 |
+
max_sequence_length: int = 512,
|
62 |
+
good_vae: Optional[Any] = None,
|
63 |
+
):
|
64 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
65 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
66 |
+
|
67 |
+
# 1. Check inputs
|
68 |
+
self.check_inputs(
|
69 |
+
prompt,
|
70 |
+
prompt_2,
|
71 |
+
height,
|
72 |
+
width,
|
73 |
+
prompt_embeds=prompt_embeds,
|
74 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
75 |
+
max_sequence_length=max_sequence_length,
|
76 |
+
)
|
77 |
+
|
78 |
+
self._guidance_scale = guidance_scale
|
79 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
80 |
+
self._interrupt = False
|
81 |
+
|
82 |
+
# 2. Define call parameters
|
83 |
+
batch_size = 1 if isinstance(prompt, str) else len(prompt)
|
84 |
+
device = self._execution_device
|
85 |
+
|
86 |
+
# 3. Encode prompt
|
87 |
+
lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
|
88 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
|
89 |
+
prompt=prompt,
|
90 |
+
prompt_2=prompt_2,
|
91 |
+
prompt_embeds=prompt_embeds,
|
92 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
93 |
+
device=device,
|
94 |
+
num_images_per_prompt=num_images_per_prompt,
|
95 |
+
max_sequence_length=max_sequence_length,
|
96 |
+
lora_scale=lora_scale,
|
97 |
+
)
|
98 |
+
# 4. Prepare latent variables
|
99 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
100 |
+
latents, latent_image_ids = self.prepare_latents(
|
101 |
+
batch_size * num_images_per_prompt,
|
102 |
+
num_channels_latents,
|
103 |
+
height,
|
104 |
+
width,
|
105 |
+
prompt_embeds.dtype,
|
106 |
+
device,
|
107 |
+
generator,
|
108 |
+
latents,
|
109 |
+
)
|
110 |
+
# 5. Prepare timesteps
|
111 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
112 |
+
image_seq_len = latents.shape[1]
|
113 |
+
mu = calculate_shift(
|
114 |
+
image_seq_len,
|
115 |
+
self.scheduler.config.base_image_seq_len,
|
116 |
+
self.scheduler.config.max_image_seq_len,
|
117 |
+
self.scheduler.config.base_shift,
|
118 |
+
self.scheduler.config.max_shift,
|
119 |
+
)
|
120 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
121 |
+
self.scheduler,
|
122 |
+
num_inference_steps,
|
123 |
+
device,
|
124 |
+
timesteps,
|
125 |
+
sigmas,
|
126 |
+
mu=mu,
|
127 |
+
)
|
128 |
+
self._num_timesteps = len(timesteps)
|
129 |
+
|
130 |
+
# Handle guidance
|
131 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
|
132 |
+
|
133 |
+
# 6. Denoising loop
|
134 |
+
for i, t in enumerate(timesteps):
|
135 |
+
if self.interrupt:
|
136 |
+
continue
|
137 |
+
|
138 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
139 |
+
|
140 |
+
noise_pred = self.transformer(
|
141 |
+
hidden_states=latents,
|
142 |
+
timestep=timestep / 1000,
|
143 |
+
guidance=guidance,
|
144 |
+
pooled_projections=pooled_prompt_embeds,
|
145 |
+
encoder_hidden_states=prompt_embeds,
|
146 |
+
txt_ids=text_ids,
|
147 |
+
img_ids=latent_image_ids,
|
148 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
149 |
+
return_dict=False,
|
150 |
+
)[0]
|
151 |
+
# Yield intermediate result
|
152 |
+
latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
153 |
+
latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
154 |
+
image = self.vae.decode(latents_for_image, return_dict=False)[0]
|
155 |
+
yield self.image_processor.postprocess(image, output_type=output_type)[0]
|
156 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
157 |
+
torch.cuda.empty_cache()
|
158 |
+
|
159 |
+
|
160 |
+
# Final image using good_vae
|
161 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
162 |
+
latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
|
163 |
+
image = good_vae.decode(latents, return_dict=False)[0]
|
164 |
+
self.maybe_free_model_hooks()
|
165 |
+
torch.cuda.empty_cache()
|
166 |
+
yield self.image_processor.postprocess(image, output_type=output_type)[0]
|
requirements.txt
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
-
accelerate
|
2 |
-
diffusers
|
3 |
-
invisible_watermark
|
4 |
torch
|
|
|
|
|
5 |
transformers
|
6 |
-
|
|
|
|
|
|
|
|
|
|
1 |
torch
|
2 |
+
git+https://github.com/huggingface/diffusers@3b604e8c384631e1f66a4fd9076ed5e7e2b08686
|
3 |
+
spaces
|
4 |
transformers
|
5 |
+
peft
|
6 |
+
sentencepiece
|