arjun1agar commited on
Commit
8a5ad73
·
verified ·
1 Parent(s): d211ab4

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,12 @@
1
  ---
2
- title: Ms Diffusion Multisubject
3
- emoji: 📉
4
- colorFrom: green
5
- colorTo: blue
6
  sdk: gradio
7
- sdk_version: 6.20.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
 
11
  ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: MS-Diffusion Multi-Subject
3
+ emoji: 🎬
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 4.44.1
 
8
  app_file: app.py
9
  pinned: false
10
+ short_description: Layout-guided multi-subject test
11
  ---
12
+ Test Space wrapping MS-Diffusion (ICLR 2025) for multi-subject character consistency.
 
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import spaces
3
+ import torch
4
+ import gradio as gr
5
+ from PIL import Image
6
+ from huggingface_hub import hf_hub_download
7
+ from diffusers import StableDiffusionXLPipeline
8
+ from transformers import CLIPVisionModelWithProjection, CLIPImageProcessor
9
+
10
+ from msdiffusion.models.projection import Resampler
11
+ from msdiffusion.models.model import MSAdapter
12
+ from msdiffusion.utils import get_phrase_idx, get_eot_idx
13
+
14
+ BASE = "stabilityai/stable-diffusion-xl-base-1.0"
15
+ IMG_ENC = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
16
+ NUM_TOKENS = 16
17
+ DTYPE = torch.float16
18
+
19
+ print("loading SDXL…")
20
+ pipe = StableDiffusionXLPipeline.from_pretrained(BASE, torch_dtype=DTYPE, add_watermarker=False)
21
+ print("loading CLIP image encoder…")
22
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(IMG_ENC, torch_dtype=DTYPE)
23
+ image_processor = CLIPImageProcessor()
24
+
25
+ print("building resampler + MSAdapter…")
26
+ image_proj_model = Resampler(
27
+ dim=1280, depth=4, dim_head=64, heads=20, num_queries=NUM_TOKENS,
28
+ embedding_dim=image_encoder.config.hidden_size,
29
+ output_dim=pipe.unet.config.cross_attention_dim, ff_mult=4,
30
+ latent_init_mode="grounding",
31
+ phrase_embeddings_dim=pipe.text_encoder.config.projection_dim,
32
+ ).to(dtype=DTYPE)
33
+ ms_ckpt = hf_hub_download("doge1516/MS-Diffusion", "ms_adapter.bin")
34
+ ms_model = MSAdapter(pipe.unet, image_proj_model, ckpt_path=ms_ckpt, device="cpu", num_tokens=NUM_TOKENS)
35
+ ms_model.to(dtype=DTYPE)
36
+ print("models ready (CPU); GPU attaches per-call.")
37
+
38
+
39
+ def _phrase_idxes(phrases, prompt):
40
+ res, cnt = [], {}
41
+ for ph in phrases:
42
+ k = cnt.get(ph, 0); cnt[ph] = k + 1
43
+ res.append(get_phrase_idx(pipe.tokenizer, ph, prompt, num=k)[0])
44
+ return res
45
+
46
+
47
+ @spaces.GPU(duration=150)
48
+ def generate(prompt, image1, image2, phrase1, phrase2, box1, box2, scale, seed, steps):
49
+ dev = "cuda"
50
+ pipe.to(dev); image_encoder.to(dev, dtype=DTYPE); ms_model.to(dev, dtype=DTYPE)
51
+
52
+ subs, phrases, boxes = [], [], []
53
+ for img, ph, bx in ((image1, phrase1, box1), (image2, phrase2, box2)):
54
+ if img is None:
55
+ continue
56
+ subs.append(Image.fromarray(img).convert("RGB").resize((512, 512)))
57
+ phrases.append(ph.strip())
58
+ boxes.append([float(x) for x in bx.split(",")])
59
+ if not subs:
60
+ raise gr.Error("Provide at least one subject image.")
61
+
62
+ phrase_idxes = [_phrase_idxes(phrases, prompt)]
63
+ eot_idxes = [[get_eot_idx(pipe.tokenizer, prompt)] * len(phrases)]
64
+
65
+ images = ms_model.generate(
66
+ pipe=pipe, pil_images=[subs], num_samples=1,
67
+ num_inference_steps=int(steps), seed=int(seed), prompt=[prompt], scale=float(scale),
68
+ image_encoder=image_encoder, image_processor=image_processor, boxes=[boxes],
69
+ image_proj_type="resampler", image_encoder_type="clip",
70
+ phrases=[phrases], drop_grounding_tokens=[0],
71
+ phrase_idxes=phrase_idxes, eot_idxes=eot_idxes,
72
+ height=1024, width=1024,
73
+ mask_threshold=0.5, start_step=5,
74
+ )
75
+ return images[0]
76
+
77
+
78
+ demo = gr.Interface(
79
+ fn=generate,
80
+ inputs=[
81
+ gr.Textbox(label="prompt", value="two men sitting in a restaurant at night, cinematic film still"),
82
+ gr.Image(label="subject 1"), gr.Image(label="subject 2"),
83
+ gr.Textbox(label="phrase 1", value="a man"), gr.Textbox(label="phrase 2", value="a man"),
84
+ gr.Textbox(label="box 1 (x1,y1,x2,y2 norm)", value="0.0,0.25,0.45,0.95"),
85
+ gr.Textbox(label="box 2", value="0.55,0.25,1.0,0.95"),
86
+ gr.Slider(0.0, 1.0, value=0.6, label="scale"),
87
+ gr.Number(value=42, label="seed"), gr.Slider(10, 50, value=30, step=1, label="steps"),
88
+ ],
89
+ outputs=gr.Image(label="result"),
90
+ title="MS-Diffusion — layout-guided multi-subject",
91
+ )
92
+ demo.queue(max_size=6).launch()
msdiffusion/__init__.py ADDED
File without changes
msdiffusion/dataset/__init__.py ADDED
File without changes
msdiffusion/models/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .model import MSAdapter
2
+
3
+ __all__ = [
4
+ "MSAdapter",
5
+ ]
msdiffusion/models/attention_processor.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py
2
+ # and https://github.com/tencent-ailab/IP-Adapter/blob/main/ip_adapter/attention_processor.py
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def minmax_normalize(batch_maps):
9
+ min_val = batch_maps.min(dim=-1, keepdim=True)[0].min(dim=-2, keepdim=True)[0]
10
+ max_val = batch_maps.max(dim=-1, keepdim=True)[0].max(dim=-2, keepdim=True)[0]
11
+
12
+ return (batch_maps - min_val) / (max_val - min_val + 1e-5)
13
+
14
+
15
+ class AttnProcessor2_0(torch.nn.Module):
16
+ r"""
17
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ hidden_size=None,
23
+ cross_attention_dim=None,
24
+ ):
25
+ super().__init__()
26
+ if not hasattr(F, "scaled_dot_product_attention"):
27
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
28
+
29
+ def __call__(
30
+ self,
31
+ attn,
32
+ hidden_states,
33
+ encoder_hidden_states=None,
34
+ attention_mask=None,
35
+ temb=None,
36
+ boxes=None,
37
+ phrase_idxes=None,
38
+ eot_idxes=None,
39
+ ):
40
+ residual = hidden_states
41
+
42
+ if attn.spatial_norm is not None:
43
+ hidden_states = attn.spatial_norm(hidden_states, temb)
44
+
45
+ input_ndim = hidden_states.ndim
46
+
47
+ if input_ndim == 4:
48
+ batch_size, channel, height, width = hidden_states.shape
49
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
50
+
51
+ batch_size, sequence_length, _ = (
52
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
53
+ )
54
+
55
+ if attention_mask is not None:
56
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
57
+ # scaled_dot_product_attention expects attention_mask shape to be
58
+ # (batch, heads, source_length, target_length)
59
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
60
+
61
+ if attn.group_norm is not None:
62
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
63
+
64
+ query = attn.to_q(hidden_states)
65
+
66
+ if encoder_hidden_states is None:
67
+ encoder_hidden_states = hidden_states
68
+ elif attn.norm_cross:
69
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
70
+
71
+ key = attn.to_k(encoder_hidden_states)
72
+ value = attn.to_v(encoder_hidden_states)
73
+
74
+ inner_dim = key.shape[-1]
75
+ head_dim = inner_dim // attn.heads
76
+
77
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
78
+
79
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
80
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
81
+
82
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
83
+ # TODO: add support for attn.scale when we move to Torch 2.1
84
+ hidden_states = F.scaled_dot_product_attention(
85
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
86
+ )
87
+
88
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
89
+ hidden_states = hidden_states.to(query.dtype)
90
+
91
+ # linear proj
92
+ hidden_states = attn.to_out[0](hidden_states)
93
+ # dropout
94
+ hidden_states = attn.to_out[1](hidden_states)
95
+
96
+ if input_ndim == 4:
97
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
98
+
99
+ if attn.residual_connection:
100
+ hidden_states = hidden_states + residual
101
+
102
+ hidden_states = hidden_states / attn.rescale_output_factor
103
+
104
+ return hidden_states
105
+
106
+
107
+ class MaskedIPAttnProcessor2_0(nn.Module):
108
+
109
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4, text_tokens=77,
110
+ need_text_attention_map=False, need_image_attention_map=True, num_dummy_tokens=4, mask_threshold=0.5,
111
+ use_psuedo_attention_mask=False, subject_scales=None, start_step=5):
112
+ super().__init__()
113
+
114
+ if not hasattr(F, "scaled_dot_product_attention"):
115
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
116
+
117
+ self.hidden_size = hidden_size
118
+ self.cross_attention_dim = cross_attention_dim
119
+ self.scale = scale
120
+ self.num_tokens = num_tokens
121
+ self.text_tokens = text_tokens
122
+ self.num_dummy_tokens = num_dummy_tokens
123
+ self.mask_threshold = mask_threshold
124
+ self.subject_scales = subject_scales
125
+ self.start_step = start_step
126
+
127
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
128
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
129
+
130
+ self.need_text_attention_map = need_text_attention_map
131
+ self.need_image_attention_map = need_image_attention_map
132
+
133
+ self.use_psuedo_attention_mask = use_psuedo_attention_mask
134
+ self.attention_maps = []
135
+
136
+ def prepare_attention_mask_qk(self, boxes, phrase_idxes, sequence_length_q, sequence_length_k,
137
+ batch_size, head_size, dtype, device, use_masked_text_attention=False):
138
+ if boxes is None:
139
+ return None, None
140
+
141
+ # TODO: only support square image now
142
+ num_patches_per_row = int(sequence_length_q ** 0.5)
143
+ box_idxes_start = torch.floor(boxes[:, :, 0:2] * num_patches_per_row)
144
+ box_idxes_end = torch.ceil(boxes[:, :, 2:4] * num_patches_per_row)
145
+ box_idxes = torch.cat([box_idxes_start, box_idxes_end], dim=-1)
146
+ box_masks = []
147
+ dummy_attention_mask = torch.ones((batch_size, sequence_length_q), dtype=dtype, device=device)
148
+ for box_idx in box_idxes.unbind(dim=1):
149
+ x_start_patch_idx, y_start_patch_idx, x_end_patch_idx, y_end_patch_idx = box_idx.unbind(dim=1)
150
+ x_indices = torch.arange(num_patches_per_row).unsqueeze(0).expand(batch_size, -1).to(device)
151
+ y_indices = torch.arange(num_patches_per_row).unsqueeze(0).expand(batch_size, -1).to(device)
152
+ x_mask = ((x_indices >= x_start_patch_idx.unsqueeze(1)) & (x_indices < x_end_patch_idx.unsqueeze(1))).to(dtype)
153
+ y_mask = ((y_indices >= y_start_patch_idx.unsqueeze(1)) & (y_indices < y_end_patch_idx.unsqueeze(1))).to(dtype)
154
+ box_mask = torch.bmm(y_mask.unsqueeze(2), x_mask.unsqueeze(1)).reshape(batch_size, -1)
155
+ box_masks.append(box_mask)
156
+ dummy_attention_mask = torch.clamp(dummy_attention_mask - box_mask, min=0)
157
+
158
+ # post mask
159
+ post_dummy_attention_mask = dummy_attention_mask.to(torch.bool)
160
+ post_dummy_attention_mask = post_dummy_attention_mask.repeat_interleave(head_size, dim=0)
161
+
162
+ attention_mask_qk_image = torch.stack(box_masks, dim=-1)
163
+ attention_mask_qk_image = attention_mask_qk_image.repeat_interleave(self.num_tokens, dim=-1)
164
+ attention_mask_qk_image = (1 - attention_mask_qk_image.to(dtype)) * -10000.0 # mask to bias
165
+ # use dummy image tokens to process the background
166
+ dummy_attention_mask = dummy_attention_mask.unsqueeze(-1).repeat_interleave(self.num_dummy_tokens, dim=-1)
167
+ dummy_attention_mask = (1 - dummy_attention_mask) * -10000.0
168
+ attention_mask_qk_image = torch.cat([dummy_attention_mask, attention_mask_qk_image], dim=-1)
169
+ if attention_mask_qk_image.shape[0] < batch_size*head_size:
170
+ attention_mask_qk_image = attention_mask_qk_image.repeat_interleave(head_size, dim=0)
171
+
172
+ if use_masked_text_attention:
173
+ attention_mask_qk_text = torch.ones((batch_size, sequence_length_q, sequence_length_k), dtype=dtype, device=device)
174
+ for i in range(batch_size):
175
+ for j in range(len(box_masks)):
176
+ start_idx, end_idx = int(phrase_idxes[i, j, 0].item()), int(phrase_idxes[i, j, 1].item())
177
+ if start_idx == 0 and end_idx == 0:
178
+ continue
179
+ attention_mask_qk_text[i, :, start_idx:end_idx] = box_masks[j][i, ...].unsqueeze(-1)
180
+ attention_mask_qk_text = (1 - attention_mask_qk_text) * -10000.0
181
+ if attention_mask_qk_text.shape[0] < batch_size*head_size:
182
+ attention_mask_qk_text = attention_mask_qk_text.repeat_interleave(head_size, dim=0)
183
+ else:
184
+ attention_mask_qk_text = None
185
+
186
+ return attention_mask_qk_image, attention_mask_qk_text, post_dummy_attention_mask
187
+
188
+ def get_text_attention_maps(self, attention_probs, boxes, phrase_idxes, head_size):
189
+ bsz = boxes.shape[0]
190
+ _, num_tokens_q, num_tokens_k = attention_probs.shape
191
+ attention_probs = attention_probs.view(bsz, head_size, num_tokens_q, num_tokens_k)
192
+ num_ref = boxes.shape[1]
193
+ h = w = int(num_tokens_q ** 0.5)
194
+ batch_attention_maps = []
195
+ for i in range(bsz):
196
+ sample_attention_maps = []
197
+ for j in range(num_ref):
198
+ start_idx, end_idx = int(phrase_idxes[i, j, 0].item()), int(phrase_idxes[i, j, 1].item())
199
+ if start_idx == 0 and end_idx == 0:
200
+ sample_attention_maps.append(
201
+ torch.zeros(num_tokens_q, dtype=attention_probs.dtype, device=attention_probs.device))
202
+ else:
203
+ attention_map = attention_probs[i, :, :,
204
+ start_idx:end_idx] # [num_heads, num_tokens_q, num_tokens_phrase]
205
+ attention_map = torch.mean(torch.mean(attention_map, dim=-1), dim=0) # [num_tokens_q]
206
+ sample_attention_maps.append(attention_map)
207
+ batch_attention_maps.append(torch.stack(sample_attention_maps))
208
+
209
+ self.attention_maps.append(torch.stack(batch_attention_maps).reshape(bsz, num_ref, h, w))
210
+
211
+ def get_psuedo_attention_mask(self, head_size):
212
+ # text_attention_maps = self.attention_maps[-1] # [bsz, num_ref, h, w]
213
+ if not self.use_psuedo_attention_mask or len(self.attention_maps) < self.start_step:
214
+ return None, None
215
+ text_attention_maps = torch.stack(self.attention_maps).mean(dim=0) # [bsz, num_ref, h, w]
216
+ text_attention_maps = minmax_normalize(text_attention_maps)
217
+ dtype, device = text_attention_maps.dtype, text_attention_maps.device
218
+ bsz, num_ref, h, w = text_attention_maps.shape
219
+ seq_len_q = h * w
220
+ text_attention_maps = text_attention_maps.view(bsz, num_ref, -1)
221
+ text_attention_maps = text_attention_maps.transpose(1, 2) # [bsz, h*w, num_ref]
222
+
223
+ # use threshold to get the mask
224
+ psuedo_attention_mask = (text_attention_maps > self.mask_threshold).to(dtype)
225
+ psuedo_dummy_attention_mask = torch.ones((bsz, seq_len_q), dtype=dtype, device=device)
226
+ for i in range(num_ref):
227
+ psuedo_box_mask = psuedo_attention_mask[..., i]
228
+ psuedo_dummy_attention_mask = torch.clamp(psuedo_dummy_attention_mask - psuedo_box_mask, min=0)
229
+
230
+ # post mask
231
+ post_psuedo_dummy_attention_mask = psuedo_dummy_attention_mask.to(torch.bool)
232
+ post_psuedo_dummy_attention_mask = post_psuedo_dummy_attention_mask.repeat_interleave(head_size, dim=0)
233
+
234
+ psuedo_attention_mask = psuedo_attention_mask.repeat_interleave(self.num_tokens, dim=-1)
235
+ psuedo_attention_mask = (1 - psuedo_attention_mask) * -10000.0 # mask to bias
236
+ psuedo_dummy_attention_mask = psuedo_dummy_attention_mask.unsqueeze(-1).repeat_interleave(self.num_dummy_tokens, dim=-1)
237
+ psuedo_dummy_attention_mask = (1 - psuedo_dummy_attention_mask) * -10000.0
238
+ psuedo_attention_mask = torch.cat([psuedo_dummy_attention_mask, psuedo_attention_mask], dim=-1)
239
+ if psuedo_attention_mask.shape[0] < bsz * head_size:
240
+ psuedo_attention_mask = psuedo_attention_mask.repeat_interleave(head_size, dim=0)
241
+
242
+ return psuedo_attention_mask, post_psuedo_dummy_attention_mask
243
+
244
+ def __call__(
245
+ self,
246
+ attn,
247
+ hidden_states,
248
+ encoder_hidden_states=None,
249
+ attention_mask=None,
250
+ temb=None,
251
+ boxes=None,
252
+ phrase_idxes=None,
253
+ eot_idxes=None,
254
+ ):
255
+ residual = hidden_states
256
+
257
+ if attn.spatial_norm is not None:
258
+ hidden_states = attn.spatial_norm(hidden_states, temb)
259
+
260
+ input_ndim = hidden_states.ndim
261
+
262
+ if input_ndim == 4:
263
+ batch_size, channel, height, width = hidden_states.shape
264
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
265
+
266
+ batch_size, sequence_length, _ = (
267
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
268
+ )
269
+
270
+ if attention_mask is not None:
271
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
272
+ # scaled_dot_product_attention expects attention_mask shape to be
273
+ # (batch, heads, source_length, target_length)
274
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
275
+ rf_attention_mask = None
276
+ custom_attention_masks = self.prepare_attention_mask_qk(boxes, phrase_idxes, hidden_states.shape[1],
277
+ self.text_tokens, batch_size, attn.heads,
278
+ hidden_states.dtype, hidden_states.device,
279
+ use_masked_text_attention=False)
280
+ attention_mask_qk_image, attention_mask_qk_text, dummy_attention_mask = custom_attention_masks
281
+ if attention_mask_qk_image is not None:
282
+ attention_mask_qk_image = attention_mask_qk_image.view(batch_size, attn.heads, -1, attention_mask_qk_image.shape[-1])
283
+ if attention_mask_qk_text is not None:
284
+ attention_mask_qk_text = attention_mask_qk_text.view(batch_size, attn.heads, -1, attention_mask_qk_text.shape[-1])
285
+
286
+ if attn.group_norm is not None:
287
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
288
+
289
+ query = attn.to_q(hidden_states)
290
+
291
+ if encoder_hidden_states is None:
292
+ encoder_hidden_states = hidden_states
293
+ else:
294
+ # get encoder_hidden_states, ip_hidden_states
295
+ # end_pos = encoder_hidden_states.shape[1] - self.num_tokens
296
+ end_pos = self.text_tokens
297
+ encoder_hidden_states, ip_hidden_states = (
298
+ encoder_hidden_states[:, :end_pos, :],
299
+ encoder_hidden_states[:, end_pos:, :],
300
+ )
301
+ attention_mask, rf_attention_mask = (
302
+ attention_mask[:, :, :, :end_pos],
303
+ attention_mask[:, :, :, end_pos:],
304
+ ) if attention_mask is not None else (None, None)
305
+ if attn.norm_cross:
306
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
307
+
308
+ key = attn.to_k(encoder_hidden_states)
309
+ value = attn.to_v(encoder_hidden_states)
310
+
311
+ inner_dim = key.shape[-1]
312
+ head_dim = inner_dim // attn.heads
313
+ attention_mask = attention_mask_qk_text if attention_mask_qk_text is not None else attention_mask
314
+ if not self.need_text_attention_map:
315
+ # original attention 2.0
316
+ new_query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
317
+
318
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
319
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
320
+
321
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
322
+ hidden_states = F.scaled_dot_product_attention(
323
+ new_query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
324
+ )
325
+
326
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
327
+ hidden_states = hidden_states.to(query.dtype)
328
+ else:
329
+ # we need get the attention map, so use the previous attention
330
+ new_query = attn.head_to_batch_dim(query)
331
+ key = attn.head_to_batch_dim(key)
332
+ value = attn.head_to_batch_dim(value)
333
+
334
+ if attention_mask is not None:
335
+ attention_mask = attention_mask.view(batch_size*attn.heads, -1, attention_mask.shape[-1])
336
+ attention_probs = attn.get_attention_scores(new_query, key, attention_mask)
337
+ self.get_text_attention_maps(attention_probs, boxes, phrase_idxes, attn.heads)
338
+ hidden_states = torch.bmm(attention_probs, value)
339
+ hidden_states = attn.batch_to_head_dim(hidden_states)
340
+
341
+ # get psuedo attention mask for image: better start after some timesteps
342
+ psuedo_attention_mask, psuedo_dummy_attention_mask = self.get_psuedo_attention_mask(attn.heads)
343
+ if psuedo_attention_mask is not None:
344
+ psuedo_attention_mask = psuedo_attention_mask.view(batch_size, attn.heads, -1,
345
+ psuedo_attention_mask.shape[-1])
346
+
347
+ ip_key = self.to_k_ip(ip_hidden_states)
348
+ ip_value = self.to_v_ip(ip_hidden_states)
349
+ rf_attention_mask = attention_mask_qk_image if attention_mask_qk_image is not None else rf_attention_mask
350
+ rf_attention_mask = psuedo_attention_mask if psuedo_attention_mask is not None else rf_attention_mask
351
+ dummy_attention_mask = psuedo_dummy_attention_mask if psuedo_dummy_attention_mask is not None else dummy_attention_mask
352
+ if not self.need_image_attention_map:
353
+ new_query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
354
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
355
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
356
+
357
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
358
+ ip_hidden_states = F.scaled_dot_product_attention(
359
+ new_query, ip_key, ip_value, attn_mask=rf_attention_mask, dropout_p=0.0, is_causal=False
360
+ )
361
+
362
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
363
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
364
+ else:
365
+ new_query = attn.head_to_batch_dim(query)
366
+ ip_key = attn.head_to_batch_dim(ip_key)
367
+ ip_value = attn.head_to_batch_dim(ip_value)
368
+
369
+ if rf_attention_mask is not None:
370
+ rf_attention_mask = rf_attention_mask.view(batch_size*attn.heads, -1, rf_attention_mask.shape[-1])
371
+ ip_attention_probs = attn.get_attention_scores(new_query, ip_key, rf_attention_mask)
372
+ # mask attention_probs in background
373
+ ip_attention_probs = torch.where(dummy_attention_mask.unsqueeze(-1), torch.zeros_like(ip_attention_probs), ip_attention_probs)
374
+ if self.subject_scales is not None:
375
+ # apply different scales to different subjects
376
+ subject_scales = torch.tensor(self.subject_scales, dtype=ip_attention_probs.dtype, device=ip_attention_probs.device)
377
+ subject_scales = subject_scales.unsqueeze(0).unsqueeze(0).repeat_interleave(self.num_tokens, dim=-1)
378
+ dummy_subject_scales = torch.ones((1, 1, 1), dtype=ip_attention_probs.dtype, device=ip_attention_probs.device).repeat_interleave(self.num_dummy_tokens, dim=-1)
379
+ subject_scales = torch.cat([dummy_subject_scales, subject_scales], dim=-1)
380
+ ip_attention_probs = ip_attention_probs * subject_scales
381
+ ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
382
+ ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
383
+
384
+ if self.subject_scales is None:
385
+ hidden_states = hidden_states + self.scale * ip_hidden_states
386
+ else:
387
+ hidden_states = hidden_states + ip_hidden_states
388
+
389
+ # linear proj
390
+ hidden_states = attn.to_out[0](hidden_states)
391
+ # dropout
392
+ hidden_states = attn.to_out[1](hidden_states)
393
+
394
+ if input_ndim == 4:
395
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
396
+
397
+ if attn.residual_connection:
398
+ hidden_states = hidden_states + residual
399
+
400
+ hidden_states = hidden_states / attn.rescale_output_factor
401
+
402
+ return hidden_states
403
+
404
+
405
+ class CNAttnProcessor2_0:
406
+ r"""
407
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
408
+ """
409
+
410
+ def __init__(self, num_tokens=4, text_tokens=77):
411
+ if not hasattr(F, "scaled_dot_product_attention"):
412
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
413
+ self.num_tokens = num_tokens
414
+ self.text_tokens = text_tokens
415
+
416
+ def __call__(
417
+ self,
418
+ attn,
419
+ hidden_states,
420
+ encoder_hidden_states=None,
421
+ attention_mask=None,
422
+ temb=None,
423
+ ):
424
+ residual = hidden_states
425
+
426
+ if attn.spatial_norm is not None:
427
+ hidden_states = attn.spatial_norm(hidden_states, temb)
428
+
429
+ input_ndim = hidden_states.ndim
430
+
431
+ if input_ndim == 4:
432
+ batch_size, channel, height, width = hidden_states.shape
433
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
434
+
435
+ batch_size, sequence_length, _ = (
436
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
437
+ )
438
+
439
+ if attention_mask is not None:
440
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
441
+ # scaled_dot_product_attention expects attention_mask shape to be
442
+ # (batch, heads, source_length, target_length)
443
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
444
+ rf_attention_mask = None
445
+
446
+ if attn.group_norm is not None:
447
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
448
+
449
+ query = attn.to_q(hidden_states)
450
+
451
+ if encoder_hidden_states is None:
452
+ encoder_hidden_states = hidden_states
453
+ else:
454
+ # end_pos = encoder_hidden_states.shape[1] - self.num_tokens
455
+ end_pos = self.text_tokens
456
+ encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
457
+ attention_mask = attention_mask[:, :, :end_pos]
458
+ if attn.norm_cross:
459
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
460
+
461
+ key = attn.to_k(encoder_hidden_states)
462
+ value = attn.to_v(encoder_hidden_states)
463
+
464
+ inner_dim = key.shape[-1]
465
+ head_dim = inner_dim // attn.heads
466
+
467
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
468
+
469
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
470
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
471
+
472
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
473
+ # TODO: add support for attn.scale when we move to Torch 2.1
474
+ hidden_states = F.scaled_dot_product_attention(
475
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
476
+ )
477
+
478
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
479
+ hidden_states = hidden_states.to(query.dtype)
480
+
481
+ # linear proj
482
+ hidden_states = attn.to_out[0](hidden_states)
483
+ # dropout
484
+ hidden_states = attn.to_out[1](hidden_states)
485
+
486
+ if input_ndim == 4:
487
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
488
+
489
+ if attn.residual_connection:
490
+ hidden_states = hidden_states + residual
491
+
492
+ hidden_states = hidden_states / attn.rescale_output_factor
493
+
494
+ return hidden_states
msdiffusion/models/model.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ from typing import List
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from diffusers.pipelines.controlnet import MultiControlNetModel
8
+
9
+ from .attention_processor import MaskedIPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor, CNAttnProcessor2_0 as CNAttnProcessor
10
+
11
+
12
+ class MSAdapter(torch.nn.Module):
13
+ def __init__(self, unet, image_proj_model, adapter_modules=None, ckpt_path=None,
14
+ num_tokens=4, text_tokens=77, max_rn=4, num_dummy_tokens=4,
15
+ device="cuda", controlnet=None):
16
+ super().__init__()
17
+ self.unet = unet
18
+ self.image_proj_model = image_proj_model
19
+ self.adapter_modules = adapter_modules
20
+ self.num_tokens = num_tokens
21
+ self.num_dummy_tokens = num_dummy_tokens
22
+ self.text_tokens = text_tokens
23
+ self.max_rn = max_rn
24
+ self.device = device
25
+ self.controlnet = controlnet
26
+ self.cross_attention_dim = self.unet.config.cross_attention_dim
27
+
28
+ # set attention processor when inference
29
+ if self.adapter_modules is None:
30
+ self.set_ms_adapter()
31
+
32
+ # dummy image tokens
33
+ self.dummy_image_tokens = nn.Parameter(torch.randn(1, self.num_dummy_tokens, self.cross_attention_dim))
34
+
35
+ if ckpt_path is not None:
36
+ self.load_from_checkpoint(ckpt_path)
37
+
38
+ def forward(self, noisy_latents, timesteps, encoder_hidden_states, unet_added_cond_kwargs, image_embeds,
39
+ rf_attention_mask=None, cross_attention_kwargs=None, grounding_kwargs=None):
40
+ bsz = encoder_hidden_states.shape[0]
41
+ if grounding_kwargs is None:
42
+ ip_tokens = self.image_proj_model(image_embeds) # (bsz*rn, num_tokens, cross_attention_dim)
43
+ else:
44
+ ip_tokens = self.image_proj_model(image_embeds, grounding_kwargs=grounding_kwargs)
45
+ # concat multiple images tokens
46
+ ip_tokens = ip_tokens.view(bsz, -1, ip_tokens.shape[-2], ip_tokens.shape[-1]) # (bsz, rn, num_tokens, cross_attention_dim)
47
+ total_num_tokens = ip_tokens.shape[-2] # num_tokens
48
+ ip_tokens = ip_tokens.view(bsz, ip_tokens.shape[-3] * ip_tokens.shape[-2], ip_tokens.shape[-1]) # (bsz, total_num_tokens*rn, cross_attention_dim)
49
+ dummy_image_tokens = self.dummy_image_tokens.repeat(bsz, 1, 1)
50
+ ip_tokens = torch.cat([dummy_image_tokens, ip_tokens], dim=1)
51
+ encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
52
+ encoder_attention_mask = None
53
+ if rf_attention_mask is not None:
54
+ attention_mask = torch.ones((bsz, self.text_tokens)).cuda()
55
+ rf_attention_mask = torch.repeat_interleave(rf_attention_mask, repeats=total_num_tokens, dim=1)
56
+ encoder_attention_mask = torch.cat([attention_mask, rf_attention_mask], dim=1)
57
+ # Predict the noise residual
58
+ noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states,
59
+ added_cond_kwargs=unet_added_cond_kwargs,
60
+ encoder_attention_mask=encoder_attention_mask,
61
+ cross_attention_kwargs=cross_attention_kwargs).sample
62
+ return noise_pred
63
+
64
+ def save_to_checkpoint(self, output_path: str):
65
+ if os.path.isdir(output_path):
66
+ os.makedirs(output_path, exist_ok=True)
67
+ output_path = os.path.join(output_path, "ms_adapter.bin")
68
+
69
+ state_dict = {
70
+ "image_proj": self.image_proj_model.state_dict(),
71
+ "ms_adapter": self.adapter_modules.state_dict(),
72
+ "dummy_image_tokens": self.dummy_image_tokens,
73
+ }
74
+ torch.save(state_dict, output_path)
75
+ print(f"Successfully saved weights to checkpoint {output_path}")
76
+
77
+ def load_from_checkpoint(self, ckpt_path: str):
78
+ if os.path.isdir(ckpt_path):
79
+ ckpt_path = os.path.join(ckpt_path, "ms_adapter.bin")
80
+
81
+ # Calculate original checksums
82
+ orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
83
+ orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
84
+
85
+ state_dict = torch.load(ckpt_path, map_location="cpu")
86
+
87
+ # Load state dict for image_proj_model and adapter_modules when using resampler
88
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
89
+ self.adapter_modules.load_state_dict(state_dict["ms_adapter"], strict=True)
90
+ self.load_state_dict({"dummy_image_tokens": state_dict["dummy_image_tokens"]}, strict=False)
91
+
92
+ # Calculate new checksums
93
+ new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
94
+ new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
95
+
96
+ # Verify if the weights have changed
97
+ assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
98
+ assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
99
+
100
+ print(f"Successfully loaded weights from checkpoint {ckpt_path}")
101
+
102
+ def set_ms_adapter(self, weight_dtype=torch.float16, cache_attention_maps=True):
103
+ # set attention processor
104
+ attn_procs = {}
105
+ for name in self.unet.attn_processors.keys():
106
+ cross_attention_dim = None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim
107
+ if name.startswith("mid_block"):
108
+ hidden_size = self.unet.config.block_out_channels[-1]
109
+ elif name.startswith("up_blocks"):
110
+ block_id = int(name[len("up_blocks.")])
111
+ hidden_size = list(reversed(self.unet.config.block_out_channels))[block_id]
112
+ elif name.startswith("down_blocks"):
113
+ block_id = int(name[len("down_blocks.")])
114
+ hidden_size = self.unet.config.block_out_channels[block_id]
115
+ if cross_attention_dim is None:
116
+ attn_procs[name] = AttnProcessor()
117
+ else:
118
+ attn_procs[name] = IPAttnProcessor(
119
+ hidden_size=hidden_size,
120
+ cross_attention_dim=cross_attention_dim,
121
+ num_tokens=self.num_tokens,
122
+ text_tokens=self.text_tokens,
123
+ ).to(self.device, dtype=weight_dtype)
124
+ self.unet.set_attn_processor(attn_procs)
125
+ self.adapter_modules = torch.nn.ModuleList(self.unet.attn_processors.values())
126
+ if self.controlnet is not None:
127
+ if isinstance(self.controlnet, MultiControlNetModel):
128
+ for controlnet in self.controlnet.nets:
129
+ controlnet.set_attn_processor(CNAttnProcessor(text_tokens=self.text_tokens, num_tokens=self.num_tokens))
130
+ else:
131
+ self.controlnet.set_attn_processor(CNAttnProcessor(text_tokens=self.text_tokens, num_tokens=self.num_tokens))
132
+
133
+ @torch.inference_mode()
134
+ def get_image_embeds(self, processed_images, image_encoder=None, image_proj_type="linear",
135
+ image_encoder_type="clip", weight_dtype=torch.float16):
136
+ # get image embeds
137
+ # processed_images: [bsz, rn, ...]
138
+ processed_images = processed_images.view(-1, processed_images.shape[-3], processed_images.shape[-2],
139
+ processed_images.shape[-1]) # (bsz*rn, ...)
140
+ if image_proj_type == "resampler":
141
+ image_embeds = image_encoder(processed_images.to(self.device, dtype=weight_dtype),
142
+ output_hidden_states=True).hidden_states[-2] # (bsz*rn, num_tokens, embedding_dim)
143
+ else:
144
+ image_embeds = image_encoder(processed_images.to(self.device, dtype=weight_dtype)).image_embeds # (bsz*rn, embedding_dim)
145
+
146
+ return image_embeds # [bsz*rn, ...]
147
+
148
+ def set_scale(self, scale, subject_scales):
149
+ for attn_processor in self.pipe.unet.attn_processors.values():
150
+ if isinstance(attn_processor, IPAttnProcessor):
151
+ attn_processor.scale = scale
152
+ attn_processor.subject_scales = subject_scales
153
+
154
+ def enable_psuedo_attention_mask(self, mask_threshold=0.5, start_step=5):
155
+ for attn_processor in self.pipe.unet.attn_processors.values():
156
+ if isinstance(attn_processor, IPAttnProcessor):
157
+ attn_processor.mask_threshold = mask_threshold
158
+ attn_processor.start_step = start_step
159
+ attn_processor.use_psuedo_attention_mask = True
160
+ attn_processor.need_text_attention_map = True
161
+ attn_processor.attention_maps = [] # clear attention maps
162
+
163
+ def generate(self, pipe, pil_images=None, processed_images=None, prompt=None, negative_prompt=None, scale=1.0,
164
+ num_samples=4, seed=None, guidance_scale=7.5, num_inference_steps=50, image_processor=None,
165
+ image_encoder=None, image_proj_type="linear", image_encoder_type="clip", weight_dtype=torch.float16,
166
+ boxes=None, phrases=None, drop_grounding_tokens=None, phrase_idxes=None,
167
+ eot_idxes=None, height=1024, width=1024, subject_scales=None, mask_threshold=None, start_step=5,
168
+ **kwargs):
169
+ # generate images (validation&inference)
170
+ self.pipe = pipe
171
+ self.set_scale(scale, subject_scales)
172
+ if mask_threshold is not None:
173
+ self.enable_psuedo_attention_mask(mask_threshold, start_step)
174
+
175
+ # pil_images: [[xxx, xxx, xxx], [xxx, xxx, xxx], ...]
176
+ bsz = len(pil_images) # only support bsz=1 now
177
+ if processed_images is None:
178
+ # write in this way to promise it can be extended to batch in the future
179
+ processed_images = []
180
+ for pil_image in pil_images:
181
+ processed_image = image_processor(images=pil_image, return_tensors="pt").pixel_values
182
+ processed_images.append(processed_image)
183
+ processed_images = torch.stack(processed_images, dim=0)
184
+
185
+ num_prompts = bsz
186
+ if prompt is None:
187
+ prompt = "best quality, high quality"
188
+ if negative_prompt is None:
189
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality" # duplicate
190
+ if not isinstance(prompt, List):
191
+ prompt = [prompt] * num_prompts
192
+ if not isinstance(negative_prompt, List):
193
+ negative_prompt = [negative_prompt] * num_prompts
194
+
195
+ cross_attention_kwargs = None
196
+ grounding_kwargs = None
197
+ if boxes is not None:
198
+ boxes = torch.tensor(boxes).to(self.device, weight_dtype)
199
+ if phrases is not None:
200
+ drop_grounding_tokens = drop_grounding_tokens if drop_grounding_tokens is not None else [0]*bsz
201
+ batch_boxes = boxes.view(bsz*boxes.shape[1], -1)
202
+ # write in this way to promise it can be extended to batch in the future
203
+ phrase_input_ids = []
204
+ for phrase in phrases:
205
+ phrase_input_id = pipe.tokenizer(phrase, max_length=pipe.tokenizer.model_max_length,
206
+ padding="max_length", truncation=True,
207
+ return_tensors="pt").input_ids
208
+ phrase_input_ids.append(phrase_input_id)
209
+ phrase_input_ids = torch.stack(phrase_input_ids)
210
+ phrase_input_ids = phrase_input_ids.view(-1, phrase_input_ids.shape[-1])
211
+ phrase_embeds = pipe.text_encoder(phrase_input_ids.to(self.device)).pooler_output
212
+ grounding_kwargs = {"boxes": batch_boxes, "phrase_embeds": phrase_embeds, "drop_grounding_tokens": drop_grounding_tokens}
213
+ else:
214
+ grounding_kwargs = None
215
+ boxes = torch.repeat_interleave(boxes, repeats=num_samples, dim=0)
216
+ uncond_boxes = torch.zeros_like(boxes)
217
+ boxes = torch.cat([uncond_boxes, boxes], dim=0)
218
+ cross_attention_kwargs = {"boxes": boxes}
219
+
220
+ if phrase_idxes is not None:
221
+ phrase_idxes = torch.tensor(phrase_idxes).to(self.device, torch.int)
222
+ eot_idxes = torch.tensor(eot_idxes).to(self.device, torch.int)
223
+ phrase_idxes = torch.repeat_interleave(phrase_idxes, repeats=num_samples, dim=0)
224
+ eot_idxes = torch.repeat_interleave(eot_idxes, repeats=num_samples, dim=0)
225
+ uncond_phrase_idxes = torch.zeros_like(phrase_idxes)
226
+ uncond_eot_idxes = torch.zeros_like(eot_idxes)
227
+ phrase_idxes = torch.cat([uncond_phrase_idxes, phrase_idxes], dim=0)
228
+ eot_idxes = torch.cat([uncond_eot_idxes, eot_idxes], dim=0)
229
+ if cross_attention_kwargs is None:
230
+ cross_attention_kwargs = {"phrase_idxes": phrase_idxes, "eot_idxes": eot_idxes}
231
+ else:
232
+ cross_attention_kwargs["phrase_idxes"] = phrase_idxes
233
+ cross_attention_kwargs["eot_idxes"] = eot_idxes
234
+
235
+ with torch.inference_mode():
236
+ image_embeds = self.get_image_embeds(processed_images, image_encoder, image_proj_type=image_proj_type,
237
+ image_encoder_type=image_encoder_type, weight_dtype=weight_dtype)
238
+ image_prompt_embeds = self.image_proj_model(image_embeds, grounding_kwargs=grounding_kwargs)
239
+ image_prompt_embeds = image_prompt_embeds.view(bsz, -1, image_prompt_embeds.shape[-2], image_prompt_embeds.shape[-1]) # (bsz, rn, num_tokens, cross_attention_dim)
240
+ image_prompt_embeds = image_prompt_embeds.view(bsz, image_prompt_embeds.shape[-3] * image_prompt_embeds.shape[-2],
241
+ image_prompt_embeds.shape[-1]) # (bsz, total_num_tokens*rn, cross_attention_dim)
242
+ image_prompt_embeds = torch.cat([self.dummy_image_tokens, image_prompt_embeds], dim=1)
243
+ uncond_image_prompt_embeds = torch.zeros_like(image_prompt_embeds)
244
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
245
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
246
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
247
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
248
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
249
+
250
+ prompt_embeds_, negative_prompt_embeds_, pooled_prompt_embeds, negative_pooled_prompt_embeds = pipe.encode_prompt(
251
+ prompt,
252
+ device=self.device,
253
+ num_images_per_prompt=num_samples,
254
+ do_classifier_free_guidance=True,
255
+ negative_prompt=negative_prompt,
256
+ )
257
+ prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
258
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
259
+
260
+ generator = torch.Generator(self.device).manual_seed(seed) if seed is not None else None
261
+ images = pipe(
262
+ prompt_embeds=prompt_embeds,
263
+ negative_prompt_embeds=negative_prompt_embeds,
264
+ pooled_prompt_embeds=pooled_prompt_embeds,
265
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
266
+ guidance_scale=guidance_scale,
267
+ num_inference_steps=num_inference_steps,
268
+ generator=generator,
269
+ cross_attention_kwargs=cross_attention_kwargs,
270
+ height=height,
271
+ width=width,
272
+ **kwargs,
273
+ ).images
274
+
275
+ return images
msdiffusion/models/projection.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
2
+ # and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
3
+ # and https://github.com/tencent-ailab/IP-Adapter/blob/main/ip_adapter/ip_adapter.py
4
+ # and https://github.com/tencent-ailab/IP-Adapter/blob/main/ip_adapter/resampler.py
5
+
6
+ import math
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from einops import rearrange
11
+ from einops.layers.torch import Rearrange
12
+
13
+
14
+ class FourierEmbedder(nn.Module):
15
+ def __init__(self, num_freqs=64, temperature=100):
16
+ super().__init__()
17
+
18
+ self.num_freqs = num_freqs
19
+ self.temperature = temperature
20
+
21
+ freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
22
+ freq_bands = freq_bands[None, None]
23
+ self.register_buffer("freq_bands", freq_bands, persistent=False)
24
+
25
+ def __call__(self, x):
26
+ x = self.freq_bands * x.unsqueeze(-1)
27
+ return torch.stack((x.sin(), x.cos()), dim=-1).permute(0, 2, 3, 1).reshape(x.shape[0], -1)
28
+
29
+
30
+ class ImageProjModel(torch.nn.Module):
31
+ """Projection Model"""
32
+
33
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
34
+ super().__init__()
35
+
36
+ self.cross_attention_dim = cross_attention_dim
37
+ self.clip_extra_context_tokens = clip_extra_context_tokens
38
+ self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
39
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
40
+
41
+ def forward(self, image_embeds):
42
+ embeds = image_embeds
43
+ clip_extra_context_tokens = self.proj(embeds).reshape(
44
+ -1, self.clip_extra_context_tokens, self.cross_attention_dim
45
+ )
46
+ clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
47
+ return clip_extra_context_tokens
48
+
49
+
50
+ # FFN
51
+ def FeedForward(dim, mult=4):
52
+ inner_dim = int(dim * mult)
53
+ return nn.Sequential(
54
+ nn.LayerNorm(dim),
55
+ nn.Linear(dim, inner_dim, bias=False),
56
+ nn.GELU(),
57
+ nn.Linear(inner_dim, dim, bias=False),
58
+ # nn.LayerNorm(dim),
59
+ )
60
+
61
+
62
+ def reshape_tensor(x, heads):
63
+ bs, length, width = x.shape
64
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
65
+ x = x.view(bs, length, heads, -1)
66
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
67
+ x = x.transpose(1, 2)
68
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
69
+ x = x.reshape(bs, heads, length, -1)
70
+ return x
71
+
72
+
73
+ class PerceiverAttention(nn.Module):
74
+ def __init__(self, *, dim, dim_head=64, heads=8):
75
+ super().__init__()
76
+ self.scale = dim_head**-0.5
77
+ self.dim_head = dim_head
78
+ self.heads = heads
79
+ inner_dim = dim_head * heads
80
+
81
+ self.norm1 = nn.LayerNorm(dim)
82
+ self.norm2 = nn.LayerNorm(dim)
83
+
84
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
85
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
86
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
87
+
88
+ def forward(self, x, latents):
89
+ """
90
+ Args:
91
+ x (torch.Tensor): image features
92
+ shape (b, n1, D)
93
+ latent (torch.Tensor): latent features
94
+ shape (b, n2, D)
95
+ """
96
+ x = self.norm1(x)
97
+ latents = self.norm2(latents)
98
+
99
+ b, l, _ = latents.shape
100
+
101
+ q = self.to_q(latents)
102
+ kv_input = torch.cat((x, latents), dim=-2)
103
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
104
+
105
+ q = reshape_tensor(q, self.heads)
106
+ k = reshape_tensor(k, self.heads)
107
+ v = reshape_tensor(v, self.heads)
108
+
109
+ # attention
110
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
111
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
112
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
113
+ out = weight @ v
114
+
115
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
116
+
117
+ return self.to_out(out)
118
+
119
+
120
+ class Resampler(nn.Module):
121
+ def __init__(
122
+ self,
123
+ dim=1024,
124
+ depth=8,
125
+ dim_head=64,
126
+ heads=16,
127
+ num_queries=8,
128
+ embedding_dim=768,
129
+ output_dim=1024,
130
+ ff_mult=4,
131
+ max_seq_len: int = 257, # CLIP tokens + CLS token
132
+ apply_pos_emb: bool = False,
133
+ num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence
134
+ latent_init_mode: str = "random",
135
+ phrase_embeddings_dim: int = 1024,
136
+ fourier_freqs: int = 8,
137
+ ):
138
+ super().__init__()
139
+ self.num_queries = num_queries
140
+ self.grounding_token_num = self.num_queries
141
+ self.dim = dim
142
+ self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
143
+
144
+ self.latent_init_mode = latent_init_mode
145
+ if latent_init_mode == "random":
146
+ self.latents = nn.Parameter(torch.randn(1, self.latents_token_num, dim) / dim**0.5)
147
+ self.fourier_embedder = None
148
+ self.latent_proj = None
149
+ self.latent_norm = None
150
+ elif latent_init_mode == "grounding":
151
+ self.latents = None
152
+ self.grounding_latents = nn.Parameter(torch.randn(1, self.grounding_token_num, dim) / dim ** 0.5)
153
+ self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
154
+ grounding_embedding_dim = phrase_embeddings_dim + fourier_freqs * 2 * 4 # 2: sin/cos, 4: xyxy
155
+ self.latent_proj = torch.nn.Sequential(
156
+ torch.nn.Linear(grounding_embedding_dim, grounding_embedding_dim * 2),
157
+ torch.nn.GELU(),
158
+ torch.nn.Linear(grounding_embedding_dim * 2, dim * self.grounding_token_num),
159
+ )
160
+ self.latent_norm = nn.LayerNorm(dim)
161
+ else:
162
+ raise ValueError(f"Invalid latent_init_mode: {latent_init_mode}")
163
+
164
+ self.proj_in = nn.Linear(embedding_dim, dim)
165
+ self.attention_norm = nn.LayerNorm(dim)
166
+
167
+ self.proj_out = nn.Linear(dim, output_dim)
168
+ self.norm_out = nn.LayerNorm(output_dim)
169
+
170
+ self.to_latents_from_mean_pooled_seq = (
171
+ nn.Sequential(
172
+ nn.LayerNorm(dim),
173
+ nn.Linear(dim, dim * num_latents_mean_pooled),
174
+ Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled),
175
+ )
176
+ if num_latents_mean_pooled > 0
177
+ else None
178
+ )
179
+
180
+ self.layers = nn.ModuleList([])
181
+ for _ in range(depth):
182
+ self.layers.append(
183
+ nn.ModuleList(
184
+ [
185
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
186
+ FeedForward(dim=dim, mult=ff_mult),
187
+ ]
188
+ )
189
+ )
190
+
191
+ def forward(self, x, grounding_kwargs=None, shortcut=False, scale=1.0):
192
+ if self.pos_emb is not None:
193
+ n, device = x.shape[1], x.device
194
+ pos_emb = self.pos_emb(torch.arange(n, device=device))
195
+ x = x + pos_emb
196
+
197
+ if self.latent_init_mode == "random":
198
+ latents = self.latents.repeat(x.size(0), 1, 1)
199
+ elif self.latent_init_mode == "grounding":
200
+ boxes = grounding_kwargs["boxes"]
201
+ phrase_embeds = grounding_kwargs["phrase_embeds"]
202
+ fourier_embeds = self.fourier_embedder(boxes)
203
+ grounding_embeds = torch.cat((phrase_embeds, fourier_embeds), dim=-1)
204
+
205
+ drop_grounding_tokens = grounding_kwargs["drop_grounding_tokens"]
206
+ num_ref = x.shape[0] // len(drop_grounding_tokens)
207
+ drop_grounding_tokens = [item for item in drop_grounding_tokens for _ in range(num_ref)]
208
+
209
+ latents = self.latent_proj(grounding_embeds)
210
+ latents = latents.view(-1, self.grounding_token_num, self.dim)
211
+ latents = self.latent_norm(latents)
212
+
213
+ # drop grounding tokens to learnable latents
214
+ drop_num = len([item for item in drop_grounding_tokens if item == 1])
215
+ if drop_num > 0:
216
+ latents_ = []
217
+ learnable_latents = self.grounding_latents.repeat(drop_num, 1, 1)
218
+ cur_idx = 0
219
+ for latent, drop_grounding_token in zip(latents, drop_grounding_tokens):
220
+ if drop_grounding_token == 1:
221
+ latent = learnable_latents[cur_idx]
222
+ cur_idx += 1
223
+ latents_.append(latent)
224
+ latents = torch.stack(latents_)
225
+ else:
226
+ raise ValueError(f"Invalid latent_init_mode: {self.latent_init_mode}")
227
+
228
+ x = self.proj_in(x)
229
+
230
+ if self.to_latents_from_mean_pooled_seq:
231
+ meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool))
232
+ meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq)
233
+ latents = torch.cat((meanpooled_latents, latents), dim=-2)
234
+
235
+ init_latents = latents
236
+
237
+ for attn, ff in self.layers:
238
+ latents = attn(x, latents) + latents
239
+ latents = ff(latents) + latents
240
+
241
+ latents = self.attention_norm(latents)
242
+ latents = self.proj_out(latents)
243
+ if shortcut:
244
+ latents = init_latents + latents * scale
245
+
246
+ return self.norm_out(latents)
247
+
248
+
249
+ def masked_mean(t, *, dim, mask=None):
250
+ if mask is None:
251
+ return t.mean(dim=dim)
252
+
253
+ denom = mask.sum(dim=dim, keepdim=True)
254
+ mask = rearrange(mask, "b n -> b n 1")
255
+ masked_t = t.masked_fill(~mask, 0.0)
256
+
257
+ return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)
msdiffusion/utils.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+
4
+ def get_phrase_idx(tokenizer, phrase, prompt, get_last_word=False, num=0):
5
+ def is_equal_words(pr_words, ph_words):
6
+ if len(pr_words) != len(ph_words):
7
+ return False
8
+ for pr_word, ph_word in zip(pr_words, ph_words):
9
+ if "-"+ph_word not in pr_word and ph_word != re.sub(r'[.!?,:]$', '', pr_word):
10
+ return False
11
+ return True
12
+
13
+ phrase_words = phrase.split()
14
+ if len(phrase_words) == 0:
15
+ return [0, 0], None
16
+ if get_last_word:
17
+ phrase_words = phrase_words[-1:]
18
+ # prompt_words = re.findall(r'\b[\w\'-]+\b', prompt)
19
+ prompt_words = prompt.split()
20
+ start = 1
21
+ end = 0
22
+ res_words = phrase_words
23
+ for i in range(len(prompt_words)):
24
+ if is_equal_words(prompt_words[i:i+len(phrase_words)], phrase_words):
25
+ if num != 0:
26
+ # skip this one
27
+ num -= 1
28
+ continue
29
+ end = start
30
+ res_words = prompt_words[i:i+len(phrase_words)]
31
+ res_words = [re.sub(r'[.!?,:]$', '', w) for w in res_words]
32
+ prompt_words[i+len(phrase_words)-1] = res_words[-1] # remove the last punctuation
33
+ for j in range(i, i+len(phrase_words)):
34
+ end += len(tokenizer.encode(prompt_words[j])) - 2
35
+ break
36
+ else:
37
+ start += len(tokenizer.encode(prompt_words[i])) - 2
38
+
39
+ if end == 0:
40
+ return [0, 0], None
41
+
42
+ return [start, end], res_words
43
+
44
+
45
+ def get_eot_idx(tokenizer, prompt):
46
+ words = prompt.split()
47
+ start = 1
48
+ for w in words:
49
+ start += len(tokenizer.encode(w)) - 2
50
+ return start
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diffusers==0.23.1
2
+ transformers==4.35.2
3
+ huggingface_hub==0.24.6
4
+ accelerate==0.25.0
5
+ numpy==1.24.4
6
+ Pillow==10.2.0
7
+ einops
8
+ scipy
9
+ opencv-python-headless
10
+ safetensors
11
+ spaces