bardofcodes commited on
Commit
e1256c0
·
verified ·
1 Parent(s): 55febf3

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +741 -0
pipeline.py ADDED
@@ -0,0 +1,741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ADOBE CONFIDENTIAL
3
+ Copyright 2024 Adobe
4
+ All Rights Reserved.
5
+ NOTICE: All information contained herein is, and remains
6
+ the property of Adobe and its suppliers, if any. The intellectual
7
+ and technical concepts contained herein are proprietary to Adobe
8
+ and its suppliers and are protected by all applicable intellectual
9
+ property laws, including trade secret and copyright laws.
10
+ Dissemination of this information or reproduction of this material
11
+ is strictly forbidden unless prior written permission is obtained
12
+ from Adobe.
13
+ """
14
+
15
+ from typing import Callable, List, Optional, Union
16
+ import inspect
17
+ import einops
18
+ import PIL.Image
19
+ import numpy as np
20
+ import torch as th
21
+ import torch.nn as nn
22
+ from torchvision import transforms
23
+
24
+ from diffusers import ModelMixin
25
+ from transformers import AutoModel, AutoConfig, SiglipVisionConfig, Dinov2Config, Dinov2Model
26
+ from transformers import SiglipVisionModel
27
+ from diffusers import DiffusionPipeline
28
+ from diffusers.image_processor import VaeImageProcessor
29
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
30
+ from diffusers.schedulers import KarrasDiffusionSchedulers
31
+ from diffusers.utils.torch_utils import randn_tensor
32
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
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"""
370
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
371
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
372
+ """
373
+
374
+ model_cpu_offload_seq = "bert->unet->vqvae"
375
+
376
+ analogy_input_processor: AnalogyInputProcessor
377
+ analogy_encoder: AnalogyEncoder
378
+ analogy_projector: AnalogyProjector
379
+ unet: UNet2DConditionModel
380
+ vae: AutoencoderKL
381
+ scheduler: KarrasDiffusionSchedulers
382
+
383
+ def __init__(self,
384
+ analogy_input_processor: AnalogyInputProcessor,
385
+ analogy_projector: AnalogyProjector,
386
+ analogy_encoder: AnalogyEncoder,
387
+ unet: UNet2DConditionModel,
388
+ vae: AutoencoderKL,
389
+ scheduler: KarrasDiffusionSchedulers,):
390
+
391
+
392
+ super().__init__()
393
+ self.register_modules(
394
+ analogy_input_processor=analogy_input_processor,
395
+ analogy_encoder=analogy_encoder,
396
+ analogy_projector=analogy_projector,
397
+ unet=unet,
398
+ vae=vae,
399
+ scheduler=scheduler,
400
+ )
401
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
402
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
403
+
404
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_image_variation.StableDiffusionImageVariationPipeline.check_inputs
405
+ def check_inputs(self, analogy_prompt, negative_analogy_prompt, height, width, callback_steps):
406
+ if (
407
+ not isinstance(analogy_prompt, th.Tensor)
408
+ and not isinstance(analogy_prompt, PIL.Image.Image)
409
+ and not isinstance(analogy_prompt, list)
410
+ ):
411
+ raise ValueError(
412
+ "`analogy_prompt` contents have to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
413
+ f" {type(analogy_prompt)}"
414
+ )
415
+ if not negative_analogy_prompt is None:
416
+ if (
417
+ not isinstance(negative_analogy_prompt, th.Tensor)
418
+ and not isinstance(negative_analogy_prompt, PIL.Image.Image)
419
+ and not isinstance(negative_analogy_prompt, list)
420
+ ):
421
+ raise ValueError(
422
+ "`negative_analogy_prompt` contents have to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
423
+ f" {type(negative_analogy_prompt)}"
424
+ )
425
+
426
+
427
+ if height % 8 != 0 or width % 8 != 0:
428
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
429
+
430
+ if (callback_steps is None) or (
431
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
432
+ ):
433
+ raise ValueError(
434
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
435
+ f" {type(callback_steps)}."
436
+ )
437
+
438
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
439
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
440
+ shape = (
441
+ batch_size,
442
+ num_channels_latents,
443
+ int(height) // self.vae_scale_factor,
444
+ int(width) // self.vae_scale_factor,
445
+ )
446
+ if isinstance(generator, list) and len(generator) != batch_size:
447
+ raise ValueError(
448
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
449
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
450
+ )
451
+
452
+ if latents is None:
453
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
454
+ else:
455
+ latents = latents.to(device)
456
+
457
+ # scale the initial noise by the standard deviation required by the scheduler
458
+ latents = latents * self.scheduler.init_noise_sigma
459
+ return latents
460
+
461
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
462
+ def prepare_extra_step_kwargs(self, generator, eta):
463
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
464
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
465
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
466
+ # and should be between [0, 1]
467
+
468
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
469
+ extra_step_kwargs = {}
470
+ if accepts_eta:
471
+ extra_step_kwargs["eta"] = eta
472
+
473
+ # check if the scheduler accepts generator
474
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
475
+ if accepts_generator:
476
+ extra_step_kwargs["generator"] = generator
477
+ return extra_step_kwargs
478
+
479
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
480
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
481
+ shape = (
482
+ batch_size,
483
+ num_channels_latents,
484
+ int(height) // self.vae_scale_factor,
485
+ int(width) // self.vae_scale_factor,
486
+ )
487
+ if isinstance(generator, list) and len(generator) != batch_size:
488
+ raise ValueError(
489
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
490
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
491
+ )
492
+
493
+ if latents is None:
494
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
495
+ else:
496
+ latents = latents.to(device)
497
+
498
+ # scale the initial noise by the standard deviation required by the scheduler
499
+ latents = latents * self.scheduler.init_noise_sigma
500
+ return latents
501
+
502
+ def _encode_prompt(self, analogy_prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
503
+ r"""
504
+ Encodes the prompt into text encoder hidden states.
505
+
506
+ Args:
507
+ prompt (`str` or `List[str]`):
508
+ prompt to be encoded
509
+ device: (`torch.device`):
510
+ torch device
511
+ num_images_per_prompt (`int`):
512
+ number of images that should be generated per prompt
513
+ do_classifier_free_guidance (`bool`):
514
+ whether to use classifier free guidance or not
515
+ negative_prompt (`str` or `List[str]`):
516
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
517
+ if `guidance_scale` is less than `1`).
518
+ """
519
+ weight_dtype = self.unet.dtype
520
+ dino_input, siglip_input = self.analogy_input_processor(analogy_prompt)
521
+ dino_input = dino_input.to(device=device).to(dtype=weight_dtype)
522
+ siglip_input = siglip_input.to(device=device).to(dtype=weight_dtype)
523
+ batch_size = dino_input.shape[1]
524
+ dino_input_reshaped = einops.rearrange(dino_input, "k b c h w -> (k b) c h w")
525
+ siglip_input_reshaped = einops.rearrange(siglip_input, "k b c h w -> (k b) c h w")
526
+ dino_enc, siglip_enc = self.analogy_encoder(dino_input_reshaped, siglip_input_reshaped)
527
+ image_embeddings = self.analogy_projector(dino_enc, siglip_enc, batch_size)
528
+ # Check size here.
529
+
530
+ bs_embed, seq_len, _ = image_embeddings.shape
531
+ image_embeddings = image_embeddings.repeat(num_images_per_prompt, 1, 1)
532
+ # get unconditional embeddings for classifier free guidance
533
+ if do_classifier_free_guidance:
534
+ uncond_images: List[str]
535
+ if negative_prompt is None:
536
+ uncond_images = [np.zeros((512, 512, 3)) + 0.5] * batch_size
537
+ elif type(negative_prompt) is not type(analogy_prompt):
538
+ raise TypeError(
539
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(analogy_prompt)} !="
540
+ f" {type(negative_prompt)}."
541
+ )
542
+ elif isinstance(negative_prompt, PIL.Image.Image):
543
+ uncond_images = [negative_prompt]
544
+ elif batch_size != len(negative_prompt):
545
+ raise ValueError(
546
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
547
+ f" {analogy_prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
548
+ " the batch size of `prompt`."
549
+ )
550
+ else:
551
+ uncond_images = negative_prompt
552
+ dino_neg, siglip_neg = self.analogy_input_processor.get_negative(dino_input, siglip_input)
553
+
554
+ dino_neg = dino_neg.to(device=device).to(dtype=weight_dtype)
555
+ siglip_neg = siglip_neg.to(device=device).to(dtype=weight_dtype)
556
+ dino_neg_reshaped = einops.rearrange(dino_neg, "k b c h w -> (k b) c h w")
557
+ siglip_neg_reshaped = einops.rearrange(siglip_neg, "k b c h w -> (k b) c h w")
558
+ dino_neg_enc, siglip_neg_enc = self.analogy_encoder(dino_neg_reshaped, siglip_neg_reshaped)
559
+ negative_prompt_embeds = self.analogy_projector(dino_neg_enc, siglip_neg_enc, batch_size)
560
+
561
+ negative_prompt_embeds = negative_prompt_embeds.repeat(num_images_per_prompt, 1, 1)
562
+ image_embeddings = th.cat([negative_prompt_embeds, image_embeddings])
563
+
564
+
565
+ return image_embeddings
566
+
567
+ @th.no_grad()
568
+ def __call__(
569
+ self,
570
+ analogy_prompt: Union[str, List[str]] = None,
571
+ num_inference_steps: int = 50,
572
+ guidance_scale: float = 7.5,
573
+ height: Optional[int] = None,
574
+ width: Optional[int] = None,
575
+ negative_analogy_prompt: Optional[Union[str, List[str]]] = None,
576
+ num_images_per_prompt: Optional[int] = 1,
577
+ eta: float = 0.0,
578
+ generator: Optional[Union[th.Generator, List[th.Generator]]] = None,
579
+ latents: Optional[th.FloatTensor] = None,
580
+ output_type: Optional[str] = "pil",
581
+ return_dict: bool = True,
582
+ callback: Optional[Callable[[int, int, th.Tensor], None]] = None,
583
+ callback_steps: int = 1,
584
+ start_step: int = 0,
585
+ ):
586
+ r"""
587
+ The call function to the pipeline for generation.
588
+
589
+ Args:
590
+ image (`PIL.Image.Image`, `List[PIL.Image.Image]` or `torch.Tensor`):
591
+ The image prompt or prompts to guide the image generation.
592
+ height (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
593
+ The height in pixels of the generated image.
594
+ width (`int`, *optional*, defaults to `self.image_unet.config.sample_size * self.vae_scale_factor`):
595
+ The width in pixels of the generated image.
596
+ num_inference_steps (`int`, *optional*, defaults to 50):
597
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
598
+ expense of slower inference.
599
+ guidance_scale (`float`, *optional*, defaults to 7.5):
600
+ A higher guidance scale value encourages the model to generate images closely linked to the text
601
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
602
+ negative_prompt (`str` or `List[str]`, *optional*):
603
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
604
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
605
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
606
+ The number of images to generate per prompt.
607
+ eta (`float`, *optional*, defaults to 0.0):
608
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
609
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
610
+ generator (`torch.Generator`, *optional*):
611
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
612
+ generation deterministic.
613
+ latents (`torch.Tensor`, *optional*):
614
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
615
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
616
+ tensor is generated by sampling using the supplied random `generator`.
617
+ output_type (`str`, *optional*, defaults to `"pil"`):
618
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
619
+ return_dict (`bool`, *optional*, defaults to `True`):
620
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
621
+ plain tuple.
622
+ callback (`Callable`, *optional*):
623
+ A function that calls every `callback_steps` steps during inference. The function is called with the
624
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
625
+ callback_steps (`int`, *optional*, defaults to 1):
626
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
627
+ every step.
628
+
629
+ Examples:
630
+
631
+ ```py
632
+ >>> from diffusers import VersatileDiffusionImageVariationPipeline
633
+ >>> import torch
634
+ >>> import requests
635
+ >>> from io import BytesIO
636
+ >>> from PIL import Image
637
+
638
+ >>> # let's download an initial image
639
+ >>> url = "https://huggingface.co/datasets/diffusers/images/resolve/main/benz.jpg"
640
+
641
+ >>> response = requests.get(url)
642
+ >>> image = Image.open(BytesIO(response.content)).convert("RGB")
643
+
644
+ >>> pipe = VersatileDiffusionImageVariationPipeline.from_pretrained(
645
+ ... "shi-labs/versatile-diffusion", torch_dtype=torch.float16
646
+ ... )
647
+ >>> pipe = pipe.to("cuda")
648
+
649
+ >>> generator = torch.Generator(device="cuda").manual_seed(0)
650
+ >>> image = pipe(image, generator=generator).images[0]
651
+ >>> image.save("./car_variation.png")
652
+ ```
653
+
654
+ Returns:
655
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
656
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
657
+ otherwise a `tuple` is returned where the first element is a list with the generated images.
658
+ """
659
+
660
+ # 1. Check inputs. Raise error if not correct
661
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
662
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
663
+
664
+ # 1. Check inputs. Raise error if not correct
665
+ self.check_inputs(analogy_prompt, negative_analogy_prompt, height, width, callback_steps)
666
+
667
+ # 2. Define call parameters
668
+ if isinstance(analogy_prompt, list):
669
+ batch_size = len(analogy_prompt)
670
+ elif isinstance(analogy_prompt, tuple):
671
+ batch_size = 1
672
+ else:
673
+ raise ValueError(
674
+ f"`analogy_prompt` has to be a list of images or a tuple of images but is of type {type(analogy_prompt)}"
675
+ )
676
+ device = self._execution_device
677
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
678
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
679
+ # corresponds to doing no classifier free guidance.
680
+ do_classifier_free_guidance = guidance_scale > 1.0
681
+
682
+ # 3. Encode input prompt
683
+ analogy_embeddings = self._encode_prompt(
684
+ analogy_prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_analogy_prompt
685
+ )
686
+
687
+ # 4. Prepare timesteps
688
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
689
+
690
+ timesteps = self.scheduler.timesteps
691
+ # Now this should be from start step onwards
692
+ timesteps = timesteps[start_step:]
693
+ # 5. Prepare latent variables
694
+ num_channels_latents = self.unet.config.in_channels
695
+ latents = self.prepare_latents(
696
+ batch_size * num_images_per_prompt,
697
+ num_channels_latents,
698
+ height,
699
+ width,
700
+ analogy_embeddings.dtype,
701
+ device,
702
+ generator,
703
+ latents,
704
+ )
705
+
706
+ # 6. Prepare extra step kwargs.
707
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
708
+
709
+ # 7. Denoising loop
710
+ for i, t in enumerate(self.progress_bar(timesteps)):
711
+ # expand the latents if we are doing classifier free guidance
712
+ latent_model_input = th.cat([latents] * 2) if do_classifier_free_guidance else latents
713
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
714
+
715
+ # predict the noise residual
716
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=analogy_embeddings).sample
717
+
718
+ # perform guidance
719
+ if do_classifier_free_guidance:
720
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
721
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
722
+
723
+ # compute the previous noisy sample x_t -> x_t-1
724
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
725
+
726
+ # call the callback, if provided
727
+ if callback is not None and i % callback_steps == 0:
728
+ step_idx = i // getattr(self.scheduler, "order", 1)
729
+ callback(step_idx, t, latents)
730
+
731
+ if not output_type == "latent":
732
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
733
+ else:
734
+ image = latents
735
+
736
+ image = self.image_processor.postprocess(image, output_type=output_type)
737
+
738
+ if not return_dict:
739
+ return (image,)
740
+
741
+ return ImagePipelineOutput(images=image)