tetrisd commited on
Commit
5780ef2
β€’
1 Parent(s): 31ccd79

Improve efficiency

Browse files
app.py CHANGED
@@ -1,15 +1,159 @@
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
5
 
6
- def predict(image):
7
- predictions = pipeline(image)
8
- return {p["label"]: p["score"] for p in predictions}
9
 
10
- gr.Interface(
11
- predict,
12
- inputs=gr.inputs.Image(label="Upload hot dog candidate", type="filepath"),
13
- outputs=gr.outputs.Label(num_top_classes=2),
14
- title="Hot Dog? Or Not?",
15
- ).launch()
 
1
+ from threading import Lock
2
+ import math
3
+ import os
4
+ import random
5
+
6
+ from diffusers import StableDiffusionPipeline
7
+ from diffusers.models.attention import get_global_heat_map, clear_heat_maps
8
+ from matplotlib import pyplot as plt
9
  import gradio as gr
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import spacy
13
+
14
+
15
+ if not os.environ.get('NO_DOWNLOAD_SPACY'):
16
+ spacy.cli.download('en_core_web_sm')
17
+
18
+
19
+ model_id = "CompVis/stable-diffusion-v1-4"
20
+ device = "cuda"
21
+
22
+ gen = torch.Generator(device='cuda')
23
+ gen.manual_seed(12758672)
24
+ orig_state = gen.get_state()
25
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True).to(device)
26
+ lock = Lock()
27
+ nlp = spacy.load('en_core_web_sm')
28
+
29
+
30
+ def expand_m(m, n: int = 1, o=512, mode='bicubic'):
31
+ m = m.unsqueeze(0).unsqueeze(0) / n
32
+ m = F.interpolate(m.float().detach(), size=(o, o), mode='bicubic', align_corners=False)
33
+ m = (m - m.min()) / (m.max() - m.min() + 1e-8)
34
+ m = m.cpu().detach()
35
+
36
+ return m
37
+
38
+
39
+ @torch.no_grad()
40
+ def predict(prompt, inf_steps, threshold):
41
+ global lock
42
+ with torch.cuda.amp.autocast(), lock:
43
+ try:
44
+ plt.close('all')
45
+ except:
46
+ pass
47
+
48
+ gen.set_state(orig_state.clone())
49
+ clear_heat_maps()
50
+
51
+ out = pipe(prompt, guidance_scale=7.5, height=512, width=512, do_intermediates=False, generator=gen, num_inference_steps=int(inf_steps))
52
+ heat_maps = get_global_heat_map()
53
+
54
+ with torch.cuda.amp.autocast(dtype=torch.float32):
55
+ m = 0
56
+ n = 0
57
+ w = ''
58
+ w_idx = 0
59
+
60
+ fig, ax = plt.subplots()
61
+ ax.imshow(out.images[0].cpu().float().detach().permute(1, 2, 0).numpy())
62
+ ax.set_xticks([])
63
+ ax.set_yticks([])
64
+
65
+ fig1, axs1 = plt.subplots(math.ceil(len(out.words) / 4), 4)#, figsize=(20, 20))
66
+ fig2, axs2 = plt.subplots(math.ceil(len(out.words) / 4), 4) # , figsize=(20, 20))
67
+
68
+ for idx in range(len(out.words) + 1):
69
+ if idx == 0:
70
+ continue
71
+
72
+ word = out.words[idx - 1]
73
+ m += heat_maps[idx]
74
+ n += 1
75
+ w += word
76
+
77
+ if '</w>' not in word:
78
+ continue
79
+ else:
80
+ mplot = expand_m(m, n)
81
+ spotlit_im = out.images[0].cpu().float().detach()
82
+ w = w.replace('</w>', '')
83
+ spotlit_im2 = torch.cat((spotlit_im, (1 - mplot.squeeze(0)).pow(1)), dim=0)
84
+
85
+ if len(out.words) <= 4:
86
+ a1 = axs1[w_idx % 4]
87
+ a2 = axs2[w_idx % 4]
88
+ else:
89
+ a1 = axs1[w_idx // 4, w_idx % 4]
90
+ a2 = axs2[w_idx // 4, w_idx % 4]
91
+
92
+ a1.set_xticks([])
93
+ a1.set_yticks([])
94
+ a1.imshow(mplot.squeeze().numpy(), cmap='jet')
95
+ a1.imshow(spotlit_im2.permute(1, 2, 0).numpy())
96
+ a1.set_title(w)
97
+
98
+ mask = torch.ones_like(mplot)
99
+ mask[mplot < threshold * mplot.max()] = 0
100
+ im2 = spotlit_im * mask.squeeze(0)
101
+ a2.set_xticks([])
102
+ a2.set_yticks([])
103
+ a2.imshow(im2.permute(1, 2, 0).numpy())
104
+ a2.set_title(w)
105
+ m = 0
106
+ n = 0
107
+ w_idx += 1
108
+ w = ''
109
+
110
+ for idx in range(w_idx, len(axs1.flatten())):
111
+ fig1.delaxes(axs1.flatten()[idx])
112
+ fig2.delaxes(axs2.flatten()[idx])
113
+
114
+ return fig, fig1, fig2
115
+
116
+
117
+ def set_prompt(prompt):
118
+ return prompt
119
+
120
+
121
+ with gr.Blocks() as demo:
122
+ md = '''# DAAM: Attention Maps for Interpreting Stable Diffusion
123
+ Check out the paper: [What the DAAM: Interpreting Stable Diffusion Using Cross Attention](http://arxiv.org/abs/2210.04885).
124
+ '''
125
+ gr.Markdown(md)
126
+
127
+ with gr.Row():
128
+ with gr.Column():
129
+ dropdown = gr.Dropdown([
130
+ 'An angry, bald man doing research',
131
+ 'Doing research at Comcast Applied AI labs',
132
+ 'Professor Jimmy Lin from the University of Waterloo',
133
+ 'Yann Lecun teaching machine learning on a chalkboard',
134
+ 'A cat eating cake for her birthday',
135
+ 'Steak and dollars on a plate',
136
+ 'A fox, a dog, and a wolf in a field'
137
+ ], label='Examples', value='An angry, bald man doing research')
138
+
139
+ text = gr.Textbox(label='Prompt', value='An angry, bald man doing research')
140
+ slider1 = gr.Slider(15, 35, value=25, interactive=True, step=1, label='Inference steps')
141
+ slider2 = gr.Slider(0, 1.0, value=0.4, interactive=True, step=0.05, label='Threshold (tau)')
142
+ submit_btn = gr.Button('Submit')
143
+
144
+ with gr.Tab('Original Image'):
145
+ p0 = gr.Plot()
146
+
147
+ with gr.Tab('Soft DAAM Maps'):
148
+ p1 = gr.Plot()
149
+
150
+ with gr.Tab('Hard DAAM Maps'):
151
+ p2 = gr.Plot()
152
+
153
+ submit_btn.click(fn=predict, inputs=[text, slider1, slider2], outputs=[p0, p1, p2])
154
+ dropdown.change(set_prompt, dropdown, text)
155
+ dropdown.update()
156
 
 
157
 
158
+ demo.launch()#server_name='0.0.0.0', server_port=8080)
 
 
159
 
 
 
 
 
 
 
diffusers/models/attention.py CHANGED
@@ -324,12 +324,12 @@ class CrossAttention(nn.Module):
324
  for map_ in x:
325
  map_ = map_.unsqueeze(1).view(map_.size(0), 1, h, w)
326
  if method == 'bicubic':
327
- map_ = F.interpolate(map_, size=(55, 55), mode="bicubic", align_corners=False)
328
  maps.append(map_.squeeze(1))
329
  else:
330
  maps.append(F.conv_transpose2d(map_, weight, stride=factor).squeeze(1).cpu())
331
 
332
- maps = torch.stack(maps, 0).cpu()
333
  return maps
334
 
335
  def _attention(self, query, key, value, sequence_length, dim, use_context: bool = True):
@@ -347,7 +347,7 @@ class CrossAttention(nn.Module):
347
  factor = int(math.sqrt(4096 // attn_slice.shape[1]))
348
  attn_slice = attn_slice.softmax(-1)
349
 
350
- if use_context:
351
  if factor >= 1:
352
  factor //= 1
353
  maps = self._up_sample_attn(attn_slice, factor)
 
324
  for map_ in x:
325
  map_ = map_.unsqueeze(1).view(map_.size(0), 1, h, w)
326
  if method == 'bicubic':
327
+ map_ = F.interpolate(map_, size=(64, 64), mode="bicubic", align_corners=False)
328
  maps.append(map_.squeeze(1))
329
  else:
330
  maps.append(F.conv_transpose2d(map_, weight, stride=factor).squeeze(1).cpu())
331
 
332
+ maps = torch.stack(maps, 0).sum(1, keepdim=True).cpu()
333
  return maps
334
 
335
  def _attention(self, query, key, value, sequence_length, dim, use_context: bool = True):
 
347
  factor = int(math.sqrt(4096 // attn_slice.shape[1]))
348
  attn_slice = attn_slice.softmax(-1)
349
 
350
+ if use_context and attn_slice.shape[-1] == 77:
351
  if factor >= 1:
352
  factor //= 1
353
  maps = self._up_sample_attn(attn_slice, factor)
diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py CHANGED
@@ -346,4 +346,8 @@ class StableDiffusionPipeline(DiffusionPipeline):
346
  if not return_dict:
347
  return (image, has_nsfw_concept)
348
 
 
 
 
 
349
  return StableDiffusionPipelineOutput(images=gpu_image, pil_images=image, nsfw_content_detected=has_nsfw_concept, text_embeddings=text_embeddings, words=words, intermediates=inters)
 
346
  if not return_dict:
347
  return (image, has_nsfw_concept)
348
 
349
+ if any(has_nsfw_concept):
350
+ gpu_image.zero_()
351
+ image[0] = None
352
+
353
  return StableDiffusionPipelineOutput(images=gpu_image, pil_images=image, nsfw_content_detected=has_nsfw_concept, text_embeddings=text_embeddings, words=words, intermediates=inters)
diffusers/pipelines/stable_diffusion/safety_checker.py CHANGED
@@ -72,6 +72,7 @@ class StableDiffusionSafetyChecker(PreTrainedModel):
72
  images[idx] = np.zeros(images[idx].shape) # black image
73
 
74
  if any(has_nsfw_concepts):
 
75
  logger.warning(
76
  "Potential NSFW content was detected in one or more images. A black image will be returned instead."
77
  " Try again with a different prompt and/or seed."
 
72
  images[idx] = np.zeros(images[idx].shape) # black image
73
 
74
  if any(has_nsfw_concepts):
75
+ images = []
76
  logger.warning(
77
  "Potential NSFW content was detected in one or more images. A black image will be returned instead."
78
  " Try again with a different prompt and/or seed."
requirements.txt CHANGED
@@ -24,3 +24,6 @@ tensorboard
24
  torch>=1.4
25
  torchvision
26
  transformers>=4.21.0
 
 
 
 
24
  torch>=1.4
25
  torchvision
26
  transformers>=4.21.0
27
+ spacy
28
+ gradio
29
+ ftfy