waveydaveygravy commited on
Commit
212be9d
1 Parent(s): 018348e

Upload 2 files

Browse files
Files changed (2) hide show
  1. multicontrolnetPV.py +187 -0
  2. multicontrolnetfull.py +975 -0
multicontrolnetPV.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from ...models.controlnet import ControlNetModel, ControlNetOutput
8
+ from ...models.modeling_utils import ModelMixin
9
+ from ...utils import logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class MultiControlNetModel(ModelMixin):
16
+ r"""
17
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
18
+
19
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
20
+ compatible with `ControlNetModel`.
21
+
22
+ Args:
23
+ controlnets (`List[ControlNetModel]`):
24
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
25
+ `ControlNetModel` as a list.
26
+ """
27
+
28
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
29
+ super().__init__()
30
+ self.nets = nn.ModuleList(controlnets)
31
+
32
+ def forward(
33
+ self,
34
+ sample: torch.FloatTensor,
35
+ timestep: Union[torch.Tensor, float, int],
36
+ encoder_hidden_states: torch.Tensor,
37
+ controlnet_cond: List[torch.tensor],
38
+ conditioning_scale: List[float],
39
+ class_labels: Optional[torch.Tensor] = None,
40
+ timestep_cond: Optional[torch.Tensor] = None,
41
+ attention_mask: Optional[torch.Tensor] = None,
42
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
43
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
44
+ guess_mode: bool = False,
45
+ return_dict: bool = True,
46
+ ) -> Union[ControlNetOutput, Tuple]:
47
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
48
+ down_samples, mid_sample = controlnet(
49
+ sample=sample,
50
+ timestep=timestep,
51
+ encoder_hidden_states=encoder_hidden_states,
52
+ controlnet_cond=image,
53
+ conditioning_scale=scale,
54
+ class_labels=class_labels,
55
+ timestep_cond=timestep_cond,
56
+ attention_mask=attention_mask,
57
+ added_cond_kwargs=added_cond_kwargs,
58
+ cross_attention_kwargs=cross_attention_kwargs,
59
+ guess_mode=guess_mode,
60
+ return_dict=return_dict,
61
+ )
62
+
63
+ # merge samples
64
+ if i == 0:
65
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
66
+ else:
67
+ down_block_res_samples = [
68
+ samples_prev + samples_curr
69
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
70
+ ]
71
+ mid_block_res_sample += mid_sample
72
+
73
+ return down_block_res_samples, mid_block_res_sample
74
+
75
+ def save_pretrained(
76
+ self,
77
+ save_directory: Union[str, os.PathLike],
78
+ is_main_process: bool = True,
79
+ save_function: Callable = None,
80
+ safe_serialization: bool = True,
81
+ variant: Optional[str] = None,
82
+ ):
83
+ """
84
+ Save a model and its configuration file to a directory, so that it can be re-loaded using the
85
+ `[`~pipelines.controlnet.MultiControlNetModel.from_pretrained`]` class method.
86
+
87
+ Arguments:
88
+ save_directory (`str` or `os.PathLike`):
89
+ Directory to which to save. Will be created if it doesn't exist.
90
+ is_main_process (`bool`, *optional*, defaults to `True`):
91
+ Whether the process calling this is the main process or not. Useful when in distributed training like
92
+ TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
93
+ the main process to avoid race conditions.
94
+ save_function (`Callable`):
95
+ The function to use to save the state dictionary. Useful on distributed training like TPUs when one
96
+ need to replace `torch.save` by another method. Can be configured with the environment variable
97
+ `DIFFUSERS_SAVE_MODE`.
98
+ safe_serialization (`bool`, *optional*, defaults to `True`):
99
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
100
+ variant (`str`, *optional*):
101
+ If specified, weights are saved in the format pytorch_model.<variant>.bin.
102
+ """
103
+ idx = 0
104
+ model_path_to_save = save_directory
105
+ for controlnet in self.nets:
106
+ controlnet.save_pretrained(
107
+ model_path_to_save,
108
+ is_main_process=is_main_process,
109
+ save_function=save_function,
110
+ safe_serialization=safe_serialization,
111
+ variant=variant,
112
+ )
113
+
114
+ idx += 1
115
+ model_path_to_save = model_path_to_save + f"_{idx}"
116
+
117
+ @classmethod
118
+ def from_pretrained(cls, pretrained_model_path: Optional[Union[str, os.PathLike]], **kwargs):
119
+ r"""
120
+ Instantiate a pretrained MultiControlNet model from multiple pre-trained controlnet models.
121
+
122
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
123
+ the model, you should first set it back in training mode with `model.train()`.
124
+
125
+ The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
126
+ pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
127
+ task.
128
+
129
+ The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
130
+ weights are discarded.
131
+
132
+ Parameters:
133
+ pretrained_model_path (`os.PathLike`):
134
+ A path to a *directory* containing model weights saved using
135
+ [`~diffusers.pipelines.controlnet.MultiControlNetModel.save_pretrained`], e.g.,
136
+ `./my_model_directory/controlnet`.
137
+ torch_dtype (`str` or `torch.dtype`, *optional*):
138
+ Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype
139
+ will be automatically derived from the model's weights.
140
+ output_loading_info(`bool`, *optional*, defaults to `False`):
141
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
142
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
143
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
144
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
145
+ same device.
146
+
147
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
148
+ more information about each option see [designing a device
149
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
150
+ max_memory (`Dict`, *optional*):
151
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
152
+ GPU and the available CPU RAM if unset.
153
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
154
+ Speed up model loading by not initializing the weights and only loading the pre-trained weights. This
155
+ also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the
156
+ model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,
157
+ setting this argument to `True` will raise an error.
158
+ variant (`str`, *optional*):
159
+ If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is
160
+ ignored when using `from_flax`.
161
+ use_safetensors (`bool`, *optional*, defaults to `None`):
162
+ If set to `None`, the `safetensors` weights will be downloaded if they're available **and** if the
163
+ `safetensors` library is installed. If set to `True`, the model will be forcibly loaded from
164
+ `safetensors` weights. If set to `False`, loading will *not* use `safetensors`.
165
+ """
166
+ idx = 0
167
+ controlnets = []
168
+
169
+ # load controlnet and append to list until no controlnet directory exists anymore
170
+ # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained`
171
+ # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ...
172
+ model_path_to_load = pretrained_model_path
173
+ while os.path.isdir(model_path_to_load):
174
+ controlnet = ControlNetModel.from_pretrained(model_path_to_load, **kwargs)
175
+ controlnets.append(controlnet)
176
+
177
+ idx += 1
178
+ model_path_to_load = pretrained_model_path + f"_{idx}"
179
+
180
+ logger.info(f"{len(controlnets)} controlnets loaded from {pretrained_model_path}.")
181
+
182
+ if len(controlnets) == 0:
183
+ raise ValueError(
184
+ f"No ControlNets found under {os.path.dirname(pretrained_model_path)}. Expected at least {pretrained_model_path + '_0'}."
185
+ )
186
+
187
+ return cls(controlnets)
multicontrolnetfull.py ADDED
@@ -0,0 +1,975 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Skip to content
3
+
4
+ Pricing
5
+
6
+ Sign in
7
+ Sign up
8
+ huggingface /
9
+ diffusers
10
+ Public
11
+
12
+ Code
13
+ Issues 275
14
+ Pull requests 91
15
+ Discussions
16
+ Actions
17
+ Projects
18
+ Security
19
+
20
+ Insights
21
+
22
+ Comparing changes
23
+ Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also
24
+ or learn more about diff comparisons.
25
+ ...
26
+ Able to merge. These branches can be automatically merged.
27
+
28
+ 6 commits
29
+ 1 file changed
30
+
31
+ 1 contributor
32
+
33
+ Commits on Mar 5, 2023
34
+
35
+ copied from controlnet pipeline
36
+
37
+ @takuma104
38
+ takuma104 committed Mar 5, 2023
39
+
40
+ tweak namespace, add simple demo
41
+ @takuma104
42
+ takuma104 committed Mar 5, 2023
43
+
44
+ add ControlNetProcessor, canny x2 test
45
+ @takuma104
46
+ takuma104 committed Mar 5, 2023
47
+
48
+ canny+openpose demo
49
+ @takuma104
50
+ takuma104 committed Mar 5, 2023
51
+
52
+ update demo
53
+ @takuma104
54
+ takuma104 committed Mar 5, 2023
55
+
56
+ variable name
57
+ @takuma104
58
+ takuma104 committed Mar 5, 2023
59
+
60
+ Showing
61
+ with 913 additions and 0 deletions.
62
+ 913 changes: 913 additions & 0 deletions 913
63
+ examples/community/stable_diffusion_multi_controlnet.py
64
+ @@ -0,0 +1,913 @@
65
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
66
+ #
67
+ # Licensed under the Apache License, Version 2.0 (the "License");
68
+ # you may not use this file except in compliance with the License.
69
+ # You may obtain a copy of the License at
70
+ #
71
+ # http://www.apache.org/licenses/LICENSE-2.0
72
+ #
73
+ # Unless required by applicable law or agreed to in writing, software
74
+ # distributed under the License is distributed on an "AS IS" BASIS,
75
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
76
+ # See the License for the specific language governing permissions and
77
+ # limitations under the License.
78
+
79
+
80
+ import inspect
81
+ from typing import Any, Callable, Dict, List, Optional, Union, Tuple
82
+
83
+ import numpy as np
84
+ import PIL.Image
85
+ import torch
86
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
87
+
88
+ from diffusers import AutoencoderKL, ControlNetModel, UNet2DConditionModel
89
+ from diffusers.schedulers import KarrasDiffusionSchedulers
90
+ from diffusers.utils import (
91
+ PIL_INTERPOLATION,
92
+ is_accelerate_available,
93
+ is_accelerate_version,
94
+ logging,
95
+ randn_tensor,
96
+ replace_example_docstring,
97
+ )
98
+ from diffusers.pipeline_utils import DiffusionPipeline
99
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
100
+ from diffusers.models.controlnet import ControlNetOutput
101
+
102
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
103
+
104
+
105
+ class ControlNetProcessor(object):
106
+ def __init__(
107
+ self,
108
+ controlnet: ControlNetModel,
109
+ image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]],
110
+ conditioning_scale: float = 1.0,
111
+ ):
112
+ self.controlnet = controlnet
113
+ self.image = image
114
+ self.conditioning_scale = conditioning_scale
115
+
116
+ def _default_height_width(self, height, width, image):
117
+ if isinstance(image, list):
118
+ image = image[0]
119
+
120
+ if height is None:
121
+ if isinstance(image, PIL.Image.Image):
122
+ height = image.height
123
+ elif isinstance(image, torch.Tensor):
124
+ height = image.shape[3]
125
+
126
+ height = (height // 8) * 8 # round down to nearest multiple of 8
127
+
128
+ if width is None:
129
+ if isinstance(image, PIL.Image.Image):
130
+ width = image.width
131
+ elif isinstance(image, torch.Tensor):
132
+ width = image.shape[2]
133
+
134
+ width = (width // 8) * 8 # round down to nearest multiple of 8
135
+
136
+ return height, width
137
+
138
+ def default_height_width(self, height, width):
139
+ return self._default_height_width(height, width, self.image)
140
+
141
+ def _prepare_image(self, image, width, height, batch_size, num_images_per_prompt, device, dtype):
142
+ if not isinstance(image, torch.Tensor):
143
+ if isinstance(image, PIL.Image.Image):
144
+ image = [image]
145
+
146
+ if isinstance(image[0], PIL.Image.Image):
147
+ image = [
148
+ np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image
149
+ ]
150
+ image = np.concatenate(image, axis=0)
151
+ image = np.array(image).astype(np.float32) / 255.0
152
+ image = image.transpose(0, 3, 1, 2)
153
+ image = torch.from_numpy(image)
154
+ elif isinstance(image[0], torch.Tensor):
155
+ image = torch.cat(image, dim=0)
156
+
157
+ image_batch_size = image.shape[0]
158
+
159
+ if image_batch_size == 1:
160
+ repeat_by = batch_size
161
+ else:
162
+ # image batch size is the same as prompt batch size
163
+ repeat_by = num_images_per_prompt
164
+
165
+ image = image.repeat_interleave(repeat_by, dim=0)
166
+
167
+ image = image.to(device=device, dtype=dtype)
168
+
169
+ return image
170
+
171
+ def _check_inputs(self, image, prompt, prompt_embeds):
172
+ image_is_pil = isinstance(image, PIL.Image.Image)
173
+ image_is_tensor = isinstance(image, torch.Tensor)
174
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
175
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
176
+
177
+ if not image_is_pil and not image_is_tensor and not image_is_pil_list and not image_is_tensor_list:
178
+ raise TypeError(
179
+ "image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors"
180
+ )
181
+
182
+ if image_is_pil:
183
+ image_batch_size = 1
184
+ elif image_is_tensor:
185
+ image_batch_size = image.shape[0]
186
+ elif image_is_pil_list:
187
+ image_batch_size = len(image)
188
+ elif image_is_tensor_list:
189
+ image_batch_size = len(image)
190
+
191
+ if prompt is not None and isinstance(prompt, str):
192
+ prompt_batch_size = 1
193
+ elif prompt is not None and isinstance(prompt, list):
194
+ prompt_batch_size = len(prompt)
195
+ elif prompt_embeds is not None:
196
+ prompt_batch_size = prompt_embeds.shape[0]
197
+
198
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
199
+ raise ValueError(
200
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
201
+ )
202
+
203
+ def check_inputs(self, prompt, prompt_embeds):
204
+ self._check_inputs(self.image, prompt, prompt_embeds)
205
+
206
+ def prepare_image(self, width, height, batch_size, num_images_per_prompt, device, do_classifier_free_guidance):
207
+ self.image = self._prepare_image(
208
+ self.image, width, height, batch_size, num_images_per_prompt, device, self.controlnet.dtype
209
+ )
210
+ if do_classifier_free_guidance:
211
+ self.image = torch.cat([self.image] * 2)
212
+
213
+ def __call__(
214
+ self,
215
+ sample: torch.FloatTensor,
216
+ timestep: Union[torch.Tensor, float, int],
217
+ encoder_hidden_states: torch.Tensor,
218
+ class_labels: Optional[torch.Tensor] = None,
219
+ timestep_cond: Optional[torch.Tensor] = None,
220
+ attention_mask: Optional[torch.Tensor] = None,
221
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
222
+ return_dict: bool = True,
223
+ ) -> Tuple:
224
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
225
+ sample=sample,
226
+ controlnet_cond=self.image,
227
+ timestep=timestep,
228
+ encoder_hidden_states=encoder_hidden_states,
229
+ class_labels=class_labels,
230
+ timestep_cond=timestep_cond,
231
+ attention_mask=attention_mask,
232
+ cross_attention_kwargs=cross_attention_kwargs,
233
+ return_dict=False,
234
+ )
235
+ down_block_res_samples = [
236
+ down_block_res_sample * self.conditioning_scale for down_block_res_sample in down_block_res_samples
237
+ ]
238
+ mid_block_res_sample *= self.conditioning_scale
239
+ return (down_block_res_samples, mid_block_res_sample)
240
+
241
+
242
+ EXAMPLE_DOC_STRING = """
243
+ Examples:
244
+ ```py
245
+ >>> # !pip install opencv-python transformers accelerate
246
+ >>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
247
+ >>> from diffusers.utils import load_image
248
+ >>> import numpy as np
249
+ >>> import torch
250
+ >>> import cv2
251
+ >>> from PIL import Image
252
+ >>> # download an image
253
+ >>> image = load_image(
254
+ ... "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
255
+ ... )
256
+ >>> image = np.array(image)
257
+ >>> # get canny image
258
+ >>> image = cv2.Canny(image, 100, 200)
259
+ >>> image = image[:, :, None]
260
+ >>> image = np.concatenate([image, image, image], axis=2)
261
+ >>> canny_image = Image.fromarray(image)
262
+ >>> # load control net and stable diffusion v1-5
263
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
264
+ >>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
265
+ ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
266
+ ... )
267
+ >>> # speed up diffusion process with faster scheduler and memory optimization
268
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
269
+ >>> # remove following line if xformers is not installed
270
+ >>> pipe.enable_xformers_memory_efficient_attention()
271
+ >>> pipe.enable_model_cpu_offload()
272
+ >>> # generate image
273
+ >>> generator = torch.manual_seed(0)
274
+ >>> image = pipe(
275
+ ... "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
276
+ ... ).images[0]
277
+ ```
278
+ """
279
+
280
+
281
+ class StableDiffusionMultiControlNetPipeline(DiffusionPipeline):
282
+ r"""
283
+ Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
284
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
285
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
286
+ Args:
287
+ vae ([`AutoencoderKL`]):
288
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
289
+ text_encoder ([`CLIPTextModel`]):
290
+ Frozen text-encoder. Stable Diffusion uses the text portion of
291
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
292
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
293
+ tokenizer (`CLIPTokenizer`):
294
+ Tokenizer of class
295
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
296
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
297
+ scheduler ([`SchedulerMixin`]):
298
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
299
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
300
+ safety_checker ([`StableDiffusionSafetyChecker`]):
301
+ Classification module that estimates whether generated images could be considered offensive or harmful.
302
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
303
+ feature_extractor ([`CLIPFeatureExtractor`]):
304
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
305
+ """
306
+ _optional_components = ["safety_checker", "feature_extractor"]
307
+
308
+ def __init__(
309
+ self,
310
+ vae: AutoencoderKL,
311
+ text_encoder: CLIPTextModel,
312
+ tokenizer: CLIPTokenizer,
313
+ unet: UNet2DConditionModel,
314
+ scheduler: KarrasDiffusionSchedulers,
315
+ safety_checker: StableDiffusionSafetyChecker,
316
+ feature_extractor: CLIPFeatureExtractor,
317
+ requires_safety_checker: bool = True,
318
+ ):
319
+ super().__init__()
320
+
321
+ if safety_checker is None and requires_safety_checker:
322
+ logger.warning(
323
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
324
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
325
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
326
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
327
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
328
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
329
+ )
330
+
331
+ if safety_checker is not None and feature_extractor is None:
332
+ raise ValueError(
333
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
334
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
335
+ )
336
+
337
+ self.register_modules(
338
+ vae=vae,
339
+ text_encoder=text_encoder,
340
+ tokenizer=tokenizer,
341
+ unet=unet,
342
+ scheduler=scheduler,
343
+ safety_checker=safety_checker,
344
+ feature_extractor=feature_extractor,
345
+ )
346
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
347
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
348
+
349
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
350
+ def enable_vae_slicing(self):
351
+ r"""
352
+ Enable sliced VAE decoding.
353
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
354
+ steps. This is useful to save some memory and allow larger batch sizes.
355
+ """
356
+ self.vae.enable_slicing()
357
+
358
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
359
+ def disable_vae_slicing(self):
360
+ r"""
361
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
362
+ computing decoding in one step.
363
+ """
364
+ self.vae.disable_slicing()
365
+
366
+ def enable_sequential_cpu_offload(self, gpu_id=0):
367
+ r"""
368
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
369
+ text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a
370
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
371
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
372
+ `enable_model_cpu_offload`, but performance is lower.
373
+ """
374
+ if is_accelerate_available():
375
+ from accelerate import cpu_offload
376
+ else:
377
+ raise ImportError("Please install accelerate via `pip install accelerate`")
378
+
379
+ device = torch.device(f"cuda:{gpu_id}")
380
+
381
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
382
+ cpu_offload(cpu_offloaded_model, device)
383
+
384
+ if self.safety_checker is not None:
385
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
386
+
387
+ def enable_model_cpu_offload(self, gpu_id=0):
388
+ r"""
389
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
390
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
391
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
392
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
393
+ """
394
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
395
+ from accelerate import cpu_offload_with_hook
396
+ else:
397
+ raise ImportError("`enable_model_offload` requires `accelerate v0.17.0` or higher.")
398
+
399
+ device = torch.device(f"cuda:{gpu_id}")
400
+
401
+ hook = None
402
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
403
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
404
+
405
+ if self.safety_checker is not None:
406
+ # the safety checker can offload the vae again
407
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
408
+
409
+ # control net hook has be manually offloaded as it alternates with unet
410
+ # cpu_offload_with_hook(self.controlnet, device)
411
+
412
+ # We'll offload the last model manually.
413
+ self.final_offload_hook = hook
414
+
415
+ @property
416
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
417
+ def _execution_device(self):
418
+ r"""
419
+ Returns the device on which the pipeline's models will be executed. After calling
420
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
421
+ hooks.
422
+ """
423
+ if not hasattr(self.unet, "_hf_hook"):
424
+ return self.device
425
+ for module in self.unet.modules():
426
+ if (
427
+ hasattr(module, "_hf_hook")
428
+ and hasattr(module._hf_hook, "execution_device")
429
+ and module._hf_hook.execution_device is not None
430
+ ):
431
+ return torch.device(module._hf_hook.execution_device)
432
+ return self.device
433
+
434
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
435
+ def _encode_prompt(
436
+ self,
437
+ prompt,
438
+ device,
439
+ num_images_per_prompt,
440
+ do_classifier_free_guidance,
441
+ negative_prompt=None,
442
+ prompt_embeds: Optional[torch.FloatTensor] = None,
443
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
444
+ ):
445
+ r"""
446
+ Encodes the prompt into text encoder hidden states.
447
+ Args:
448
+ prompt (`str` or `List[str]`, *optional*):
449
+ prompt to be encoded
450
+ device: (`torch.device`):
451
+ torch device
452
+ num_images_per_prompt (`int`):
453
+ number of images that should be generated per prompt
454
+ do_classifier_free_guidance (`bool`):
455
+ whether to use classifier free guidance or not
456
+ negative_prompt (`str` or `List[str]`, *optional*):
457
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
458
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
459
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
460
+ prompt_embeds (`torch.FloatTensor`, *optional*):
461
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
462
+ provided, text embeddings will be generated from `prompt` input argument.
463
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
464
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
465
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
466
+ argument.
467
+ """
468
+ if prompt is not None and isinstance(prompt, str):
469
+ batch_size = 1
470
+ elif prompt is not None and isinstance(prompt, list):
471
+ batch_size = len(prompt)
472
+ else:
473
+ batch_size = prompt_embeds.shape[0]
474
+
475
+ if prompt_embeds is None:
476
+ text_inputs = self.tokenizer(
477
+ prompt,
478
+ padding="max_length",
479
+ max_length=self.tokenizer.model_max_length,
480
+ truncation=True,
481
+ return_tensors="pt",
482
+ )
483
+ text_input_ids = text_inputs.input_ids
484
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
485
+
486
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
487
+ text_input_ids, untruncated_ids
488
+ ):
489
+ removed_text = self.tokenizer.batch_decode(
490
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
491
+ )
492
+ logger.warning(
493
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
494
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
495
+ )
496
+
497
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
498
+ attention_mask = text_inputs.attention_mask.to(device)
499
+ else:
500
+ attention_mask = None
501
+
502
+ prompt_embeds = self.text_encoder(
503
+ text_input_ids.to(device),
504
+ attention_mask=attention_mask,
505
+ )
506
+ prompt_embeds = prompt_embeds[0]
507
+
508
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
509
+
510
+ bs_embed, seq_len, _ = prompt_embeds.shape
511
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
512
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
513
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
514
+
515
+ # get unconditional embeddings for classifier free guidance
516
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
517
+ uncond_tokens: List[str]
518
+ if negative_prompt is None:
519
+ uncond_tokens = [""] * batch_size
520
+ elif type(prompt) is not type(negative_prompt):
521
+ raise TypeError(
522
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
523
+ f" {type(prompt)}."
524
+ )
525
+ elif isinstance(negative_prompt, str):
526
+ uncond_tokens = [negative_prompt]
527
+ elif batch_size != len(negative_prompt):
528
+ raise ValueError(
529
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
530
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
531
+ " the batch size of `prompt`."
532
+ )
533
+ else:
534
+ uncond_tokens = negative_prompt
535
+
536
+ max_length = prompt_embeds.shape[1]
537
+ uncond_input = self.tokenizer(
538
+ uncond_tokens,
539
+ padding="max_length",
540
+ max_length=max_length,
541
+ truncation=True,
542
+ return_tensors="pt",
543
+ )
544
+
545
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
546
+ attention_mask = uncond_input.attention_mask.to(device)
547
+ else:
548
+ attention_mask = None
549
+
550
+ negative_prompt_embeds = self.text_encoder(
551
+ uncond_input.input_ids.to(device),
552
+ attention_mask=attention_mask,
553
+ )
554
+ negative_prompt_embeds = negative_prompt_embeds[0]
555
+
556
+ if do_classifier_free_guidance:
557
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
558
+ seq_len = negative_prompt_embeds.shape[1]
559
+
560
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
561
+
562
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
563
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
564
+
565
+ # For classifier free guidance, we need to do two forward passes.
566
+ # Here we concatenate the unconditional and text embeddings into a single batch
567
+ # to avoid doing two forward passes
568
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
569
+
570
+ return prompt_embeds
571
+
572
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
573
+ def run_safety_checker(self, image, device, dtype):
574
+ if self.safety_checker is not None:
575
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
576
+ image, has_nsfw_concept = self.safety_checker(
577
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
578
+ )
579
+ else:
580
+ has_nsfw_concept = None
581
+ return image, has_nsfw_concept
582
+
583
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
584
+ def decode_latents(self, latents):
585
+ latents = 1 / self.vae.config.scaling_factor * latents
586
+ image = self.vae.decode(latents).sample
587
+ image = (image / 2 + 0.5).clamp(0, 1)
588
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
589
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
590
+ return image
591
+
592
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
593
+ def prepare_extra_step_kwargs(self, generator, eta):
594
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
595
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
596
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
597
+ # and should be between [0, 1]
598
+
599
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
600
+ extra_step_kwargs = {}
601
+ if accepts_eta:
602
+ extra_step_kwargs["eta"] = eta
603
+
604
+ # check if the scheduler accepts generator
605
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
606
+ if accepts_generator:
607
+ extra_step_kwargs["generator"] = generator
608
+ return extra_step_kwargs
609
+
610
+ def check_inputs(
611
+ self,
612
+ prompt,
613
+ height,
614
+ width,
615
+ callback_steps,
616
+ negative_prompt=None,
617
+ prompt_embeds=None,
618
+ negative_prompt_embeds=None,
619
+ ):
620
+ if height % 8 != 0 or width % 8 != 0:
621
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
622
+
623
+ if (callback_steps is None) or (
624
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
625
+ ):
626
+ raise ValueError(
627
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
628
+ f" {type(callback_steps)}."
629
+ )
630
+
631
+ if prompt is not None and prompt_embeds is not None:
632
+ raise ValueError(
633
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
634
+ " only forward one of the two."
635
+ )
636
+ elif prompt is None and prompt_embeds is None:
637
+ raise ValueError(
638
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
639
+ )
640
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
641
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
642
+
643
+ if negative_prompt is not None and negative_prompt_embeds is not None:
644
+ raise ValueError(
645
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
646
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
647
+ )
648
+
649
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
650
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
651
+ raise ValueError(
652
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
653
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
654
+ f" {negative_prompt_embeds.shape}."
655
+ )
656
+
657
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
658
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
659
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
660
+ if isinstance(generator, list) and len(generator) != batch_size:
661
+ raise ValueError(
662
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
663
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
664
+ )
665
+
666
+ if latents is None:
667
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
668
+ else:
669
+ latents = latents.to(device)
670
+
671
+ # scale the initial noise by the standard deviation required by the scheduler
672
+ latents = latents * self.scheduler.init_noise_sigma
673
+ return latents
674
+
675
+ @torch.no_grad()
676
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
677
+ def __call__(
678
+ self,
679
+ processors: List[ControlNetProcessor],
680
+ prompt: Union[str, List[str]] = None,
681
+ height: Optional[int] = None,
682
+ width: Optional[int] = None,
683
+ num_inference_steps: int = 50,
684
+ guidance_scale: float = 7.5,
685
+ negative_prompt: Optional[Union[str, List[str]]] = None,
686
+ num_images_per_prompt: Optional[int] = 1,
687
+ eta: float = 0.0,
688
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
689
+ latents: Optional[torch.FloatTensor] = None,
690
+ prompt_embeds: Optional[torch.FloatTensor] = None,
691
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
692
+ output_type: Optional[str] = "pil",
693
+ return_dict: bool = True,
694
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
695
+ callback_steps: int = 1,
696
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
697
+ ):
698
+ r"""
699
+ Function invoked when calling the pipeline for generation.
700
+ Args:
701
+ prompt (`str` or `List[str]`, *optional*):
702
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
703
+ instead.
704
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
705
+ The height in pixels of the generated image.
706
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
707
+ The width in pixels of the generated image.
708
+ num_inference_steps (`int`, *optional*, defaults to 50):
709
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
710
+ expense of slower inference.
711
+ guidance_scale (`float`, *optional*, defaults to 7.5):
712
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
713
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
714
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
715
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
716
+ usually at the expense of lower image quality.
717
+ negative_prompt (`str` or `List[str]`, *optional*):
718
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
719
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
720
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
721
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
722
+ The number of images to generate per prompt.
723
+ eta (`float`, *optional*, defaults to 0.0):
724
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
725
+ [`schedulers.DDIMScheduler`], will be ignored for others.
726
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
727
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
728
+ to make generation deterministic.
729
+ latents (`torch.FloatTensor`, *optional*):
730
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
731
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
732
+ tensor will ge generated by sampling using the supplied random `generator`.
733
+ prompt_embeds (`torch.FloatTensor`, *optional*):
734
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
735
+ provided, text embeddings will be generated from `prompt` input argument.
736
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
737
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
738
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
739
+ argument.
740
+ output_type (`str`, *optional*, defaults to `"pil"`):
741
+ The output format of the generate image. Choose between
742
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
743
+ return_dict (`bool`, *optional*, defaults to `True`):
744
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
745
+ plain tuple.
746
+ callback (`Callable`, *optional*):
747
+ A function that will be called every `callback_steps` steps during inference. The function will be
748
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
749
+ callback_steps (`int`, *optional*, defaults to 1):
750
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
751
+ called at every step.
752
+ cross_attention_kwargs (`dict`, *optional*):
753
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
754
+ `self.processor` in
755
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
756
+ Examples:
757
+ Returns:
758
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
759
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
760
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
761
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
762
+ (nsfw) content, according to the `safety_checker`.
763
+ """
764
+ # 0. Default height and width to unet
765
+ height, width = processors[0].default_height_width(height, width)
766
+
767
+ # 1. Check inputs. Raise error if not correct
768
+ self.check_inputs(
769
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
770
+ )
771
+ for processor in processors:
772
+ processor.check_inputs(prompt, prompt_embeds)
773
+
774
+ # 2. Define call parameters
775
+ if prompt is not None and isinstance(prompt, str):
776
+ batch_size = 1
777
+ elif prompt is not None and isinstance(prompt, list):
778
+ batch_size = len(prompt)
779
+ else:
780
+ batch_size = prompt_embeds.shape[0]
781
+
782
+ device = self._execution_device
783
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
784
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
785
+ # corresponds to doing no classifier free guidance.
786
+ do_classifier_free_guidance = guidance_scale > 1.0
787
+
788
+ # 3. Encode input prompt
789
+ prompt_embeds = self._encode_prompt(
790
+ prompt,
791
+ device,
792
+ num_images_per_prompt,
793
+ do_classifier_free_guidance,
794
+ negative_prompt,
795
+ prompt_embeds=prompt_embeds,
796
+ negative_prompt_embeds=negative_prompt_embeds,
797
+ )
798
+
799
+ # 4. Prepare image
800
+ for processor in processors:
801
+ processor.prepare_image(
802
+ width=width,
803
+ height=height,
804
+ batch_size=batch_size * num_images_per_prompt,
805
+ num_images_per_prompt=num_images_per_prompt,
806
+ device=device,
807
+ do_classifier_free_guidance=do_classifier_free_guidance,
808
+ )
809
+
810
+ # 5. Prepare timesteps
811
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
812
+ timesteps = self.scheduler.timesteps
813
+
814
+ # 6. Prepare latent variables
815
+ num_channels_latents = self.unet.in_channels
816
+ latents = self.prepare_latents(
817
+ batch_size * num_images_per_prompt,
818
+ num_channels_latents,
819
+ height,
820
+ width,
821
+ prompt_embeds.dtype,
822
+ device,
823
+ generator,
824
+ latents,
825
+ )
826
+
827
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
828
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
829
+
830
+ # 8. Denoising loop
831
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
832
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
833
+ for i, t in enumerate(timesteps):
834
+ # expand the latents if we are doing classifier free guidance
835
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
836
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
837
+
838
+ # controlnet inference
839
+ for i, processor in enumerate(processors):
840
+ down_samples, mid_sample = processor(
841
+ latent_model_input,
842
+ t,
843
+ encoder_hidden_states=prompt_embeds,
844
+ return_dict=False,
845
+ )
846
+ if i == 0:
847
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
848
+ else:
849
+ down_block_res_samples = [
850
+ d_prev + d_curr for d_prev, d_curr in zip(down_block_res_samples, down_samples)
851
+ ]
852
+ mid_block_res_sample = mid_block_res_sample + mid_sample
853
+
854
+ # predict the noise residual
855
+ noise_pred = self.unet(
856
+ latent_model_input,
857
+ t,
858
+ encoder_hidden_states=prompt_embeds,
859
+ cross_attention_kwargs=cross_attention_kwargs,
860
+ down_block_additional_residuals=down_block_res_samples,
861
+ mid_block_additional_residual=mid_block_res_sample,
862
+ ).sample
863
+
864
+ # perform guidance
865
+ if do_classifier_free_guidance:
866
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
867
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
868
+
869
+ # compute the previous noisy sample x_t -> x_t-1
870
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
871
+
872
+ # call the callback, if provided
873
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
874
+ progress_bar.update()
875
+ if callback is not None and i % callback_steps == 0:
876
+ callback(i, t, latents)
877
+
878
+ # If we do sequential model offloading, let's offload unet and controlnet
879
+ # manually for max memory savings
880
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
881
+ self.unet.to("cpu")
882
+ torch.cuda.empty_cache()
883
+
884
+ if output_type == "latent":
885
+ image = latents
886
+ has_nsfw_concept = None
887
+ elif output_type == "pil":
888
+ # 8. Post-processing
889
+ image = self.decode_latents(latents)
890
+
891
+ # 9. Run safety checker
892
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
893
+
894
+ # 10. Convert to PIL
895
+ image = self.numpy_to_pil(image)
896
+ else:
897
+ # 8. Post-processing
898
+ image = self.decode_latents(latents)
899
+
900
+ # 9. Run safety checker
901
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
902
+
903
+ # Offload last model to CPU
904
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
905
+ self.final_offload_hook.offload()
906
+
907
+ if not return_dict:
908
+ return (image, has_nsfw_concept)
909
+
910
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
911
+
912
+
913
+ # demo & simple test
914
+ def main():
915
+ from diffusers.utils import load_image
916
+
917
+ pipe = StableDiffusionMultiControlNetPipeline.from_pretrained(
918
+ "runwayml/stable-diffusion-v1-5", safety_checker=None, torch_dtype=torch.float16
919
+ ).to("cuda")
920
+ pipe.enable_xformers_memory_efficient_attention()
921
+
922
+ controlnet_canny = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16).to(
923
+ "cuda"
924
+ )
925
+ controlnet_pose = ControlNetModel.from_pretrained(
926
+ "lllyasviel/sd-controlnet-openpose", torch_dtype=torch.float16
927
+ ).to("cuda")
928
+
929
+ canny_left = load_image("https://huggingface.co/takuma104/controlnet_dev/resolve/main/vermeer_left.png")
930
+ canny_right = load_image("https://huggingface.co/takuma104/controlnet_dev/resolve/main/vermeer_right.png")
931
+ pose_right = load_image("https://huggingface.co/takuma104/controlnet_dev/resolve/main/pose_right.png")
932
+
933
+ image = pipe(
934
+ prompt="best quality, extremely detailed",
935
+ negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
936
+ processors=[
937
+ ControlNetProcessor(controlnet_canny, canny_left),
938
+ ControlNetProcessor(controlnet_canny, canny_right),
939
+ ],
940
+ generator=torch.Generator(device="cpu").manual_seed(0),
941
+ num_inference_steps=30,
942
+ width=512,
943
+ height=512,
944
+ ).images[0]
945
+ image.save("/tmp/canny_left_right.png")
946
+
947
+ image = pipe(
948
+ prompt="best quality, extremely detailed",
949
+ negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
950
+ processors=[
951
+ ControlNetProcessor(controlnet_canny, canny_left),
952
+ ControlNetProcessor(controlnet_pose, pose_right),
953
+ ],
954
+ generator=torch.Generator(device="cpu").manual_seed(0),
955
+ num_inference_steps=30,
956
+ width=512,
957
+ height=512,
958
+ ).images[0]
959
+ image.save("/tmp/canny_left_pose_right.png")
960
+
961
+
962
+ if __name__ == "__main__":
963
+ main()
964
+ Footer
965
+ © 2024 GitHub, Inc.
966
+ Footer navigation
967
+
968
+ Terms
969
+ Privacy
970
+ Security
971
+ Status
972
+ Docs
973
+ Contact
974
+
975
+ update demo · huggingface/diffusers@f718c4e · GitHub