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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import warnings
|
2 |
+
from diffusers import StableDiffusionPipeline
|
3 |
+
import torch
|
4 |
+
import spaces
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
from typing import Optional
|
7 |
+
from tqdm import tqdm
|
8 |
+
import math
|
9 |
+
import torch.nn.functional as F
|
10 |
+
from diffusers import DDIMScheduler
|
11 |
+
import numpy as np
|
12 |
+
import gradio as gr
|
13 |
+
|
14 |
+
model_id = "stabilityai/stable-diffusion-2-1-base"
|
15 |
+
|
16 |
+
|
17 |
+
|
18 |
+
def gaussian_blur_2d(img, kernel_size, sigma):
|
19 |
+
height = img.shape[-1]
|
20 |
+
kernel_size = min(kernel_size, height - (height % 2 - 1))
|
21 |
+
ksize_half = (kernel_size - 1) * 0.5
|
22 |
+
|
23 |
+
x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
|
24 |
+
|
25 |
+
pdf = torch.exp(-0.5 * (x / sigma).pow(2))
|
26 |
+
|
27 |
+
x_kernel = pdf / pdf.sum()
|
28 |
+
x_kernel = x_kernel.to(device=img.device, dtype=img.dtype)
|
29 |
+
|
30 |
+
kernel2d = torch.mm(x_kernel[:, None], x_kernel[None, :])
|
31 |
+
kernel2d = kernel2d.expand(img.shape[-3], 1, kernel2d.shape[0], kernel2d.shape[1])
|
32 |
+
|
33 |
+
padding = [kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2]
|
34 |
+
img = F.pad(img, padding, mode="reflect")
|
35 |
+
img = F.conv2d(img, kernel2d, groups=img.shape[-3])
|
36 |
+
|
37 |
+
return img
|
38 |
+
|
39 |
+
blur_inf = '∞'
|
40 |
+
|
41 |
+
def contextual_forward(self, blur_sigma = 0.0):
|
42 |
+
|
43 |
+
self.blur_sigma = blur_sigma
|
44 |
+
|
45 |
+
def forward_modified(
|
46 |
+
hidden_states: torch.FloatTensor,
|
47 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
48 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
49 |
+
temb: Optional[torch.FloatTensor] = None,
|
50 |
+
) -> torch.FloatTensor:
|
51 |
+
|
52 |
+
dimension_squared = hidden_states.shape[1]
|
53 |
+
|
54 |
+
is_cross = not encoder_hidden_states is None
|
55 |
+
|
56 |
+
residual = hidden_states
|
57 |
+
if self.spatial_norm is not None:
|
58 |
+
hidden_states = self.spatial_norm(hidden_states, temb)
|
59 |
+
|
60 |
+
input_ndim = hidden_states.ndim
|
61 |
+
|
62 |
+
if input_ndim == 4:
|
63 |
+
batch_size, channel, height, width = hidden_states.shape
|
64 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
65 |
+
|
66 |
+
batch_size, sequence_length, _ = (
|
67 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
68 |
+
)
|
69 |
+
|
70 |
+
if attention_mask is not None:
|
71 |
+
attention_mask = self.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
72 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
73 |
+
# (batch, heads, source_length, target_length)
|
74 |
+
attention_mask = attention_mask.view(batch_size, self.heads, -1, attention_mask.shape[-1])
|
75 |
+
|
76 |
+
if self.group_norm is not None:
|
77 |
+
hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
78 |
+
|
79 |
+
query = self.to_q(hidden_states)
|
80 |
+
|
81 |
+
if encoder_hidden_states is None:
|
82 |
+
encoder_hidden_states = hidden_states
|
83 |
+
elif self.norm_cross:
|
84 |
+
encoder_hidden_states = self.norm_encoder_hidden_states(encoder_hidden_states)
|
85 |
+
|
86 |
+
key = self.to_k(encoder_hidden_states)
|
87 |
+
value = self.to_v(encoder_hidden_states)
|
88 |
+
|
89 |
+
inner_dim = key.shape[-1]
|
90 |
+
head_dim = inner_dim // self.heads
|
91 |
+
|
92 |
+
query = query.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
|
93 |
+
|
94 |
+
key = key.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
|
95 |
+
value = value.view(batch_size, -1, self.heads, head_dim).transpose(1, 2)
|
96 |
+
|
97 |
+
height = width = math.isqrt(query.shape[2])
|
98 |
+
|
99 |
+
|
100 |
+
if not is_cross and (self.blur_sigma == blur_inf or self.blur_sigma > 0):
|
101 |
+
|
102 |
+
# based of empirical findings
|
103 |
+
# 8x8 and 16x16
|
104 |
+
allowed_res = [pipe.unet.config.sample_size // 4, pipe.unet.config.sample_size // 8]
|
105 |
+
|
106 |
+
if (dimension_squared == allowed_res[0] * allowed_res[0] or dimension_squared == allowed_res[1] * allowed_res[1]):
|
107 |
+
|
108 |
+
query_uncond, query_org, query_ptb = query.chunk(3)
|
109 |
+
query_ptb = query_ptb.permute(0, 1, 3, 2).view(batch_size//3, self.heads * head_dim, height, width)
|
110 |
+
|
111 |
+
if self.blur_sigma != blur_inf:
|
112 |
+
kernel_size = math.ceil(6 * self.blur_sigma) + 1 - math.ceil(6 * self.blur_sigma) % 2
|
113 |
+
query_ptb = gaussian_blur_2d(query_ptb, kernel_size, self.blur_sigma)
|
114 |
+
else:
|
115 |
+
query_ptb[:] = query_ptb.mean(dim=(-2, -1), keepdim=True)
|
116 |
+
|
117 |
+
query_ptb = query_ptb.view(batch_size//3, self.heads, head_dim, height * width).permute(0, 1, 3, 2)
|
118 |
+
query = torch.cat((query_uncond, query_org, query_ptb), dim=0)
|
119 |
+
|
120 |
+
|
121 |
+
|
122 |
+
hidden_states = F.scaled_dot_product_attention(
|
123 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False,
|
124 |
+
)
|
125 |
+
|
126 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, self.heads * head_dim)
|
127 |
+
hidden_states = hidden_states.to(query.dtype)
|
128 |
+
|
129 |
+
# linear proj
|
130 |
+
hidden_states = self.to_out[0](hidden_states)
|
131 |
+
# dropout
|
132 |
+
hidden_states = self.to_out[1](hidden_states)
|
133 |
+
|
134 |
+
if input_ndim == 4:
|
135 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
136 |
+
|
137 |
+
if self.residual_connection:
|
138 |
+
hidden_states = hidden_states + residual
|
139 |
+
|
140 |
+
hidden_states = hidden_states / self.rescale_output_factor
|
141 |
+
|
142 |
+
return hidden_states
|
143 |
+
|
144 |
+
return forward_modified
|
145 |
+
|
146 |
+
def apply_seg(unet, child = None, blur_sigma=1.0):
|
147 |
+
if child == None:
|
148 |
+
children = unet.named_children()
|
149 |
+
for child in children:
|
150 |
+
apply_seg(unet, child[1], blur_sigma=blur_sigma)
|
151 |
+
else:
|
152 |
+
if child.__class__.__name__ == 'Attention':
|
153 |
+
child.forward = contextual_forward(child, blur_sigma=blur_sigma)
|
154 |
+
elif hasattr(child, 'children'):
|
155 |
+
for sub_child in child.children():
|
156 |
+
apply_seg(unet, sub_child, blur_sigma=blur_sigma)
|
157 |
+
|
158 |
+
def sample(prompt, cfg = 7.5, blur_sigma = blur_inf, seed=123, steps=50, signal_scale = 1.0):
|
159 |
+
|
160 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id)
|
161 |
+
|
162 |
+
scheduler = DDIMScheduler.from_pretrained(model_id, subfolder="scheduler")
|
163 |
+
|
164 |
+
pipe = pipe.to("cuda")
|
165 |
+
|
166 |
+
guidance_scale = cfg
|
167 |
+
num_inference_steps = steps
|
168 |
+
scheduler.set_timesteps(num_inference_steps, device="cuda")
|
169 |
+
timesteps = scheduler.timesteps
|
170 |
+
|
171 |
+
shape = (1, pipe.unet.in_channels, pipe.unet.config.sample_size, pipe.unet.config.sample_size)
|
172 |
+
latents = torch.randn(shape, generator=torch.Generator(device="cuda").manual_seed(seed), device="cuda").to("cuda")
|
173 |
+
|
174 |
+
prompt_cond = pipe.encode_prompt(prompt=prompt, device="cuda", num_images_per_prompt=1, do_classifier_free_guidance=False)[0]
|
175 |
+
prompt_uncond = pipe.encode_prompt(prompt="", device="cuda", num_images_per_prompt=1, do_classifier_free_guidance=False)[0]
|
176 |
+
|
177 |
+
prompt_embeds_combined = torch.cat([prompt_uncond, prompt_cond, prompt_cond])
|
178 |
+
|
179 |
+
with torch.no_grad():
|
180 |
+
|
181 |
+
apply_seg(pipe.unet, blur_sigma=blur_sigma)
|
182 |
+
|
183 |
+
for i, t in tqdm(enumerate(timesteps), total=len(timesteps), desc="Inference steps"):
|
184 |
+
|
185 |
+
latent_model_input = torch.cat([latents] * 3)
|
186 |
+
|
187 |
+
noise_pred = pipe.unet(
|
188 |
+
latent_model_input,
|
189 |
+
t,
|
190 |
+
encoder_hidden_states=prompt_embeds_combined,
|
191 |
+
cross_attention_kwargs=None,
|
192 |
+
return_dict=False,
|
193 |
+
)[0]
|
194 |
+
|
195 |
+
noise_pred_uncond, noise_pred_cond, noise_pred_cond_perturb = noise_pred.chunk(3)
|
196 |
+
|
197 |
+
# Classfier Free Guidance
|
198 |
+
noise_cfg = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
199 |
+
|
200 |
+
# Smoothed Energy Guidance
|
201 |
+
noise_pred = noise_cfg + signal_scale * (noise_pred_cond - noise_pred_cond_perturb)
|
202 |
+
|
203 |
+
latents = scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
204 |
+
|
205 |
+
image = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]
|
206 |
+
image_cpu = image.squeeze(0).float().permute(1, 2, 0).detach().cpu()
|
207 |
+
image_cpu = (image_cpu / 2 + 0.5).clamp(0, 1)
|
208 |
+
|
209 |
+
return (image_cpu, cfg, blur_sigma)
|
210 |
+
|
211 |
+
|
212 |
+
def gradio_generate(prompt: str, cfg: float, blur_sigma: float):
|
213 |
+
# run your sample() and get back a torch.Tensor in [0–1]
|
214 |
+
image_tensor, _, _ = sample(prompt, cfg=cfg, blur_sigma=blur_sigma, seed=123, steps=50, signal_scale=1.0)
|
215 |
+
# to HxWxC uint8
|
216 |
+
image_np = (image_tensor.cpu().numpy() * 255).round().astype(np.uint8)
|
217 |
+
return image_np
|
218 |
+
|
219 |
+
examples = [
|
220 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
221 |
+
"An astronaut riding a green horse",
|
222 |
+
"A delicious ceviche cheesecake slice",
|
223 |
+
]
|
224 |
+
|
225 |
+
css="""
|
226 |
+
#col-container {
|
227 |
+
margin: 0 auto;
|
228 |
+
max-width: 580px;
|
229 |
+
}
|
230 |
+
"""
|
231 |
+
|
232 |
+
with gr.Blocks(css=css) as demo:
|
233 |
+
with gr.Column(elem_id="col-container"):
|
234 |
+
prompt_in = gr.Textbox(
|
235 |
+
label="Prompt",
|
236 |
+
placeholder="Type your prompt here...",
|
237 |
+
lines=2
|
238 |
+
)
|
239 |
+
|
240 |
+
image_out = gr.Image(
|
241 |
+
label="Generated Image",
|
242 |
+
type="numpy"
|
243 |
+
)
|
244 |
+
|
245 |
+
with gr.Row():
|
246 |
+
cfg_slider = gr.Slider(
|
247 |
+
minimum=1.0, maximum=20.0, value=7.5, step=0.1,
|
248 |
+
label="CFG Scale"
|
249 |
+
)
|
250 |
+
blur_slider = gr.Slider(
|
251 |
+
minimum=0.0, maximum=10.0, value=10.0, step=0.1,
|
252 |
+
label="Blur σ"
|
253 |
+
)
|
254 |
+
|
255 |
+
generate_btn = gr.Button("Generate")
|
256 |
+
|
257 |
+
gr.Examples(
|
258 |
+
examples = examples,
|
259 |
+
inputs = [prompt_in]
|
260 |
+
)
|
261 |
+
|
262 |
+
# wire up
|
263 |
+
generate_btn.click(
|
264 |
+
fn=gradio_generate,
|
265 |
+
inputs=[prompt_in, cfg_slider, blur_slider],
|
266 |
+
outputs=image_out
|
267 |
+
)
|
268 |
+
|
269 |
+
|
270 |
+
demo.launch()
|
271 |
+
|