ACCC1380 commited on
Commit
6f25cf1
1 Parent(s): b7e6339

Upload lora-scripts/sd-scripts/library/lpw_stable_diffusion.py with huggingface_hub

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