fatoudiene commited on
Commit
071a8ea
·
verified ·
1 Parent(s): 42624d2

Mise à jour du modèle fine-tuné

Browse files
Files changed (1) hide show
  1. clip_camera_projection/zero123.py +660 -0
clip_camera_projection/zero123.py ADDED
@@ -0,0 +1,660 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ import math
18
+ import warnings
19
+ from typing import Any, Callable, Dict, List, Optional, Union
20
+
21
+ import PIL
22
+ import torch
23
+ import torchvision.transforms.functional as TF
24
+ from diffusers.configuration_utils import ConfigMixin, FrozenDict, register_to_config
25
+ from diffusers.image_processor import VaeImageProcessor
26
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
27
+ from diffusers.models.modeling_utils import ModelMixin
28
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
29
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
30
+ from diffusers.pipelines.stable_diffusion.safety_checker import (
31
+ StableDiffusionSafetyChecker,
32
+ )
33
+ from diffusers.schedulers import KarrasDiffusionSchedulers
34
+ from diffusers.utils import deprecate, is_accelerate_available, logging
35
+ from diffusers.utils.torch_utils import randn_tensor
36
+ from packaging import version
37
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ class CLIPCameraProjection(ModelMixin, ConfigMixin):
43
+ """
44
+ A Projection layer for CLIP embedding and camera embedding.
45
+ Parameters:
46
+ embedding_dim (`int`, *optional*, defaults to 768): The dimension of the model input `clip_embed`
47
+ additional_embeddings (`int`, *optional*, defaults to 4): The number of additional tokens appended to the
48
+ projected `hidden_states`. The actual length of the used `hidden_states` is `num_embeddings +
49
+ additional_embeddings`.
50
+ """
51
+
52
+ @register_to_config
53
+ def __init__(self, embedding_dim: int = 768, additional_embeddings: int = 4):
54
+ super().__init__()
55
+ self.embedding_dim = embedding_dim
56
+ self.additional_embeddings = additional_embeddings
57
+
58
+ self.input_dim = self.embedding_dim + self.additional_embeddings
59
+ self.output_dim = self.embedding_dim
60
+
61
+ self.proj = torch.nn.Linear(self.input_dim, self.output_dim)
62
+
63
+ def forward(
64
+ self,
65
+ embedding: torch.FloatTensor,
66
+ ):
67
+ """
68
+ The [`PriorTransformer`] forward method.
69
+ Args:
70
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, input_dim)`):
71
+ The currently input embeddings.
72
+ Returns:
73
+ The output embedding projection (`torch.FloatTensor` of shape `(batch_size, output_dim)`).
74
+ """
75
+ proj_embedding = self.proj(embedding)
76
+ return proj_embedding
77
+
78
+
79
+ class Zero123Pipeline(DiffusionPipeline):
80
+ r"""
81
+ Pipeline to generate variations from an input image using Stable Diffusion.
82
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
83
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
84
+ Args:
85
+ vae ([`AutoencoderKL`]):
86
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
87
+ image_encoder ([`CLIPVisionModelWithProjection`]):
88
+ Frozen CLIP image-encoder. Stable Diffusion Image Variation uses the vision portion of
89
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModelWithProjection),
90
+ specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
91
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
92
+ scheduler ([`SchedulerMixin`]):
93
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
94
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
95
+ safety_checker ([`StableDiffusionSafetyChecker`]):
96
+ Classification module that estimates whether generated images could be considered offensive or harmful.
97
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
98
+ feature_extractor ([`CLIPImageProcessor`]):
99
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
100
+ """
101
+ # TODO: feature_extractor is required to encode images (if they are in PIL format),
102
+ # we should give a descriptive message if the pipeline doesn't have one.
103
+ _optional_components = ["safety_checker"]
104
+
105
+ def __init__(
106
+ self,
107
+ vae: AutoencoderKL,
108
+ image_encoder: CLIPVisionModelWithProjection,
109
+ unet: UNet2DConditionModel,
110
+ scheduler: KarrasDiffusionSchedulers,
111
+ safety_checker: StableDiffusionSafetyChecker,
112
+ feature_extractor: CLIPImageProcessor,
113
+ clip_camera_projection: CLIPCameraProjection,
114
+ requires_safety_checker: bool = True,
115
+ ):
116
+ super().__init__()
117
+
118
+ if safety_checker is None and requires_safety_checker:
119
+ logger.warn(
120
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
121
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
122
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
123
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
124
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
125
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
126
+ )
127
+
128
+ if safety_checker is not None and feature_extractor is None:
129
+ raise ValueError(
130
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
131
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
132
+ )
133
+
134
+ is_unet_version_less_0_9_0 = hasattr(
135
+ unet.config, "_diffusers_version"
136
+ ) and version.parse(
137
+ version.parse(unet.config._diffusers_version).base_version
138
+ ) < version.parse(
139
+ "0.9.0.dev0"
140
+ )
141
+ is_unet_sample_size_less_64 = (
142
+ hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
143
+ )
144
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
145
+ deprecation_message = (
146
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
147
+ " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
148
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
149
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
150
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
151
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
152
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
153
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
154
+ " the `unet/config.json` file"
155
+ )
156
+ deprecate(
157
+ "sample_size<64", "1.0.0", deprecation_message, standard_warn=False
158
+ )
159
+ new_config = dict(unet.config)
160
+ new_config["sample_size"] = 64
161
+ unet._internal_dict = FrozenDict(new_config)
162
+
163
+ self.register_modules(
164
+ vae=vae,
165
+ image_encoder=image_encoder,
166
+ unet=unet,
167
+ scheduler=scheduler,
168
+ safety_checker=safety_checker,
169
+ feature_extractor=feature_extractor,
170
+ clip_camera_projection=clip_camera_projection,
171
+ )
172
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
173
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
174
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
175
+
176
+ def enable_sequential_cpu_offload(self, gpu_id=0):
177
+ r"""
178
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
179
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
180
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
181
+ """
182
+ if is_accelerate_available():
183
+ from accelerate import cpu_offload
184
+ else:
185
+ raise ImportError("Please install accelerate via `pip install accelerate`")
186
+
187
+ device = torch.device(f"cuda:{gpu_id}")
188
+
189
+ for cpu_offloaded_model in [
190
+ self.unet,
191
+ self.image_encoder,
192
+ self.vae,
193
+ self.safety_checker,
194
+ ]:
195
+ if cpu_offloaded_model is not None:
196
+ cpu_offload(cpu_offloaded_model, device)
197
+
198
+ @property
199
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
200
+ def _execution_device(self):
201
+ r"""
202
+ Returns the device on which the pipeline's models will be executed. After calling
203
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
204
+ hooks.
205
+ """
206
+ if not hasattr(self.unet, "_hf_hook"):
207
+ return self.device
208
+ for module in self.unet.modules():
209
+ if (
210
+ hasattr(module, "_hf_hook")
211
+ and hasattr(module._hf_hook, "execution_device")
212
+ and module._hf_hook.execution_device is not None
213
+ ):
214
+ return torch.device(module._hf_hook.execution_device)
215
+ return self.device
216
+
217
+ def _encode_image(
218
+ self,
219
+ image,
220
+ elevation,
221
+ azimuth,
222
+ distance,
223
+ device,
224
+ num_images_per_prompt,
225
+ do_classifier_free_guidance,
226
+ clip_image_embeddings=None,
227
+ image_camera_embeddings=None,
228
+ ):
229
+ dtype = next(self.image_encoder.parameters()).dtype
230
+
231
+ if image_camera_embeddings is None:
232
+ if image is None:
233
+ assert clip_image_embeddings is not None
234
+ image_embeddings = clip_image_embeddings.to(device=device, dtype=dtype)
235
+ else:
236
+ if not isinstance(image, torch.Tensor):
237
+ image = self.feature_extractor(
238
+ images=image, return_tensors="pt"
239
+ ).pixel_values
240
+
241
+ image = image.to(device=device, dtype=dtype)
242
+ image_embeddings = self.image_encoder(image).image_embeds
243
+ image_embeddings = image_embeddings.unsqueeze(1)
244
+
245
+ bs_embed, seq_len, _ = image_embeddings.shape
246
+
247
+ if isinstance(elevation, float):
248
+ elevation = torch.as_tensor(
249
+ [elevation] * bs_embed, dtype=dtype, device=device
250
+ )
251
+ if isinstance(azimuth, float):
252
+ azimuth = torch.as_tensor(
253
+ [azimuth] * bs_embed, dtype=dtype, device=device
254
+ )
255
+ if isinstance(distance, float):
256
+ distance = torch.as_tensor(
257
+ [distance] * bs_embed, dtype=dtype, device=device
258
+ )
259
+
260
+ camera_embeddings = torch.stack(
261
+ [
262
+ torch.deg2rad(elevation),
263
+ torch.sin(torch.deg2rad(azimuth)),
264
+ torch.cos(torch.deg2rad(azimuth)),
265
+ distance,
266
+ ],
267
+ dim=-1,
268
+ )[:, None, :]
269
+
270
+ image_embeddings = torch.cat([image_embeddings, camera_embeddings], dim=-1)
271
+
272
+ # project (image, camera) embeddings to the same dimension as clip embeddings
273
+ image_embeddings = self.clip_camera_projection(image_embeddings)
274
+ else:
275
+ image_embeddings = image_camera_embeddings.to(device=device, dtype=dtype)
276
+ bs_embed, seq_len, _ = image_embeddings.shape
277
+
278
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
279
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
280
+ image_embeddings = image_embeddings.view(
281
+ bs_embed * num_images_per_prompt, seq_len, -1
282
+ )
283
+
284
+ if do_classifier_free_guidance:
285
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
286
+
287
+ # For classifier free guidance, we need to do two forward passes.
288
+ # Here we concatenate the unconditional and text embeddings into a single batch
289
+ # to avoid doing two forward passes
290
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
291
+
292
+ return image_embeddings
293
+
294
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
295
+ def run_safety_checker(self, image, device, dtype):
296
+ if self.safety_checker is None:
297
+ has_nsfw_concept = None
298
+ else:
299
+ if torch.is_tensor(image):
300
+ feature_extractor_input = self.image_processor.postprocess(
301
+ image, output_type="pil"
302
+ )
303
+ else:
304
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
305
+ safety_checker_input = self.feature_extractor(
306
+ feature_extractor_input, return_tensors="pt"
307
+ ).to(device)
308
+ image, has_nsfw_concept = self.safety_checker(
309
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
310
+ )
311
+ return image, has_nsfw_concept
312
+
313
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
314
+ def decode_latents(self, latents):
315
+ warnings.warn(
316
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
317
+ " use VaeImageProcessor instead",
318
+ FutureWarning,
319
+ )
320
+ latents = 1 / self.vae.config.scaling_factor * latents
321
+ image = self.vae.decode(latents, return_dict=False)[0]
322
+ image = (image / 2 + 0.5).clamp(0, 1)
323
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
324
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
325
+ return image
326
+
327
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
328
+ def prepare_extra_step_kwargs(self, generator, eta):
329
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
330
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
331
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
332
+ # and should be between [0, 1]
333
+
334
+ accepts_eta = "eta" in set(
335
+ inspect.signature(self.scheduler.step).parameters.keys()
336
+ )
337
+ extra_step_kwargs = {}
338
+ if accepts_eta:
339
+ extra_step_kwargs["eta"] = eta
340
+
341
+ # check if the scheduler accepts generator
342
+ accepts_generator = "generator" in set(
343
+ inspect.signature(self.scheduler.step).parameters.keys()
344
+ )
345
+ if accepts_generator:
346
+ extra_step_kwargs["generator"] = generator
347
+ return extra_step_kwargs
348
+
349
+ def check_inputs(self, image, height, width, callback_steps):
350
+ # TODO: check image size or adjust image size to (height, width)
351
+
352
+ if height % 8 != 0 or width % 8 != 0:
353
+ raise ValueError(
354
+ f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
355
+ )
356
+
357
+ if (callback_steps is None) or (
358
+ callback_steps is not None
359
+ and (not isinstance(callback_steps, int) or callback_steps <= 0)
360
+ ):
361
+ raise ValueError(
362
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
363
+ f" {type(callback_steps)}."
364
+ )
365
+
366
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
367
+ def prepare_latents(
368
+ self,
369
+ batch_size,
370
+ num_channels_latents,
371
+ height,
372
+ width,
373
+ dtype,
374
+ device,
375
+ generator,
376
+ latents=None,
377
+ ):
378
+ shape = (
379
+ batch_size,
380
+ num_channels_latents,
381
+ height // self.vae_scale_factor,
382
+ width // self.vae_scale_factor,
383
+ )
384
+ if isinstance(generator, list) and len(generator) != batch_size:
385
+ raise ValueError(
386
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
387
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
388
+ )
389
+
390
+ if latents is None:
391
+ latents = randn_tensor(
392
+ shape, generator=generator, device=device, dtype=dtype
393
+ )
394
+ else:
395
+ latents = latents.to(device)
396
+
397
+ # scale the initial noise by the standard deviation required by the scheduler
398
+ latents = latents * self.scheduler.init_noise_sigma
399
+ return latents
400
+
401
+ def _get_latent_model_input(
402
+ self,
403
+ latents: torch.FloatTensor,
404
+ image: Optional[
405
+ Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor]
406
+ ],
407
+ num_images_per_prompt: int,
408
+ do_classifier_free_guidance: bool,
409
+ image_latents: Optional[torch.FloatTensor] = None,
410
+ ):
411
+ if isinstance(image, PIL.Image.Image):
412
+ image_pt = TF.to_tensor(image).unsqueeze(0).to(latents)
413
+ elif isinstance(image, list):
414
+ image_pt = torch.stack([TF.to_tensor(img) for img in image], dim=0).to(
415
+ latents
416
+ )
417
+ elif isinstance(image, torch.Tensor):
418
+ image_pt = image
419
+ else:
420
+ image_pt = None
421
+
422
+ if image_pt is None:
423
+ assert image_latents is not None
424
+ image_pt = image_latents.repeat_interleave(num_images_per_prompt, dim=0)
425
+ else:
426
+ image_pt = image_pt * 2.0 - 1.0 # scale to [-1, 1]
427
+ # FIXME: encoded latents should be multiplied with self.vae.config.scaling_factor
428
+ # but zero123 was not trained this way
429
+ image_pt = self.vae.encode(image_pt).latent_dist.mode()
430
+ image_pt = image_pt.repeat_interleave(num_images_per_prompt, dim=0)
431
+ if do_classifier_free_guidance:
432
+ latent_model_input = torch.cat(
433
+ [
434
+ torch.cat([latents, latents], dim=0),
435
+ torch.cat([torch.zeros_like(image_pt), image_pt], dim=0),
436
+ ],
437
+ dim=1,
438
+ )
439
+ else:
440
+ latent_model_input = torch.cat([latents, image_pt], dim=1)
441
+
442
+ return latent_model_input
443
+
444
+ @torch.no_grad()
445
+ def __call__(
446
+ self,
447
+ image: Optional[
448
+ Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor]
449
+ ] = None,
450
+ elevation: Optional[Union[float, torch.FloatTensor]] = None,
451
+ azimuth: Optional[Union[float, torch.FloatTensor]] = None,
452
+ distance: Optional[Union[float, torch.FloatTensor]] = None,
453
+ height: Optional[int] = None,
454
+ width: Optional[int] = None,
455
+ num_inference_steps: int = 50,
456
+ guidance_scale: float = 3.0,
457
+ num_images_per_prompt: int = 1,
458
+ eta: float = 0.0,
459
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
460
+ latents: Optional[torch.FloatTensor] = None,
461
+ clip_image_embeddings: Optional[torch.FloatTensor] = None,
462
+ image_camera_embeddings: Optional[torch.FloatTensor] = None,
463
+ image_latents: Optional[torch.FloatTensor] = None,
464
+ output_type: Optional[str] = "pil",
465
+ return_dict: bool = True,
466
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
467
+ callback_steps: int = 1,
468
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
469
+ ):
470
+ r"""
471
+ Function invoked when calling the pipeline for generation.
472
+ Args:
473
+ image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
474
+ The image or images to guide the image generation. If you provide a tensor, it needs to comply with the
475
+ configuration of
476
+ [this](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json)
477
+ `CLIPImageProcessor`
478
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
479
+ The height in pixels of the generated image.
480
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
481
+ The width in pixels of the generated image.
482
+ num_inference_steps (`int`, *optional*, defaults to 50):
483
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
484
+ expense of slower inference.
485
+ guidance_scale (`float`, *optional*, defaults to 7.5):
486
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
487
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
488
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
489
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
490
+ usually at the expense of lower image quality.
491
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
492
+ The number of images to generate per prompt.
493
+ eta (`float`, *optional*, defaults to 0.0):
494
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
495
+ [`schedulers.DDIMScheduler`], will be ignored for others.
496
+ generator (`torch.Generator`, *optional*):
497
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
498
+ to make generation deterministic.
499
+ latents (`torch.FloatTensor`, *optional*):
500
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
501
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
502
+ tensor will ge generated by sampling using the supplied random `generator`.
503
+ output_type (`str`, *optional*, defaults to `"pil"`):
504
+ The output format of the generate image. Choose between
505
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
506
+ return_dict (`bool`, *optional*, defaults to `True`):
507
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
508
+ plain tuple.
509
+ callback (`Callable`, *optional*):
510
+ A function that will be called every `callback_steps` steps during inference. The function will be
511
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
512
+ callback_steps (`int`, *optional*, defaults to 1):
513
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
514
+ called at every step.
515
+ Returns:
516
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
517
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
518
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
519
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
520
+ (nsfw) content, according to the `safety_checker`.
521
+ """
522
+ # 0. Default height and width to unet
523
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
524
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
525
+
526
+ # 1. Check inputs. Raise error if not correct
527
+ # TODO: check input elevation, azimuth, and distance
528
+ # TODO: check image, clip_image_embeddings, image_latents
529
+ self.check_inputs(image, height, width, callback_steps)
530
+
531
+ # 2. Define call parameters
532
+ if isinstance(image, PIL.Image.Image):
533
+ batch_size = 1
534
+ elif isinstance(image, list):
535
+ batch_size = len(image)
536
+ elif isinstance(image, torch.Tensor):
537
+ batch_size = image.shape[0]
538
+ else:
539
+ assert image_latents is not None
540
+ assert (
541
+ clip_image_embeddings is not None or image_camera_embeddings is not None
542
+ )
543
+ batch_size = image_latents.shape[0]
544
+
545
+ device = self._execution_device
546
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
547
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
548
+ # corresponds to doing no classifier free guidance.
549
+ do_classifier_free_guidance = guidance_scale > 1.0
550
+
551
+ # 3. Encode input image
552
+ if isinstance(image, PIL.Image.Image) or isinstance(image, list):
553
+ pil_image = image
554
+ elif isinstance(image, torch.Tensor):
555
+ pil_image = [TF.to_pil_image(image[i]) for i in range(image.shape[0])]
556
+ else:
557
+ pil_image = None
558
+ image_embeddings = self._encode_image(
559
+ pil_image,
560
+ elevation,
561
+ azimuth,
562
+ distance,
563
+ device,
564
+ num_images_per_prompt,
565
+ do_classifier_free_guidance,
566
+ clip_image_embeddings,
567
+ image_camera_embeddings,
568
+ )
569
+
570
+ # 4. Prepare timesteps
571
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
572
+ timesteps = self.scheduler.timesteps
573
+
574
+ # 5. Prepare latent variables
575
+ # num_channels_latents = self.unet.config.in_channels
576
+ num_channels_latents = 4 # FIXME: hard-coded
577
+ latents = self.prepare_latents(
578
+ batch_size * num_images_per_prompt,
579
+ num_channels_latents,
580
+ height,
581
+ width,
582
+ image_embeddings.dtype,
583
+ device,
584
+ generator,
585
+ latents,
586
+ )
587
+
588
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
589
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
590
+
591
+ # 7. Denoising loop
592
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
593
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
594
+ for i, t in enumerate(timesteps):
595
+ # expand the latents if we are doing classifier free guidance
596
+ latent_model_input = self._get_latent_model_input(
597
+ latents,
598
+ image,
599
+ num_images_per_prompt,
600
+ do_classifier_free_guidance,
601
+ image_latents,
602
+ )
603
+ latent_model_input = self.scheduler.scale_model_input(
604
+ latent_model_input, t
605
+ )
606
+
607
+ # predict the noise residual
608
+ noise_pred = self.unet(
609
+ latent_model_input,
610
+ t,
611
+ encoder_hidden_states=image_embeddings,
612
+ cross_attention_kwargs=cross_attention_kwargs,
613
+ ).sample
614
+
615
+ # perform guidance
616
+ if do_classifier_free_guidance:
617
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
618
+ noise_pred = noise_pred_uncond + guidance_scale * (
619
+ noise_pred_text - noise_pred_uncond
620
+ )
621
+
622
+ # compute the previous noisy sample x_t -> x_t-1
623
+ latents = self.scheduler.step(
624
+ noise_pred, t, latents, **extra_step_kwargs
625
+ ).prev_sample
626
+
627
+ # call the callback, if provided
628
+ if i == len(timesteps) - 1 or (
629
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
630
+ ):
631
+ progress_bar.update()
632
+ if callback is not None and i % callback_steps == 0:
633
+ callback(i, t, latents)
634
+
635
+ if not output_type == "latent":
636
+ image = self.vae.decode(
637
+ latents / self.vae.config.scaling_factor, return_dict=False
638
+ )[0]
639
+ image, has_nsfw_concept = self.run_safety_checker(
640
+ image, device, image_embeddings.dtype
641
+ )
642
+ else:
643
+ image = latents
644
+ has_nsfw_concept = None
645
+
646
+ if has_nsfw_concept is None:
647
+ do_denormalize = [True] * image.shape[0]
648
+ else:
649
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
650
+
651
+ image = self.image_processor.postprocess(
652
+ image, output_type=output_type, do_denormalize=do_denormalize
653
+ )
654
+
655
+ if not return_dict:
656
+ return (image, has_nsfw_concept)
657
+
658
+ return StableDiffusionPipelineOutput(
659
+ images=image, nsfw_content_detected=has_nsfw_concept
660
+ )