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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A diffuser version implementation of Zero1to3 (https://github.com/cvlab-columbia/zero123), ICCV 2023
|
| 2 |
+
# by Xin Kong
|
| 3 |
+
|
| 4 |
+
import inspect
|
| 5 |
+
import sys
|
| 6 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from packaging import version
|
| 11 |
+
from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
| 12 |
+
import einops
|
| 13 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, DiffusionPipeline
|
| 14 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
|
| 15 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 16 |
+
from diffusers.utils import (
|
| 17 |
+
deprecate,
|
| 18 |
+
is_accelerate_available,
|
| 19 |
+
is_accelerate_version,
|
| 20 |
+
logging,
|
| 21 |
+
replace_example_docstring,
|
| 22 |
+
)
|
| 23 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 24 |
+
from diffusers.configuration_utils import FrozenDict
|
| 25 |
+
import PIL
|
| 26 |
+
import numpy as np
|
| 27 |
+
import math
|
| 28 |
+
import kornia
|
| 29 |
+
from diffusers.configuration_utils import ConfigMixin
|
| 30 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 33 |
+
# todo
|
| 34 |
+
EXAMPLE_DOC_STRING = """
|
| 35 |
+
Examples:
|
| 36 |
+
```py
|
| 37 |
+
>>> import torch
|
| 38 |
+
>>> from diffusers import StableDiffusionPipeline
|
| 39 |
+
|
| 40 |
+
>>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
|
| 41 |
+
>>> pipe = pipe.to("cuda")
|
| 42 |
+
|
| 43 |
+
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
| 44 |
+
>>> image = pipe(prompt).images[0]
|
| 45 |
+
```
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class CCProjection(ModelMixin, ConfigMixin):
|
| 50 |
+
def __init__(self, in_channel=772, out_channel=768):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.in_channel = in_channel
|
| 53 |
+
self.out_channel = out_channel
|
| 54 |
+
self.projection = torch.nn.Linear(in_channel, out_channel)
|
| 55 |
+
|
| 56 |
+
def forward(self, x):
|
| 57 |
+
return self.projection(x)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Zero1to3StableDiffusionPipeline(DiffusionPipeline):
|
| 61 |
+
r"""
|
| 62 |
+
Pipeline for single view conditioned novel view generation using Zero1to3.
|
| 63 |
+
|
| 64 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
| 65 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
vae ([`AutoencoderKL`]):
|
| 69 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 70 |
+
image_encoder ([`CLIPVisionModelWithProjection`]):
|
| 71 |
+
Frozen CLIP image-encoder. Stable Diffusion Image Variation uses the vision portion of
|
| 72 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModelWithProjection),
|
| 73 |
+
specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 74 |
+
tokenizer (`CLIPTokenizer`):
|
| 75 |
+
Tokenizer of class
|
| 76 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 77 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
| 78 |
+
scheduler ([`SchedulerMixin`]):
|
| 79 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 80 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 81 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 82 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 83 |
+
Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
|
| 84 |
+
feature_extractor ([`CLIPFeatureExtractor`]):
|
| 85 |
+
Model that extracts features from generated images to be used as inputs for the `safety_checker`.
|
| 86 |
+
"""
|
| 87 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
vae: AutoencoderKL,
|
| 92 |
+
image_encoder: CLIPVisionModelWithProjection,
|
| 93 |
+
unet: UNet2DConditionModel,
|
| 94 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 95 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 96 |
+
feature_extractor: CLIPFeatureExtractor,
|
| 97 |
+
cc_projection: CCProjection,
|
| 98 |
+
requires_safety_checker: bool = True,
|
| 99 |
+
):
|
| 100 |
+
super().__init__()
|
| 101 |
+
|
| 102 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
| 103 |
+
deprecation_message = (
|
| 104 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
| 105 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
| 106 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
| 107 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
| 108 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
| 109 |
+
" file"
|
| 110 |
+
)
|
| 111 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
| 112 |
+
new_config = dict(scheduler.config)
|
| 113 |
+
new_config["steps_offset"] = 1
|
| 114 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 115 |
+
|
| 116 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
| 117 |
+
deprecation_message = (
|
| 118 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
| 119 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
| 120 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
| 121 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
| 122 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
| 123 |
+
)
|
| 124 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
| 125 |
+
new_config = dict(scheduler.config)
|
| 126 |
+
new_config["clip_sample"] = False
|
| 127 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 128 |
+
|
| 129 |
+
if safety_checker is None and requires_safety_checker:
|
| 130 |
+
logger.warning(
|
| 131 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 132 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
| 133 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 134 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 135 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 136 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if safety_checker is not None and feature_extractor is None:
|
| 140 |
+
raise ValueError(
|
| 141 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 142 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
| 146 |
+
version.parse(unet.config._diffusers_version).base_version
|
| 147 |
+
) < version.parse("0.9.0.dev0")
|
| 148 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
| 149 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
| 150 |
+
deprecation_message = (
|
| 151 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
| 152 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
| 153 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
| 154 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
| 155 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
| 156 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
| 157 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
| 158 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
| 159 |
+
" the `unet/config.json` file"
|
| 160 |
+
)
|
| 161 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
| 162 |
+
new_config = dict(unet.config)
|
| 163 |
+
new_config["sample_size"] = 64
|
| 164 |
+
unet._internal_dict = FrozenDict(new_config)
|
| 165 |
+
|
| 166 |
+
self.register_modules(
|
| 167 |
+
vae=vae,
|
| 168 |
+
image_encoder=image_encoder,
|
| 169 |
+
unet=unet,
|
| 170 |
+
scheduler=scheduler,
|
| 171 |
+
safety_checker=safety_checker,
|
| 172 |
+
feature_extractor=feature_extractor,
|
| 173 |
+
cc_projection=cc_projection,
|
| 174 |
+
)
|
| 175 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 176 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 177 |
+
# self.model_mode = None
|
| 178 |
+
|
| 179 |
+
def enable_vae_slicing(self):
|
| 180 |
+
r"""
|
| 181 |
+
Enable sliced VAE decoding.
|
| 182 |
+
|
| 183 |
+
When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
|
| 184 |
+
steps. This is useful to save some memory and allow larger batch sizes.
|
| 185 |
+
"""
|
| 186 |
+
self.vae.enable_slicing()
|
| 187 |
+
|
| 188 |
+
def disable_vae_slicing(self):
|
| 189 |
+
r"""
|
| 190 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
|
| 191 |
+
computing decoding in one step.
|
| 192 |
+
"""
|
| 193 |
+
self.vae.disable_slicing()
|
| 194 |
+
|
| 195 |
+
def enable_vae_tiling(self):
|
| 196 |
+
r"""
|
| 197 |
+
Enable tiled VAE decoding.
|
| 198 |
+
|
| 199 |
+
When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
|
| 200 |
+
several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
|
| 201 |
+
"""
|
| 202 |
+
self.vae.enable_tiling()
|
| 203 |
+
|
| 204 |
+
def disable_vae_tiling(self):
|
| 205 |
+
r"""
|
| 206 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
|
| 207 |
+
computing decoding in one step.
|
| 208 |
+
"""
|
| 209 |
+
self.vae.disable_tiling()
|
| 210 |
+
|
| 211 |
+
def enable_sequential_cpu_offload(self, gpu_id=0):
|
| 212 |
+
r"""
|
| 213 |
+
Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
|
| 214 |
+
text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
|
| 215 |
+
`torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
|
| 216 |
+
Note that offloading happens on a submodule basis. Memory savings are higher than with
|
| 217 |
+
`enable_model_cpu_offload`, but performance is lower.
|
| 218 |
+
"""
|
| 219 |
+
if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
|
| 220 |
+
from accelerate import cpu_offload
|
| 221 |
+
else:
|
| 222 |
+
raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
|
| 223 |
+
|
| 224 |
+
device = torch.device(f"cuda:{gpu_id}")
|
| 225 |
+
|
| 226 |
+
if self.device.type != "cpu":
|
| 227 |
+
self.to("cpu", silence_dtype_warnings=True)
|
| 228 |
+
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
|
| 229 |
+
|
| 230 |
+
for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
|
| 231 |
+
cpu_offload(cpu_offloaded_model, device)
|
| 232 |
+
|
| 233 |
+
if self.safety_checker is not None:
|
| 234 |
+
cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
|
| 235 |
+
|
| 236 |
+
def enable_model_cpu_offload(self, gpu_id=0):
|
| 237 |
+
r"""
|
| 238 |
+
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
|
| 239 |
+
to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
|
| 240 |
+
method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
|
| 241 |
+
`enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
|
| 242 |
+
"""
|
| 243 |
+
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
| 244 |
+
from accelerate import cpu_offload_with_hook
|
| 245 |
+
else:
|
| 246 |
+
raise ImportError("`enable_model_offload` requires `accelerate v0.17.0` or higher.")
|
| 247 |
+
|
| 248 |
+
device = torch.device(f"cuda:{gpu_id}")
|
| 249 |
+
|
| 250 |
+
if self.device.type != "cpu":
|
| 251 |
+
self.to("cpu", silence_dtype_warnings=True)
|
| 252 |
+
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
|
| 253 |
+
|
| 254 |
+
hook = None
|
| 255 |
+
for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
|
| 256 |
+
_, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
|
| 257 |
+
|
| 258 |
+
if self.safety_checker is not None:
|
| 259 |
+
_, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
|
| 260 |
+
|
| 261 |
+
# We'll offload the last model manually.
|
| 262 |
+
self.final_offload_hook = hook
|
| 263 |
+
|
| 264 |
+
@property
|
| 265 |
+
def _execution_device(self):
|
| 266 |
+
r"""
|
| 267 |
+
Returns the device on which the pipeline's models will be executed. After calling
|
| 268 |
+
`pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
|
| 269 |
+
hooks.
|
| 270 |
+
"""
|
| 271 |
+
if not hasattr(self.unet, "_hf_hook"):
|
| 272 |
+
return self.device
|
| 273 |
+
for module in self.unet.modules():
|
| 274 |
+
if (
|
| 275 |
+
hasattr(module, "_hf_hook")
|
| 276 |
+
and hasattr(module._hf_hook, "execution_device")
|
| 277 |
+
and module._hf_hook.execution_device is not None
|
| 278 |
+
):
|
| 279 |
+
return torch.device(module._hf_hook.execution_device)
|
| 280 |
+
return self.device
|
| 281 |
+
|
| 282 |
+
def _encode_prompt(
|
| 283 |
+
self,
|
| 284 |
+
prompt,
|
| 285 |
+
device,
|
| 286 |
+
num_images_per_prompt,
|
| 287 |
+
do_classifier_free_guidance,
|
| 288 |
+
negative_prompt=None,
|
| 289 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 290 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 291 |
+
):
|
| 292 |
+
r"""
|
| 293 |
+
Encodes the prompt into text encoder hidden states.
|
| 294 |
+
|
| 295 |
+
Args:
|
| 296 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 297 |
+
prompt to be encoded
|
| 298 |
+
device: (`torch.device`):
|
| 299 |
+
torch device
|
| 300 |
+
num_images_per_prompt (`int`):
|
| 301 |
+
number of images that should be generated per prompt
|
| 302 |
+
do_classifier_free_guidance (`bool`):
|
| 303 |
+
whether to use classifier free guidance or not
|
| 304 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 305 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 306 |
+
`negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
|
| 307 |
+
Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
|
| 308 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 309 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 310 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 311 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 312 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 313 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 314 |
+
argument.
|
| 315 |
+
"""
|
| 316 |
+
if prompt is not None and isinstance(prompt, str):
|
| 317 |
+
batch_size = 1
|
| 318 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 319 |
+
batch_size = len(prompt)
|
| 320 |
+
else:
|
| 321 |
+
batch_size = prompt_embeds.shape[0]
|
| 322 |
+
|
| 323 |
+
if prompt_embeds is None:
|
| 324 |
+
text_inputs = self.tokenizer(
|
| 325 |
+
prompt,
|
| 326 |
+
padding="max_length",
|
| 327 |
+
max_length=self.tokenizer.model_max_length,
|
| 328 |
+
truncation=True,
|
| 329 |
+
return_tensors="pt",
|
| 330 |
+
)
|
| 331 |
+
text_input_ids = text_inputs.input_ids
|
| 332 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 333 |
+
|
| 334 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 335 |
+
text_input_ids, untruncated_ids
|
| 336 |
+
):
|
| 337 |
+
removed_text = self.tokenizer.batch_decode(
|
| 338 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 339 |
+
)
|
| 340 |
+
logger.warning(
|
| 341 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 342 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 346 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 347 |
+
else:
|
| 348 |
+
attention_mask = None
|
| 349 |
+
|
| 350 |
+
prompt_embeds = self.text_encoder(
|
| 351 |
+
text_input_ids.to(device),
|
| 352 |
+
attention_mask=attention_mask,
|
| 353 |
+
)
|
| 354 |
+
prompt_embeds = prompt_embeds[0]
|
| 355 |
+
|
| 356 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
| 357 |
+
|
| 358 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 359 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 360 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 361 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 362 |
+
|
| 363 |
+
# get unconditional embeddings for classifier free guidance
|
| 364 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 365 |
+
uncond_tokens: List[str]
|
| 366 |
+
if negative_prompt is None:
|
| 367 |
+
uncond_tokens = [""] * batch_size
|
| 368 |
+
elif type(prompt) is not type(negative_prompt):
|
| 369 |
+
raise TypeError(
|
| 370 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 371 |
+
f" {type(prompt)}."
|
| 372 |
+
)
|
| 373 |
+
elif isinstance(negative_prompt, str):
|
| 374 |
+
uncond_tokens = [negative_prompt]
|
| 375 |
+
elif batch_size != len(negative_prompt):
|
| 376 |
+
raise ValueError(
|
| 377 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 378 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 379 |
+
" the batch size of `prompt`."
|
| 380 |
+
)
|
| 381 |
+
else:
|
| 382 |
+
uncond_tokens = negative_prompt
|
| 383 |
+
|
| 384 |
+
max_length = prompt_embeds.shape[1]
|
| 385 |
+
uncond_input = self.tokenizer(
|
| 386 |
+
uncond_tokens,
|
| 387 |
+
padding="max_length",
|
| 388 |
+
max_length=max_length,
|
| 389 |
+
truncation=True,
|
| 390 |
+
return_tensors="pt",
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 394 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 395 |
+
else:
|
| 396 |
+
attention_mask = None
|
| 397 |
+
|
| 398 |
+
negative_prompt_embeds = self.text_encoder(
|
| 399 |
+
uncond_input.input_ids.to(device),
|
| 400 |
+
attention_mask=attention_mask,
|
| 401 |
+
)
|
| 402 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 403 |
+
|
| 404 |
+
if do_classifier_free_guidance:
|
| 405 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 406 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 407 |
+
|
| 408 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
| 409 |
+
|
| 410 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 411 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 412 |
+
|
| 413 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 414 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 415 |
+
# to avoid doing two forward passes
|
| 416 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 417 |
+
|
| 418 |
+
return prompt_embeds
|
| 419 |
+
|
| 420 |
+
def CLIP_preprocess(self, x):
|
| 421 |
+
dtype = x.dtype
|
| 422 |
+
# following openai's implementation
|
| 423 |
+
# TODO HF OpenAI CLIP preprocessing issue https://github.com/huggingface/transformers/issues/22505#issuecomment-1650170741
|
| 424 |
+
# follow openai preprocessing to keep exact same, input tensor [-1, 1], otherwise the preprocessing will be different, https://github.com/huggingface/transformers/pull/22608
|
| 425 |
+
if isinstance(x, torch.Tensor):
|
| 426 |
+
if x.min() < -1.0 or x.max() > 1.0:
|
| 427 |
+
raise ValueError("Expected input tensor to have values in the range [-1, 1]")
|
| 428 |
+
x = kornia.geometry.resize(x.to(torch.float32), (224, 224), interpolation='bicubic', align_corners=True, antialias=False).to(dtype=dtype)
|
| 429 |
+
x = (x + 1.) / 2.
|
| 430 |
+
# renormalize according to clip
|
| 431 |
+
x = kornia.enhance.normalize(x, torch.Tensor([0.48145466, 0.4578275, 0.40821073]),
|
| 432 |
+
torch.Tensor([0.26862954, 0.26130258, 0.27577711]))
|
| 433 |
+
return x
|
| 434 |
+
|
| 435 |
+
# from image_variation
|
| 436 |
+
def _encode_image(self, image, device, num_images_per_prompt, do_classifier_free_guidance):
|
| 437 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 438 |
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
| 439 |
+
raise ValueError(
|
| 440 |
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
if isinstance(image, torch.Tensor):
|
| 444 |
+
# Batch single image
|
| 445 |
+
if image.ndim == 3:
|
| 446 |
+
assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
|
| 447 |
+
image = image.unsqueeze(0)
|
| 448 |
+
|
| 449 |
+
assert image.ndim == 4, "Image must have 4 dimensions"
|
| 450 |
+
|
| 451 |
+
# Check image is in [-1, 1]
|
| 452 |
+
if image.min() < -1 or image.max() > 1:
|
| 453 |
+
raise ValueError("Image should be in [-1, 1] range")
|
| 454 |
+
else:
|
| 455 |
+
# preprocess image
|
| 456 |
+
if isinstance(image, (PIL.Image.Image, np.ndarray)):
|
| 457 |
+
image = [image]
|
| 458 |
+
|
| 459 |
+
if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
|
| 460 |
+
image = [np.array(i.convert("RGB"))[None, :] for i in image]
|
| 461 |
+
image = np.concatenate(image, axis=0)
|
| 462 |
+
elif isinstance(image, list) and isinstance(image[0], np.ndarray):
|
| 463 |
+
image = np.concatenate([i[None, :] for i in image], axis=0)
|
| 464 |
+
|
| 465 |
+
image = image.transpose(0, 3, 1, 2)
|
| 466 |
+
image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
|
| 467 |
+
|
| 468 |
+
image = image.to(device=device, dtype=dtype)
|
| 469 |
+
|
| 470 |
+
image = self.CLIP_preprocess(image)
|
| 471 |
+
# if not isinstance(image, torch.Tensor):
|
| 472 |
+
# # 0-255
|
| 473 |
+
# print("Warning: image is processed by hf's preprocess, which is different from openai original's.")
|
| 474 |
+
# image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
|
| 475 |
+
image_embeddings = self.image_encoder(image).image_embeds.to(dtype=dtype)
|
| 476 |
+
image_embeddings = image_embeddings.unsqueeze(1)
|
| 477 |
+
|
| 478 |
+
# duplicate image embeddings for each generation per prompt, using mps friendly method
|
| 479 |
+
bs_embed, seq_len, _ = image_embeddings.shape
|
| 480 |
+
image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
|
| 481 |
+
image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 482 |
+
|
| 483 |
+
if do_classifier_free_guidance:
|
| 484 |
+
negative_prompt_embeds = torch.zeros_like(image_embeddings)
|
| 485 |
+
|
| 486 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 487 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 488 |
+
# to avoid doing two forward passes
|
| 489 |
+
image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
|
| 490 |
+
|
| 491 |
+
return image_embeddings
|
| 492 |
+
|
| 493 |
+
def _encode_pose(self, pose, device, num_images_per_prompt, do_classifier_free_guidance):
|
| 494 |
+
dtype = next(self.cc_projection.parameters()).dtype
|
| 495 |
+
if isinstance(pose, torch.Tensor):
|
| 496 |
+
pose_embeddings = pose.unsqueeze(1).to(device=device, dtype=dtype)
|
| 497 |
+
else:
|
| 498 |
+
if isinstance(pose[0], list):
|
| 499 |
+
pose = torch.Tensor(pose)
|
| 500 |
+
else:
|
| 501 |
+
pose = torch.Tensor([pose])
|
| 502 |
+
x, y, z = pose[:,0].unsqueeze(1), pose[:,1].unsqueeze(1), pose[:,2].unsqueeze(1)
|
| 503 |
+
pose_embeddings = torch.cat([torch.deg2rad(x),
|
| 504 |
+
torch.sin(torch.deg2rad(y)),
|
| 505 |
+
torch.cos(torch.deg2rad(y)),
|
| 506 |
+
z], dim=-1).unsqueeze(1).to(device=device, dtype=dtype) # B, 1, 4
|
| 507 |
+
# duplicate pose embeddings for each generation per prompt, using mps friendly method
|
| 508 |
+
bs_embed, seq_len, _ = pose_embeddings.shape
|
| 509 |
+
pose_embeddings = pose_embeddings.repeat(1, num_images_per_prompt, 1)
|
| 510 |
+
pose_embeddings = pose_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 511 |
+
if do_classifier_free_guidance:
|
| 512 |
+
negative_prompt_embeds = torch.zeros_like(pose_embeddings)
|
| 513 |
+
|
| 514 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 515 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 516 |
+
# to avoid doing two forward passes
|
| 517 |
+
pose_embeddings = torch.cat([negative_prompt_embeds, pose_embeddings])
|
| 518 |
+
return pose_embeddings
|
| 519 |
+
|
| 520 |
+
def _encode_image_with_pose(self, image, pose, device, num_images_per_prompt, do_classifier_free_guidance):
|
| 521 |
+
img_prompt_embeds = self._encode_image(image, device, num_images_per_prompt, False)
|
| 522 |
+
pose_prompt_embeds = self._encode_pose(pose, device, num_images_per_prompt, False)
|
| 523 |
+
prompt_embeds = torch.cat([img_prompt_embeds, pose_prompt_embeds], dim=-1)
|
| 524 |
+
prompt_embeds = self.cc_projection(prompt_embeds)
|
| 525 |
+
# prompt_embeds = img_prompt_embeds
|
| 526 |
+
# follow 0123, add negative prompt, after projection
|
| 527 |
+
if do_classifier_free_guidance:
|
| 528 |
+
negative_prompt = torch.zeros_like(prompt_embeds)
|
| 529 |
+
prompt_embeds = torch.cat([negative_prompt, prompt_embeds])
|
| 530 |
+
return prompt_embeds
|
| 531 |
+
|
| 532 |
+
def run_safety_checker(self, image, device, dtype):
|
| 533 |
+
if self.safety_checker is not None:
|
| 534 |
+
safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
|
| 535 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 536 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 537 |
+
)
|
| 538 |
+
else:
|
| 539 |
+
has_nsfw_concept = None
|
| 540 |
+
return image, has_nsfw_concept
|
| 541 |
+
|
| 542 |
+
def decode_latents(self, latents):
|
| 543 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 544 |
+
image = self.vae.decode(latents).sample
|
| 545 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 546 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 547 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 548 |
+
return image
|
| 549 |
+
|
| 550 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 551 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 552 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 553 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 554 |
+
# and should be between [0, 1]
|
| 555 |
+
|
| 556 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 557 |
+
extra_step_kwargs = {}
|
| 558 |
+
if accepts_eta:
|
| 559 |
+
extra_step_kwargs["eta"] = eta
|
| 560 |
+
|
| 561 |
+
# check if the scheduler accepts generator
|
| 562 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 563 |
+
if accepts_generator:
|
| 564 |
+
extra_step_kwargs["generator"] = generator
|
| 565 |
+
return extra_step_kwargs
|
| 566 |
+
|
| 567 |
+
def check_inputs(self, image, height, width, callback_steps):
|
| 568 |
+
if (
|
| 569 |
+
not isinstance(image, torch.Tensor)
|
| 570 |
+
and not isinstance(image, PIL.Image.Image)
|
| 571 |
+
and not isinstance(image, list)
|
| 572 |
+
):
|
| 573 |
+
raise ValueError(
|
| 574 |
+
"`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
|
| 575 |
+
f" {type(image)}"
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 579 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 580 |
+
|
| 581 |
+
if (callback_steps is None) or (
|
| 582 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 583 |
+
):
|
| 584 |
+
raise ValueError(
|
| 585 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 586 |
+
f" {type(callback_steps)}."
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 590 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 591 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 592 |
+
raise ValueError(
|
| 593 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 594 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
if latents is None:
|
| 598 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 599 |
+
else:
|
| 600 |
+
latents = latents.to(device)
|
| 601 |
+
|
| 602 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 603 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 604 |
+
return latents
|
| 605 |
+
|
| 606 |
+
def prepare_img_latents(self, image, batch_size, dtype, device, generator=None, do_classifier_free_guidance=False):
|
| 607 |
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
| 608 |
+
raise ValueError(
|
| 609 |
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
if isinstance(image, torch.Tensor):
|
| 613 |
+
# Batch single image
|
| 614 |
+
if image.ndim == 3:
|
| 615 |
+
assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
|
| 616 |
+
image = image.unsqueeze(0)
|
| 617 |
+
|
| 618 |
+
assert image.ndim == 4, "Image must have 4 dimensions"
|
| 619 |
+
|
| 620 |
+
# Check image is in [-1, 1]
|
| 621 |
+
if image.min() < -1 or image.max() > 1:
|
| 622 |
+
raise ValueError("Image should be in [-1, 1] range")
|
| 623 |
+
else:
|
| 624 |
+
# preprocess image
|
| 625 |
+
if isinstance(image, (PIL.Image.Image, np.ndarray)):
|
| 626 |
+
image = [image]
|
| 627 |
+
|
| 628 |
+
if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
|
| 629 |
+
image = [np.array(i.convert("RGB"))[None, :] for i in image]
|
| 630 |
+
image = np.concatenate(image, axis=0)
|
| 631 |
+
elif isinstance(image, list) and isinstance(image[0], np.ndarray):
|
| 632 |
+
image = np.concatenate([i[None, :] for i in image], axis=0)
|
| 633 |
+
|
| 634 |
+
image = image.transpose(0, 3, 1, 2)
|
| 635 |
+
image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
|
| 636 |
+
|
| 637 |
+
image = image.to(device=device, dtype=dtype)
|
| 638 |
+
|
| 639 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 640 |
+
raise ValueError(
|
| 641 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 642 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
if isinstance(generator, list):
|
| 646 |
+
init_latents = [
|
| 647 |
+
self.vae.encode(image[i : i + 1]).latent_dist.mode(generator[i]) for i in range(batch_size) # sample
|
| 648 |
+
]
|
| 649 |
+
init_latents = torch.cat(init_latents, dim=0)
|
| 650 |
+
else:
|
| 651 |
+
init_latents = self.vae.encode(image).latent_dist.mode()
|
| 652 |
+
|
| 653 |
+
# init_latents = self.vae.config.scaling_factor * init_latents # todo in original zero123's inference gradio_new.py, model.encode_first_stage() is not scaled by scaling_factor
|
| 654 |
+
if batch_size > init_latents.shape[0]:
|
| 655 |
+
# init_latents = init_latents.repeat(batch_size // init_latents.shape[0], 1, 1, 1)
|
| 656 |
+
num_images_per_prompt = batch_size // init_latents.shape[0]
|
| 657 |
+
# duplicate image latents for each generation per prompt, using mps friendly method
|
| 658 |
+
bs_embed, emb_c, emb_h, emb_w = init_latents.shape
|
| 659 |
+
init_latents = init_latents.unsqueeze(1)
|
| 660 |
+
init_latents = init_latents.repeat(1, num_images_per_prompt, 1, 1, 1)
|
| 661 |
+
init_latents = init_latents.view(bs_embed * num_images_per_prompt, emb_c, emb_h, emb_w)
|
| 662 |
+
|
| 663 |
+
# init_latents = torch.cat([init_latents]*2) if do_classifier_free_guidance else init_latents # follow zero123
|
| 664 |
+
init_latents = torch.cat([torch.zeros_like(init_latents), init_latents]) if do_classifier_free_guidance else init_latents
|
| 665 |
+
|
| 666 |
+
init_latents = init_latents.to(device=device, dtype=dtype)
|
| 667 |
+
return init_latents
|
| 668 |
+
|
| 669 |
+
# def load_cc_projection(self, pretrained_weights=None):
|
| 670 |
+
# self.cc_projection = torch.nn.Linear(772, 768)
|
| 671 |
+
# torch.nn.init.eye_(list(self.cc_projection.parameters())[0][:768, :768])
|
| 672 |
+
# torch.nn.init.zeros_(list(self.cc_projection.parameters())[1])
|
| 673 |
+
# if pretrained_weights is not None:
|
| 674 |
+
# self.cc_projection.load_state_dict(pretrained_weights)
|
| 675 |
+
|
| 676 |
+
@torch.no_grad()
|
| 677 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 678 |
+
def __call__(
|
| 679 |
+
self,
|
| 680 |
+
input_imgs: Union[torch.FloatTensor, PIL.Image.Image] = None,
|
| 681 |
+
prompt_imgs: Union[torch.FloatTensor, PIL.Image.Image] = None,
|
| 682 |
+
poses: Union[List[float], List[List[float]]] = None,
|
| 683 |
+
torch_dtype=torch.float32,
|
| 684 |
+
height: Optional[int] = None,
|
| 685 |
+
width: Optional[int] = None,
|
| 686 |
+
num_inference_steps: int = 50,
|
| 687 |
+
guidance_scale: float = 3.0,
|
| 688 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 689 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 690 |
+
eta: float = 0.0,
|
| 691 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 692 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 693 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 694 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 695 |
+
output_type: Optional[str] = "pil",
|
| 696 |
+
return_dict: bool = True,
|
| 697 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 698 |
+
callback_steps: int = 1,
|
| 699 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 700 |
+
controlnet_conditioning_scale: float = 1.0,
|
| 701 |
+
):
|
| 702 |
+
r"""
|
| 703 |
+
Function invoked when calling the pipeline for generation.
|
| 704 |
+
|
| 705 |
+
Args:
|
| 706 |
+
input_imgs (`PIL` or `List[PIL]`, *optional*):
|
| 707 |
+
The single input image for each 3D object
|
| 708 |
+
prompt_imgs (`PIL` or `List[PIL]`, *optional*):
|
| 709 |
+
Same as input_imgs, but will be used later as an image prompt condition, encoded by CLIP feature
|
| 710 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 711 |
+
The height in pixels of the generated image.
|
| 712 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 713 |
+
The width in pixels of the generated image.
|
| 714 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 715 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 716 |
+
expense of slower inference.
|
| 717 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 718 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 719 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 720 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 721 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 722 |
+
usually at the expense of lower image quality.
|
| 723 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 724 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 725 |
+
`negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
|
| 726 |
+
Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
|
| 727 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 728 |
+
The number of images to generate per prompt.
|
| 729 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 730 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 731 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 732 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 733 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 734 |
+
to make generation deterministic.
|
| 735 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 736 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 737 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 738 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 739 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 740 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 741 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 742 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 743 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 744 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 745 |
+
argument.
|
| 746 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 747 |
+
The output format of the generate image. Choose between
|
| 748 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 749 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 750 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 751 |
+
plain tuple.
|
| 752 |
+
callback (`Callable`, *optional*):
|
| 753 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 754 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 755 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 756 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 757 |
+
called at every step.
|
| 758 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 759 |
+
A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
|
| 760 |
+
`self.processor` in
|
| 761 |
+
[diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
| 762 |
+
|
| 763 |
+
Examples:
|
| 764 |
+
|
| 765 |
+
Returns:
|
| 766 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 767 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
|
| 768 |
+
When returning a tuple, the first element is a list with the generated images, and the second element is a
|
| 769 |
+
list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
|
| 770 |
+
(nsfw) content, according to the `safety_checker`.
|
| 771 |
+
"""
|
| 772 |
+
# 0. Default height and width to unet
|
| 773 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 774 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 775 |
+
|
| 776 |
+
# 1. Check inputs. Raise error if not correct
|
| 777 |
+
# input_image = hint_imgs
|
| 778 |
+
self.check_inputs(input_imgs, height, width, callback_steps)
|
| 779 |
+
|
| 780 |
+
# 2. Define call parameters
|
| 781 |
+
if isinstance(input_imgs, PIL.Image.Image):
|
| 782 |
+
batch_size = 1
|
| 783 |
+
elif isinstance(input_imgs, list):
|
| 784 |
+
batch_size = len(input_imgs)
|
| 785 |
+
else:
|
| 786 |
+
batch_size = input_imgs.shape[0]
|
| 787 |
+
device = self._execution_device
|
| 788 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 789 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 790 |
+
# corresponds to doing no classifier free guidance.
|
| 791 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 792 |
+
|
| 793 |
+
# 3. Encode input image with pose as prompt
|
| 794 |
+
prompt_embeds = self._encode_image_with_pose(prompt_imgs, poses, device, num_images_per_prompt, do_classifier_free_guidance)
|
| 795 |
+
|
| 796 |
+
# 4. Prepare timesteps
|
| 797 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 798 |
+
timesteps = self.scheduler.timesteps
|
| 799 |
+
|
| 800 |
+
# 5. Prepare latent variables
|
| 801 |
+
latents = self.prepare_latents(
|
| 802 |
+
batch_size * num_images_per_prompt,
|
| 803 |
+
4,
|
| 804 |
+
height,
|
| 805 |
+
width,
|
| 806 |
+
prompt_embeds.dtype,
|
| 807 |
+
device,
|
| 808 |
+
generator,
|
| 809 |
+
latents,
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
# 6. Prepare image latents
|
| 813 |
+
img_latents = self.prepare_img_latents(input_imgs,
|
| 814 |
+
batch_size * num_images_per_prompt,
|
| 815 |
+
prompt_embeds.dtype,
|
| 816 |
+
device,
|
| 817 |
+
generator,
|
| 818 |
+
do_classifier_free_guidance)
|
| 819 |
+
|
| 820 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 821 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 822 |
+
|
| 823 |
+
# 7. Denoising loop
|
| 824 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 825 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 826 |
+
for i, t in enumerate(timesteps):
|
| 827 |
+
# expand the latents if we are doing classifier free guidance
|
| 828 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 829 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 830 |
+
latent_model_input = torch.cat([latent_model_input, img_latents], dim=1)
|
| 831 |
+
|
| 832 |
+
# predict the noise residual
|
| 833 |
+
noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds).sample
|
| 834 |
+
|
| 835 |
+
# perform guidance
|
| 836 |
+
if do_classifier_free_guidance:
|
| 837 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 838 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 839 |
+
|
| 840 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 841 |
+
# latents = self.scheduler.step(noise_pred.to(dtype=torch.float32), t, latents.to(dtype=torch.float32)).prev_sample.to(prompt_embeds.dtype)
|
| 842 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 843 |
+
|
| 844 |
+
# call the callback, if provided
|
| 845 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 846 |
+
progress_bar.update()
|
| 847 |
+
if callback is not None and i % callback_steps == 0:
|
| 848 |
+
callback(i, t, latents)
|
| 849 |
+
|
| 850 |
+
# 8. Post-processing
|
| 851 |
+
has_nsfw_concept = None
|
| 852 |
+
if output_type == "latent":
|
| 853 |
+
image = latents
|
| 854 |
+
elif output_type == "pil":
|
| 855 |
+
# 8. Post-processing
|
| 856 |
+
image = self.decode_latents(latents)
|
| 857 |
+
# 10. Convert to PIL
|
| 858 |
+
image = self.numpy_to_pil(image)
|
| 859 |
+
else:
|
| 860 |
+
# 8. Post-processing
|
| 861 |
+
image = self.decode_latents(latents)
|
| 862 |
+
|
| 863 |
+
# Offload last model to CPU
|
| 864 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 865 |
+
self.final_offload_hook.offload()
|
| 866 |
+
|
| 867 |
+
if not return_dict:
|
| 868 |
+
return (image, has_nsfw_concept)
|
| 869 |
+
|
| 870 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|