JOY-Huang commited on
Commit
b4cad83
1 Parent(s): 025b1f9

update repo

Browse files
module/aggregator.py CHANGED
@@ -1,16 +1,3 @@
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
  from dataclasses import dataclass
15
  from typing import Any, Dict, List, Optional, Tuple, Union
16
 
@@ -19,7 +6,7 @@ from torch import nn
19
  from torch.nn import functional as F
20
 
21
  from diffusers.configuration_utils import ConfigMixin, register_to_config
22
- from diffusers.loaders import FromOriginalControlNetMixin
23
  from diffusers.utils import BaseOutput, logging
24
  from diffusers.models.attention_processor import (
25
  ADDED_KV_ATTENTION_PROCESSORS,
@@ -168,7 +155,7 @@ class ConditioningEmbedding(nn.Module):
168
  return embedding
169
 
170
 
171
- class Aggregator(ModelMixin, ConfigMixin, FromOriginalControlNetMixin):
172
  """
173
  Aggregator model.
174
 
@@ -781,7 +768,6 @@ class Aggregator(ModelMixin, ConfigMixin, FromOriginalControlNetMixin):
781
  attention_mask: Optional[torch.Tensor] = None,
782
  added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
783
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
784
- guess_mode: bool = False,
785
  return_dict: bool = True,
786
  ) -> Union[AggregatorOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
787
  """
@@ -812,9 +798,6 @@ class Aggregator(ModelMixin, ConfigMixin, FromOriginalControlNetMixin):
812
  Additional conditions for the Stable Diffusion XL UNet.
813
  cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
814
  A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
815
- guess_mode (`bool`, defaults to `False`):
816
- In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
817
- you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
818
  return_dict (`bool`, defaults to `True`):
819
  Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
820
 
@@ -977,14 +960,8 @@ class Aggregator(ModelMixin, ConfigMixin, FromOriginalControlNetMixin):
977
  mid_block_res_sample = self.controlnet_mid_block((cond_latent, ref_latent), )
978
 
979
  # 6. scaling
980
- if guess_mode and not self.config.global_pool_conditions:
981
- scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
982
- scales = scales * conditioning_scale
983
- down_block_res_samples = [sample*scale for sample, scale in zip(down_block_res_samples, scales)]
984
- mid_block_res_sample = mid_block_res_sample*scales[-1] # last scale
985
- else:
986
- down_block_res_samples = [sample*conditioning_scale for sample in down_block_res_samples]
987
- mid_block_res_sample = mid_block_res_sample*conditioning_scale
988
 
989
  if self.config.global_pool_conditions:
990
  down_block_res_samples = [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from dataclasses import dataclass
2
  from typing import Any, Dict, List, Optional, Tuple, Union
3
 
 
6
  from torch.nn import functional as F
7
 
8
  from diffusers.configuration_utils import ConfigMixin, register_to_config
9
+ from diffusers.loaders.single_file_model import FromOriginalModelMixin
10
  from diffusers.utils import BaseOutput, logging
11
  from diffusers.models.attention_processor import (
12
  ADDED_KV_ATTENTION_PROCESSORS,
 
155
  return embedding
156
 
157
 
158
+ class Aggregator(ModelMixin, ConfigMixin, FromOriginalModelMixin):
159
  """
160
  Aggregator model.
161
 
 
768
  attention_mask: Optional[torch.Tensor] = None,
769
  added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
770
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
 
771
  return_dict: bool = True,
772
  ) -> Union[AggregatorOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
773
  """
 
798
  Additional conditions for the Stable Diffusion XL UNet.
799
  cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
800
  A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
 
 
 
801
  return_dict (`bool`, defaults to `True`):
802
  Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
803
 
 
960
  mid_block_res_sample = self.controlnet_mid_block((cond_latent, ref_latent), )
961
 
962
  # 6. scaling
963
+ down_block_res_samples = [sample*conditioning_scale for sample in down_block_res_samples]
964
+ mid_block_res_sample = mid_block_res_sample*conditioning_scale
 
 
 
 
 
 
965
 
966
  if self.config.global_pool_conditions:
967
  down_block_res_samples = [
module/ip_adapter/attention_processor.py CHANGED
@@ -1361,7 +1361,7 @@ class CNAttnProcessor2_0:
1361
  return hidden_states
1362
 
1363
 
1364
- def init_attn_proc(unet, ip_adapter_tokens=16, use_lcm=True, use_adaln=True, use_external_kv=False):
1365
  attn_procs = {}
1366
  unet_sd = unet.state_dict()
1367
  for name in unet.attn_processors.keys():
 
1361
  return hidden_states
1362
 
1363
 
1364
+ def init_attn_proc(unet, ip_adapter_tokens=16, use_lcm=False, use_adaln=True, use_external_kv=False):
1365
  attn_procs = {}
1366
  unet_sd = unet.state_dict()
1367
  for name in unet.attn_processors.keys():
module/ip_adapter/resampler.py CHANGED
@@ -81,11 +81,11 @@ class PerceiverAttention(nn.Module):
81
  class Resampler(nn.Module):
82
  def __init__(
83
  self,
84
- dim=1024,
85
- depth=8,
86
  dim_head=64,
87
- heads=16,
88
- num_queries=8,
89
  embedding_dim=768,
90
  output_dim=1024,
91
  ff_mult=4,
 
81
  class Resampler(nn.Module):
82
  def __init__(
83
  self,
84
+ dim=1280,
85
+ depth=4,
86
  dim_head=64,
87
+ heads=20,
88
+ num_queries=64,
89
  embedding_dim=768,
90
  output_dim=1024,
91
  ff_mult=4,
module/ip_adapter/utils.py CHANGED
@@ -1,23 +1,32 @@
1
- import random
2
  import torch
3
  from collections import namedtuple, OrderedDict
4
  from safetensors import safe_open
5
  from .attention_processor import init_attn_proc
6
  from .ip_adapter import MultiIPAdapterImageProjection
 
7
  from transformers import (
8
  AutoModel, AutoImageProcessor,
9
  CLIPVisionModelWithProjection, CLIPImageProcessor)
10
 
11
 
12
- def init_ip_adapter_in_unet(
13
  unet,
14
- image_proj_model,
15
  pretrained_model_path_or_dict=None,
16
- adapter_tokens=16,
 
17
  use_lcm=False,
18
  use_adaln=True,
19
- use_external_kv=False,
20
  ):
 
 
 
 
 
 
 
 
 
21
  if pretrained_model_path_or_dict is not None:
22
  if not isinstance(pretrained_model_path_or_dict, dict):
23
  if pretrained_model_path_or_dict.endswith(".safetensors"):
@@ -37,7 +46,7 @@ def init_ip_adapter_in_unet(
37
  state_dict = revise_state_dict(state_dict)
38
 
39
  # Creat IP cross-attention in unet.
40
- attn_procs = init_attn_proc(unet, adapter_tokens, use_lcm, use_adaln, use_external_kv)
41
  unet.set_attn_processor(attn_procs)
42
 
43
  # Load pretrinaed model if needed.
@@ -58,24 +67,24 @@ def init_ip_adapter_in_unet(
58
 
59
  # Adjust unet config to handle addtional ip hidden states.
60
  unet.config.encoder_hid_dim_type = "ip_image_proj"
 
61
 
62
 
63
- def load_ip_adapter_to_pipe(
64
  pipe,
65
  pretrained_model_path_or_dict,
66
- image_encoder_path=None,
67
- feature_extractor_path=None,
68
- use_dino=False,
69
- ip_adapter_tokens=16,
70
- use_lcm=True,
71
  use_adaln=True,
72
- low_cpu_mem_usage=True,
73
  ):
74
 
75
  if not isinstance(pretrained_model_path_or_dict, dict):
76
  if pretrained_model_path_or_dict.endswith(".safetensors"):
77
  state_dict = {"image_proj": {}, "ip_adapter": {}}
78
- with safe_open(pretrained_model_path_or_dict, framework="pt", device="cpu") as f:
79
  for key in f.keys():
80
  if key.startswith("image_proj."):
81
  state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
@@ -85,150 +94,72 @@ def load_ip_adapter_to_pipe(
85
  state_dict = torch.load(pretrained_model_path_or_dict, map_location=pipe.device)
86
  else:
87
  state_dict = pretrained_model_path_or_dict
88
-
89
  keys = list(state_dict.keys())
90
- if keys != ["image_proj", "ip_adapter"]:
91
  state_dict = revise_state_dict(state_dict)
92
 
93
  # load CLIP image encoder here if it has not been registered to the pipeline yet
94
- if image_encoder_path is not None:
95
- if isinstance(image_encoder_path, str):
96
- feature_extractor_path = image_encoder_path if feature_extractor_path is None else feature_extractor_path
97
-
98
- image_encoder_path = AutoModel.from_pretrained(
99
- image_encoder_path) if use_dino else \
100
- CLIPVisionModelWithProjection.from_pretrained(
101
- image_encoder_path)
102
- image_encoder = image_encoder_path.to(pipe.device, dtype=pipe.dtype)
 
103
 
104
- if feature_extractor_path is not None:
105
- if isinstance(feature_extractor_path, str):
106
- feature_extractor_path = AutoImageProcessor.from_pretrained(feature_extractor_path) \
107
- if use_dino else CLIPImageProcessor()
108
- feature_extractor = feature_extractor_path
 
109
 
110
  # create image encoder if it has not been registered to the pipeline yet
111
  if hasattr(pipe, "image_encoder") and getattr(pipe, "image_encoder", None) is None:
 
112
  pipe.register_modules(image_encoder=image_encoder)
113
-
114
- # create feature extractor if it has not been registered to the pipeline yet
115
- if hasattr(pipe, "feature_extractor") and getattr(pipe, "feature_extractor", None) is None:
116
- pipe.register_modules(feature_extractor=feature_extractor)
117
-
118
- # load ip-adapter into unet
119
- unet = getattr(pipe, pipe.unet_name) if not hasattr(pipe, "unet") else pipe.unet
120
- attn_procs = init_attn_proc(unet, ip_adapter_tokens, use_lcm, use_adaln)
121
- unet.set_attn_processor(attn_procs)
122
- adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
123
- missing, _ = adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=False)
124
- if len(missing) > 0:
125
- raise ValueError(f"Missing keys in adapter_modules: {missing}")
126
-
127
- # convert IP-Adapter Image Projection layers to diffusers
128
- image_projection_layers = []
129
- image_projection_layer = unet._convert_ip_adapter_image_proj_to_diffusers(
130
- state_dict["image_proj"], low_cpu_mem_usage=low_cpu_mem_usage
131
- )
132
- image_projection_layers.append(image_projection_layer)
133
-
134
- unet.encoder_hid_proj = MultiIPAdapterImageProjection(image_projection_layers)
135
- unet.config.encoder_hid_dim_type = "ip_image_proj"
136
-
137
- unet.to(dtype=pipe.dtype, device=pipe.device)
138
-
139
-
140
- def load_ip_adapter_to_controlnet_pipe(
141
- pipe,
142
- pretrained_model_path_or_dict,
143
- image_encoder_path=None,
144
- feature_extractor_path=None,
145
- use_dino=False,
146
- ip_adapter_tokens=16,
147
- use_lcm=True,
148
- use_adaln=True,
149
- low_cpu_mem_usage=True,
150
- ):
151
-
152
- if not isinstance(pretrained_model_path_or_dict, dict):
153
- if pretrained_model_path_or_dict.endswith(".safetensors"):
154
- state_dict = {"image_proj": {}, "ip_adapter": {}}
155
- with safe_open(pretrained_model_path_or_dict, framework="pt", device="cpu") as f:
156
- for key in f.keys():
157
- if key.startswith("image_proj."):
158
- state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
159
- elif key.startswith("ip_adapter."):
160
- state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
161
- else:
162
- state_dict = torch.load(pretrained_model_path_or_dict, map_location=pipe.device)
163
  else:
164
- state_dict = pretrained_model_path_or_dict
165
-
166
- keys = list(state_dict.keys())
167
- if keys != ["image_proj", "ip_adapter"]:
168
- state_dict = revise_state_dict(state_dict)
169
-
170
- # load CLIP image encoder here if it has not been registered to the pipeline yet
171
- if image_encoder_path is not None:
172
- if isinstance(image_encoder_path, str):
173
- feature_extractor_path = image_encoder_path if feature_extractor_path is None else feature_extractor_path
174
-
175
- image_encoder_path = AutoModel.from_pretrained(
176
- image_encoder_path) if use_dino else \
177
- CLIPVisionModelWithProjection.from_pretrained(
178
- image_encoder_path)
179
- image_encoder = image_encoder_path.to(pipe.device, dtype=pipe.dtype)
180
-
181
- if feature_extractor_path is not None:
182
- if isinstance(feature_extractor_path, str):
183
- feature_extractor_path = AutoImageProcessor.from_pretrained(feature_extractor_path) \
184
- if use_dino else CLIPImageProcessor()
185
- feature_extractor = feature_extractor_path
186
-
187
- # create image encoder if it has not been registered to the pipeline yet
188
- if hasattr(pipe, "image_encoder") and getattr(pipe, "image_encoder", None) is None:
189
- pipe.register_modules(image_encoder=image_encoder)
190
 
191
  # create feature extractor if it has not been registered to the pipeline yet
192
  if hasattr(pipe, "feature_extractor") and getattr(pipe, "feature_extractor", None) is None:
 
193
  pipe.register_modules(feature_extractor=feature_extractor)
 
 
194
 
195
- # load ip-adapter into unet
196
  unet = getattr(pipe, pipe.unet_name) if not hasattr(pipe, "unet") else pipe.unet
197
- attn_procs = init_attn_proc(unet, ip_adapter_tokens, use_lcm, use_adaln)
198
  unet.set_attn_processor(attn_procs)
199
- adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
200
- missing, _ = adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=False)
201
- if len(missing) > 0:
202
- raise ValueError(f"Missing keys in adapter_modules: {missing}")
 
203
 
204
- controlnet = getattr(pipe, pipe.controlnet_name) if not hasattr(pipe, "controlnet") else pipe.controlnet
205
- controlnet_attn_procs = init_attn_proc(controlnet, ip_adapter_tokens, use_lcm, use_adaln)
206
- controlnet.set_attn_processor(controlnet_attn_procs)
207
- controlnet_adapter_modules = torch.nn.ModuleList(controlnet.attn_processors.values())
208
- missing, unexpected = controlnet_adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=False)
209
- if len(missing) > 0:
210
- raise ValueError(f"Missing keys in adapter_modules: {missing}")
211
- if len(unexpected) > 0:
212
- for mk in unexpected:
213
- layer_id = int(mk.split(".")[0])
214
- if layer_id < len(controlnet.attn_processors.keys()):
215
- raise ValueError(f"Failed to load {unexpected} in controlnet adapter_modules")
216
 
217
  # convert IP-Adapter Image Projection layers to diffusers
218
  image_projection_layers = []
219
- image_projection_layer = unet._convert_ip_adapter_image_proj_to_diffusers(
220
- state_dict["image_proj"], low_cpu_mem_usage=low_cpu_mem_usage
221
- )
222
- image_projection_layers.append(image_projection_layer)
223
-
224
  unet.encoder_hid_proj = MultiIPAdapterImageProjection(image_projection_layers)
225
- unet.config.encoder_hid_dim_type = "ip_image_proj"
226
-
227
- controlnet.encoder_hid_proj = MultiIPAdapterImageProjection(image_projection_layers)
228
- controlnet.config.encoder_hid_dim_type = "ip_image_proj"
229
 
 
 
230
  unet.to(dtype=pipe.dtype, device=pipe.device)
231
- controlnet.to(dtype=pipe.dtype, device=pipe.device)
232
 
233
  def revise_state_dict(old_state_dict_or_path, map_location="cpu"):
234
  new_state_dict = OrderedDict()
 
 
1
  import torch
2
  from collections import namedtuple, OrderedDict
3
  from safetensors import safe_open
4
  from .attention_processor import init_attn_proc
5
  from .ip_adapter import MultiIPAdapterImageProjection
6
+ from .resampler import Resampler
7
  from transformers import (
8
  AutoModel, AutoImageProcessor,
9
  CLIPVisionModelWithProjection, CLIPImageProcessor)
10
 
11
 
12
+ def init_adapter_in_unet(
13
  unet,
14
+ image_proj_model=None,
15
  pretrained_model_path_or_dict=None,
16
+ adapter_tokens=64,
17
+ embedding_dim=None,
18
  use_lcm=False,
19
  use_adaln=True,
 
20
  ):
21
+ device = unet.device
22
+ dtype = unet.dtype
23
+ if image_proj_model is None:
24
+ assert embedding_dim is not None, "embedding_dim must be provided if image_proj_model is None."
25
+ image_proj_model = Resampler(
26
+ embedding_dim=embedding_dim,
27
+ output_dim=unet.config.cross_attention_dim,
28
+ num_queries=adapter_tokens,
29
+ )
30
  if pretrained_model_path_or_dict is not None:
31
  if not isinstance(pretrained_model_path_or_dict, dict):
32
  if pretrained_model_path_or_dict.endswith(".safetensors"):
 
46
  state_dict = revise_state_dict(state_dict)
47
 
48
  # Creat IP cross-attention in unet.
49
+ attn_procs = init_attn_proc(unet, adapter_tokens, use_lcm, use_adaln)
50
  unet.set_attn_processor(attn_procs)
51
 
52
  # Load pretrinaed model if needed.
 
67
 
68
  # Adjust unet config to handle addtional ip hidden states.
69
  unet.config.encoder_hid_dim_type = "ip_image_proj"
70
+ unet.to(dtype=dtype, device=device)
71
 
72
 
73
+ def load_adapter_to_pipe(
74
  pipe,
75
  pretrained_model_path_or_dict,
76
+ image_encoder_or_path=None,
77
+ feature_extractor_or_path=None,
78
+ use_clip_encoder=False,
79
+ adapter_tokens=64,
80
+ use_lcm=False,
81
  use_adaln=True,
 
82
  ):
83
 
84
  if not isinstance(pretrained_model_path_or_dict, dict):
85
  if pretrained_model_path_or_dict.endswith(".safetensors"):
86
  state_dict = {"image_proj": {}, "ip_adapter": {}}
87
+ with safe_open(pretrained_model_path_or_dict, framework="pt", device=pipe.device) as f:
88
  for key in f.keys():
89
  if key.startswith("image_proj."):
90
  state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
 
94
  state_dict = torch.load(pretrained_model_path_or_dict, map_location=pipe.device)
95
  else:
96
  state_dict = pretrained_model_path_or_dict
 
97
  keys = list(state_dict.keys())
98
+ if "image_proj" not in keys and "ip_adapter" not in keys:
99
  state_dict = revise_state_dict(state_dict)
100
 
101
  # load CLIP image encoder here if it has not been registered to the pipeline yet
102
+ if image_encoder_or_path is not None:
103
+ if isinstance(image_encoder_or_path, str):
104
+ feature_extractor_or_path = image_encoder_or_path if feature_extractor_or_path is None else feature_extractor_or_path
105
+
106
+ image_encoder_or_path = (
107
+ CLIPVisionModelWithProjection.from_pretrained(
108
+ image_encoder_or_path
109
+ ) if use_clip_encoder else
110
+ AutoModel.from_pretrained(image_encoder_or_path)
111
+ )
112
 
113
+ if feature_extractor_or_path is not None:
114
+ if isinstance(feature_extractor_or_path, str):
115
+ feature_extractor_or_path = (
116
+ CLIPImageProcessor() if use_clip_encoder else
117
+ AutoImageProcessor.from_pretrained(feature_extractor_or_path)
118
+ )
119
 
120
  # create image encoder if it has not been registered to the pipeline yet
121
  if hasattr(pipe, "image_encoder") and getattr(pipe, "image_encoder", None) is None:
122
+ image_encoder = image_encoder_or_path.to(pipe.device, dtype=pipe.dtype)
123
  pipe.register_modules(image_encoder=image_encoder)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  else:
125
+ image_encoder = pipe.image_encoder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  # create feature extractor if it has not been registered to the pipeline yet
128
  if hasattr(pipe, "feature_extractor") and getattr(pipe, "feature_extractor", None) is None:
129
+ feature_extractor = feature_extractor_or_path
130
  pipe.register_modules(feature_extractor=feature_extractor)
131
+ else:
132
+ feature_extractor = pipe.feature_extractor
133
 
134
+ # load adapter into unet
135
  unet = getattr(pipe, pipe.unet_name) if not hasattr(pipe, "unet") else pipe.unet
136
+ attn_procs = init_attn_proc(unet, adapter_tokens, use_lcm, use_adaln)
137
  unet.set_attn_processor(attn_procs)
138
+ image_proj_model = Resampler(
139
+ embedding_dim=image_encoder.config.hidden_size,
140
+ output_dim=unet.config.cross_attention_dim,
141
+ num_queries=adapter_tokens,
142
+ )
143
 
144
+ # Load pretrinaed model if needed.
145
+ if "ip_adapter" in state_dict.keys():
146
+ adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
147
+ missing, unexpected = adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=False)
148
+ for mk in missing:
149
+ if "ln" not in mk:
150
+ raise ValueError(f"Missing keys in adapter_modules: {missing}")
151
+ if "image_proj" in state_dict.keys():
152
+ image_proj_model.load_state_dict(state_dict["image_proj"])
 
 
 
153
 
154
  # convert IP-Adapter Image Projection layers to diffusers
155
  image_projection_layers = []
156
+ image_projection_layers.append(image_proj_model)
 
 
 
 
157
  unet.encoder_hid_proj = MultiIPAdapterImageProjection(image_projection_layers)
 
 
 
 
158
 
159
+ # Adjust unet config to handle addtional ip hidden states.
160
+ unet.config.encoder_hid_dim_type = "ip_image_proj"
161
  unet.to(dtype=pipe.dtype, device=pipe.device)
162
+
163
 
164
  def revise_state_dict(old_state_dict_or_path, map_location="cpu"):
165
  new_state_dict = OrderedDict()
pipelines/sdxl_instantir.py CHANGED
@@ -1,4 +1,4 @@
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.
@@ -53,6 +53,7 @@ from diffusers.utils import (
53
  replace_example_docstring,
54
  scale_lora_layers,
55
  unscale_lora_layers,
 
56
  )
57
  from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
58
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
@@ -62,6 +63,7 @@ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffus
62
  if is_invisible_watermark_available():
63
  from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
64
 
 
65
  from module.aggregator import Aggregator
66
 
67
 
@@ -71,44 +73,52 @@ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
71
  EXAMPLE_DOC_STRING = """
72
  Examples:
73
  ```py
74
- >>> # !pip install opencv-python transformers accelerate
75
- >>> from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
76
- >>> from diffusers.utils import load_image
77
- >>> import numpy as np
78
  >>> import torch
79
-
80
- >>> import cv2
81
  >>> from PIL import Image
82
 
83
- >>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
84
- >>> negative_prompt = "low quality, bad quality, sketches"
85
 
86
- >>> # download an image
87
- >>> image = load_image(
88
- ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
89
- ... )
90
 
91
- >>> # initialize the models and pipeline
92
- >>> controlnet_conditioning_scale = 0.5 # recommended for good generalization
93
- >>> controlnet = ControlNetModel.from_pretrained(
94
- ... "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
95
- ... )
96
- >>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
97
- >>> pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
98
  ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16
99
  ... )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  >>> pipe.enable_model_cpu_offload()
101
 
102
- >>> # get canny image
103
- >>> image = np.array(image)
104
- >>> image = cv2.Canny(image, 100, 200)
105
- >>> image = image[:, :, None]
106
- >>> image = np.concatenate([image, image, image], axis=2)
107
- >>> canny_image = Image.fromarray(image)
108
 
109
- >>> # generate image
110
  >>> image = pipe(
111
- ... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
 
112
  ... ).images[0]
113
  ```
114
  """
@@ -299,8 +309,8 @@ class InstantIRPipeline(
299
  tokenizer: CLIPTokenizer,
300
  tokenizer_2: CLIPTokenizer,
301
  unet: UNet2DConditionModel,
302
- aggregator: Aggregator,
303
  scheduler: KarrasDiffusionSchedulers,
 
304
  force_zeros_for_empty_prompt: bool = True,
305
  add_watermarker: Optional[bool] = None,
306
  feature_extractor: CLIPImageProcessor = None,
@@ -308,6 +318,8 @@ class InstantIRPipeline(
308
  ):
309
  super().__init__()
310
 
 
 
311
  remove_attn2(aggregator)
312
 
313
  self.register_modules(
@@ -336,6 +348,55 @@ class InstantIRPipeline(
336
 
337
  self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
340
  def encode_prompt(
341
  self,
@@ -1011,10 +1072,10 @@ class InstantIRPipeline(
1011
  image: PipelineImageInput = None,
1012
  height: Optional[int] = None,
1013
  width: Optional[int] = None,
1014
- num_inference_steps: int = 50,
1015
  timesteps: List[int] = None,
1016
  denoising_end: Optional[float] = None,
1017
- guidance_scale: float = 5.0,
1018
  negative_prompt: Optional[Union[str, List[str]]] = None,
1019
  negative_prompt_2: Optional[Union[str, List[str]]] = None,
1020
  num_images_per_prompt: Optional[int] = 1,
@@ -1032,11 +1093,14 @@ class InstantIRPipeline(
1032
  save_preview_row: bool = False,
1033
  init_latents_with_lq: bool = True,
1034
  multistep_restore: bool = False,
 
1035
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1036
  guidance_rescale: float = 0.0,
1037
- controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
1038
- control_guidance_start: Union[float, List[float]] = 0.0,
1039
- control_guidance_end: Union[float, List[float]] = 1.0,
 
 
1040
  original_size: Tuple[int, int] = None,
1041
  crops_coords_top_left: Tuple[int, int] = (0, 0),
1042
  target_size: Tuple[int, int] = None,
@@ -1212,6 +1276,8 @@ class InstantIRPipeline(
1212
  )
1213
 
1214
  aggregator = self.aggregator._orig_mod if is_compiled_module(self.aggregator) else self.aggregator
 
 
1215
 
1216
  # 1. Check inputs. Raise error if not correct
1217
  self.check_inputs(
@@ -1303,8 +1369,14 @@ class InstantIRPipeline(
1303
  )
1304
  height, width = image.shape[-2:]
1305
  if image.shape[1] != 4:
 
 
 
 
1306
  image = self.vae.encode(image).latent_dist.sample()
1307
  image = image * self.vae.config.scaling_factor
 
 
1308
  else:
1309
  height = int(height * self.vae_scale_factor)
1310
  width = int(width * self.vae_scale_factor)
@@ -1341,9 +1413,12 @@ class InstantIRPipeline(
1341
 
1342
  # 7.1 Create tensor stating which controlnets to keep
1343
  controlnet_keep = []
 
1344
  for i in range(len(timesteps)):
1345
  keeps = 1.0 - float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
1346
  controlnet_keep.append(keeps)
 
 
1347
  if isinstance(controlnet_conditioning_scale, list):
1348
  assert len(controlnet_conditioning_scale) == len(timesteps), f"{len(controlnet_conditioning_scale)} controlnet scales do not match number of sampling steps {len(timesteps)}"
1349
  else:
@@ -1427,83 +1502,105 @@ class InstantIRPipeline(
1427
  # expand the latents if we are doing classifier free guidance
1428
  latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1429
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
 
 
1430
 
1431
- added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1432
-
1433
- # preview with LCM
1434
- previewer_model_input = latent_model_input
1435
- previewer_prompt_embeds = prompt_embeds
1436
- previewer_added_cond_kwargs = {
1437
  "text_embeds": add_text_embeds,
1438
  "time_ids": add_time_ids,
1439
  "image_embeds": image_embeds
1440
  }
1441
- self.unet.enable_adapters()
1442
- preview_noise = self.unet(
1443
- previewer_model_input,
1444
- t,
1445
- encoder_hidden_states=previewer_prompt_embeds,
1446
- timestep_cond=timestep_cond,
1447
- cross_attention_kwargs=self.cross_attention_kwargs,
1448
- added_cond_kwargs=previewer_added_cond_kwargs,
1449
- return_dict=False,
1450
- )[0]
1451
- preview_latent = previewer_scheduler.step(
1452
- preview_noise,
1453
- t.to(dtype=torch.int64),
1454
- # torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
1455
- latent_model_input,
1456
- return_dict=False
1457
- )[0]
1458
- self.unet.disable_adapters()
1459
- if self.do_classifier_free_guidance:
1460
- _, preview_latent_cond = preview_latent.chunk(2)
1461
- _, noise_preview = preview_noise.chunk(2)
1462
- preview_row.append(preview_latent_cond.to('cpu'))
1463
- else:
1464
- noise_preview = preview_noise
1465
- preview_row.append(preview_latent.to('cpu'))
1466
- # Prepare 2nd order step.
1467
- if multistep_restore and i+1 < len(timesteps):
1468
- first_step = self.scheduler.step(noise_preview, t, latents, **extra_step_kwargs, return_dict=True, step_forward=False)
1469
- prev_t = timesteps[i + 1]
1470
- unet_model_input = torch.cat([first_step.prev_sample] * 2) if self.do_classifier_free_guidance else first_step.prev_sample
1471
- unet_model_input = self.scheduler.scale_model_input(unet_model_input, prev_t, heun_step=True)
1472
- else:
1473
- prev_t = t
1474
- unet_model_input = latent_model_input
1475
 
1476
- if reference_latents is not None:
1477
- preview_latent = torch.cat([reference_latents] * 2) if self.do_classifier_free_guidance else reference_latents
 
 
1478
 
1479
- # Add fresh noise
1480
- # preview_noise = torch.randn_like(preview_latent)
1481
- # preview_latent = self.scheduler.add_noise(preview_latent, preview_noise, t)
 
 
 
 
1482
 
1483
- preview_latent=preview_latent.to(dtype=next(aggregator.parameters()).dtype)
 
1484
 
1485
- # Aggregator inference
1486
- generative_reference = preview_latent
 
 
 
1487
 
1488
- adaRes_scale = preview_factor.to(generative_reference.dtype).clamp(0.0, controlnet_conditioning_scale[i])
 
1489
  cond_scale = adaRes_scale * controlnet_keep[i]
1490
  cond_scale = torch.cat([cond_scale] * 2) if self.do_classifier_free_guidance else cond_scale
1491
- print(cond_scale.squeeze())
1492
 
1493
- extra_kwargs = {"log_attn": 10} if i == 0 else None
1494
- down_block_res_samples, mid_block_res_sample = aggregator(
1495
- image,
1496
- prev_t,
1497
- encoder_hidden_states=prompt_embeds,
1498
- controlnet_cond=generative_reference,
1499
- conditioning_scale=cond_scale,
1500
- # cross_attention_kwargs=extra_kwargs,
1501
- added_cond_kwargs=added_cond_kwargs,
1502
- return_dict=False,
1503
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1504
 
1505
- if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1506
- added_cond_kwargs["image_embeds"] = image_embeds
 
1507
 
1508
  # predict the noise residual
1509
  noise_pred = self.unet(
@@ -1536,14 +1633,15 @@ class InstantIRPipeline(
1536
  unet_pred_latent = unet_step.pred_original_sample
1537
 
1538
  # Adaptive restoration.
1539
- pred_x0_l2 = ((preview_latent[latents.shape[0]:].float()-unet_pred_latent.float())).pow(2).sum(dim=(1,2,3))
1540
- previewer_l2 = ((preview_latent[latents.shape[0]:].float()-previewer_mean.float())).pow(2).sum(dim=(1,2,3))
1541
- # unet_l2 = ((unet_pred_latent.float()-unet_mean.float())).pow(2).sum(dim=(1,2,3)).sqrt()
1542
- # l2_error = (((preview_latent[latents.shape[0]:]-previewer_mean) - (unet_pred_latent-unet_mean))).pow(2).mean(dim=(1,2,3))
1543
- # preview_error = torch.nn.functional.cosine_similarity(preview_latent[latents.shape[0]:].reshape(latents.shape[0], -1), unet_pred_latent.reshape(latents.shape[0],-1))
1544
- previewer_mean = preview_latent[latents.shape[0]:]
1545
- unet_mean = unet_pred_latent
1546
- preview_factor = (pred_x0_l2 / previewer_l2).reshape(-1, 1, 1, 1)
 
1547
 
1548
  if latents.dtype != latents_dtype:
1549
  if torch.backends.mps.is_available():
@@ -1610,7 +1708,7 @@ class InstantIRPipeline(
1610
  if needs_upcasting:
1611
  self.upcast_vae()
1612
  for preview_latents in preview_row:
1613
- preview_latents = preview_latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1614
  if has_latents_mean and has_latents_std:
1615
  latents_mean = (
1616
  torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(preview_latents.device, preview_latents.dtype)
 
1
+ # Copyright 2024 The InstantX 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.
 
53
  replace_example_docstring,
54
  scale_lora_layers,
55
  unscale_lora_layers,
56
+ convert_unet_state_dict_to_peft
57
  )
58
  from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
59
  from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
 
63
  if is_invisible_watermark_available():
64
  from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
65
 
66
+ from peft import LoraConfig, set_peft_model_state_dict
67
  from module.aggregator import Aggregator
68
 
69
 
 
73
  EXAMPLE_DOC_STRING = """
74
  Examples:
75
  ```py
76
+ >>> # !pip install diffusers pillow transformers accelerate
 
 
 
77
  >>> import torch
 
 
78
  >>> from PIL import Image
79
 
80
+ >>> from diffusers import DDPMScheduler
81
+ >>> from schedulers.lcm_single_step_scheduler import LCMSingleStepScheduler
82
 
83
+ >>> from module.ip_adapter.utils import load_adapter_to_pipe
84
+ >>> from pipelines.sdxl_instantir import InstantIRPipeline
 
 
85
 
86
+ >>> # download models under ./models
87
+ >>> dcp_adapter = f'./models/adapter.pt'
88
+ >>> previewer_lora_path = f'./models'
89
+ >>> instantir_path = f'./models/aggregator.pt'
90
+
91
+ >>> # load pretrained models
92
+ >>> pipe = InstantIRPipeline.from_pretrained(
93
  ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16
94
  ... )
95
+ >>> # load adapter
96
+ >>> load_adapter_to_pipe(
97
+ ... pipe,
98
+ ... dcp_adapter,
99
+ ... image_encoder_or_path = 'facebook/dinov2-large',
100
+ ... )
101
+ >>> # load previewer lora
102
+ >>> pipe.prepare_previewers(previewer_lora_path)
103
+ >>> pipe.scheduler = DDPMScheduler.from_pretrained('stabilityai/stable-diffusion-xl-base-1.0', subfolder="scheduler")
104
+ >>> lcm_scheduler = LCMSingleStepScheduler.from_config(pipe.scheduler.config)
105
+
106
+ >>> # load aggregator weights
107
+ >>> pretrained_state_dict = torch.load(instantir_path)
108
+ >>> pipe.aggregator.load_state_dict(pretrained_state_dict)
109
+
110
+ >>> # send to GPU and fp16
111
+ >>> pipe.to(device="cuda", dtype=torch.float16)
112
+ >>> pipe.aggregator.to(device="cuda", dtype=torch.float16)
113
  >>> pipe.enable_model_cpu_offload()
114
 
115
+ >>> # load a broken image
116
+ >>> low_quality_image = Image.open('path/to/your-image').convert("RGB")
 
 
 
 
117
 
118
+ >>> # restoration
119
  >>> image = pipe(
120
+ ... image=low_quality_image,
121
+ ... previewer_scheduler=lcm_scheduler,
122
  ... ).images[0]
123
  ```
124
  """
 
309
  tokenizer: CLIPTokenizer,
310
  tokenizer_2: CLIPTokenizer,
311
  unet: UNet2DConditionModel,
 
312
  scheduler: KarrasDiffusionSchedulers,
313
+ aggregator: Aggregator = None,
314
  force_zeros_for_empty_prompt: bool = True,
315
  add_watermarker: Optional[bool] = None,
316
  feature_extractor: CLIPImageProcessor = None,
 
318
  ):
319
  super().__init__()
320
 
321
+ if aggregator is None:
322
+ aggregator = Aggregator.from_unet(unet)
323
  remove_attn2(aggregator)
324
 
325
  self.register_modules(
 
348
 
349
  self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
350
 
351
+ def prepare_previewers(self, previewer_lora_path: str, use_lcm=False):
352
+ if use_lcm:
353
+ lora_state_dict, alpha_dict = self.lora_state_dict(
354
+ previewer_lora_path,
355
+ )
356
+ else:
357
+ lora_state_dict, alpha_dict = self.lora_state_dict(
358
+ previewer_lora_path,
359
+ weight_name="previewer_lora_weights.bin"
360
+ )
361
+ unet_state_dict = {
362
+ f'{k.replace("unet.", "")}': v for k, v in lora_state_dict.items() if k.startswith("unet.")
363
+ }
364
+ unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
365
+ lora_state_dict = dict()
366
+ for k, v in unet_state_dict.items():
367
+ if "ip" in k:
368
+ k = k.replace("attn2", "attn2.processor")
369
+ lora_state_dict[k] = v
370
+ else:
371
+ lora_state_dict[k] = v
372
+ if alpha_dict:
373
+ lora_alpha = next(iter(alpha_dict.values()))
374
+ else:
375
+ lora_alpha = 1
376
+ logger.info(f"use lora alpha {lora_alpha}")
377
+ lora_config = LoraConfig(
378
+ r=64,
379
+ target_modules=LCM_LORA_MODULES if use_lcm else PREVIEWER_LORA_MODULES,
380
+ lora_alpha=lora_alpha,
381
+ lora_dropout=0.0,
382
+ )
383
+
384
+ adapter_name = "lcm" if use_lcm else "previewer"
385
+ self.unet.add_adapter(lora_config, adapter_name)
386
+ incompatible_keys = set_peft_model_state_dict(self.unet, lora_state_dict, adapter_name=adapter_name)
387
+ if incompatible_keys is not None:
388
+ # check only for unexpected keys
389
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
390
+ missing_keys = getattr(incompatible_keys, "missing_keys", None)
391
+ if unexpected_keys:
392
+ raise ValueError(
393
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
394
+ f" {unexpected_keys}. "
395
+ )
396
+ self.unet.disable_adapters()
397
+
398
+ return lora_alpha
399
+
400
  # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
401
  def encode_prompt(
402
  self,
 
1072
  image: PipelineImageInput = None,
1073
  height: Optional[int] = None,
1074
  width: Optional[int] = None,
1075
+ num_inference_steps: int = 30,
1076
  timesteps: List[int] = None,
1077
  denoising_end: Optional[float] = None,
1078
+ guidance_scale: float = 7.0,
1079
  negative_prompt: Optional[Union[str, List[str]]] = None,
1080
  negative_prompt_2: Optional[Union[str, List[str]]] = None,
1081
  num_images_per_prompt: Optional[int] = 1,
 
1093
  save_preview_row: bool = False,
1094
  init_latents_with_lq: bool = True,
1095
  multistep_restore: bool = False,
1096
+ adastep_restore: bool = False,
1097
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1098
  guidance_rescale: float = 0.0,
1099
+ controlnet_conditioning_scale: float = 1.0,
1100
+ control_guidance_start: float = 0.0,
1101
+ control_guidance_end: float = 1.0,
1102
+ preview_start: float = 0.0,
1103
+ preview_end: float = 1.0,
1104
  original_size: Tuple[int, int] = None,
1105
  crops_coords_top_left: Tuple[int, int] = (0, 0),
1106
  target_size: Tuple[int, int] = None,
 
1276
  )
1277
 
1278
  aggregator = self.aggregator._orig_mod if is_compiled_module(self.aggregator) else self.aggregator
1279
+ if not isinstance(ip_adapter_image, list):
1280
+ ip_adapter_image = [ip_adapter_image] if ip_adapter_image is not None else [image]
1281
 
1282
  # 1. Check inputs. Raise error if not correct
1283
  self.check_inputs(
 
1369
  )
1370
  height, width = image.shape[-2:]
1371
  if image.shape[1] != 4:
1372
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1373
+ if needs_upcasting:
1374
+ image = image.float()
1375
+ self.vae.to(dtype=torch.float32)
1376
  image = self.vae.encode(image).latent_dist.sample()
1377
  image = image * self.vae.config.scaling_factor
1378
+ if needs_upcasting:
1379
+ self.vae.to(dtype=torch.float16)
1380
  else:
1381
  height = int(height * self.vae_scale_factor)
1382
  width = int(width * self.vae_scale_factor)
 
1413
 
1414
  # 7.1 Create tensor stating which controlnets to keep
1415
  controlnet_keep = []
1416
+ previewing = []
1417
  for i in range(len(timesteps)):
1418
  keeps = 1.0 - float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
1419
  controlnet_keep.append(keeps)
1420
+ use_preview = 1.0 - float(i / len(timesteps) < preview_start or (i + 1) / len(timesteps) > preview_end)
1421
+ previewing.append(use_preview)
1422
  if isinstance(controlnet_conditioning_scale, list):
1423
  assert len(controlnet_conditioning_scale) == len(timesteps), f"{len(controlnet_conditioning_scale)} controlnet scales do not match number of sampling steps {len(timesteps)}"
1424
  else:
 
1502
  # expand the latents if we are doing classifier free guidance
1503
  latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1504
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1505
+ prev_t = t
1506
+ unet_model_input = latent_model_input
1507
 
1508
+ added_cond_kwargs = {
 
 
 
 
 
1509
  "text_embeds": add_text_embeds,
1510
  "time_ids": add_time_ids,
1511
  "image_embeds": image_embeds
1512
  }
1513
+ aggregator_added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1514
 
1515
+ # prepare time_embeds in advance as adapter input
1516
+ cross_attention_t_emb = self.unet.get_time_embed(sample=latent_model_input, timestep=t)
1517
+ cross_attention_emb = self.unet.time_embedding(cross_attention_t_emb, timestep_cond)
1518
+ cross_attention_aug_emb = None
1519
 
1520
+ cross_attention_aug_emb = self.unet.get_aug_embed(
1521
+ emb=cross_attention_emb,
1522
+ encoder_hidden_states=prompt_embeds,
1523
+ added_cond_kwargs=added_cond_kwargs
1524
+ )
1525
+
1526
+ cross_attention_emb = cross_attention_emb + cross_attention_aug_emb if cross_attention_aug_emb is not None else cross_attention_emb
1527
 
1528
+ if self.unet.time_embed_act is not None:
1529
+ cross_attention_emb = self.unet.time_embed_act(cross_attention_emb)
1530
 
1531
+ current_cross_attention_kwargs = {"temb": cross_attention_emb}
1532
+ if cross_attention_kwargs is not None:
1533
+ for k,v in cross_attention_kwargs.items():
1534
+ current_cross_attention_kwargs[k] = v
1535
+ self._cross_attention_kwargs = current_cross_attention_kwargs
1536
 
1537
+ # adaptive restoration factors
1538
+ adaRes_scale = preview_factor.to(latent_model_input.dtype).clamp(0.0, controlnet_conditioning_scale[i])
1539
  cond_scale = adaRes_scale * controlnet_keep[i]
1540
  cond_scale = torch.cat([cond_scale] * 2) if self.do_classifier_free_guidance else cond_scale
 
1541
 
1542
+ if (cond_scale>0.1).sum().item() > 0:
1543
+ if previewing[i] > 0:
1544
+ # preview with LCM
1545
+ self.unet.enable_adapters()
1546
+ preview_noise = self.unet(
1547
+ latent_model_input,
1548
+ t,
1549
+ encoder_hidden_states=prompt_embeds,
1550
+ timestep_cond=timestep_cond,
1551
+ cross_attention_kwargs=self.cross_attention_kwargs,
1552
+ added_cond_kwargs=added_cond_kwargs,
1553
+ return_dict=False,
1554
+ )[0]
1555
+ preview_latent = previewer_scheduler.step(
1556
+ preview_noise,
1557
+ t.to(dtype=torch.int64),
1558
+ # torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
1559
+ latent_model_input, # scaled latents here for compatibility
1560
+ return_dict=False
1561
+ )[0]
1562
+ self.unet.disable_adapters()
1563
+
1564
+ if self.do_classifier_free_guidance:
1565
+ preview_row.append(preview_latent.chunk(2)[1].to('cpu'))
1566
+ else:
1567
+ preview_row.append(preview_latent.to('cpu'))
1568
+ # Prepare 2nd order step.
1569
+ if multistep_restore and i+1 < len(timesteps):
1570
+ noise_preview = preview_noise.chunk(2)[1] if self.do_classifier_free_guidance else preview_noise
1571
+ first_step = self.scheduler.step(
1572
+ noise_preview, t, latents,
1573
+ **extra_step_kwargs, return_dict=True, step_forward=False
1574
+ )
1575
+ prev_t = timesteps[i + 1]
1576
+ unet_model_input = torch.cat([first_step.prev_sample] * 2) if self.do_classifier_free_guidance else first_step.prev_sample
1577
+ unet_model_input = self.scheduler.scale_model_input(unet_model_input, prev_t, heun_step=True)
1578
+
1579
+ elif reference_latents is not None:
1580
+ preview_latent = torch.cat([reference_latents] * 2) if self.do_classifier_free_guidance else reference_latents
1581
+ else:
1582
+ preview_latent = image
1583
+
1584
+ # Add fresh noise
1585
+ # preview_noise = torch.randn_like(preview_latent)
1586
+ # preview_latent = self.scheduler.add_noise(preview_latent, preview_noise, t)
1587
+
1588
+ preview_latent=preview_latent.to(dtype=next(aggregator.parameters()).dtype)
1589
+
1590
+ # Aggregator inference
1591
+ down_block_res_samples, mid_block_res_sample = aggregator(
1592
+ image,
1593
+ prev_t,
1594
+ encoder_hidden_states=prompt_embeds,
1595
+ controlnet_cond=preview_latent,
1596
+ # conditioning_scale=cond_scale,
1597
+ added_cond_kwargs=aggregator_added_cond_kwargs,
1598
+ return_dict=False,
1599
+ )
1600
 
1601
+ # aggregator features scaling
1602
+ down_block_res_samples = [sample*cond_scale for sample in down_block_res_samples]
1603
+ mid_block_res_sample = mid_block_res_sample*cond_scale
1604
 
1605
  # predict the noise residual
1606
  noise_pred = self.unet(
 
1633
  unet_pred_latent = unet_step.pred_original_sample
1634
 
1635
  # Adaptive restoration.
1636
+ if adastep_restore:
1637
+ pred_x0_l2 = ((preview_latent[latents.shape[0]:].float()-unet_pred_latent.float())).pow(2).sum(dim=(1,2,3))
1638
+ previewer_l2 = ((preview_latent[latents.shape[0]:].float()-previewer_mean.float())).pow(2).sum(dim=(1,2,3))
1639
+ # unet_l2 = ((unet_pred_latent.float()-unet_mean.float())).pow(2).sum(dim=(1,2,3)).sqrt()
1640
+ # l2_error = (((preview_latent[latents.shape[0]:]-previewer_mean) - (unet_pred_latent-unet_mean))).pow(2).mean(dim=(1,2,3))
1641
+ # preview_error = torch.nn.functional.cosine_similarity(preview_latent[latents.shape[0]:].reshape(latents.shape[0], -1), unet_pred_latent.reshape(latents.shape[0],-1))
1642
+ previewer_mean = preview_latent[latents.shape[0]:]
1643
+ unet_mean = unet_pred_latent
1644
+ preview_factor = (pred_x0_l2 / previewer_l2).reshape(-1, 1, 1, 1)
1645
 
1646
  if latents.dtype != latents_dtype:
1647
  if torch.backends.mps.is_available():
 
1708
  if needs_upcasting:
1709
  self.upcast_vae()
1710
  for preview_latents in preview_row:
1711
+ preview_latents = preview_latents.to(device=self.device, dtype=next(iter(self.vae.post_quant_conv.parameters())).dtype)
1712
  if has_latents_mean and has_latents_std:
1713
  latents_mean = (
1714
  torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(preview_latents.device, preview_latents.dtype)
pipelines/stage1_sdxl_pipeline.py ADDED
@@ -0,0 +1,1283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Tuple, Union
17
+
18
+ import torch
19
+ from transformers import (
20
+ CLIPImageProcessor,
21
+ CLIPTextModel,
22
+ CLIPTextModelWithProjection,
23
+ CLIPTokenizer,
24
+ CLIPVisionModelWithProjection,
25
+ )
26
+
27
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
28
+ from ...loaders import (
29
+ FromSingleFileMixin,
30
+ IPAdapterMixin,
31
+ StableDiffusionXLLoraLoaderMixin,
32
+ TextualInversionLoaderMixin,
33
+ )
34
+ from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
35
+ from ...models.attention_processor import (
36
+ AttnProcessor2_0,
37
+ FusedAttnProcessor2_0,
38
+ LoRAAttnProcessor2_0,
39
+ LoRAXFormersAttnProcessor,
40
+ XFormersAttnProcessor,
41
+ )
42
+ from ...models.lora import adjust_lora_scale_text_encoder
43
+ from ...schedulers import KarrasDiffusionSchedulers
44
+ from ...utils import (
45
+ USE_PEFT_BACKEND,
46
+ deprecate,
47
+ is_invisible_watermark_available,
48
+ is_torch_xla_available,
49
+ logging,
50
+ replace_example_docstring,
51
+ scale_lora_layers,
52
+ unscale_lora_layers,
53
+ )
54
+ from ...utils.torch_utils import randn_tensor
55
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
56
+ from .pipeline_output import StableDiffusionXLPipelineOutput
57
+
58
+
59
+ if is_invisible_watermark_available():
60
+ from .watermark import StableDiffusionXLWatermarker
61
+
62
+ if is_torch_xla_available():
63
+ import torch_xla.core.xla_model as xm
64
+
65
+ XLA_AVAILABLE = True
66
+ else:
67
+ XLA_AVAILABLE = False
68
+
69
+
70
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
71
+
72
+ EXAMPLE_DOC_STRING = """
73
+ Examples:
74
+ ```py
75
+ >>> import torch
76
+ >>> from diffusers import StableDiffusionXLPipeline
77
+
78
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
79
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
80
+ ... )
81
+ >>> pipe = pipe.to("cuda")
82
+
83
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
84
+ >>> image = pipe(prompt).images[0]
85
+ ```
86
+ """
87
+
88
+
89
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
90
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
91
+ """
92
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
93
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
94
+ """
95
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
96
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
97
+ # rescale the results from guidance (fixes overexposure)
98
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
99
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
100
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
101
+ return noise_cfg
102
+
103
+
104
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
105
+ def retrieve_timesteps(
106
+ scheduler,
107
+ num_inference_steps: Optional[int] = None,
108
+ device: Optional[Union[str, torch.device]] = None,
109
+ timesteps: Optional[List[int]] = None,
110
+ **kwargs,
111
+ ):
112
+ """
113
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
114
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
115
+
116
+ Args:
117
+ scheduler (`SchedulerMixin`):
118
+ The scheduler to get timesteps from.
119
+ num_inference_steps (`int`):
120
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
121
+ must be `None`.
122
+ device (`str` or `torch.device`, *optional*):
123
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
124
+ timesteps (`List[int]`, *optional*):
125
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
126
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
127
+ must be `None`.
128
+
129
+ Returns:
130
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
131
+ second element is the number of inference steps.
132
+ """
133
+ if timesteps is not None:
134
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
135
+ if not accepts_timesteps:
136
+ raise ValueError(
137
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
138
+ f" timestep schedules. Please check whether you are using the correct scheduler."
139
+ )
140
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
141
+ timesteps = scheduler.timesteps
142
+ num_inference_steps = len(timesteps)
143
+ else:
144
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
145
+ timesteps = scheduler.timesteps
146
+ return timesteps, num_inference_steps
147
+
148
+
149
+ class StableDiffusionXLPipeline(
150
+ DiffusionPipeline,
151
+ StableDiffusionMixin,
152
+ FromSingleFileMixin,
153
+ StableDiffusionXLLoraLoaderMixin,
154
+ TextualInversionLoaderMixin,
155
+ IPAdapterMixin,
156
+ ):
157
+ r"""
158
+ Pipeline for text-to-image generation using Stable Diffusion XL.
159
+
160
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
161
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
162
+
163
+ The pipeline also inherits the following loading methods:
164
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
165
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
166
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
167
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
168
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
169
+
170
+ Args:
171
+ vae ([`AutoencoderKL`]):
172
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
173
+ text_encoder ([`CLIPTextModel`]):
174
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
175
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
176
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
177
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
178
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
179
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
180
+ specifically the
181
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
182
+ variant.
183
+ tokenizer (`CLIPTokenizer`):
184
+ Tokenizer of class
185
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
186
+ tokenizer_2 (`CLIPTokenizer`):
187
+ Second Tokenizer of class
188
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
189
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
190
+ scheduler ([`SchedulerMixin`]):
191
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
192
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
193
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
194
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
195
+ `stabilityai/stable-diffusion-xl-base-1-0`.
196
+ add_watermarker (`bool`, *optional*):
197
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
198
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
199
+ watermarker will be used.
200
+ """
201
+
202
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
203
+ _optional_components = [
204
+ "tokenizer",
205
+ "tokenizer_2",
206
+ "text_encoder",
207
+ "text_encoder_2",
208
+ "image_encoder",
209
+ "feature_extractor",
210
+ ]
211
+ _callback_tensor_inputs = [
212
+ "latents",
213
+ "prompt_embeds",
214
+ "negative_prompt_embeds",
215
+ "add_text_embeds",
216
+ "add_time_ids",
217
+ "negative_pooled_prompt_embeds",
218
+ "negative_add_time_ids",
219
+ ]
220
+
221
+ def __init__(
222
+ self,
223
+ vae: AutoencoderKL,
224
+ text_encoder: CLIPTextModel,
225
+ text_encoder_2: CLIPTextModelWithProjection,
226
+ tokenizer: CLIPTokenizer,
227
+ tokenizer_2: CLIPTokenizer,
228
+ unet: UNet2DConditionModel,
229
+ scheduler: KarrasDiffusionSchedulers,
230
+ image_encoder: CLIPVisionModelWithProjection = None,
231
+ feature_extractor: CLIPImageProcessor = None,
232
+ force_zeros_for_empty_prompt: bool = True,
233
+ add_watermarker: Optional[bool] = None,
234
+ ):
235
+ super().__init__()
236
+
237
+ self.register_modules(
238
+ vae=vae,
239
+ text_encoder=text_encoder,
240
+ text_encoder_2=text_encoder_2,
241
+ tokenizer=tokenizer,
242
+ tokenizer_2=tokenizer_2,
243
+ unet=unet,
244
+ scheduler=scheduler,
245
+ image_encoder=image_encoder,
246
+ feature_extractor=feature_extractor,
247
+ )
248
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
249
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
250
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
251
+
252
+ self.default_sample_size = self.unet.config.sample_size
253
+
254
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
255
+
256
+ if add_watermarker:
257
+ self.watermark = StableDiffusionXLWatermarker()
258
+ else:
259
+ self.watermark = None
260
+
261
+ def encode_prompt(
262
+ self,
263
+ prompt: str,
264
+ prompt_2: Optional[str] = None,
265
+ device: Optional[torch.device] = None,
266
+ num_images_per_prompt: int = 1,
267
+ do_classifier_free_guidance: bool = True,
268
+ negative_prompt: Optional[str] = None,
269
+ negative_prompt_2: Optional[str] = None,
270
+ prompt_embeds: Optional[torch.FloatTensor] = None,
271
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
272
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
273
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
274
+ lora_scale: Optional[float] = None,
275
+ clip_skip: Optional[int] = None,
276
+ ):
277
+ r"""
278
+ Encodes the prompt into text encoder hidden states.
279
+
280
+ Args:
281
+ prompt (`str` or `List[str]`, *optional*):
282
+ prompt to be encoded
283
+ prompt_2 (`str` or `List[str]`, *optional*):
284
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
285
+ used in both text-encoders
286
+ device: (`torch.device`):
287
+ torch device
288
+ num_images_per_prompt (`int`):
289
+ number of images that should be generated per prompt
290
+ do_classifier_free_guidance (`bool`):
291
+ whether to use classifier free guidance or not
292
+ negative_prompt (`str` or `List[str]`, *optional*):
293
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
294
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
295
+ less than `1`).
296
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
297
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
298
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
299
+ prompt_embeds (`torch.FloatTensor`, *optional*):
300
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
301
+ provided, text embeddings will be generated from `prompt` input argument.
302
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
303
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
304
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
305
+ argument.
306
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
307
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
308
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
309
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
310
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
311
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
312
+ input argument.
313
+ lora_scale (`float`, *optional*):
314
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
315
+ clip_skip (`int`, *optional*):
316
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
317
+ the output of the pre-final layer will be used for computing the prompt embeddings.
318
+ """
319
+ device = device or self._execution_device
320
+
321
+ # set lora scale so that monkey patched LoRA
322
+ # function of text encoder can correctly access it
323
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
324
+ self._lora_scale = lora_scale
325
+
326
+ # dynamically adjust the LoRA scale
327
+ if self.text_encoder is not None:
328
+ if not USE_PEFT_BACKEND:
329
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
330
+ else:
331
+ scale_lora_layers(self.text_encoder, lora_scale)
332
+
333
+ if self.text_encoder_2 is not None:
334
+ if not USE_PEFT_BACKEND:
335
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
336
+ else:
337
+ scale_lora_layers(self.text_encoder_2, lora_scale)
338
+
339
+ prompt = [prompt] if isinstance(prompt, str) else prompt
340
+
341
+ if prompt is not None:
342
+ batch_size = len(prompt)
343
+ else:
344
+ batch_size = prompt_embeds.shape[0]
345
+
346
+ # Define tokenizers and text encoders
347
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
348
+ text_encoders = (
349
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
350
+ )
351
+
352
+ if prompt_embeds is None:
353
+ prompt_2 = prompt_2 or prompt
354
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
355
+
356
+ # textual inversion: process multi-vector tokens if necessary
357
+ prompt_embeds_list = []
358
+ prompts = [prompt, prompt_2]
359
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
360
+ if isinstance(self, TextualInversionLoaderMixin):
361
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
362
+
363
+ text_inputs = tokenizer(
364
+ prompt,
365
+ padding="max_length",
366
+ max_length=tokenizer.model_max_length,
367
+ truncation=True,
368
+ return_tensors="pt",
369
+ )
370
+
371
+ text_input_ids = text_inputs.input_ids
372
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
373
+
374
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
375
+ text_input_ids, untruncated_ids
376
+ ):
377
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
378
+ logger.warning(
379
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
380
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
381
+ )
382
+
383
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
384
+
385
+ # We are only ALWAYS interested in the pooled output of the final text encoder
386
+ pooled_prompt_embeds = prompt_embeds[0]
387
+ if clip_skip is None:
388
+ prompt_embeds = prompt_embeds.hidden_states[-2]
389
+ else:
390
+ # "2" because SDXL always indexes from the penultimate layer.
391
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
392
+
393
+ prompt_embeds_list.append(prompt_embeds)
394
+
395
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
396
+
397
+ # get unconditional embeddings for classifier free guidance
398
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
399
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
400
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
401
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
402
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
403
+ negative_prompt = negative_prompt or ""
404
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
405
+
406
+ # normalize str to list
407
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
408
+ negative_prompt_2 = (
409
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
410
+ )
411
+
412
+ uncond_tokens: List[str]
413
+ if prompt is not None and type(prompt) is not type(negative_prompt):
414
+ raise TypeError(
415
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
416
+ f" {type(prompt)}."
417
+ )
418
+ elif batch_size != len(negative_prompt):
419
+ raise ValueError(
420
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
421
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
422
+ " the batch size of `prompt`."
423
+ )
424
+ else:
425
+ uncond_tokens = [negative_prompt, negative_prompt_2]
426
+
427
+ negative_prompt_embeds_list = []
428
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
429
+ if isinstance(self, TextualInversionLoaderMixin):
430
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
431
+
432
+ max_length = prompt_embeds.shape[1]
433
+ uncond_input = tokenizer(
434
+ negative_prompt,
435
+ padding="max_length",
436
+ max_length=max_length,
437
+ truncation=True,
438
+ return_tensors="pt",
439
+ )
440
+
441
+ negative_prompt_embeds = text_encoder(
442
+ uncond_input.input_ids.to(device),
443
+ output_hidden_states=True,
444
+ )
445
+ # We are only ALWAYS interested in the pooled output of the final text encoder
446
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
447
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
448
+
449
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
450
+
451
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
452
+
453
+ if self.text_encoder_2 is not None:
454
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
455
+ else:
456
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
457
+
458
+ bs_embed, seq_len, _ = prompt_embeds.shape
459
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
460
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
461
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
462
+
463
+ if do_classifier_free_guidance:
464
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
465
+ seq_len = negative_prompt_embeds.shape[1]
466
+
467
+ if self.text_encoder_2 is not None:
468
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
469
+ else:
470
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
471
+
472
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
473
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
474
+
475
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
476
+ bs_embed * num_images_per_prompt, -1
477
+ )
478
+ if do_classifier_free_guidance:
479
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
480
+ bs_embed * num_images_per_prompt, -1
481
+ )
482
+
483
+ if self.text_encoder is not None:
484
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
485
+ # Retrieve the original scale by scaling back the LoRA layers
486
+ unscale_lora_layers(self.text_encoder, lora_scale)
487
+
488
+ if self.text_encoder_2 is not None:
489
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
490
+ # Retrieve the original scale by scaling back the LoRA layers
491
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
492
+
493
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
494
+
495
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
496
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
497
+ dtype = next(self.image_encoder.parameters()).dtype
498
+
499
+ if not isinstance(image, torch.Tensor):
500
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
501
+
502
+ image = image.to(device=device, dtype=dtype)
503
+ if output_hidden_states:
504
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
505
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
506
+ uncond_image_enc_hidden_states = self.image_encoder(
507
+ torch.zeros_like(image), output_hidden_states=True
508
+ ).hidden_states[-2]
509
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
510
+ num_images_per_prompt, dim=0
511
+ )
512
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
513
+ else:
514
+ image_embeds = self.image_encoder(image).image_embeds
515
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
516
+ uncond_image_embeds = torch.zeros_like(image_embeds)
517
+
518
+ return image_embeds, uncond_image_embeds
519
+
520
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
521
+ def prepare_ip_adapter_image_embeds(
522
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
523
+ ):
524
+ if ip_adapter_image_embeds is None:
525
+ if not isinstance(ip_adapter_image, list):
526
+ ip_adapter_image = [ip_adapter_image]
527
+
528
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
529
+ raise ValueError(
530
+ 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."
531
+ )
532
+
533
+ image_embeds = []
534
+ for single_ip_adapter_image, image_proj_layer in zip(
535
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
536
+ ):
537
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
538
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
539
+ single_ip_adapter_image, device, 1, output_hidden_state
540
+ )
541
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
542
+ single_negative_image_embeds = torch.stack(
543
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
544
+ )
545
+
546
+ if do_classifier_free_guidance:
547
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
548
+ single_image_embeds = single_image_embeds.to(device)
549
+
550
+ image_embeds.append(single_image_embeds)
551
+ else:
552
+ repeat_dims = [1]
553
+ image_embeds = []
554
+ for single_image_embeds in ip_adapter_image_embeds:
555
+ if do_classifier_free_guidance:
556
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
557
+ single_image_embeds = single_image_embeds.repeat(
558
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
559
+ )
560
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
561
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
562
+ )
563
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
564
+ else:
565
+ single_image_embeds = single_image_embeds.repeat(
566
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
567
+ )
568
+ image_embeds.append(single_image_embeds)
569
+
570
+ return image_embeds
571
+
572
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
573
+ def prepare_extra_step_kwargs(self, generator, eta):
574
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
575
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
576
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
577
+ # and should be between [0, 1]
578
+
579
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
580
+ extra_step_kwargs = {}
581
+ if accepts_eta:
582
+ extra_step_kwargs["eta"] = eta
583
+
584
+ # check if the scheduler accepts generator
585
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
586
+ if accepts_generator:
587
+ extra_step_kwargs["generator"] = generator
588
+ return extra_step_kwargs
589
+
590
+ def check_inputs(
591
+ self,
592
+ prompt,
593
+ prompt_2,
594
+ height,
595
+ width,
596
+ callback_steps,
597
+ negative_prompt=None,
598
+ negative_prompt_2=None,
599
+ prompt_embeds=None,
600
+ negative_prompt_embeds=None,
601
+ pooled_prompt_embeds=None,
602
+ negative_pooled_prompt_embeds=None,
603
+ ip_adapter_image=None,
604
+ ip_adapter_image_embeds=None,
605
+ callback_on_step_end_tensor_inputs=None,
606
+ ):
607
+ if height % 8 != 0 or width % 8 != 0:
608
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
609
+
610
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
611
+ raise ValueError(
612
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
613
+ f" {type(callback_steps)}."
614
+ )
615
+
616
+ if callback_on_step_end_tensor_inputs is not None and not all(
617
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
618
+ ):
619
+ raise ValueError(
620
+ 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]}"
621
+ )
622
+
623
+ if prompt is not None and prompt_embeds is not None:
624
+ raise ValueError(
625
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
626
+ " only forward one of the two."
627
+ )
628
+ elif prompt_2 is not None and prompt_embeds is not None:
629
+ raise ValueError(
630
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
631
+ " only forward one of the two."
632
+ )
633
+ elif prompt is None and prompt_embeds is None:
634
+ raise ValueError(
635
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
636
+ )
637
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
638
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
639
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
640
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
641
+
642
+ if negative_prompt is not None and negative_prompt_embeds is not None:
643
+ raise ValueError(
644
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
645
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
646
+ )
647
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
648
+ raise ValueError(
649
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
650
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
651
+ )
652
+
653
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
654
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
655
+ raise ValueError(
656
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
657
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
658
+ f" {negative_prompt_embeds.shape}."
659
+ )
660
+
661
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
662
+ raise ValueError(
663
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
664
+ )
665
+
666
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
667
+ raise ValueError(
668
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
669
+ )
670
+
671
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
672
+ raise ValueError(
673
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
674
+ )
675
+
676
+ if ip_adapter_image_embeds is not None:
677
+ if not isinstance(ip_adapter_image_embeds, list):
678
+ raise ValueError(
679
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
680
+ )
681
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
682
+ raise ValueError(
683
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
684
+ )
685
+
686
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
687
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
688
+ shape = (
689
+ batch_size,
690
+ num_channels_latents,
691
+ int(height) // self.vae_scale_factor,
692
+ int(width) // self.vae_scale_factor,
693
+ )
694
+ if isinstance(generator, list) and len(generator) != batch_size:
695
+ raise ValueError(
696
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
697
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
698
+ )
699
+
700
+ if latents is None:
701
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
702
+ else:
703
+ latents = latents.to(device)
704
+
705
+ # scale the initial noise by the standard deviation required by the scheduler
706
+ latents = latents * self.scheduler.init_noise_sigma
707
+ return latents
708
+
709
+ def _get_add_time_ids(
710
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
711
+ ):
712
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
713
+
714
+ passed_add_embed_dim = (
715
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
716
+ )
717
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
718
+
719
+ if expected_add_embed_dim != passed_add_embed_dim:
720
+ raise ValueError(
721
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
722
+ )
723
+
724
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
725
+ return add_time_ids
726
+
727
+ def upcast_vae(self):
728
+ dtype = self.vae.dtype
729
+ self.vae.to(dtype=torch.float32)
730
+ use_torch_2_0_or_xformers = isinstance(
731
+ self.vae.decoder.mid_block.attentions[0].processor,
732
+ (
733
+ AttnProcessor2_0,
734
+ XFormersAttnProcessor,
735
+ LoRAXFormersAttnProcessor,
736
+ LoRAAttnProcessor2_0,
737
+ FusedAttnProcessor2_0,
738
+ ),
739
+ )
740
+ # if xformers or torch_2_0 is used attention block does not need
741
+ # to be in float32 which can save lots of memory
742
+ if use_torch_2_0_or_xformers:
743
+ self.vae.post_quant_conv.to(dtype)
744
+ self.vae.decoder.conv_in.to(dtype)
745
+ self.vae.decoder.mid_block.to(dtype)
746
+
747
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
748
+ def get_guidance_scale_embedding(
749
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
750
+ ) -> torch.FloatTensor:
751
+ """
752
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
753
+
754
+ Args:
755
+ w (`torch.Tensor`):
756
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
757
+ embedding_dim (`int`, *optional*, defaults to 512):
758
+ Dimension of the embeddings to generate.
759
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
760
+ Data type of the generated embeddings.
761
+
762
+ Returns:
763
+ `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
764
+ """
765
+ assert len(w.shape) == 1
766
+ w = w * 1000.0
767
+
768
+ half_dim = embedding_dim // 2
769
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
770
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
771
+ emb = w.to(dtype)[:, None] * emb[None, :]
772
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
773
+ if embedding_dim % 2 == 1: # zero pad
774
+ emb = torch.nn.functional.pad(emb, (0, 1))
775
+ assert emb.shape == (w.shape[0], embedding_dim)
776
+ return emb
777
+
778
+ @property
779
+ def guidance_scale(self):
780
+ return self._guidance_scale
781
+
782
+ @property
783
+ def guidance_rescale(self):
784
+ return self._guidance_rescale
785
+
786
+ @property
787
+ def clip_skip(self):
788
+ return self._clip_skip
789
+
790
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
791
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
792
+ # corresponds to doing no classifier free guidance.
793
+ @property
794
+ def do_classifier_free_guidance(self):
795
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
796
+
797
+ @property
798
+ def cross_attention_kwargs(self):
799
+ return self._cross_attention_kwargs
800
+
801
+ @property
802
+ def denoising_end(self):
803
+ return self._denoising_end
804
+
805
+ @property
806
+ def num_timesteps(self):
807
+ return self._num_timesteps
808
+
809
+ @property
810
+ def interrupt(self):
811
+ return self._interrupt
812
+
813
+ @torch.no_grad()
814
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
815
+ def __call__(
816
+ self,
817
+ prompt: Union[str, List[str]] = None,
818
+ prompt_2: Optional[Union[str, List[str]]] = None,
819
+ height: Optional[int] = None,
820
+ width: Optional[int] = None,
821
+ num_inference_steps: int = 50,
822
+ timesteps: List[int] = None,
823
+ denoising_end: Optional[float] = None,
824
+ guidance_scale: float = 5.0,
825
+ negative_prompt: Optional[Union[str, List[str]]] = None,
826
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
827
+ num_images_per_prompt: Optional[int] = 1,
828
+ eta: float = 0.0,
829
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
830
+ latents: Optional[torch.FloatTensor] = None,
831
+ prompt_embeds: Optional[torch.FloatTensor] = None,
832
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
833
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
834
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
835
+ ip_adapter_image: Optional[PipelineImageInput] = None,
836
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
837
+ output_type: Optional[str] = "pil",
838
+ return_dict: bool = True,
839
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
840
+ guidance_rescale: float = 0.0,
841
+ original_size: Optional[Tuple[int, int]] = None,
842
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
843
+ target_size: Optional[Tuple[int, int]] = None,
844
+ negative_original_size: Optional[Tuple[int, int]] = None,
845
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
846
+ negative_target_size: Optional[Tuple[int, int]] = None,
847
+ clip_skip: Optional[int] = None,
848
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
849
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
850
+ **kwargs,
851
+ ):
852
+ r"""
853
+ Function invoked when calling the pipeline for generation.
854
+
855
+ Args:
856
+ prompt (`str` or `List[str]`, *optional*):
857
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
858
+ instead.
859
+ prompt_2 (`str` or `List[str]`, *optional*):
860
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
861
+ used in both text-encoders
862
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
863
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
864
+ Anything below 512 pixels won't work well for
865
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
866
+ and checkpoints that are not specifically fine-tuned on low resolutions.
867
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
868
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
869
+ Anything below 512 pixels won't work well for
870
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
871
+ and checkpoints that are not specifically fine-tuned on low resolutions.
872
+ num_inference_steps (`int`, *optional*, defaults to 50):
873
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
874
+ expense of slower inference.
875
+ timesteps (`List[int]`, *optional*):
876
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
877
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
878
+ passed will be used. Must be in descending order.
879
+ denoising_end (`float`, *optional*):
880
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
881
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
882
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
883
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
884
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
885
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
886
+ guidance_scale (`float`, *optional*, defaults to 5.0):
887
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
888
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
889
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
890
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
891
+ usually at the expense of lower image quality.
892
+ negative_prompt (`str` or `List[str]`, *optional*):
893
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
894
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
895
+ less than `1`).
896
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
897
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
898
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
899
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
900
+ The number of images to generate per prompt.
901
+ eta (`float`, *optional*, defaults to 0.0):
902
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
903
+ [`schedulers.DDIMScheduler`], will be ignored for others.
904
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
905
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
906
+ to make generation deterministic.
907
+ latents (`torch.FloatTensor`, *optional*):
908
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
909
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
910
+ tensor will ge generated by sampling using the supplied random `generator`.
911
+ prompt_embeds (`torch.FloatTensor`, *optional*):
912
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
913
+ provided, text embeddings will be generated from `prompt` input argument.
914
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
915
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
916
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
917
+ argument.
918
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
919
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
920
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
921
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
922
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
923
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
924
+ input argument.
925
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
926
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
927
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
928
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
929
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
930
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
931
+ output_type (`str`, *optional*, defaults to `"pil"`):
932
+ The output format of the generate image. Choose between
933
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
934
+ return_dict (`bool`, *optional*, defaults to `True`):
935
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
936
+ of a plain tuple.
937
+ cross_attention_kwargs (`dict`, *optional*):
938
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
939
+ `self.processor` in
940
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
941
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
942
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
943
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
944
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
945
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
946
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
947
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
948
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
949
+ explained in section 2.2 of
950
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
951
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
952
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
953
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
954
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
955
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
956
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
957
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
958
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
959
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
960
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
961
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
962
+ micro-conditioning as explained in section 2.2 of
963
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
964
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
965
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
966
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
967
+ micro-conditioning as explained in section 2.2 of
968
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
969
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
970
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
971
+ To negatively condition the generation process based on a target image resolution. It should be as same
972
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
973
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
974
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
975
+ callback_on_step_end (`Callable`, *optional*):
976
+ A function that calls at the end of each denoising steps during the inference. The function is called
977
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
978
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
979
+ `callback_on_step_end_tensor_inputs`.
980
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
981
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
982
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
983
+ `._callback_tensor_inputs` attribute of your pipeline class.
984
+
985
+ Examples:
986
+
987
+ Returns:
988
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
989
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
990
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
991
+ """
992
+
993
+ callback = kwargs.pop("callback", None)
994
+ callback_steps = kwargs.pop("callback_steps", None)
995
+
996
+ if callback is not None:
997
+ deprecate(
998
+ "callback",
999
+ "1.0.0",
1000
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1001
+ )
1002
+ if callback_steps is not None:
1003
+ deprecate(
1004
+ "callback_steps",
1005
+ "1.0.0",
1006
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1007
+ )
1008
+
1009
+ # 0. Default height and width to unet
1010
+ height = height or self.default_sample_size * self.vae_scale_factor
1011
+ width = width or self.default_sample_size * self.vae_scale_factor
1012
+
1013
+ original_size = original_size or (height, width)
1014
+ target_size = target_size or (height, width)
1015
+
1016
+ # 1. Check inputs. Raise error if not correct
1017
+ self.check_inputs(
1018
+ prompt,
1019
+ prompt_2,
1020
+ height,
1021
+ width,
1022
+ callback_steps,
1023
+ negative_prompt,
1024
+ negative_prompt_2,
1025
+ prompt_embeds,
1026
+ negative_prompt_embeds,
1027
+ pooled_prompt_embeds,
1028
+ negative_pooled_prompt_embeds,
1029
+ ip_adapter_image,
1030
+ ip_adapter_image_embeds,
1031
+ callback_on_step_end_tensor_inputs,
1032
+ )
1033
+
1034
+ self._guidance_scale = guidance_scale
1035
+ self._guidance_rescale = guidance_rescale
1036
+ self._clip_skip = clip_skip
1037
+ self._cross_attention_kwargs = cross_attention_kwargs
1038
+ self._denoising_end = denoising_end
1039
+ self._interrupt = False
1040
+
1041
+ # 2. Define call parameters
1042
+ if prompt is not None and isinstance(prompt, str):
1043
+ batch_size = 1
1044
+ elif prompt is not None and isinstance(prompt, list):
1045
+ batch_size = len(prompt)
1046
+ else:
1047
+ batch_size = prompt_embeds.shape[0]
1048
+
1049
+ device = self._execution_device
1050
+
1051
+ # 3. Encode input prompt
1052
+ lora_scale = (
1053
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1054
+ )
1055
+
1056
+ (
1057
+ prompt_embeds,
1058
+ negative_prompt_embeds,
1059
+ pooled_prompt_embeds,
1060
+ negative_pooled_prompt_embeds,
1061
+ ) = self.encode_prompt(
1062
+ prompt=prompt,
1063
+ prompt_2=prompt_2,
1064
+ device=device,
1065
+ num_images_per_prompt=num_images_per_prompt,
1066
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1067
+ negative_prompt=negative_prompt,
1068
+ negative_prompt_2=negative_prompt_2,
1069
+ prompt_embeds=prompt_embeds,
1070
+ negative_prompt_embeds=negative_prompt_embeds,
1071
+ pooled_prompt_embeds=pooled_prompt_embeds,
1072
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1073
+ lora_scale=lora_scale,
1074
+ clip_skip=self.clip_skip,
1075
+ )
1076
+
1077
+ # 4. Prepare timesteps
1078
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1079
+
1080
+ # 5. Prepare latent variables
1081
+ num_channels_latents = self.unet.config.in_channels
1082
+ latents = self.prepare_latents(
1083
+ batch_size * num_images_per_prompt,
1084
+ num_channels_latents,
1085
+ height,
1086
+ width,
1087
+ prompt_embeds.dtype,
1088
+ device,
1089
+ generator,
1090
+ latents,
1091
+ )
1092
+
1093
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1094
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1095
+
1096
+ # 7. Prepare added time ids & embeddings
1097
+ add_text_embeds = pooled_prompt_embeds
1098
+ if self.text_encoder_2 is None:
1099
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1100
+ else:
1101
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1102
+
1103
+ add_time_ids = self._get_add_time_ids(
1104
+ original_size,
1105
+ crops_coords_top_left,
1106
+ target_size,
1107
+ dtype=prompt_embeds.dtype,
1108
+ text_encoder_projection_dim=text_encoder_projection_dim,
1109
+ )
1110
+ if negative_original_size is not None and negative_target_size is not None:
1111
+ negative_add_time_ids = self._get_add_time_ids(
1112
+ negative_original_size,
1113
+ negative_crops_coords_top_left,
1114
+ negative_target_size,
1115
+ dtype=prompt_embeds.dtype,
1116
+ text_encoder_projection_dim=text_encoder_projection_dim,
1117
+ )
1118
+ else:
1119
+ negative_add_time_ids = add_time_ids
1120
+
1121
+ if self.do_classifier_free_guidance:
1122
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1123
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1124
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1125
+
1126
+ prompt_embeds = prompt_embeds.to(device)
1127
+ add_text_embeds = add_text_embeds.to(device)
1128
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1129
+
1130
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1131
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1132
+ ip_adapter_image,
1133
+ ip_adapter_image_embeds,
1134
+ device,
1135
+ batch_size * num_images_per_prompt,
1136
+ self.do_classifier_free_guidance,
1137
+ )
1138
+
1139
+ # 8. Denoising loop
1140
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1141
+
1142
+ # 8.1 Apply denoising_end
1143
+ if (
1144
+ self.denoising_end is not None
1145
+ and isinstance(self.denoising_end, float)
1146
+ and self.denoising_end > 0
1147
+ and self.denoising_end < 1
1148
+ ):
1149
+ discrete_timestep_cutoff = int(
1150
+ round(
1151
+ self.scheduler.config.num_train_timesteps
1152
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1153
+ )
1154
+ )
1155
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1156
+ timesteps = timesteps[:num_inference_steps]
1157
+
1158
+ # 9. Optionally get Guidance Scale Embedding
1159
+ timestep_cond = None
1160
+ if self.unet.config.time_cond_proj_dim is not None:
1161
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1162
+ timestep_cond = self.get_guidance_scale_embedding(
1163
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1164
+ ).to(device=device, dtype=latents.dtype)
1165
+
1166
+ self._num_timesteps = len(timesteps)
1167
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1168
+ for i, t in enumerate(timesteps):
1169
+ if self.interrupt:
1170
+ continue
1171
+
1172
+ # expand the latents if we are doing classifier free guidance
1173
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1174
+
1175
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1176
+
1177
+ # predict the noise residual
1178
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1179
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1180
+ added_cond_kwargs["image_embeds"] = image_embeds
1181
+
1182
+ noise_pred = self.unet(
1183
+ latent_model_input,
1184
+ t,
1185
+ encoder_hidden_states=prompt_embeds, # [B, 77, 2048]
1186
+ timestep_cond=timestep_cond, # None
1187
+ cross_attention_kwargs=self.cross_attention_kwargs, # None
1188
+ added_cond_kwargs=added_cond_kwargs, # {[B, 1280], [B, 6]}
1189
+ return_dict=False,
1190
+ )[0]
1191
+
1192
+ # perform guidance
1193
+ if self.do_classifier_free_guidance:
1194
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1195
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1196
+
1197
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1198
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1199
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1200
+
1201
+ # compute the previous noisy sample x_t -> x_t-1
1202
+ latents_dtype = latents.dtype
1203
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1204
+ if latents.dtype != latents_dtype:
1205
+ if torch.backends.mps.is_available():
1206
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1207
+ latents = latents.to(latents_dtype)
1208
+
1209
+ if callback_on_step_end is not None:
1210
+ callback_kwargs = {}
1211
+ for k in callback_on_step_end_tensor_inputs:
1212
+ callback_kwargs[k] = locals()[k]
1213
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1214
+
1215
+ latents = callback_outputs.pop("latents", latents)
1216
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1217
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1218
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1219
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1220
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1221
+ )
1222
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1223
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1224
+
1225
+ # call the callback, if provided
1226
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1227
+ progress_bar.update()
1228
+ if callback is not None and i % callback_steps == 0:
1229
+ step_idx = i // getattr(self.scheduler, "order", 1)
1230
+ callback(step_idx, t, latents)
1231
+
1232
+ if XLA_AVAILABLE:
1233
+ xm.mark_step()
1234
+
1235
+ if not output_type == "latent":
1236
+ # make sure the VAE is in float32 mode, as it overflows in float16
1237
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1238
+
1239
+ if needs_upcasting:
1240
+ self.upcast_vae()
1241
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1242
+ elif latents.dtype != self.vae.dtype:
1243
+ if torch.backends.mps.is_available():
1244
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1245
+ self.vae = self.vae.to(latents.dtype)
1246
+
1247
+ # unscale/denormalize the latents
1248
+ # denormalize with the mean and std if available and not None
1249
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1250
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1251
+ if has_latents_mean and has_latents_std:
1252
+ latents_mean = (
1253
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1254
+ )
1255
+ latents_std = (
1256
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1257
+ )
1258
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1259
+ else:
1260
+ latents = latents / self.vae.config.scaling_factor
1261
+
1262
+ image = self.vae.decode(latents, return_dict=False)[0]
1263
+
1264
+ # cast back to fp16 if needed
1265
+ if needs_upcasting:
1266
+ self.vae.to(dtype=torch.float16)
1267
+ else:
1268
+ image = latents
1269
+
1270
+ if not output_type == "latent":
1271
+ # apply watermark if available
1272
+ if self.watermark is not None:
1273
+ image = self.watermark.apply_watermark(image)
1274
+
1275
+ image = self.image_processor.postprocess(image, output_type=output_type)
1276
+
1277
+ # Offload all models
1278
+ self.maybe_free_model_hooks()
1279
+
1280
+ if not return_dict:
1281
+ return (image,)
1282
+
1283
+ return StableDiffusionXLPipelineOutput(images=image)