lcybuaa commited on
Commit
db4dc2c
·
verified ·
1 Parent(s): d964202

Upload folder using huggingface_hub

Browse files
feature_extractor/preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 224,
3
+ "do_center_crop": true,
4
+ "do_convert_rgb": true,
5
+ "do_normalize": true,
6
+ "do_resize": true,
7
+ "feature_extractor_type": "CLIPFeatureExtractor",
8
+ "image_mean": [
9
+ 0.48145466,
10
+ 0.4578275,
11
+ 0.40821073
12
+ ],
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "resample": 3,
19
+ "size": 224
20
+ }
model_index.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "Text2EarthDiffusionInpaintPipeline",
3
+ "_diffusers_version": "0.8.0",
4
+ "feature_extractor": [
5
+ "transformers",
6
+ "CLIPImageProcessor"
7
+ ],
8
+ "requires_safety_checker": false,
9
+ "safety_checker": [
10
+ null,
11
+ null
12
+ ],
13
+ "scheduler": [
14
+ "diffusers",
15
+ "PNDMScheduler"
16
+ ],
17
+ "text_encoder": [
18
+ "transformers",
19
+ "CLIPTextModel"
20
+ ],
21
+ "tokenizer": [
22
+ "transformers",
23
+ "CLIPTokenizer"
24
+ ],
25
+ "unet": [
26
+ "diffusers",
27
+ "UNet2DConditionModel"
28
+ ],
29
+ "vae": [
30
+ "diffusers",
31
+ "AutoencoderKL"
32
+ ]
33
+ }
pipeline_text2earth_diffusion_inpaint.py ADDED
@@ -0,0 +1,1520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from packaging import version
22
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
23
+
24
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from diffusers.configuration_utils import FrozenDict
26
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
27
+ from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
28
+ from diffusers.models import AsymmetricAutoencoderKL, AutoencoderKL, ImageProjection, UNet2DConditionModel
29
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
30
+ from diffusers.schedulers import KarrasDiffusionSchedulers
31
+ from diffusers.utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+ from diffusers import DiffusionPipeline, StableDiffusionMixin
34
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
35
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ def prepare_mask_and_masked_image(image, mask, height, width, return_image: bool = False):
42
+ """
43
+ Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be
44
+ converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the
45
+ ``image`` and ``1`` for the ``mask``.
46
+
47
+ The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be
48
+ binarized (``mask > 0.5``) and cast to ``torch.float32`` too.
49
+
50
+ Args:
51
+ image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint.
52
+ It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width``
53
+ ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``.
54
+ mask (_type_): The mask to apply to the image, i.e. regions to inpaint.
55
+ It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width``
56
+ ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``.
57
+
58
+
59
+ Raises:
60
+ ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask
61
+ should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions.
62
+ TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not
63
+ (ot the other way around).
64
+
65
+ Returns:
66
+ tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4
67
+ dimensions: ``batch x channels x height x width``.
68
+ """
69
+ deprecation_message = "The prepare_mask_and_masked_image method is deprecated and will be removed in a future version. Please use VaeImageProcessor.preprocess instead"
70
+ deprecate(
71
+ "prepare_mask_and_masked_image",
72
+ "0.30.0",
73
+ deprecation_message,
74
+ )
75
+ if image is None:
76
+ raise ValueError("`image` input cannot be undefined.")
77
+
78
+ if mask is None:
79
+ raise ValueError("`mask_image` input cannot be undefined.")
80
+
81
+ if isinstance(image, torch.Tensor):
82
+ if not isinstance(mask, torch.Tensor):
83
+ raise TypeError(f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not")
84
+
85
+ # Batch single image
86
+ if image.ndim == 3:
87
+ assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
88
+ image = image.unsqueeze(0)
89
+
90
+ # Batch and add channel dim for single mask
91
+ if mask.ndim == 2:
92
+ mask = mask.unsqueeze(0).unsqueeze(0)
93
+
94
+ # Batch single mask or add channel dim
95
+ if mask.ndim == 3:
96
+ # Single batched mask, no channel dim or single mask not batched but channel dim
97
+ if mask.shape[0] == 1:
98
+ mask = mask.unsqueeze(0)
99
+
100
+ # Batched masks no channel dim
101
+ else:
102
+ mask = mask.unsqueeze(1)
103
+
104
+ assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions"
105
+ assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions"
106
+ assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size"
107
+
108
+ # Check image is in [-1, 1]
109
+ if image.min() < -1 or image.max() > 1:
110
+ raise ValueError("Image should be in [-1, 1] range")
111
+
112
+ # Check mask is in [0, 1]
113
+ if mask.min() < 0 or mask.max() > 1:
114
+ raise ValueError("Mask should be in [0, 1] range")
115
+
116
+ # Binarize mask
117
+ mask[mask < 0.5] = 0
118
+ mask[mask >= 0.5] = 1
119
+
120
+ # Image as float32
121
+ image = image.to(dtype=torch.float32)
122
+ elif isinstance(mask, torch.Tensor):
123
+ raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not")
124
+ else:
125
+ # preprocess image
126
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
127
+ image = [image]
128
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
129
+ # resize all images w.r.t passed height an width
130
+ image = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image]
131
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
132
+ image = np.concatenate(image, axis=0)
133
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
134
+ image = np.concatenate([i[None, :] for i in image], axis=0)
135
+
136
+ image = image.transpose(0, 3, 1, 2)
137
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
138
+
139
+ # preprocess mask
140
+ if isinstance(mask, (PIL.Image.Image, np.ndarray)):
141
+ mask = [mask]
142
+
143
+ if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image):
144
+ mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask]
145
+ mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0)
146
+ mask = mask.astype(np.float32) / 255.0
147
+ elif isinstance(mask, list) and isinstance(mask[0], np.ndarray):
148
+ mask = np.concatenate([m[None, None, :] for m in mask], axis=0)
149
+
150
+ mask[mask < 0.5] = 0
151
+ mask[mask >= 0.5] = 1
152
+ mask = torch.from_numpy(mask)
153
+
154
+ masked_image = image * (mask < 0.5)
155
+
156
+ # n.b. ensure backwards compatibility as old function does not return image
157
+ if return_image:
158
+ return mask, masked_image, image
159
+
160
+ return mask, masked_image
161
+
162
+
163
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
164
+ def retrieve_latents(
165
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
166
+ ):
167
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
168
+ return encoder_output.latent_dist.sample(generator)
169
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
170
+ return encoder_output.latent_dist.mode()
171
+ elif hasattr(encoder_output, "latents"):
172
+ return encoder_output.latents
173
+ else:
174
+ raise AttributeError("Could not access latents of provided encoder_output")
175
+
176
+
177
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
178
+ def retrieve_timesteps(
179
+ scheduler,
180
+ num_inference_steps: Optional[int] = None,
181
+ device: Optional[Union[str, torch.device]] = None,
182
+ timesteps: Optional[List[int]] = None,
183
+ sigmas: Optional[List[float]] = None,
184
+ **kwargs,
185
+ ):
186
+ """
187
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
188
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
189
+
190
+ Args:
191
+ scheduler (`SchedulerMixin`):
192
+ The scheduler to get timesteps from.
193
+ num_inference_steps (`int`):
194
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
195
+ must be `None`.
196
+ device (`str` or `torch.device`, *optional*):
197
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
198
+ timesteps (`List[int]`, *optional*):
199
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
200
+ `num_inference_steps` and `sigmas` must be `None`.
201
+ sigmas (`List[float]`, *optional*):
202
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
203
+ `num_inference_steps` and `timesteps` must be `None`.
204
+
205
+ Returns:
206
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
207
+ second element is the number of inference steps.
208
+ """
209
+ if timesteps is not None and sigmas is not None:
210
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
211
+ if timesteps is not None:
212
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
213
+ if not accepts_timesteps:
214
+ raise ValueError(
215
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
216
+ f" timestep schedules. Please check whether you are using the correct scheduler."
217
+ )
218
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
219
+ timesteps = scheduler.timesteps
220
+ num_inference_steps = len(timesteps)
221
+ elif sigmas is not None:
222
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
223
+ if not accept_sigmas:
224
+ raise ValueError(
225
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
226
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
227
+ )
228
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
229
+ timesteps = scheduler.timesteps
230
+ num_inference_steps = len(timesteps)
231
+ else:
232
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
233
+ timesteps = scheduler.timesteps
234
+ return timesteps, num_inference_steps
235
+
236
+
237
+ class Text2EarthDiffusionInpaintPipeline(
238
+ DiffusionPipeline,
239
+ StableDiffusionMixin,
240
+ TextualInversionLoaderMixin,
241
+ IPAdapterMixin,
242
+ LoraLoaderMixin,
243
+ FromSingleFileMixin,
244
+ ):
245
+ r"""
246
+ Pipeline for text-guided image inpainting using Stable Diffusion.
247
+
248
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
249
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
250
+
251
+ The pipeline also inherits the following loading methods:
252
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
253
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
254
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
255
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
256
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
257
+
258
+ Args:
259
+ vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]):
260
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
261
+ text_encoder ([`CLIPTextModel`]):
262
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
263
+ tokenizer ([`~transformers.CLIPTokenizer`]):
264
+ A `CLIPTokenizer` to tokenize text.
265
+ unet ([`UNet2DConditionModel`]):
266
+ A `UNet2DConditionModel` to denoise the encoded image latents.
267
+ scheduler ([`SchedulerMixin`]):
268
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
269
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
270
+ safety_checker ([`StableDiffusionSafetyChecker`]):
271
+ Classification module that estimates whether generated images could be considered offensive or harmful.
272
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
273
+ about a model's potential harms.
274
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
275
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
276
+ """
277
+
278
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
279
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
280
+ _exclude_from_cpu_offload = ["safety_checker"]
281
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "mask", "masked_image_latents"]
282
+
283
+ def __init__(
284
+ self,
285
+ vae: Union[AutoencoderKL, AsymmetricAutoencoderKL],
286
+ text_encoder: CLIPTextModel,
287
+ tokenizer: CLIPTokenizer,
288
+ unet: UNet2DConditionModel,
289
+ scheduler: KarrasDiffusionSchedulers,
290
+ safety_checker: StableDiffusionSafetyChecker,
291
+ feature_extractor: CLIPImageProcessor,
292
+ image_encoder: CLIPVisionModelWithProjection = None,
293
+ requires_safety_checker: bool = True,
294
+ ):
295
+ super().__init__()
296
+
297
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
298
+ deprecation_message = (
299
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
300
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
301
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
302
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
303
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
304
+ " file"
305
+ )
306
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
307
+ new_config = dict(scheduler.config)
308
+ new_config["steps_offset"] = 1
309
+ scheduler._internal_dict = FrozenDict(new_config)
310
+
311
+ if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
312
+ deprecation_message = (
313
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration"
314
+ " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
315
+ " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
316
+ " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
317
+ " Hub, it would be very nice if you could open a Pull request for the"
318
+ " `scheduler/scheduler_config.json` file"
319
+ )
320
+ deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False)
321
+ new_config = dict(scheduler.config)
322
+ new_config["skip_prk_steps"] = True
323
+ scheduler._internal_dict = FrozenDict(new_config)
324
+
325
+ if safety_checker is None and requires_safety_checker:
326
+ logger.warning(
327
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
328
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
329
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
330
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
331
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
332
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
333
+ )
334
+
335
+ if safety_checker is not None and feature_extractor is None:
336
+ raise ValueError(
337
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
338
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
339
+ )
340
+
341
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
342
+ version.parse(unet.config._diffusers_version).base_version
343
+ ) < version.parse("0.9.0.dev0")
344
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
345
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
346
+ deprecation_message = (
347
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
348
+ " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
349
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
350
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
351
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
352
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
353
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
354
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
355
+ " the `unet/config.json` file"
356
+ )
357
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
358
+ new_config = dict(unet.config)
359
+ new_config["sample_size"] = 64
360
+ unet._internal_dict = FrozenDict(new_config)
361
+
362
+ # Check shapes, assume num_channels_latents == 4, num_channels_mask == 1, num_channels_masked == 4
363
+ if unet.config.in_channels != 9:
364
+ logger.info(f"You have loaded a UNet with {unet.config.in_channels} input channels which.")
365
+
366
+ self.register_modules(
367
+ vae=vae,
368
+ text_encoder=text_encoder,
369
+ tokenizer=tokenizer,
370
+ unet=unet,
371
+ scheduler=scheduler,
372
+ safety_checker=safety_checker,
373
+ feature_extractor=feature_extractor,
374
+ image_encoder=image_encoder,
375
+ )
376
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
377
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
378
+ # self.mask_processor = VaeImageProcessor(
379
+ # vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
380
+ # )
381
+ # FIXME:
382
+ self.mask_processor = VaeImageProcessor(
383
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=False, do_convert_grayscale=True
384
+ )
385
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
386
+
387
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
388
+ def _encode_prompt(
389
+ self,
390
+ prompt,
391
+ device,
392
+ num_images_per_prompt,
393
+ do_classifier_free_guidance,
394
+ negative_prompt=None,
395
+ prompt_embeds: Optional[torch.Tensor] = None,
396
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
397
+ lora_scale: Optional[float] = None,
398
+ **kwargs,
399
+ ):
400
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
401
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
402
+
403
+ prompt_embeds_tuple = self.encode_prompt(
404
+ prompt=prompt,
405
+ device=device,
406
+ num_images_per_prompt=num_images_per_prompt,
407
+ do_classifier_free_guidance=do_classifier_free_guidance,
408
+ negative_prompt=negative_prompt,
409
+ prompt_embeds=prompt_embeds,
410
+ negative_prompt_embeds=negative_prompt_embeds,
411
+ lora_scale=lora_scale,
412
+ **kwargs,
413
+ )
414
+
415
+ # concatenate for backwards comp
416
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
417
+
418
+ return prompt_embeds
419
+
420
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
421
+ def encode_prompt(
422
+ self,
423
+ prompt,
424
+ device,
425
+ num_images_per_prompt,
426
+ do_classifier_free_guidance,
427
+ negative_prompt=None,
428
+ prompt_embeds: Optional[torch.Tensor] = None,
429
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
430
+ lora_scale: Optional[float] = None,
431
+ clip_skip: Optional[int] = None,
432
+ ):
433
+ r"""
434
+ Encodes the prompt into text encoder hidden states.
435
+
436
+ Args:
437
+ prompt (`str` or `List[str]`, *optional*):
438
+ prompt to be encoded
439
+ device: (`torch.device`):
440
+ torch device
441
+ num_images_per_prompt (`int`):
442
+ number of images that should be generated per prompt
443
+ do_classifier_free_guidance (`bool`):
444
+ whether to use classifier free guidance or not
445
+ negative_prompt (`str` or `List[str]`, *optional*):
446
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
447
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
448
+ less than `1`).
449
+ prompt_embeds (`torch.Tensor`, *optional*):
450
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
451
+ provided, text embeddings will be generated from `prompt` input argument.
452
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
453
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
454
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
455
+ argument.
456
+ lora_scale (`float`, *optional*):
457
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
458
+ clip_skip (`int`, *optional*):
459
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
460
+ the output of the pre-final layer will be used for computing the prompt embeddings.
461
+ """
462
+ # set lora scale so that monkey patched LoRA
463
+ # function of text encoder can correctly access it
464
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
465
+ self._lora_scale = lora_scale
466
+
467
+ # dynamically adjust the LoRA scale
468
+ if not USE_PEFT_BACKEND:
469
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
470
+ else:
471
+ scale_lora_layers(self.text_encoder, lora_scale)
472
+
473
+ if prompt is not None and isinstance(prompt, str):
474
+ batch_size = 1
475
+ elif prompt is not None and isinstance(prompt, list):
476
+ batch_size = len(prompt)
477
+ else:
478
+ batch_size = prompt_embeds.shape[0]
479
+
480
+ if prompt_embeds is None:
481
+ # textual inversion: process multi-vector tokens if necessary
482
+ if isinstance(self, TextualInversionLoaderMixin):
483
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
484
+
485
+ text_inputs = self.tokenizer(
486
+ prompt,
487
+ padding="max_length",
488
+ max_length=self.tokenizer.model_max_length,
489
+ truncation=True,
490
+ return_tensors="pt",
491
+ )
492
+ text_input_ids = text_inputs.input_ids
493
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
494
+
495
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
496
+ text_input_ids, untruncated_ids
497
+ ):
498
+ removed_text = self.tokenizer.batch_decode(
499
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
500
+ )
501
+ logger.warning(
502
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
503
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
504
+ )
505
+
506
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
507
+ attention_mask = text_inputs.attention_mask.to(device)
508
+ else:
509
+ attention_mask = None
510
+
511
+ if clip_skip is None:
512
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
513
+ prompt_embeds = prompt_embeds[0]
514
+ else:
515
+ prompt_embeds = self.text_encoder(
516
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
517
+ )
518
+ # Access the `hidden_states` first, that contains a tuple of
519
+ # all the hidden states from the encoder layers. Then index into
520
+ # the tuple to access the hidden states from the desired layer.
521
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
522
+ # We also need to apply the final LayerNorm here to not mess with the
523
+ # representations. The `last_hidden_states` that we typically use for
524
+ # obtaining the final prompt representations passes through the LayerNorm
525
+ # layer.
526
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
527
+
528
+ if self.text_encoder is not None:
529
+ prompt_embeds_dtype = self.text_encoder.dtype
530
+ elif self.unet is not None:
531
+ prompt_embeds_dtype = self.unet.dtype
532
+ else:
533
+ prompt_embeds_dtype = prompt_embeds.dtype
534
+
535
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
536
+
537
+ bs_embed, seq_len, _ = prompt_embeds.shape
538
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
539
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
540
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
541
+
542
+ # get unconditional embeddings for classifier free guidance
543
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
544
+ uncond_tokens: List[str]
545
+ if negative_prompt is None:
546
+ uncond_tokens = [""] * batch_size
547
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
548
+ raise TypeError(
549
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
550
+ f" {type(prompt)}."
551
+ )
552
+ elif isinstance(negative_prompt, str):
553
+ uncond_tokens = [negative_prompt]
554
+ elif batch_size != len(negative_prompt):
555
+ raise ValueError(
556
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
557
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
558
+ " the batch size of `prompt`."
559
+ )
560
+ else:
561
+ uncond_tokens = negative_prompt
562
+
563
+ # textual inversion: process multi-vector tokens if necessary
564
+ if isinstance(self, TextualInversionLoaderMixin):
565
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
566
+
567
+ max_length = prompt_embeds.shape[1]
568
+ uncond_input = self.tokenizer(
569
+ uncond_tokens,
570
+ padding="max_length",
571
+ max_length=max_length,
572
+ truncation=True,
573
+ return_tensors="pt",
574
+ )
575
+
576
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
577
+ attention_mask = uncond_input.attention_mask.to(device)
578
+ else:
579
+ attention_mask = None
580
+
581
+ negative_prompt_embeds = self.text_encoder(
582
+ uncond_input.input_ids.to(device),
583
+ attention_mask=attention_mask,
584
+ )
585
+ negative_prompt_embeds = negative_prompt_embeds[0]
586
+
587
+ if do_classifier_free_guidance:
588
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
589
+ seq_len = negative_prompt_embeds.shape[1]
590
+
591
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
592
+
593
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
594
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
595
+
596
+ if self.text_encoder is not None:
597
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
598
+ # Retrieve the original scale by scaling back the LoRA layers
599
+ unscale_lora_layers(self.text_encoder, lora_scale)
600
+
601
+ return prompt_embeds, negative_prompt_embeds
602
+
603
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
604
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
605
+ dtype = next(self.image_encoder.parameters()).dtype
606
+
607
+ if not isinstance(image, torch.Tensor):
608
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
609
+
610
+ image = image.to(device=device, dtype=dtype)
611
+ if output_hidden_states:
612
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
613
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
614
+ uncond_image_enc_hidden_states = self.image_encoder(
615
+ torch.zeros_like(image), output_hidden_states=True
616
+ ).hidden_states[-2]
617
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
618
+ num_images_per_prompt, dim=0
619
+ )
620
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
621
+ else:
622
+ image_embeds = self.image_encoder(image).image_embeds
623
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
624
+ uncond_image_embeds = torch.zeros_like(image_embeds)
625
+
626
+ return image_embeds, uncond_image_embeds
627
+
628
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
629
+ def prepare_ip_adapter_image_embeds(
630
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
631
+ ):
632
+ if ip_adapter_image_embeds is None:
633
+ if not isinstance(ip_adapter_image, list):
634
+ ip_adapter_image = [ip_adapter_image]
635
+
636
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
637
+ raise ValueError(
638
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
639
+ )
640
+
641
+ image_embeds = []
642
+ for single_ip_adapter_image, image_proj_layer in zip(
643
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
644
+ ):
645
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
646
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
647
+ single_ip_adapter_image, device, 1, output_hidden_state
648
+ )
649
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
650
+ single_negative_image_embeds = torch.stack(
651
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
652
+ )
653
+
654
+ if do_classifier_free_guidance:
655
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
656
+ single_image_embeds = single_image_embeds.to(device)
657
+
658
+ image_embeds.append(single_image_embeds)
659
+ else:
660
+ repeat_dims = [1]
661
+ image_embeds = []
662
+ for single_image_embeds in ip_adapter_image_embeds:
663
+ if do_classifier_free_guidance:
664
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
665
+ single_image_embeds = single_image_embeds.repeat(
666
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
667
+ )
668
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
669
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
670
+ )
671
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
672
+ else:
673
+ single_image_embeds = single_image_embeds.repeat(
674
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
675
+ )
676
+ image_embeds.append(single_image_embeds)
677
+
678
+ return image_embeds
679
+
680
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
681
+ def run_safety_checker(self, image, device, dtype):
682
+ if self.safety_checker is None:
683
+ has_nsfw_concept = None
684
+ else:
685
+ if torch.is_tensor(image):
686
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
687
+ else:
688
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
689
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
690
+ image, has_nsfw_concept = self.safety_checker(
691
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
692
+ )
693
+ return image, has_nsfw_concept
694
+
695
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
696
+ def prepare_extra_step_kwargs(self, generator, eta):
697
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
698
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
699
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
700
+ # and should be between [0, 1]
701
+
702
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
703
+ extra_step_kwargs = {}
704
+ if accepts_eta:
705
+ extra_step_kwargs["eta"] = eta
706
+
707
+ # check if the scheduler accepts generator
708
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
709
+ if accepts_generator:
710
+ extra_step_kwargs["generator"] = generator
711
+ return extra_step_kwargs
712
+
713
+ def check_inputs(
714
+ self,
715
+ prompt,
716
+ image,
717
+ mask_image,
718
+ height,
719
+ width,
720
+ strength,
721
+ callback_steps,
722
+ output_type,
723
+ negative_prompt=None,
724
+ prompt_embeds=None,
725
+ negative_prompt_embeds=None,
726
+ ip_adapter_image=None,
727
+ ip_adapter_image_embeds=None,
728
+ callback_on_step_end_tensor_inputs=None,
729
+ padding_mask_crop=None,
730
+ ):
731
+ if strength < 0 or strength > 1:
732
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
733
+
734
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
735
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
736
+
737
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
738
+ raise ValueError(
739
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
740
+ f" {type(callback_steps)}."
741
+ )
742
+
743
+ if callback_on_step_end_tensor_inputs is not None and not all(
744
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
745
+ ):
746
+ raise ValueError(
747
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
748
+ )
749
+
750
+ if prompt is not None and prompt_embeds is not None:
751
+ raise ValueError(
752
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
753
+ " only forward one of the two."
754
+ )
755
+ elif prompt is None and prompt_embeds is None:
756
+ raise ValueError(
757
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
758
+ )
759
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
760
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
761
+
762
+ if negative_prompt is not None and negative_prompt_embeds is not None:
763
+ raise ValueError(
764
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
765
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
766
+ )
767
+
768
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
769
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
770
+ raise ValueError(
771
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
772
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
773
+ f" {negative_prompt_embeds.shape}."
774
+ )
775
+ if padding_mask_crop is not None:
776
+ if not isinstance(image, PIL.Image.Image):
777
+ raise ValueError(
778
+ f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
779
+ )
780
+ if not isinstance(mask_image, PIL.Image.Image):
781
+ raise ValueError(
782
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
783
+ f" {type(mask_image)}."
784
+ )
785
+ if output_type != "pil":
786
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.")
787
+
788
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
789
+ raise ValueError(
790
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
791
+ )
792
+
793
+ if ip_adapter_image_embeds is not None:
794
+ if not isinstance(ip_adapter_image_embeds, list):
795
+ raise ValueError(
796
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
797
+ )
798
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
799
+ raise ValueError(
800
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
801
+ )
802
+
803
+ def prepare_latents(
804
+ self,
805
+ batch_size,
806
+ num_channels_latents,
807
+ height,
808
+ width,
809
+ dtype,
810
+ device,
811
+ generator,
812
+ latents=None,
813
+ image=None,
814
+ timestep=None,
815
+ is_strength_max=True,
816
+ return_noise=False,
817
+ return_image_latents=False,
818
+ ):
819
+ shape = (
820
+ batch_size,
821
+ num_channels_latents,
822
+ int(height) // self.vae_scale_factor,
823
+ int(width) // self.vae_scale_factor,
824
+ )
825
+ if isinstance(generator, list) and len(generator) != batch_size:
826
+ raise ValueError(
827
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
828
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
829
+ )
830
+
831
+ if (image is None or timestep is None) and not is_strength_max:
832
+ raise ValueError(
833
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
834
+ "However, either the image or the noise timestep has not been provided."
835
+ )
836
+
837
+ if return_image_latents or (latents is None and not is_strength_max):
838
+ image = image.to(device=device, dtype=dtype)
839
+
840
+ if image.shape[1] == 4:
841
+ image_latents = image
842
+ else:
843
+ image_latents = self._encode_vae_image(image=image, generator=generator)
844
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
845
+
846
+ if latents is None:
847
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
848
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
849
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
850
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
851
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
852
+ else:
853
+ noise = latents.to(device)
854
+ latents = noise * self.scheduler.init_noise_sigma
855
+
856
+ outputs = (latents,)
857
+
858
+ if return_noise:
859
+ outputs += (noise,)
860
+
861
+ if return_image_latents:
862
+ outputs += (image_latents,)
863
+
864
+ return outputs
865
+
866
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
867
+ if isinstance(generator, list):
868
+ image_latents = [
869
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
870
+ for i in range(image.shape[0])
871
+ ]
872
+ image_latents = torch.cat(image_latents, dim=0)
873
+ else:
874
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
875
+
876
+ image_latents = self.vae.config.scaling_factor * image_latents
877
+
878
+ return image_latents
879
+
880
+ def prepare_mask_latents(
881
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
882
+ ):
883
+ # resize the mask to latents shape as we concatenate the mask to the latents
884
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
885
+ # and half precision
886
+ mask = torch.nn.functional.interpolate(
887
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
888
+ )
889
+ mask = mask.to(device=device, dtype=dtype)
890
+
891
+ masked_image = masked_image.to(device=device, dtype=dtype)
892
+
893
+ if masked_image.shape[1] == 4:
894
+ masked_image_latents = masked_image
895
+ else:
896
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
897
+
898
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
899
+ if mask.shape[0] < batch_size:
900
+ if not batch_size % mask.shape[0] == 0:
901
+ raise ValueError(
902
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
903
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
904
+ " of masks that you pass is divisible by the total requested batch size."
905
+ )
906
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
907
+ if masked_image_latents.shape[0] < batch_size:
908
+ if not batch_size % masked_image_latents.shape[0] == 0:
909
+ raise ValueError(
910
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
911
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
912
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
913
+ )
914
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
915
+
916
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
917
+ masked_image_latents = (
918
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
919
+ )
920
+
921
+ # aligning device to prevent device errors when concating it with the latent model input
922
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
923
+ return mask, masked_image_latents
924
+
925
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
926
+ def get_timesteps(self, num_inference_steps, strength, device):
927
+ # get the original timestep using init_timestep
928
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
929
+
930
+ t_start = max(num_inference_steps - init_timestep, 0)
931
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
932
+ if hasattr(self.scheduler, "set_begin_index"):
933
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
934
+
935
+ return timesteps, num_inference_steps - t_start
936
+
937
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
938
+ def get_guidance_scale_embedding(
939
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
940
+ ) -> torch.Tensor:
941
+ """
942
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
943
+
944
+ Args:
945
+ w (`torch.Tensor`):
946
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
947
+ embedding_dim (`int`, *optional*, defaults to 512):
948
+ Dimension of the embeddings to generate.
949
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
950
+ Data type of the generated embeddings.
951
+
952
+ Returns:
953
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
954
+ """
955
+ assert len(w.shape) == 1
956
+ w = w * 1000.0
957
+
958
+ half_dim = embedding_dim // 2
959
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
960
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
961
+ emb = w.to(dtype)[:, None] * emb[None, :]
962
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
963
+ if embedding_dim % 2 == 1: # zero pad
964
+ emb = torch.nn.functional.pad(emb, (0, 1))
965
+ assert emb.shape == (w.shape[0], embedding_dim)
966
+ return emb
967
+
968
+ @property
969
+ def guidance_scale(self):
970
+ return self._guidance_scale
971
+
972
+ @property
973
+ def clip_skip(self):
974
+ return self._clip_skip
975
+
976
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
977
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
978
+ # corresponds to doing no classifier free guidance.
979
+ @property
980
+ def do_classifier_free_guidance(self):
981
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
982
+
983
+ @property
984
+ def cross_attention_kwargs(self):
985
+ return self._cross_attention_kwargs
986
+
987
+ @property
988
+ def num_timesteps(self):
989
+ return self._num_timesteps
990
+
991
+ @property
992
+ def interrupt(self):
993
+ return self._interrupt
994
+
995
+ @torch.no_grad()
996
+ def __call__(
997
+ self,
998
+ prompt: Union[str, List[str]] = None,
999
+ image: PipelineImageInput = None,
1000
+ mask_image: PipelineImageInput = None,
1001
+ masked_image_latents: torch.Tensor = None,
1002
+ height: Optional[int] = None,
1003
+ width: Optional[int] = None,
1004
+ padding_mask_crop: Optional[int] = None,
1005
+ strength: float = 1.0,
1006
+ num_inference_steps: int = 50,
1007
+ timesteps: List[int] = None,
1008
+ sigmas: List[float] = None,
1009
+ guidance_scale: float = 3.5,
1010
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1011
+ num_images_per_prompt: Optional[int] = 1,
1012
+ eta: float = 0.0,
1013
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1014
+ latents: Optional[torch.Tensor] = None,
1015
+ prompt_embeds: Optional[torch.Tensor] = None,
1016
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1017
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1018
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1019
+ output_type: Optional[str] = "pil",
1020
+ return_dict: bool = True,
1021
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1022
+ clip_skip: int = None,
1023
+ callback_on_step_end: Optional[
1024
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1025
+ ] = None,
1026
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1027
+ **kwargs,
1028
+ ):
1029
+ r"""
1030
+ The call function to the pipeline for generation.
1031
+
1032
+ Args:
1033
+ prompt (`str` or `List[str]`, *optional*):
1034
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1035
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
1036
+ `Image`, numpy array or tensor representing an image batch to be inpainted (which parts of the image to
1037
+ be masked out with `mask_image` and repainted according to `prompt`). For both numpy array and pytorch
1038
+ tensor, the expected value range is between `[0, 1]` If it's a tensor or a list or tensors, the
1039
+ expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a list of arrays, the
1040
+ expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image latents as `image`, but
1041
+ if passing latents directly it is not encoded again.
1042
+ mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
1043
+ `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
1044
+ are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
1045
+ single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
1046
+ color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
1047
+ H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
1048
+ 1)`, or `(H, W)`.
1049
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1050
+ The height in pixels of the generated image.
1051
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1052
+ The width in pixels of the generated image.
1053
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
1054
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
1055
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
1056
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
1057
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
1058
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
1059
+ the image is large and contain information irrelevant for inpainting, such as background.
1060
+ strength (`float`, *optional*, defaults to 1.0):
1061
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
1062
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
1063
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
1064
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
1065
+ essentially ignores `image`.
1066
+ num_inference_steps (`int`, *optional*, defaults to 50):
1067
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1068
+ expense of slower inference. This parameter is modulated by `strength`.
1069
+ timesteps (`List[int]`, *optional*):
1070
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1071
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1072
+ passed will be used. Must be in descending order.
1073
+ sigmas (`List[float]`, *optional*):
1074
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1075
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1076
+ will be used.
1077
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1078
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1079
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1080
+ negative_prompt (`str` or `List[str]`, *optional*):
1081
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1082
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1083
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1084
+ The number of images to generate per prompt.
1085
+ eta (`float`, *optional*, defaults to 0.0):
1086
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1087
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1088
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1089
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1090
+ generation deterministic.
1091
+ latents (`torch.Tensor`, *optional*):
1092
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1093
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1094
+ tensor is generated by sampling using the supplied random `generator`.
1095
+ prompt_embeds (`torch.Tensor`, *optional*):
1096
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1097
+ provided, text embeddings are generated from the `prompt` input argument.
1098
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1099
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1100
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1101
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1102
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1103
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1104
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1105
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1106
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1107
+ output_type (`str`, *optional*, defaults to `"pil"`):
1108
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1109
+ return_dict (`bool`, *optional*, defaults to `True`):
1110
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1111
+ plain tuple.
1112
+ cross_attention_kwargs (`dict`, *optional*):
1113
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1114
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1115
+ clip_skip (`int`, *optional*):
1116
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1117
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1118
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1119
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1120
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1121
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1122
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1123
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1124
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1125
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1126
+ `._callback_tensor_inputs` attribute of your pipeline class.
1127
+ Examples:
1128
+
1129
+ ```py
1130
+ >>> import PIL
1131
+ >>> import requests
1132
+ >>> import torch
1133
+ >>> from io import BytesIO
1134
+
1135
+ >>> from diffusers import Text2EarthDiffusionInpaintPipeline
1136
+
1137
+
1138
+ >>> def download_image(url):
1139
+ ... response = requests.get(url)
1140
+ ... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
1141
+
1142
+
1143
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
1144
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
1145
+
1146
+ >>> init_image = download_image(img_url).resize((512, 512))
1147
+ >>> mask_image = download_image(mask_url).resize((512, 512))
1148
+
1149
+ >>> pipe = Text2EarthDiffusionInpaintPipeline.from_pretrained(
1150
+ ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16
1151
+ ... )
1152
+ >>> pipe = pipe.to("cuda")
1153
+
1154
+ >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
1155
+ >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
1156
+ ```
1157
+
1158
+ Returns:
1159
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1160
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1161
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
1162
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
1163
+ "not-safe-for-work" (nsfw) content.
1164
+ """
1165
+
1166
+ callback = kwargs.pop("callback", None)
1167
+ callback_steps = kwargs.pop("callback_steps", None)
1168
+
1169
+ if callback is not None:
1170
+ deprecate(
1171
+ "callback",
1172
+ "1.0.0",
1173
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1174
+ )
1175
+ if callback_steps is not None:
1176
+ deprecate(
1177
+ "callback_steps",
1178
+ "1.0.0",
1179
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1180
+ )
1181
+
1182
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1183
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1184
+
1185
+ # 0. Default height and width to unet
1186
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1187
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1188
+
1189
+ # 1. Check inputs
1190
+ self.check_inputs(
1191
+ prompt,
1192
+ image,
1193
+ mask_image,
1194
+ height,
1195
+ width,
1196
+ strength,
1197
+ callback_steps,
1198
+ output_type,
1199
+ negative_prompt,
1200
+ prompt_embeds,
1201
+ negative_prompt_embeds,
1202
+ ip_adapter_image,
1203
+ ip_adapter_image_embeds,
1204
+ callback_on_step_end_tensor_inputs,
1205
+ padding_mask_crop,
1206
+ )
1207
+
1208
+ self._guidance_scale = guidance_scale
1209
+ self._clip_skip = clip_skip
1210
+ self._cross_attention_kwargs = cross_attention_kwargs
1211
+ self._interrupt = False
1212
+
1213
+ # 2. Define call parameters
1214
+ if prompt is not None and isinstance(prompt, str):
1215
+ batch_size = 1
1216
+ elif prompt is not None and isinstance(prompt, list):
1217
+ batch_size = len(prompt)
1218
+ else:
1219
+ batch_size = prompt_embeds.shape[0]
1220
+
1221
+ device = self._execution_device
1222
+
1223
+ # 3. Encode input prompt
1224
+ text_encoder_lora_scale = (
1225
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1226
+ )
1227
+
1228
+ # FIXME: 判断prompt是str还是list
1229
+ if prompt is not None and isinstance(prompt, str):
1230
+ # assert '_GOOGLE_LEVEL_' in prompt
1231
+ if '_GOOGLE_LEVEL_' in prompt:
1232
+ res = [int(prompt.split('_GOOGLE_LEVEL_')[0])]
1233
+ prompt = prompt.split('_GOOGLE_LEVEL_')[-1]
1234
+ else:
1235
+ res = [0]
1236
+ prompt = prompt.split('_GOOGLE_LEVEL_')[-1]
1237
+ elif prompt is not None and isinstance(prompt, list):
1238
+ res_list = []
1239
+ prompt_buff = []
1240
+ for p in prompt:
1241
+ # assert '_GOOGLE_LEVEL_' in p
1242
+ if '_GOOGLE_LEVEL_' in p:
1243
+ res = int(p.split('_GOOGLE_LEVEL_')[0])
1244
+ p = p.split('_GOOGLE_LEVEL_')[-1]
1245
+ else:
1246
+ res = 0
1247
+ p = p.split('_GOOGLE_LEVEL_')[-1]
1248
+ res_list.append(res)
1249
+ prompt_buff.append(p)
1250
+ res = res_list
1251
+ prompt = prompt_buff
1252
+
1253
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1254
+ prompt,
1255
+ device,
1256
+ num_images_per_prompt,
1257
+ self.do_classifier_free_guidance,
1258
+ negative_prompt,
1259
+ prompt_embeds=prompt_embeds,
1260
+ negative_prompt_embeds=negative_prompt_embeds,
1261
+ lora_scale=text_encoder_lora_scale,
1262
+ clip_skip=self.clip_skip,
1263
+ )
1264
+ # For classifier free guidance, we need to do two forward passes.
1265
+ # Here we concatenate the unconditional and text embeddings into a single batch
1266
+ # to avoid doing two forward passes
1267
+ if self.do_classifier_free_guidance:
1268
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1269
+
1270
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1271
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1272
+ ip_adapter_image,
1273
+ ip_adapter_image_embeds,
1274
+ device,
1275
+ batch_size * num_images_per_prompt,
1276
+ self.do_classifier_free_guidance,
1277
+ )
1278
+
1279
+ # 4. set timesteps
1280
+ timesteps, num_inference_steps = retrieve_timesteps(
1281
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1282
+ )
1283
+ timesteps, num_inference_steps = self.get_timesteps(
1284
+ num_inference_steps=num_inference_steps, strength=strength, device=device
1285
+ )
1286
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1287
+ if num_inference_steps < 1:
1288
+ raise ValueError(
1289
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1290
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1291
+ )
1292
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1293
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1294
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1295
+ is_strength_max = strength == 1.0
1296
+
1297
+ # 5. Preprocess mask and image
1298
+
1299
+ if padding_mask_crop is not None:
1300
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
1301
+ resize_mode = "fill"
1302
+ else:
1303
+ crops_coords = None
1304
+ resize_mode = "default"
1305
+
1306
+ original_image = image
1307
+ init_image = self.image_processor.preprocess(
1308
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
1309
+ )
1310
+ init_image = init_image.to(dtype=torch.float32) # range: (-1,1)
1311
+
1312
+ # 6. Prepare latent variables
1313
+ num_channels_latents = self.vae.config.latent_channels
1314
+ num_channels_unet = self.unet.config.in_channels
1315
+ return_image_latents = num_channels_unet == 4
1316
+
1317
+ latents_outputs = self.prepare_latents(
1318
+ batch_size * num_images_per_prompt,
1319
+ num_channels_latents,
1320
+ height,
1321
+ width,
1322
+ prompt_embeds.dtype,
1323
+ device,
1324
+ generator,
1325
+ latents,
1326
+ image=init_image,
1327
+ timestep=latent_timestep,
1328
+ is_strength_max=is_strength_max,
1329
+ return_noise=True,
1330
+ return_image_latents=return_image_latents,
1331
+ )
1332
+
1333
+ if return_image_latents:
1334
+ latents, noise, image_latents = latents_outputs
1335
+ else:
1336
+ latents, noise = latents_outputs
1337
+
1338
+ # 7. Prepare mask latent variables
1339
+ mask_condition = self.mask_processor.preprocess(
1340
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
1341
+ )
1342
+
1343
+ if masked_image_latents is None:
1344
+ masked_image = init_image * (mask_condition < 0.5)
1345
+ # masked_image[masked_image == 0] = -1
1346
+ else:
1347
+ masked_image = masked_image_latents
1348
+
1349
+ mask, masked_image_latents = self.prepare_mask_latents(
1350
+ mask_condition,
1351
+ masked_image,
1352
+ batch_size * num_images_per_prompt,
1353
+ height,
1354
+ width,
1355
+ prompt_embeds.dtype,
1356
+ device,
1357
+ generator,
1358
+ self.do_classifier_free_guidance,
1359
+ )
1360
+
1361
+ # 8. Check that sizes of mask, masked image and latents match
1362
+ if num_channels_unet == 9:
1363
+ # default case for runwayml/stable-diffusion-inpainting
1364
+ num_channels_mask = mask.shape[1]
1365
+ num_channels_masked_image = masked_image_latents.shape[1]
1366
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
1367
+ raise ValueError(
1368
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1369
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1370
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1371
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1372
+ " `pipeline.unet` or your `mask_image` or `image` input."
1373
+ )
1374
+ elif num_channels_unet != 4:
1375
+ raise ValueError(
1376
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1377
+ )
1378
+
1379
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1380
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1381
+
1382
+ # 9.1 Add image embeds for IP-Adapter
1383
+ added_cond_kwargs = (
1384
+ {"image_embeds": image_embeds}
1385
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
1386
+ else None
1387
+ )
1388
+
1389
+ # 9.2 Optionally get Guidance Scale Embedding
1390
+ timestep_cond = None
1391
+ if self.unet.config.time_cond_proj_dim is not None:
1392
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1393
+ timestep_cond = self.get_guidance_scale_embedding(
1394
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1395
+ ).to(device=device, dtype=latents.dtype)
1396
+
1397
+ # 10. Denoising loop
1398
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1399
+ self._num_timesteps = len(timesteps)
1400
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1401
+ for i, t in enumerate(timesteps):
1402
+ if self.interrupt:
1403
+ continue
1404
+
1405
+ # expand the latents if we are doing classifier free guidance
1406
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1407
+
1408
+ # concat latents, mask, masked_image_latents in the channel dimension
1409
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1410
+
1411
+ if num_channels_unet == 9:
1412
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
1413
+
1414
+ # fixme
1415
+ assert num_images_per_prompt == 1
1416
+ res = torch.tensor(res, dtype=t.dtype, device=device).clone().detach()#torch.tensor(res).to(t.dtype).to(device).clone().detach()
1417
+ res_null = torch.tensor([0] * batch_size, dtype=t.dtype, device=device).clone().detach()
1418
+ # res_in = torch.cat([res]*2) if self.do_classifier_free_guidance else res
1419
+ res_in = torch.cat([res_null, res]) if self.do_classifier_free_guidance else res
1420
+ # TODO: assert num_images_per_prompt != 1
1421
+
1422
+ # predict the noise residual
1423
+ noise_pred = self.unet(
1424
+ latent_model_input,
1425
+ t,
1426
+ encoder_hidden_states=prompt_embeds,
1427
+ timestep_cond=timestep_cond,
1428
+ class_labels=res_in if self.unet.class_embedding is not None else None, # FIXME: res_in
1429
+ cross_attention_kwargs=self.cross_attention_kwargs,
1430
+ added_cond_kwargs=added_cond_kwargs,
1431
+ return_dict=False,
1432
+ )[0]
1433
+
1434
+ # perform guidance
1435
+ if self.do_classifier_free_guidance:
1436
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1437
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1438
+
1439
+ # compute the previous noisy sample x_t -> x_t-1
1440
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1441
+ if num_channels_unet == 4:
1442
+ init_latents_proper = image_latents
1443
+ if self.do_classifier_free_guidance:
1444
+ init_mask, _ = mask.chunk(2)
1445
+ else:
1446
+ init_mask = mask
1447
+
1448
+ if i < len(timesteps) - 1:
1449
+ noise_timestep = timesteps[i + 1]
1450
+ init_latents_proper = self.scheduler.add_noise(
1451
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1452
+ )
1453
+
1454
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1455
+ # latents = (init_mask) * init_latents_proper + (1-init_mask) * latents
1456
+
1457
+ if callback_on_step_end is not None:
1458
+ callback_kwargs = {}
1459
+ for k in callback_on_step_end_tensor_inputs:
1460
+ callback_kwargs[k] = locals()[k]
1461
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1462
+
1463
+ latents = callback_outputs.pop("latents", latents)
1464
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1465
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1466
+ mask = callback_outputs.pop("mask", mask)
1467
+ masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
1468
+
1469
+ # call the callback, if provided
1470
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1471
+ progress_bar.update()
1472
+ if callback is not None and i % callback_steps == 0:
1473
+ step_idx = i // getattr(self.scheduler, "order", 1)
1474
+ callback(step_idx, t, latents)
1475
+
1476
+ # image = self.vae.decode(
1477
+ # latents / self.vae.config.scaling_factor, return_dict=False, generator=generator
1478
+ # )[0]
1479
+ # image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1480
+ # if has_nsfw_concept is None:
1481
+ # do_denormalize = [True] * image.shape[0]
1482
+ # else:
1483
+ # do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1484
+ #
1485
+ # image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1486
+ # print('xxx')
1487
+
1488
+ if not output_type == "latent":
1489
+ condition_kwargs = {}
1490
+ if isinstance(self.vae, AsymmetricAutoencoderKL):
1491
+ init_image = init_image.to(device=device, dtype=masked_image_latents.dtype)
1492
+ init_image_condition = init_image.clone()
1493
+ init_image = self._encode_vae_image(init_image, generator=generator)
1494
+ mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype)
1495
+ condition_kwargs = {"image": init_image_condition, "mask": mask_condition}
1496
+ image = self.vae.decode(
1497
+ latents / self.vae.config.scaling_factor, return_dict=False, generator=generator, **condition_kwargs
1498
+ )[0]
1499
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1500
+ else:
1501
+ image = latents
1502
+ has_nsfw_concept = None
1503
+
1504
+ if has_nsfw_concept is None:
1505
+ do_denormalize = [True] * image.shape[0]
1506
+ else:
1507
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1508
+
1509
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1510
+
1511
+ if padding_mask_crop is not None:
1512
+ image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
1513
+
1514
+ # Offload all models
1515
+ self.maybe_free_model_hooks()
1516
+
1517
+ if not return_dict:
1518
+ return (image, has_nsfw_concept)
1519
+
1520
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
scheduler/scheduler_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "PNDMScheduler",
3
+ "_diffusers_version": "0.8.0",
4
+ "beta_end": 0.012,
5
+ "beta_schedule": "scaled_linear",
6
+ "beta_start": 0.00085,
7
+ "clip_sample": false,
8
+ "num_train_timesteps": 1000,
9
+ "set_alpha_to_one": false,
10
+ "skip_prk_steps": true,
11
+ "steps_offset": 1,
12
+ "trained_betas": null
13
+ }
text_encoder/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./hf-models/stable-diffusion-v2-inpainting/text_encoder",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "gelu",
11
+ "hidden_size": 1024,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 4096,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 23,
20
+ "pad_token_id": 1,
21
+ "projection_dim": 512,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.25.0.dev0",
24
+ "vocab_size": 49408
25
+ }
text_encoder/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cce6febb0b6d876ee5eb24af35e27e764eb4f9b1d0b7c026c8c3333d4cfc916c
3
+ size 1361597018
tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "!",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "do_lower_case": true,
12
+ "eos_token": {
13
+ "__type": "AddedToken",
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "errors": "replace",
21
+ "model_max_length": 77,
22
+ "name_or_path": "./hf-models/stable-diffusion-v2-inpainting/tokenizer",
23
+ "pad_token": "<|endoftext|>",
24
+ "special_tokens_map_file": "./special_tokens_map.json",
25
+ "tokenizer_class": "CLIPTokenizer",
26
+ "unk_token": {
27
+ "__type": "AddedToken",
28
+ "content": "<|endoftext|>",
29
+ "lstrip": false,
30
+ "normalized": true,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
unet/config.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.29.0.dev0",
4
+ "_name_or_path": "/mnt/dataset/liuchenyang/huggingface/hub/models--stabilityai--stable-diffusion-2-inpainting/snapshots/81a84f49b15956b60b4272a405ad3daef3da4590",
5
+ "act_fn": "silu",
6
+ "addition_embed_type": null,
7
+ "addition_embed_type_num_heads": 64,
8
+ "addition_time_embed_dim": null,
9
+ "attention_head_dim": [
10
+ 5,
11
+ 10,
12
+ 20,
13
+ 20
14
+ ],
15
+ "attention_type": "default",
16
+ "block_out_channels": [
17
+ 320,
18
+ 640,
19
+ 1280,
20
+ 1280
21
+ ],
22
+ "center_input_sample": false,
23
+ "class_embed_type": "timestep",
24
+ "class_embeddings_concat": false,
25
+ "conv_in_kernel": 3,
26
+ "conv_out_kernel": 3,
27
+ "cross_attention_dim": 1024,
28
+ "cross_attention_norm": null,
29
+ "down_block_types": [
30
+ "CrossAttnDownBlock2D",
31
+ "CrossAttnDownBlock2D",
32
+ "CrossAttnDownBlock2D",
33
+ "DownBlock2D"
34
+ ],
35
+ "downsample_padding": 1,
36
+ "dropout": 0.0,
37
+ "dual_cross_attention": false,
38
+ "encoder_hid_dim": null,
39
+ "encoder_hid_dim_type": null,
40
+ "flip_sin_to_cos": true,
41
+ "freq_shift": 0,
42
+ "in_channels": 9,
43
+ "layers_per_block": 2,
44
+ "mid_block_only_cross_attention": null,
45
+ "mid_block_scale_factor": 1,
46
+ "mid_block_type": "UNetMidBlock2DCrossAttn",
47
+ "norm_eps": 1e-05,
48
+ "norm_num_groups": 32,
49
+ "num_attention_heads": null,
50
+ "num_class_embeds": null,
51
+ "only_cross_attention": false,
52
+ "out_channels": 4,
53
+ "projection_class_embeddings_input_dim": null,
54
+ "resnet_out_scale_factor": 1.0,
55
+ "resnet_skip_time_act": false,
56
+ "resnet_time_scale_shift": "default",
57
+ "reverse_transformer_layers_per_block": null,
58
+ "sample_size": 64,
59
+ "time_cond_proj_dim": null,
60
+ "time_embedding_act_fn": null,
61
+ "time_embedding_dim": null,
62
+ "time_embedding_type": "positional",
63
+ "timestep_post_act": null,
64
+ "transformer_layers_per_block": 1,
65
+ "up_block_types": [
66
+ "UpBlock2D",
67
+ "CrossAttnUpBlock2D",
68
+ "CrossAttnUpBlock2D",
69
+ "CrossAttnUpBlock2D"
70
+ ],
71
+ "upcast_attention": false,
72
+ "use_linear_projection": true
73
+ }
unet/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:273eef54f3432be3afd7539d9a25b09e87a740deefd11160c3ec21cc9e9cb828
3
+ size 1736035136
vae/config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.8.0",
4
+ "_name_or_path": "./hf-models/stable-diffusion-v2-inpainting/vae",
5
+ "act_fn": "silu",
6
+ "block_out_channels": [
7
+ 128,
8
+ 256,
9
+ 512,
10
+ 512
11
+ ],
12
+ "down_block_types": [
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D"
17
+ ],
18
+ "in_channels": 3,
19
+ "latent_channels": 4,
20
+ "layers_per_block": 2,
21
+ "norm_num_groups": 32,
22
+ "out_channels": 3,
23
+ "sample_size": 512,
24
+ "up_block_types": [
25
+ "UpDecoderBlock2D",
26
+ "UpDecoderBlock2D",
27
+ "UpDecoderBlock2D",
28
+ "UpDecoderBlock2D"
29
+ ]
30
+ }
vae/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1d993488569e928462932c8c38a0760b874d166399b14414135bd9c42df5815
3
+ size 334643276