Update pipeline.py
Browse files- pipeline.py +331 -3
pipeline.py
CHANGED
@@ -33,9 +33,337 @@ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineO
|
|
33 |
|
34 |
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
35 |
# REf: https://github.com/tatp22/multidim-positional-encoding/tree/master
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
class PatternAnalogyTrifuser(DiffusionPipeline):
|
41 |
r"""
|
|
|
33 |
|
34 |
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
35 |
# REf: https://github.com/tatp22/multidim-positional-encoding/tree/master
|
36 |
+
|
37 |
+
|
38 |
+
OUT_SIZE = 768
|
39 |
+
IN_SIZE = 2048
|
40 |
+
|
41 |
+
DINO_SIZE = 224
|
42 |
+
DINO_MEAN = [0.485, 0.456, 0.406]
|
43 |
+
DINO_STD = [0.229, 0.224, 0.225]
|
44 |
+
|
45 |
+
SIGLIP_SIZE = 256
|
46 |
+
SIGLIP_MEAN = [0.5]
|
47 |
+
SIGLIP_STD = [0.5]
|
48 |
+
|
49 |
+
|
50 |
+
def get_emb(sin_inp):
|
51 |
+
"""
|
52 |
+
Gets a base embedding for one dimension with sin and cos intertwined
|
53 |
+
"""
|
54 |
+
emb = th.stack((sin_inp.sin(), sin_inp.cos()), dim=-1)
|
55 |
+
return th.flatten(emb, -2, -1)
|
56 |
+
|
57 |
+
|
58 |
+
class PositionalEncoding1D(nn.Module):
|
59 |
+
def __init__(self, channels):
|
60 |
+
"""
|
61 |
+
:param channels: The last dimension of the tensor you want to apply pos emb to.
|
62 |
+
"""
|
63 |
+
super(PositionalEncoding1D, self).__init__()
|
64 |
+
self.org_channels = channels
|
65 |
+
channels = int(np.ceil(channels / 2) * 2)
|
66 |
+
self.channels = channels
|
67 |
+
inv_freq = 1.0 / (10000 ** (th.arange(0, channels, 2).float() / channels))
|
68 |
+
self.register_buffer("inv_freq", inv_freq)
|
69 |
+
self.register_buffer("cached_penc", None, persistent=False)
|
70 |
+
|
71 |
+
def forward(self, tensor):
|
72 |
+
"""
|
73 |
+
:param tensor: A 3d tensor of size (batch_size, x, ch)
|
74 |
+
:return: Positional Encoding Matrix of size (batch_size, x, ch)
|
75 |
+
"""
|
76 |
+
if len(tensor.shape) != 3:
|
77 |
+
raise RuntimeError("The input tensor has to be 3d!")
|
78 |
+
|
79 |
+
if self.cached_penc is not None and self.cached_penc.shape == tensor.shape:
|
80 |
+
return self.cached_penc
|
81 |
+
|
82 |
+
self.cached_penc = None
|
83 |
+
batch_size, x, orig_ch = tensor.shape
|
84 |
+
pos_x = th.arange(x, device=tensor.device, dtype=self.inv_freq.dtype)
|
85 |
+
sin_inp_x = th.einsum("i,j->ij", pos_x, self.inv_freq)
|
86 |
+
emb_x = get_emb(sin_inp_x)
|
87 |
+
emb = th.zeros((x, self.channels), device=tensor.device, dtype=tensor.dtype)
|
88 |
+
emb[:, : self.channels] = emb_x
|
89 |
+
|
90 |
+
self.cached_penc = emb[None, :, :orig_ch].repeat(batch_size, 1, 1)
|
91 |
+
return self.cached_penc
|
92 |
+
|
93 |
+
|
94 |
+
|
95 |
+
class PositionalEncoding3D(nn.Module):
|
96 |
+
def __init__(self, channels):
|
97 |
+
"""
|
98 |
+
:param channels: The last dimension of the tensor you want to apply pos emb to.
|
99 |
+
"""
|
100 |
+
super(PositionalEncoding3D, self).__init__()
|
101 |
+
self.org_channels = channels
|
102 |
+
channels = int(np.ceil(channels / 6) * 2)
|
103 |
+
if channels % 2:
|
104 |
+
channels += 1
|
105 |
+
self.channels = channels
|
106 |
+
inv_freq = 1.0 / (10000 ** (th.arange(0, channels, 2).float() / channels))
|
107 |
+
self.register_buffer("inv_freq", inv_freq)
|
108 |
+
self.register_buffer("cached_penc", None, persistent=False)
|
109 |
+
|
110 |
+
def forward(self, tensor):
|
111 |
+
"""
|
112 |
+
:param tensor: A 5d tensor of size (batch_size, x, y, z, ch)
|
113 |
+
:return: Positional Encoding Matrix of size (batch_size, x, y, z, ch)
|
114 |
+
"""
|
115 |
+
if len(tensor.shape) != 5:
|
116 |
+
raise RuntimeError("The input tensor has to be 5d!")
|
117 |
+
|
118 |
+
if self.cached_penc is not None and self.cached_penc.shape == tensor.shape:
|
119 |
+
return self.cached_penc
|
120 |
+
|
121 |
+
self.cached_penc = None
|
122 |
+
batch_size, x, y, z, orig_ch = tensor.shape
|
123 |
+
pos_x = th.arange(x, device=tensor.device, dtype=self.inv_freq.dtype)
|
124 |
+
pos_y = th.arange(y, device=tensor.device, dtype=self.inv_freq.dtype)
|
125 |
+
pos_z = th.arange(z, device=tensor.device, dtype=self.inv_freq.dtype)
|
126 |
+
sin_inp_x = th.einsum("i,j->ij", pos_x, self.inv_freq)
|
127 |
+
sin_inp_y = th.einsum("i,j->ij", pos_y, self.inv_freq)
|
128 |
+
sin_inp_z = th.einsum("i,j->ij", pos_z, self.inv_freq)
|
129 |
+
emb_x = get_emb(sin_inp_x).unsqueeze(1).unsqueeze(1)
|
130 |
+
emb_y = get_emb(sin_inp_y).unsqueeze(1)
|
131 |
+
emb_z = get_emb(sin_inp_z)
|
132 |
+
emb = th.zeros(
|
133 |
+
(x, y, z, self.channels * 3),
|
134 |
+
device=tensor.device,
|
135 |
+
dtype=tensor.dtype,
|
136 |
+
)
|
137 |
+
emb[:, :, :, : self.channels] = emb_x
|
138 |
+
emb[:, :, :, self.channels : 2 * self.channels] = emb_y
|
139 |
+
emb[:, :, :, 2 * self.channels :] = emb_z
|
140 |
+
|
141 |
+
self.cached_penc = emb[None, :, :, :, :orig_ch].repeat(batch_size, 1, 1, 1, 1)
|
142 |
+
return self.cached_penc
|
143 |
+
|
144 |
+
class AnalogyInputProcessor(ModelMixin, ConfigMixin):
|
145 |
+
|
146 |
+
@register_to_config
|
147 |
+
def __init__(self,):
|
148 |
+
super(AnalogyInputProcessor, self).__init__()
|
149 |
+
|
150 |
+
self.dino_transform = transforms.Compose(
|
151 |
+
[
|
152 |
+
transforms.Resize((DINO_SIZE, DINO_SIZE)),
|
153 |
+
transforms.ToTensor(),
|
154 |
+
transforms.Normalize(DINO_MEAN, DINO_STD), # SIGLIP normalization
|
155 |
+
]
|
156 |
+
)
|
157 |
+
|
158 |
+
self.siglip_transform = transforms.Compose(
|
159 |
+
[
|
160 |
+
transforms.Resize((SIGLIP_SIZE, SIGLIP_SIZE)),
|
161 |
+
transforms.ToTensor(),
|
162 |
+
transforms.Normalize(SIGLIP_MEAN, SIGLIP_STD), # SIGLIP normalization
|
163 |
+
]
|
164 |
+
)
|
165 |
+
|
166 |
+
dino_mean = th.tensor(DINO_MEAN).view(1, 3, 1, 1)
|
167 |
+
dino_std = th.tensor(DINO_STD).view(1, 3, 1, 1)
|
168 |
+
siglip_mean = [SIGLIP_MEAN[0],] * 3
|
169 |
+
siglip_std = [SIGLIP_STD[0],] * 3
|
170 |
+
siglip_mean = th.tensor(siglip_mean).view(1, 3, 1, 1)
|
171 |
+
siglip_std = th.tensor(siglip_std).view(1, 3, 1, 1)
|
172 |
+
self.register_buffer("dino_mean", dino_mean)
|
173 |
+
self.register_buffer("dino_std", dino_std)
|
174 |
+
self.register_buffer("siglip_mean", siglip_mean)
|
175 |
+
self.register_buffer("siglip_std", siglip_std)
|
176 |
+
|
177 |
+
def __call__(self, analogy_prompt):
|
178 |
+
# List of tuples of (A, A*, B)
|
179 |
+
img_a_dino = []
|
180 |
+
img_a_siglip = []
|
181 |
+
img_a_star_dino = []
|
182 |
+
img_a_star_siglip = []
|
183 |
+
img_b_dino = []
|
184 |
+
img_b_siglip = []
|
185 |
+
|
186 |
+
for im_set in analogy_prompt:
|
187 |
+
img_a, img_a_star, img_b = im_set
|
188 |
+
img_a_dino.append(self.dino_transform(img_a))
|
189 |
+
img_a_siglip.append(self.siglip_transform(img_a))
|
190 |
+
img_a_star_dino.append(self.dino_transform(img_a_star))
|
191 |
+
img_a_star_siglip.append(self.siglip_transform(img_a_star))
|
192 |
+
img_b_dino.append(self.dino_transform(img_b))
|
193 |
+
img_b_siglip.append(self.siglip_transform(img_b))
|
194 |
+
|
195 |
+
img_a_dino = th.stack(img_a_dino, 0)
|
196 |
+
img_a_siglip = th.stack(img_a_siglip, 0)
|
197 |
+
img_a_star_dino = th.stack(img_a_star_dino, 0)
|
198 |
+
img_a_star_siglip = th.stack(img_a_star_siglip, 0)
|
199 |
+
img_b_dino = th.stack(img_b_dino, 0)
|
200 |
+
img_b_siglip = th.stack(img_b_siglip, 0)
|
201 |
+
|
202 |
+
dino_combined_input = th.stack([img_b_dino, img_a_dino, img_a_star_dino], 0)
|
203 |
+
siglip_combined_input = th.stack([img_b_siglip, img_a_siglip, img_a_star_siglip], 0)
|
204 |
+
|
205 |
+
return dino_combined_input, siglip_combined_input
|
206 |
+
def get_negative(self, dino_in, siglip_in):
|
207 |
+
|
208 |
+
dino_i = ((dino_in * 0 + 0.5) - self.dino_mean) / self.dino_std
|
209 |
+
siglip_i = ((siglip_in * 0 + 0.5) - self.siglip_mean) / self.siglip_std
|
210 |
+
return dino_i, siglip_i
|
211 |
+
|
212 |
+
|
213 |
+
class AnalogyProjector(ModelMixin, ConfigMixin):
|
214 |
+
|
215 |
+
@register_to_config
|
216 |
+
def __init__(self):
|
217 |
+
super(AnalogyProjector, self).__init__()
|
218 |
+
self.projector = DinoSiglipMixer()
|
219 |
+
self.pos_embd_1D = PositionalEncoding1D(OUT_SIZE)
|
220 |
+
self.pos_embd_3D = PositionalEncoding3D(OUT_SIZE)
|
221 |
+
|
222 |
+
|
223 |
+
def forward(self, dino_in, siglip_in, batch_size):
|
224 |
+
|
225 |
+
image_embeddings = self.projector(dino_in, siglip_in)
|
226 |
+
|
227 |
+
image_embeddings = einops.rearrange(image_embeddings, '(k b) t d -> b k t d', b=batch_size)
|
228 |
+
image_embeddings = self.position_embd(image_embeddings)
|
229 |
+
return image_embeddings
|
230 |
+
|
231 |
+
def position_embd(self, image_embeddings, concat=False):
|
232 |
+
canvas_embd = image_embeddings[:, :, 1:, :]
|
233 |
+
batch_size = canvas_embd.shape[0]
|
234 |
+
type_size = canvas_embd.shape[1]
|
235 |
+
xy_size = canvas_embd.shape[2]
|
236 |
+
|
237 |
+
x_size = int(xy_size ** 0.5)
|
238 |
+
|
239 |
+
canvas_embd = canvas_embd.reshape(batch_size, type_size, x_size, x_size, -1)
|
240 |
+
if concat:
|
241 |
+
canvas_embd = th.cat([canvas_embd, self.pos_embd_3D(canvas_embd)], -1)
|
242 |
+
else:
|
243 |
+
canvas_embd = self.pos_embd_3D(canvas_embd) + canvas_embd
|
244 |
+
canvas_embd = canvas_embd.reshape(batch_size, type_size, xy_size, -1)
|
245 |
+
|
246 |
+
class_embd = image_embeddings[:, :, 0, :]
|
247 |
+
if concat:
|
248 |
+
class_embd = th.cat([class_embd, self.pos_embd_1D(class_embd)], -1)
|
249 |
+
else:
|
250 |
+
class_embd = self.pos_embd_1D(class_embd) + class_embd
|
251 |
+
all_embd_list = []
|
252 |
+
for i in range(type_size):
|
253 |
+
all_embd_list.append(class_embd[:, i:i+1])
|
254 |
+
all_embd_list.append(canvas_embd[:, i])
|
255 |
+
image_embeddings = th.cat(all_embd_list, 1)
|
256 |
+
return image_embeddings
|
257 |
+
|
258 |
+
|
259 |
+
class HighLowMixer(th.nn.Module):
|
260 |
+
def __init__(self, in_size=IN_SIZE, out_size=OUT_SIZE):
|
261 |
+
super().__init__()
|
262 |
+
mid_size = (in_size + out_size) // 2
|
263 |
+
|
264 |
+
self.lower_projector = th.nn.Sequential(
|
265 |
+
th.nn.LayerNorm(IN_SIZE//2),
|
266 |
+
th.nn.SiLU()
|
267 |
+
)
|
268 |
+
self.upper_projector = th.nn.Sequential(
|
269 |
+
th.nn.LayerNorm(IN_SIZE//2),
|
270 |
+
th.nn.SiLU()
|
271 |
+
)
|
272 |
+
self.projectors = th.nn.ModuleList([
|
273 |
+
# add layer norm
|
274 |
+
th.nn.Linear(in_size, mid_size),
|
275 |
+
th.nn.SiLU(),
|
276 |
+
th.nn.Linear(mid_size, out_size)
|
277 |
+
])
|
278 |
+
# initialize
|
279 |
+
for proj in self.projectors:
|
280 |
+
if isinstance(proj, th.nn.Linear):
|
281 |
+
th.nn.init.xavier_uniform_(proj.weight)
|
282 |
+
th.nn.init.zeros_(proj.bias)
|
283 |
+
|
284 |
+
def forward(self, lower_in, upper_in, ):
|
285 |
+
# ALso format lower_in
|
286 |
+
lower_in = self.lower_projector(lower_in)
|
287 |
+
upper_in = self.upper_projector(upper_in)
|
288 |
+
x = th.cat([lower_in, upper_in], -1)
|
289 |
+
for proj in self.projectors:
|
290 |
+
x = proj(x)
|
291 |
+
return x
|
292 |
+
|
293 |
+
class DinoSiglipMixer(th.nn.Module):
|
294 |
+
def __init__(self, in_size=OUT_SIZE * 2, out_size=OUT_SIZE):
|
295 |
+
super().__init__()
|
296 |
+
self.dino_projector = HighLowMixer()
|
297 |
+
self.siglip_projector = HighLowMixer()
|
298 |
+
self.projectors = th.nn.Sequential(
|
299 |
+
th.nn.SiLU(),
|
300 |
+
th.nn.Linear(in_size, out_size),
|
301 |
+
)
|
302 |
+
# initialize
|
303 |
+
for proj in self.projectors:
|
304 |
+
if isinstance(proj, th.nn.Linear):
|
305 |
+
th.nn.init.xavier_uniform_(proj.weight)
|
306 |
+
th.nn.init.zeros_(proj.bias)
|
307 |
+
|
308 |
+
|
309 |
+
def forward(self, dino_in, siglip_in):
|
310 |
+
# ALso format lower_in
|
311 |
+
lower, upper = th.chunk(dino_in, 2, -1)
|
312 |
+
dino_out = self.dino_projector(lower, upper)
|
313 |
+
lower, upper = th.chunk(siglip_in, 2, -1)
|
314 |
+
siglip_out = self.siglip_projector(lower, upper)
|
315 |
+
x = th.cat([dino_out, siglip_out], -1)
|
316 |
+
for proj in self.projectors:
|
317 |
+
x = proj(x)
|
318 |
+
return x
|
319 |
+
|
320 |
+
class AnalogyEncoder(ModelMixin, ConfigMixin):
|
321 |
+
@register_to_config
|
322 |
+
def __init__(self, load_pretrained=False,
|
323 |
+
dino_config_dict=None, siglip_config_dict=None):
|
324 |
+
super().__init__()
|
325 |
+
if load_pretrained:
|
326 |
+
image_encoder_dino = AutoModel.from_pretrained('facebook/dinov2-large', torch_dtype=th.float16)
|
327 |
+
image_encoder_siglip = SiglipVisionModel.from_pretrained("google/siglip-large-patch16-256", torch_dtype=th.float16, attn_implementation="sdpa")
|
328 |
+
else:
|
329 |
+
image_encoder_dino = AutoModel.from_config(Dinov2Config.from_dict(dino_config_dict))
|
330 |
+
image_encoder_siglip = AutoModel.from_config(SiglipVisionConfig.from_dict(siglip_config_dict))
|
331 |
+
|
332 |
+
image_encoder_dino.requires_grad_(False)
|
333 |
+
image_encoder_dino = image_encoder_dino.to(memory_format=th.channels_last)
|
334 |
+
|
335 |
+
image_encoder_siglip.requires_grad_(False)
|
336 |
+
image_encoder_siglip = image_encoder_siglip.to(memory_format=th.channels_last)
|
337 |
+
self.image_encoder_dino = image_encoder_dino
|
338 |
+
self.image_encoder_siglip = image_encoder_siglip
|
339 |
+
|
340 |
+
|
341 |
+
def dino_normalization(self, encoder_output):
|
342 |
+
embeds = encoder_output.last_hidden_state
|
343 |
+
embeds_pooled = embeds[:, 0:1]
|
344 |
+
embeds = embeds / th.norm(embeds_pooled, dim=-1, keepdim=True)
|
345 |
+
return embeds
|
346 |
+
|
347 |
+
def siglip_normalization(self, encoder_output):
|
348 |
+
embeds = th.cat ([encoder_output.pooler_output[:, None, :], encoder_output.last_hidden_state], dim=1)
|
349 |
+
embeds_pooled = embeds[:, 0:1]
|
350 |
+
embeds = embeds / th.norm(embeds_pooled, dim=-1, keepdim=True)
|
351 |
+
return embeds
|
352 |
+
|
353 |
+
def forward(self, dino_in, siglip_in):
|
354 |
+
|
355 |
+
x_1 = self.image_encoder_dino(dino_in, output_hidden_states=True)
|
356 |
+
x_1_first = x_1.hidden_states[0]
|
357 |
+
x_1 = self.dino_normalization(x_1)
|
358 |
+
x_2 = self.image_encoder_siglip(siglip_in, output_hidden_states=True)
|
359 |
+
x_2_first = x_2.hidden_states[0]
|
360 |
+
x_2_first_pool = th.mean(x_2_first, dim=1, keepdim=True)
|
361 |
+
x_2_first = th.cat([x_2_first_pool, x_2_first], 1)
|
362 |
+
x_2 = self.siglip_normalization(x_2)
|
363 |
+
dino_embd = th.cat([x_1, x_1_first], -1)
|
364 |
+
siglip_embd = th.cat([x_2, x_2_first], -1)
|
365 |
+
return dino_embd, siglip_embd
|
366 |
+
|
367 |
|
368 |
class PatternAnalogyTrifuser(DiffusionPipeline):
|
369 |
r"""
|