skytnt commited on
Commit
099cac4
1 Parent(s): 1ba2c12

Create new file

Browse files
Files changed (1) hide show
  1. pipeline.py +1137 -0
pipeline.py ADDED
@@ -0,0 +1,1137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+ import PIL
5
+ import numpy as np
6
+ import torch
7
+
8
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers.configuration_utils import FrozenDict
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.pipeline_utils import DiffusionPipeline
13
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
14
+ from diffusers.utils import deprecate, logging
15
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
16
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
17
+
18
+
19
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
20
+
21
+ re_attention = re.compile(r"""
22
+ \\\(|
23
+ \\\)|
24
+ \\\[|
25
+ \\]|
26
+ \\\\|
27
+ \\|
28
+ \(|
29
+ \[|
30
+ :([+-]?[.\d]+)\)|
31
+ \)|
32
+ ]|
33
+ [^\\()\[\]:]+|
34
+ :
35
+ """, re.X)
36
+
37
+
38
+ def parse_prompt_attention(text):
39
+ """
40
+ Parses a string with attention tokens and returns a list of pairs: text and its assoicated weight.
41
+ Accepted tokens are:
42
+ (abc) - increases attention to abc by a multiplier of 1.1
43
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
44
+ [abc] - decreases attention to abc by a multiplier of 1.1
45
+ \( - literal character '('
46
+ \[ - literal character '['
47
+ \) - literal character ')'
48
+ \] - literal character ']'
49
+ \\ - literal character '\'
50
+ anything else - just text
51
+ >>> parse_prompt_attention('normal text')
52
+ [['normal text', 1.0]]
53
+ >>> parse_prompt_attention('an (important) word')
54
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
55
+ >>> parse_prompt_attention('(unbalanced')
56
+ [['unbalanced', 1.1]]
57
+ >>> parse_prompt_attention('\(literal\]')
58
+ [['(literal]', 1.0]]
59
+ >>> parse_prompt_attention('(unnecessary)(parens)')
60
+ [['unnecessaryparens', 1.1]]
61
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
62
+ [['a ', 1.0],
63
+ ['house', 1.5730000000000004],
64
+ [' ', 1.1],
65
+ ['on', 1.0],
66
+ [' a ', 1.1],
67
+ ['hill', 0.55],
68
+ [', sun, ', 1.1],
69
+ ['sky', 1.4641000000000006],
70
+ ['.', 1.1]]
71
+ """
72
+
73
+ res = []
74
+ round_brackets = []
75
+ square_brackets = []
76
+
77
+ round_bracket_multiplier = 1.1
78
+ square_bracket_multiplier = 1 / 1.1
79
+
80
+ def multiply_range(start_position, multiplier):
81
+ for p in range(start_position, len(res)):
82
+ res[p][1] *= multiplier
83
+
84
+ for m in re_attention.finditer(text):
85
+ text = m.group(0)
86
+ weight = m.group(1)
87
+
88
+ if text.startswith('\\'):
89
+ res.append([text[1:], 1.0])
90
+ elif text == '(':
91
+ round_brackets.append(len(res))
92
+ elif text == '[':
93
+ square_brackets.append(len(res))
94
+ elif weight is not None and len(round_brackets) > 0:
95
+ multiply_range(round_brackets.pop(), float(weight))
96
+ elif text == ')' and len(round_brackets) > 0:
97
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
98
+ elif text == ']' and len(square_brackets) > 0:
99
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
100
+ else:
101
+ res.append([text, 1.0])
102
+
103
+ for pos in round_brackets:
104
+ multiply_range(pos, round_bracket_multiplier)
105
+
106
+ for pos in square_brackets:
107
+ multiply_range(pos, square_bracket_multiplier)
108
+
109
+ if len(res) == 0:
110
+ res = [["", 1.0]]
111
+
112
+ # merge runs of identical weights
113
+ i = 0
114
+ while i + 1 < len(res):
115
+ if res[i][1] == res[i + 1][1]:
116
+ res[i][0] += res[i + 1][0]
117
+ res.pop(i + 1)
118
+ else:
119
+ i += 1
120
+
121
+ return res
122
+
123
+
124
+ def get_prompts_with_weights(
125
+ pipe: DiffusionPipeline,
126
+ prompt: List[str],
127
+ max_length: int
128
+ ):
129
+ r"""
130
+ Tokenize a list of prompts and return its tokens with weights of each token.
131
+
132
+ No padding, starting or ending token is included.
133
+ """
134
+ tokens = []
135
+ weights = []
136
+ for text in prompt:
137
+ texts_and_weights = parse_prompt_attention(text)
138
+ text_token = []
139
+ text_weight = []
140
+ for word, weight in texts_and_weights:
141
+ # tokenize and discard the starting and the ending token
142
+ token = pipe.tokenizer(word).input_ids[1:-1]
143
+ text_token += token
144
+
145
+ # copy the weight by length of token
146
+ text_weight += [weight] * len(token)
147
+
148
+ # stop if the text is too long (longer than truncation limit)
149
+ if len(text_token) > max_length:
150
+ break
151
+
152
+ # truncate
153
+ if len(text_token) > max_length:
154
+ text_token = text_token[:max_length]
155
+ text_weight = text_weight[:max_length]
156
+
157
+ tokens.append(text_token)
158
+ weights.append(text_weight)
159
+ return tokens, weights
160
+
161
+
162
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos,
163
+ no_boseos_middle=True,
164
+ chunk_length=77):
165
+ r"""
166
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
167
+ """
168
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
169
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
170
+ for i in range(len(tokens)):
171
+ tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i]))
172
+ if no_boseos_middle:
173
+ weights[i] = [1.] + weights[i] + [1.] * (max_length - 1 - len(weights[i]))
174
+ else:
175
+ w = []
176
+ if len(weights[i]) == 0:
177
+ w = [1.] * weights_length
178
+ else:
179
+ for j in range((len(weights[i]) - 1) // chunk_length + 1):
180
+ w.append(1.) # weight for starting token in this chunk
181
+ w += weights[i][j * chunk_length: min(len(weights[i]), (j + 1) * chunk_length)]
182
+ w.append(1.) # weight for ending token in this chunk
183
+ w += [1.] * (weights_length - len(w))
184
+ weights[i] = w[:]
185
+
186
+ return tokens, weights
187
+
188
+
189
+ def get_unweighted_text_embeddings(
190
+ pipe: DiffusionPipeline,
191
+ text_input: torch.Tensor,
192
+ chunk_length: int,
193
+ no_boseos_middle: Optional[bool] = True
194
+ ):
195
+ """
196
+ When the length of tokens is a multiple of the capacity of the text encoder,
197
+ it should be split into chunks and sent to the text encoder individually.
198
+ """
199
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
200
+ if max_embeddings_multiples > 1:
201
+ text_embeddings = []
202
+ for i in range(max_embeddings_multiples):
203
+ # extract the i-th chunk
204
+ text_input_chunk = text_input[:, i * (chunk_length - 2):(i + 1) * (chunk_length - 2) + 2].clone()
205
+
206
+ # cover the head and the tail by the starting and the ending tokens
207
+ text_input_chunk[:, 0] = text_input[0, 0]
208
+ text_input_chunk[:, -1] = text_input[0, -1]
209
+ text_embedding = pipe.text_encoder(text_input_chunk)[0]
210
+
211
+ if no_boseos_middle:
212
+ if i == 0:
213
+ # discard the ending token
214
+ text_embedding = text_embedding[:, :-1]
215
+ elif i == max_embeddings_multiples - 1:
216
+ # discard the starting token
217
+ text_embedding = text_embedding[:, 1:]
218
+ else:
219
+ # discard both starting and ending tokens
220
+ text_embedding = text_embedding[:, 1:-1]
221
+
222
+ text_embeddings.append(text_embedding)
223
+ text_embeddings = torch.concat(text_embeddings, axis=1)
224
+ else:
225
+ text_embeddings = pipe.text_encoder(text_input)[0]
226
+ return text_embeddings
227
+
228
+
229
+ def get_weighted_text_embeddings(
230
+ pipe: DiffusionPipeline,
231
+ prompt: Union[str, List[str]],
232
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
233
+ max_embeddings_multiples: Optional[int] = 1,
234
+ no_boseos_middle: Optional[bool] = False,
235
+ skip_parsing: Optional[bool] = False,
236
+ skip_weighting: Optional[bool] = False,
237
+ **kwargs
238
+ ):
239
+ r"""
240
+ Prompts can be assigned with local weights using brackets. For example,
241
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
242
+ and the embedding tokens corresponding to the words get multipled by a constant, 1.1.
243
+
244
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the origional mean.
245
+
246
+ Args:
247
+ pipe (`DiffusionPipeline`):
248
+ Pipe to provide access to the tokenizer and the text encoder.
249
+ prompt (`str` or `List[str]`):
250
+ The prompt or prompts to guide the image generation.
251
+ uncond_prompt (`str` or `List[str]`):
252
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
253
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
254
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
255
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
256
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
257
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
258
+ ending token in each of the chunk in the middle.
259
+ skip_parsing (`bool`, *optional*, defaults to `False`):
260
+ Skip the parsing of brackets.
261
+ skip_weighting (`bool`, *optional*, defaults to `False`):
262
+ Skip the weighting. When the parsing is skipped, it is forced True.
263
+ """
264
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
265
+ if isinstance(prompt, str):
266
+ prompt = [prompt]
267
+
268
+ if not skip_parsing:
269
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
270
+ if uncond_prompt is not None:
271
+ if isinstance(uncond_prompt, str):
272
+ uncond_prompt = [uncond_prompt]
273
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
274
+ else:
275
+ prompt_tokens = [token[1:-1] for token in
276
+ pipe.tokenizer(prompt, max_length=max_length, truncation=True).input_ids]
277
+ prompt_weights = [[1.] * len(token) for token in prompt_tokens]
278
+ if uncond_prompt is not None:
279
+ if isinstance(uncond_prompt, str):
280
+ uncond_prompt = [uncond_prompt]
281
+ uncond_tokens = [token[1:-1] for token in
282
+ pipe.tokenizer(uncond_prompt, max_length=max_length, truncation=True).input_ids]
283
+ uncond_weights = [[1.] * len(token) for token in uncond_tokens]
284
+
285
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
286
+ max_length = max([len(token) for token in prompt_tokens])
287
+ if uncond_prompt is not None:
288
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
289
+
290
+ max_embeddings_multiples = min(max_embeddings_multiples,
291
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1)
292
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
293
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
294
+
295
+ # pad the length of tokens and weights
296
+ bos = pipe.tokenizer.bos_token_id
297
+ eos = pipe.tokenizer.eos_token_id
298
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(prompt_tokens, prompt_weights, max_length, bos, eos,
299
+ no_boseos_middle=no_boseos_middle,
300
+ chunk_length=pipe.tokenizer.model_max_length)
301
+ prompt_tokens = torch.tensor(prompt_tokens, dtype=torch.long, device=pipe.device)
302
+ if uncond_prompt is not None:
303
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(uncond_tokens, uncond_weights, max_length, bos, eos,
304
+ no_boseos_middle=no_boseos_middle,
305
+ chunk_length=pipe.tokenizer.model_max_length)
306
+ uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=pipe.device)
307
+
308
+ # get the embeddings
309
+ text_embeddings = get_unweighted_text_embeddings(pipe, prompt_tokens, pipe.tokenizer.model_max_length,
310
+ no_boseos_middle=no_boseos_middle)
311
+ prompt_weights = torch.tensor(prompt_weights, dtype=text_embeddings.dtype, device=pipe.device)
312
+ if uncond_prompt is not None:
313
+ uncond_embeddings = get_unweighted_text_embeddings(pipe, uncond_tokens, pipe.tokenizer.model_max_length,
314
+ no_boseos_middle=no_boseos_middle)
315
+ uncond_weights = torch.tensor(uncond_weights, dtype=uncond_embeddings.dtype, device=pipe.device)
316
+
317
+ # assign weights to the prompts and normalize in the sense of mean
318
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
319
+ if (not skip_parsing) and (not skip_weighting):
320
+ previous_mean = text_embeddings.mean(axis=[-2, -1])
321
+ text_embeddings *= prompt_weights.unsqueeze(-1)
322
+ text_embeddings *= previous_mean / text_embeddings.mean(axis=[-2, -1])
323
+ if uncond_prompt is not None:
324
+ previous_mean = uncond_embeddings.mean(axis=[-2, -1])
325
+ uncond_embeddings *= uncond_weights.unsqueeze(-1)
326
+ uncond_embeddings *= previous_mean / uncond_embeddings.mean(axis=[-2, -1])
327
+
328
+ # For classifier free guidance, we need to do two forward passes.
329
+ # Here we concatenate the unconditional and text embeddings into a single batch
330
+ # to avoid doing two forward passes
331
+ if uncond_prompt is not None:
332
+ text_embeddings = torch.concat([uncond_embeddings, text_embeddings])
333
+
334
+ return text_embeddings
335
+
336
+
337
+ def preprocess_image(image):
338
+ w, h = image.size
339
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
340
+ image = image.resize((w, h), resample=PIL.Image.LANCZOS)
341
+ image = np.array(image).astype(np.float32) / 255.0
342
+ image = image[None].transpose(0, 3, 1, 2)
343
+ image = torch.from_numpy(image)
344
+ return 2.0 * image - 1.0
345
+
346
+
347
+ def preprocess_mask(mask):
348
+ mask = mask.convert("L")
349
+ w, h = mask.size
350
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
351
+ mask = mask.resize((w // 8, h // 8), resample=PIL.Image.NEAREST)
352
+ mask = np.array(mask).astype(np.float32) / 255.0
353
+ mask = np.tile(mask, (4, 1, 1))
354
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
355
+ mask = 1 - mask # repaint white, keep black
356
+ mask = torch.from_numpy(mask)
357
+ return mask
358
+
359
+
360
+ class StableDiffusionLongPromptPipeline(DiffusionPipeline):
361
+ r"""
362
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
363
+ weighting in prompt.
364
+
365
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
366
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
367
+
368
+ Args:
369
+ vae ([`AutoencoderKL`]):
370
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
371
+ text_encoder ([`CLIPTextModel`]):
372
+ Frozen text-encoder. Stable Diffusion uses the text portion of
373
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
374
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
375
+ tokenizer (`CLIPTokenizer`):
376
+ Tokenizer of class
377
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
378
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
379
+ scheduler ([`SchedulerMixin`]):
380
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
381
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
382
+ safety_checker ([`StableDiffusionSafetyChecker`]):
383
+ Classification module that estimates whether generated images could be considered offensive or harmful.
384
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
385
+ feature_extractor ([`CLIPFeatureExtractor`]):
386
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
387
+ """
388
+
389
+ def __init__(
390
+ self,
391
+ vae: AutoencoderKL,
392
+ text_encoder: CLIPTextModel,
393
+ tokenizer: CLIPTokenizer,
394
+ unet: UNet2DConditionModel,
395
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
396
+ safety_checker: StableDiffusionSafetyChecker,
397
+ feature_extractor: CLIPFeatureExtractor,
398
+ ):
399
+ super().__init__()
400
+
401
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
402
+ deprecation_message = (
403
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
404
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
405
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
406
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
407
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
408
+ " file"
409
+ )
410
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
411
+ new_config = dict(scheduler.config)
412
+ new_config["steps_offset"] = 1
413
+ scheduler._internal_dict = FrozenDict(new_config)
414
+
415
+ if safety_checker is None:
416
+ logger.warn(
417
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
418
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
419
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
420
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
421
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
422
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
423
+ )
424
+
425
+ self.register_modules(
426
+ vae=vae,
427
+ text_encoder=text_encoder,
428
+ tokenizer=tokenizer,
429
+ unet=unet,
430
+ scheduler=scheduler,
431
+ safety_checker=safety_checker,
432
+ feature_extractor=feature_extractor,
433
+ )
434
+
435
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
436
+ r"""
437
+ Enable sliced attention computation.
438
+
439
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
440
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
441
+
442
+ Args:
443
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
444
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
445
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
446
+ `attention_head_dim` must be a multiple of `slice_size`.
447
+ """
448
+ if slice_size == "auto":
449
+ # half the attention head size is usually a good trade-off between
450
+ # speed and memory
451
+ slice_size = self.unet.config.attention_head_dim // 2
452
+ self.unet.set_attention_slice(slice_size)
453
+
454
+ def disable_attention_slicing(self):
455
+ r"""
456
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
457
+ back to computing attention in one step.
458
+ """
459
+ # set slice_size = `None` to disable `attention slicing`
460
+ self.enable_attention_slicing(None)
461
+
462
+ @torch.no_grad()
463
+ def text2img(
464
+ self,
465
+ prompt: Union[str, List[str]],
466
+ height: int = 512,
467
+ width: int = 512,
468
+ num_inference_steps: int = 50,
469
+ guidance_scale: float = 7.5,
470
+ negative_prompt: Optional[Union[str, List[str]]] = None,
471
+ num_images_per_prompt: Optional[int] = 1,
472
+ eta: float = 0.0,
473
+ generator: Optional[torch.Generator] = None,
474
+ latents: Optional[torch.FloatTensor] = None,
475
+ max_embeddings_multiples: Optional[int] = 1,
476
+ output_type: Optional[str] = "pil",
477
+ return_dict: bool = True,
478
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
479
+ callback_steps: Optional[int] = 1,
480
+ **kwargs,
481
+ ):
482
+ r"""
483
+ Function invoked when calling the pipeline for generation.
484
+
485
+ Args:
486
+ prompt (`str` or `List[str]`):
487
+ The prompt or prompts to guide the image generation.
488
+ height (`int`, *optional*, defaults to 512):
489
+ The height in pixels of the generated image.
490
+ width (`int`, *optional*, defaults to 512):
491
+ The width in pixels of the generated image.
492
+ num_inference_steps (`int`, *optional*, defaults to 50):
493
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
494
+ expense of slower inference.
495
+ guidance_scale (`float`, *optional*, defaults to 7.5):
496
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
497
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
498
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
499
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
500
+ usually at the expense of lower image quality.
501
+ negative_prompt (`str` or `List[str]`, *optional*):
502
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
503
+ if `guidance_scale` is less than `1`).
504
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
505
+ The number of images to generate per prompt.
506
+ eta (`float`, *optional*, defaults to 0.0):
507
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
508
+ [`schedulers.DDIMScheduler`], will be ignored for others.
509
+ generator (`torch.Generator`, *optional*):
510
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
511
+ deterministic.
512
+ latents (`torch.FloatTensor`, *optional*):
513
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
514
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
515
+ tensor will ge generated by sampling using the supplied random `generator`.
516
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
517
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
518
+ output_type (`str`, *optional*, defaults to `"pil"`):
519
+ The output format of the generate image. Choose between
520
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
521
+ return_dict (`bool`, *optional*, defaults to `True`):
522
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
523
+ plain tuple.
524
+ callback (`Callable`, *optional*):
525
+ A function that will be called every `callback_steps` steps during inference. The function will be
526
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
527
+ callback_steps (`int`, *optional*, defaults to 1):
528
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
529
+ called at every step.
530
+
531
+ Returns:
532
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
533
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
534
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
535
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
536
+ (nsfw) content, according to the `safety_checker`.
537
+ """
538
+
539
+ if isinstance(prompt, str):
540
+ batch_size = 1
541
+ elif isinstance(prompt, list):
542
+ batch_size = len(prompt)
543
+ else:
544
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
545
+
546
+ if height % 8 != 0 or width % 8 != 0:
547
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
548
+
549
+ if (callback_steps is None) or (
550
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
551
+ ):
552
+ raise ValueError(
553
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
554
+ f" {type(callback_steps)}."
555
+ )
556
+
557
+ # get prompt text embeddings
558
+
559
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
560
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
561
+ # corresponds to doing no classifier free guidance.
562
+ do_classifier_free_guidance = guidance_scale > 1.0
563
+ # get unconditional embeddings for classifier free guidance
564
+ uncond_tokens = [""]
565
+ if do_classifier_free_guidance:
566
+ if type(prompt) is not type(negative_prompt):
567
+ raise TypeError(
568
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
569
+ f" {type(prompt)}."
570
+ )
571
+ elif isinstance(negative_prompt, str):
572
+ uncond_tokens = [negative_prompt]
573
+ elif batch_size != len(negative_prompt):
574
+ raise ValueError(
575
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
576
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
577
+ " the batch size of `prompt`."
578
+ )
579
+ else:
580
+ uncond_tokens = negative_prompt
581
+
582
+ text_embeddings = get_weighted_text_embeddings(
583
+ pipe=self,
584
+ prompt=prompt,
585
+ uncond_prompt=uncond_tokens if do_classifier_free_guidance else None,
586
+ max_embeddings_multiples=max_embeddings_multiples,
587
+ **kwargs
588
+ )
589
+
590
+ # get the initial random noise unless the user supplied it
591
+
592
+ # Unlike in other pipelines, latents need to be generated in the target device
593
+ # for 1-to-1 results reproducibility with the CompVis implementation.
594
+ # However this currently doesn't work in `mps`.
595
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
596
+ latents_dtype = text_embeddings.dtype
597
+ if latents is None:
598
+ if self.device.type == "mps":
599
+ # randn does not exist on mps
600
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
601
+ self.device
602
+ )
603
+ else:
604
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
605
+ else:
606
+ if latents.shape != latents_shape:
607
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
608
+ latents = latents.to(self.device)
609
+
610
+ # set timesteps
611
+ self.scheduler.set_timesteps(num_inference_steps)
612
+
613
+ # Some schedulers like PNDM have timesteps as arrays
614
+ # It's more optimized to move all timesteps to correct device beforehand
615
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
616
+
617
+ # scale the initial noise by the standard deviation required by the scheduler
618
+ latents = latents * self.scheduler.init_noise_sigma
619
+
620
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
621
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
622
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
623
+ # and should be between [0, 1]
624
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
625
+ extra_step_kwargs = {}
626
+ if accepts_eta:
627
+ extra_step_kwargs["eta"] = eta
628
+
629
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
630
+ # expand the latents if we are doing classifier free guidance
631
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
632
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
633
+
634
+ # predict the noise residual
635
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
636
+
637
+ # perform guidance
638
+ if do_classifier_free_guidance:
639
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
640
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
641
+
642
+ # compute the previous noisy sample x_t -> x_t-1
643
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
644
+
645
+ # call the callback, if provided
646
+ if callback is not None and i % callback_steps == 0:
647
+ callback(i, t, latents)
648
+
649
+ latents = 1 / 0.18215 * latents
650
+ image = self.vae.decode(latents).sample
651
+
652
+ image = (image / 2 + 0.5).clamp(0, 1)
653
+
654
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
655
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
656
+
657
+ if self.safety_checker is not None:
658
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
659
+ self.device
660
+ )
661
+ image, has_nsfw_concept = self.safety_checker(
662
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
663
+ )
664
+ else:
665
+ has_nsfw_concept = None
666
+
667
+ if output_type == "pil":
668
+ image = self.numpy_to_pil(image)
669
+
670
+ if not return_dict:
671
+ return (image, has_nsfw_concept)
672
+
673
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
674
+
675
+ @torch.no_grad()
676
+ def img2img(
677
+ self,
678
+ prompt: Union[str, List[str]],
679
+ init_image: Union[torch.FloatTensor, PIL.Image.Image],
680
+ strength: float = 0.8,
681
+ num_inference_steps: Optional[int] = 50,
682
+ guidance_scale: Optional[float] = 7.5,
683
+ negative_prompt: Optional[Union[str, List[str]]] = None,
684
+ num_images_per_prompt: Optional[int] = 1,
685
+ eta: Optional[float] = 0.0,
686
+ generator: Optional[torch.Generator] = None,
687
+ max_embeddings_multiples: Optional[int] = 1,
688
+ output_type: Optional[str] = "pil",
689
+ return_dict: bool = True,
690
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
691
+ callback_steps: Optional[int] = 1,
692
+ **kwargs,
693
+ ):
694
+ r"""
695
+ Function invoked when calling the pipeline for generation.
696
+
697
+ Args:
698
+ prompt (`str` or `List[str]`):
699
+ The prompt or prompts to guide the image generation.
700
+ init_image (`torch.FloatTensor` or `PIL.Image.Image`):
701
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
702
+ process.
703
+ strength (`float`, *optional*, defaults to 0.8):
704
+ Conceptually, indicates how much to transform the reference `init_image`. Must be between 0 and 1.
705
+ `init_image` will be used as a starting point, adding more noise to it the larger the `strength`. The
706
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
707
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
708
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `init_image`.
709
+ num_inference_steps (`int`, *optional*, defaults to 50):
710
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
711
+ expense of slower inference. This parameter will be modulated by `strength`.
712
+ guidance_scale (`float`, *optional*, defaults to 7.5):
713
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
714
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
715
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
716
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
717
+ usually at the expense of lower image quality.
718
+ negative_prompt (`str` or `List[str]`, *optional*):
719
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
720
+ if `guidance_scale` is less than `1`).
721
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
722
+ The number of images to generate per prompt.
723
+ eta (`float`, *optional*, defaults to 0.0):
724
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
725
+ [`schedulers.DDIMScheduler`], will be ignored for others.
726
+ generator (`torch.Generator`, *optional*):
727
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
728
+ deterministic.
729
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
730
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
731
+ output_type (`str`, *optional*, defaults to `"pil"`):
732
+ The output format of the generate image. Choose between
733
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
734
+ return_dict (`bool`, *optional*, defaults to `True`):
735
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
736
+ plain tuple.
737
+ callback (`Callable`, *optional*):
738
+ A function that will be called every `callback_steps` steps during inference. The function will be
739
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
740
+ callback_steps (`int`, *optional*, defaults to 1):
741
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
742
+ called at every step.
743
+
744
+ Returns:
745
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
746
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
747
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
748
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
749
+ (nsfw) content, according to the `safety_checker`.
750
+ """
751
+ if isinstance(prompt, str):
752
+ batch_size = 1
753
+ elif isinstance(prompt, list):
754
+ batch_size = len(prompt)
755
+ else:
756
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
757
+
758
+ if strength < 0 or strength > 1:
759
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
760
+
761
+ if (callback_steps is None) or (
762
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
763
+ ):
764
+ raise ValueError(
765
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
766
+ f" {type(callback_steps)}."
767
+ )
768
+
769
+ # set timesteps
770
+ self.scheduler.set_timesteps(num_inference_steps)
771
+
772
+ if isinstance(init_image, PIL.Image.Image):
773
+ init_image = preprocess_image(init_image)
774
+
775
+ # get prompt text embeddings
776
+
777
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
778
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
779
+ # corresponds to doing no classifier free guidance.
780
+ do_classifier_free_guidance = guidance_scale > 1.0
781
+ # get unconditional embeddings for classifier free guidance
782
+ uncond_tokens = [""]
783
+ if do_classifier_free_guidance:
784
+ if type(prompt) is not type(negative_prompt):
785
+ raise TypeError(
786
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
787
+ f" {type(prompt)}."
788
+ )
789
+ elif isinstance(negative_prompt, str):
790
+ uncond_tokens = [negative_prompt]
791
+ elif batch_size != len(negative_prompt):
792
+ raise ValueError("The length of `negative_prompt` should be equal to batch_size.")
793
+ else:
794
+ uncond_tokens = negative_prompt
795
+
796
+ text_embeddings = get_weighted_text_embeddings(
797
+ pipe=self,
798
+ prompt=prompt,
799
+ uncond_prompt=uncond_tokens if do_classifier_free_guidance else None,
800
+ max_embeddings_multiples=max_embeddings_multiples,
801
+ **kwargs
802
+ )
803
+
804
+ # encode the init image into latents and scale the latents
805
+ latents_dtype = text_embeddings.dtype
806
+ init_image = init_image.to(device=self.device, dtype=latents_dtype)
807
+ init_latent_dist = self.vae.encode(init_image).latent_dist
808
+ init_latents = init_latent_dist.sample(generator=generator)
809
+ init_latents = 0.18215 * init_latents
810
+
811
+ if isinstance(prompt, str):
812
+ prompt = [prompt]
813
+ if len(prompt) > init_latents.shape[0] and len(prompt) % init_latents.shape[0] == 0:
814
+ # expand init_latents for batch_size
815
+ deprecation_message = (
816
+ f"You have passed {len(prompt)} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
817
+ " images (`init_image`). Initial images are now duplicating to match the number of text prompts. Note"
818
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
819
+ " your script to pass as many init images as text prompts to suppress this warning."
820
+ )
821
+ deprecate("len(prompt) != len(init_image)", "1.0.0", deprecation_message, standard_warn=False)
822
+ additional_image_per_prompt = len(prompt) // init_latents.shape[0]
823
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt * num_images_per_prompt, dim=0)
824
+ elif len(prompt) > init_latents.shape[0] and len(prompt) % init_latents.shape[0] != 0:
825
+ raise ValueError(
826
+ f"Cannot duplicate `init_image` of batch size {init_latents.shape[0]} to {len(prompt)} text prompts."
827
+ )
828
+ else:
829
+ init_latents = torch.cat([init_latents] * num_images_per_prompt, dim=0)
830
+
831
+ # get the original timestep using init_timestep
832
+ offset = self.scheduler.config.get("steps_offset", 0)
833
+ init_timestep = int(num_inference_steps * strength) + offset
834
+ init_timestep = min(init_timestep, num_inference_steps)
835
+
836
+ timesteps = self.scheduler.timesteps[-init_timestep]
837
+ timesteps = torch.tensor([timesteps] * batch_size * num_images_per_prompt, device=self.device)
838
+
839
+ # add noise to latents using the timesteps
840
+ noise = torch.randn(init_latents.shape, generator=generator, device=self.device, dtype=latents_dtype)
841
+ init_latents = self.scheduler.add_noise(init_latents, noise, timesteps)
842
+
843
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
844
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
845
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
846
+ # and should be between [0, 1]
847
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
848
+ extra_step_kwargs = {}
849
+ if accepts_eta:
850
+ extra_step_kwargs["eta"] = eta
851
+
852
+ latents = init_latents
853
+
854
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
855
+
856
+ # Some schedulers like PNDM have timesteps as arrays
857
+ # It's more optimized to move all timesteps to correct device beforehand
858
+ timesteps = self.scheduler.timesteps[t_start:].to(self.device)
859
+
860
+ for i, t in enumerate(self.progress_bar(timesteps)):
861
+ # expand the latents if we are doing classifier free guidance
862
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
863
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
864
+
865
+ # predict the noise residual
866
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
867
+
868
+ # perform guidance
869
+ if do_classifier_free_guidance:
870
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
871
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
872
+
873
+ # compute the previous noisy sample x_t -> x_t-1
874
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
875
+
876
+ # call the callback, if provided
877
+ if callback is not None and i % callback_steps == 0:
878
+ callback(i, t, latents)
879
+
880
+ latents = 1 / 0.18215 * latents
881
+ image = self.vae.decode(latents).sample
882
+
883
+ image = (image / 2 + 0.5).clamp(0, 1)
884
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
885
+
886
+ if self.safety_checker is not None:
887
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
888
+ self.device
889
+ )
890
+ image, has_nsfw_concept = self.safety_checker(
891
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
892
+ )
893
+ else:
894
+ has_nsfw_concept = None
895
+
896
+ if output_type == "pil":
897
+ image = self.numpy_to_pil(image)
898
+
899
+ if not return_dict:
900
+ return (image, has_nsfw_concept)
901
+
902
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
903
+
904
+ @torch.no_grad()
905
+ def inpaint(
906
+ self,
907
+ prompt: Union[str, List[str]],
908
+ init_image: Union[torch.FloatTensor, PIL.Image.Image],
909
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
910
+ strength: float = 0.8,
911
+ num_inference_steps: Optional[int] = 50,
912
+ guidance_scale: Optional[float] = 7.5,
913
+ negative_prompt: Optional[Union[str, List[str]]] = None,
914
+ num_images_per_prompt: Optional[int] = 1,
915
+ eta: Optional[float] = 0.0,
916
+ generator: Optional[torch.Generator] = None,
917
+ max_embeddings_multiples: Optional[int] = 1,
918
+ output_type: Optional[str] = "pil",
919
+ return_dict: bool = True,
920
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
921
+ callback_steps: Optional[int] = 1,
922
+ **kwargs,
923
+ ):
924
+ r"""
925
+ Function invoked when calling the pipeline for generation.
926
+
927
+ Args:
928
+ prompt (`str` or `List[str]`):
929
+ The prompt or prompts to guide the image generation.
930
+ init_image (`torch.FloatTensor` or `PIL.Image.Image`):
931
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
932
+ process. This is the image whose masked region will be inpainted.
933
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
934
+ `Image`, or tensor representing an image batch, to mask `init_image`. White pixels in the mask will be
935
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
936
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
937
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
938
+ strength (`float`, *optional*, defaults to 0.8):
939
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
940
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
941
+ in `num_inference_steps`. `init_image` will be used as a reference for the masked area, adding more
942
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
943
+ num_inference_steps (`int`, *optional*, defaults to 50):
944
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
945
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
946
+ guidance_scale (`float`, *optional*, defaults to 7.5):
947
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
948
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
949
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
950
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
951
+ usually at the expense of lower image quality.
952
+ negative_prompt (`str` or `List[str]`, *optional*):
953
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
954
+ if `guidance_scale` is less than `1`).
955
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
956
+ The number of images to generate per prompt.
957
+ eta (`float`, *optional*, defaults to 0.0):
958
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
959
+ [`schedulers.DDIMScheduler`], will be ignored for others.
960
+ generator (`torch.Generator`, *optional*):
961
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
962
+ deterministic.
963
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
964
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
965
+ output_type (`str`, *optional*, defaults to `"pil"`):
966
+ The output format of the generate image. Choose between
967
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
968
+ return_dict (`bool`, *optional*, defaults to `True`):
969
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
970
+ plain tuple.
971
+ callback (`Callable`, *optional*):
972
+ A function that will be called every `callback_steps` steps during inference. The function will be
973
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
974
+ callback_steps (`int`, *optional*, defaults to 1):
975
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
976
+ called at every step.
977
+
978
+ Returns:
979
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
980
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
981
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
982
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
983
+ (nsfw) content, according to the `safety_checker`.
984
+ """
985
+ if isinstance(prompt, str):
986
+ batch_size = 1
987
+ elif isinstance(prompt, list):
988
+ batch_size = len(prompt)
989
+ else:
990
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
991
+
992
+ if strength < 0 or strength > 1:
993
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
994
+
995
+ if (callback_steps is None) or (
996
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
997
+ ):
998
+ raise ValueError(
999
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
1000
+ f" {type(callback_steps)}."
1001
+ )
1002
+
1003
+ # set timesteps
1004
+ self.scheduler.set_timesteps(num_inference_steps)
1005
+
1006
+ # get prompt text embeddings
1007
+
1008
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1009
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1010
+ # corresponds to doing no classifier free guidance.
1011
+ do_classifier_free_guidance = guidance_scale > 1.0
1012
+ # get unconditional embeddings for classifier free guidance
1013
+ uncond_tokens = [""]
1014
+ if do_classifier_free_guidance:
1015
+ if type(prompt) is not type(negative_prompt):
1016
+ raise TypeError(
1017
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
1018
+ f" {type(prompt)}."
1019
+ )
1020
+ elif isinstance(negative_prompt, str):
1021
+ uncond_tokens = [negative_prompt]
1022
+ elif batch_size != len(negative_prompt):
1023
+ raise ValueError(
1024
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
1025
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
1026
+ " the batch size of `prompt`."
1027
+ )
1028
+ else:
1029
+ uncond_tokens = negative_prompt
1030
+
1031
+ text_embeddings = get_weighted_text_embeddings(
1032
+ pipe=self,
1033
+ prompt=prompt,
1034
+ uncond_prompt=uncond_tokens if do_classifier_free_guidance else None,
1035
+ max_embeddings_multiples=max_embeddings_multiples,
1036
+ **kwargs
1037
+ )
1038
+
1039
+ # preprocess image
1040
+ if not isinstance(init_image, torch.FloatTensor):
1041
+ init_image = preprocess_image(init_image)
1042
+
1043
+ # encode the init image into latents and scale the latents
1044
+ latents_dtype = text_embeddings.dtype
1045
+ init_image = init_image.to(device=self.device, dtype=latents_dtype)
1046
+ init_latent_dist = self.vae.encode(init_image).latent_dist
1047
+ init_latents = init_latent_dist.sample(generator=generator)
1048
+ init_latents = 0.18215 * init_latents
1049
+
1050
+ # Expand init_latents for batch_size and num_images_per_prompt
1051
+ init_latents = torch.cat([init_latents] * batch_size * num_images_per_prompt, dim=0)
1052
+ init_latents_orig = init_latents
1053
+
1054
+ # preprocess mask
1055
+ if not isinstance(mask_image, torch.FloatTensor):
1056
+ mask_image = preprocess_mask(mask_image)
1057
+ mask_image = mask_image.to(device=self.device, dtype=latents_dtype)
1058
+ mask = torch.cat([mask_image] * batch_size * num_images_per_prompt)
1059
+
1060
+ # check sizes
1061
+ if not mask.shape == init_latents.shape:
1062
+ raise ValueError("The mask and init_image should be the same size!")
1063
+
1064
+ # get the original timestep using init_timestep
1065
+ offset = self.scheduler.config.get("steps_offset", 0)
1066
+ init_timestep = int(num_inference_steps * strength) + offset
1067
+ init_timestep = min(init_timestep, num_inference_steps)
1068
+
1069
+ timesteps = self.scheduler.timesteps[-init_timestep]
1070
+ timesteps = torch.tensor([timesteps] * batch_size * num_images_per_prompt, device=self.device)
1071
+
1072
+ # add noise to latents using the timesteps
1073
+ noise = torch.randn(init_latents.shape, generator=generator, device=self.device, dtype=latents_dtype)
1074
+ init_latents = self.scheduler.add_noise(init_latents, noise, timesteps)
1075
+
1076
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
1077
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
1078
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
1079
+ # and should be between [0, 1]
1080
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
1081
+ extra_step_kwargs = {}
1082
+ if accepts_eta:
1083
+ extra_step_kwargs["eta"] = eta
1084
+
1085
+ latents = init_latents
1086
+
1087
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
1088
+
1089
+ # Some schedulers like PNDM have timesteps as arrays
1090
+ # It's more optimized to move all timesteps to correct device beforehand
1091
+ timesteps = self.scheduler.timesteps[t_start:].to(self.device)
1092
+
1093
+ for i, t in enumerate(self.progress_bar(timesteps)):
1094
+ # expand the latents if we are doing classifier free guidance
1095
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1096
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1097
+
1098
+ # predict the noise residual
1099
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
1100
+
1101
+ # perform guidance
1102
+ if do_classifier_free_guidance:
1103
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1104
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1105
+
1106
+ # compute the previous noisy sample x_t -> x_t-1
1107
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1108
+ # masking
1109
+ init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, torch.tensor([t]))
1110
+
1111
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
1112
+
1113
+ # call the callback, if provided
1114
+ if callback is not None and i % callback_steps == 0:
1115
+ callback(i, t, latents)
1116
+
1117
+ latents = 1 / 0.18215 * latents
1118
+ image = self.vae.decode(latents).sample
1119
+
1120
+ image = (image / 2 + 0.5).clamp(0, 1)
1121
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
1122
+
1123
+ if self.safety_checker is not None:
1124
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
1125
+ self.device
1126
+ )
1127
+ image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_checker_input.pixel_values)
1128
+ else:
1129
+ has_nsfw_concept = None
1130
+
1131
+ if output_type == "pil":
1132
+ image = self.numpy_to_pil(image)
1133
+
1134
+ if not return_dict:
1135
+ return (image, has_nsfw_concept)
1136
+
1137
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)