Datasets:

ArXiv:
Diffusers Bot commited on
Commit
3df17b8
1 Parent(s): bd3b328

Upload folder using huggingface_hub

Browse files
v0.10.1/README.md ADDED
@@ -0,0 +1,776 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Community Examples
2
+
3
+ > **For more information about community pipelines, please have a look at [this issue](https://github.com/huggingface/diffusers/issues/841).**
4
+
5
+ **Community** examples consist of both inference and training examples that have been added by the community.
6
+ Please have a look at the following table to get an overview of all community examples. Click on the **Code Example** to get a copy-and-paste ready code example that you can try out.
7
+ If a community doesn't work as expected, please open an issue and ping the author on it.
8
+
9
+ | Example | Description | Code Example | Colab | Author |
10
+ |:---------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------:|
11
+ | CLIP Guided Stable Diffusion | Doing CLIP guidance for text to image generation with Stable Diffusion | [CLIP Guided Stable Diffusion](#clip-guided-stable-diffusion) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/CLIP_Guided_Stable_diffusion_with_diffusers.ipynb) | [Suraj Patil](https://github.com/patil-suraj/) |
12
+ | One Step U-Net (Dummy) | Example showcasing of how to use Community Pipelines (see https://github.com/huggingface/diffusers/issues/841) | [One Step U-Net](#one-step-unet) | - | [Patrick von Platen](https://github.com/patrickvonplaten/) |
13
+ | Stable Diffusion Interpolation | Interpolate the latent space of Stable Diffusion between different prompts/seeds | [Stable Diffusion Interpolation](#stable-diffusion-interpolation) | - | [Nate Raw](https://github.com/nateraw/) |
14
+ | Stable Diffusion Mega | **One** Stable Diffusion Pipeline with all functionalities of [Text2Image](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py), [Image2Image](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py) and [Inpainting](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py) | [Stable Diffusion Mega](#stable-diffusion-mega) | - | [Patrick von Platen](https://github.com/patrickvonplaten/) |
15
+ | Long Prompt Weighting Stable Diffusion | **One** Stable Diffusion Pipeline without tokens length limit, and support parsing weighting in prompt. | [Long Prompt Weighting Stable Diffusion](#long-prompt-weighting-stable-diffusion) | - | [SkyTNT](https://github.com/SkyTNT) |
16
+ | Speech to Image | Using automatic-speech-recognition to transcribe text and Stable Diffusion to generate images | [Speech to Image](#speech-to-image) | - | [Mikail Duzenli](https://github.com/MikailINTech)
17
+ | Wild Card Stable Diffusion | Stable Diffusion Pipeline that supports prompts that contain wildcard terms (indicated by surrounding double underscores), with values instantiated randomly from a corresponding txt file or a dictionary of possible values | [Wildcard Stable Diffusion](#wildcard-stable-diffusion) | - | [Shyam Sudhakaran](https://github.com/shyamsn97) |
18
+ | [Composable Stable Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/) | Stable Diffusion Pipeline that supports prompts that contain "|" in prompts (as an AND condition) and weights (separated by "|" as well) to positively / negatively weight prompts. | [Composable Stable Diffusion](#composable-stable-diffusion) | - | [Mark Rich](https://github.com/MarkRich) |
19
+ | Seed Resizing Stable Diffusion| Stable Diffusion Pipeline that supports resizing an image and retaining the concepts of the 512 by 512 generation. | [Seed Resizing](#seed-resizing) | - | [Mark Rich](https://github.com/MarkRich) |
20
+ | Imagic Stable Diffusion | Stable Diffusion Pipeline that enables writing a text prompt to edit an existing image| [Imagic Stable Diffusion](#imagic-stable-diffusion) | - | [Mark Rich](https://github.com/MarkRich) |
21
+ | Multilingual Stable Diffusion| Stable Diffusion Pipeline that supports prompts in 50 different languages. | [Multilingual Stable Diffusion](#multilingual-stable-diffusion-pipeline) | - | [Juan Carlos Piñeros](https://github.com/juancopi81) |
22
+ | Image to Image Inpainting Stable Diffusion | Stable Diffusion Pipeline that enables the overlaying of two images and subsequent inpainting| [Image to Image Inpainting Stable Diffusion](#image-to-image-inpainting-stable-diffusion) | - | [Alex McKinney](https://github.com/vvvm23) |
23
+ | Text Based Inpainting Stable Diffusion | Stable Diffusion Inpainting Pipeline that enables passing a text prompt to generate the mask for inpainting| [Text Based Inpainting Stable Diffusion](#image-to-image-inpainting-stable-diffusion) | - | [Dhruv Karan](https://github.com/unography) |
24
+ | Bit Diffusion | Diffusion on discrete data | [Bit Diffusion](#bit-diffusion) | - |[Stuti R.](https://github.com/kingstut) |
25
+ | K-Diffusion Stable Diffusion | Run Stable Diffusion with any of [K-Diffusion's samplers](https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py) | [Stable Diffusion with K Diffusion](#stable-diffusion-with-k-diffusion) | - | [Patrick von Platen](https://github.com/patrickvonplaten/) |
26
+ | Checkpoint Merger Pipeline | Diffusion Pipeline that enables merging of saved model checkpoints | [Checkpoint Merger Pipeline](#checkpoint-merger-pipeline) | - | [Naga Sai Abhinay Devarinti](https://github.com/Abhinay1997/) |
27
+
28
+
29
+
30
+ To load a custom pipeline you just need to pass the `custom_pipeline` argument to `DiffusionPipeline`, as one of the files in `diffusers/examples/community`. Feel free to send a PR with your own pipelines, we will merge them quickly.
31
+ ```py
32
+ pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", custom_pipeline="filename_in_the_community_folder")
33
+ ```
34
+
35
+ ## Example usages
36
+
37
+ ### CLIP Guided Stable Diffusion
38
+
39
+ CLIP guided stable diffusion can help to generate more realistic images
40
+ by guiding stable diffusion at every denoising step with an additional CLIP model.
41
+
42
+ The following code requires roughly 12GB of GPU RAM.
43
+
44
+ ```python
45
+ from diffusers import DiffusionPipeline
46
+ from transformers import CLIPFeatureExtractor, CLIPModel
47
+ import torch
48
+
49
+
50
+ feature_extractor = CLIPFeatureExtractor.from_pretrained("laion/CLIP-ViT-B-32-laion2B-s34B-b79K")
51
+ clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-B-32-laion2B-s34B-b79K", torch_dtype=torch.float16)
52
+
53
+
54
+ guided_pipeline = DiffusionPipeline.from_pretrained(
55
+ "runwayml/stable-diffusion-v1-5",
56
+ custom_pipeline="clip_guided_stable_diffusion",
57
+ clip_model=clip_model,
58
+ feature_extractor=feature_extractor,
59
+ revision="fp16",
60
+ torch_dtype=torch.float16,
61
+ )
62
+ guided_pipeline.enable_attention_slicing()
63
+ guided_pipeline = guided_pipeline.to("cuda")
64
+
65
+ prompt = "fantasy book cover, full moon, fantasy forest landscape, golden vector elements, fantasy magic, dark light night, intricate, elegant, sharp focus, illustration, highly detailed, digital painting, concept art, matte, art by WLOP and Artgerm and Albert Bierstadt, masterpiece"
66
+
67
+ generator = torch.Generator(device="cuda").manual_seed(0)
68
+ images = []
69
+ for i in range(4):
70
+ image = guided_pipeline(
71
+ prompt,
72
+ num_inference_steps=50,
73
+ guidance_scale=7.5,
74
+ clip_guidance_scale=100,
75
+ num_cutouts=4,
76
+ use_cutouts=False,
77
+ generator=generator,
78
+ ).images[0]
79
+ images.append(image)
80
+
81
+ # save images locally
82
+ for i, img in enumerate(images):
83
+ img.save(f"./clip_guided_sd/image_{i}.png")
84
+ ```
85
+
86
+ The `images` list contains a list of PIL images that can be saved locally or displayed directly in a google colab.
87
+ Generated images tend to be of higher qualtiy than natively using stable diffusion. E.g. the above script generates the following images:
88
+
89
+ ![clip_guidance](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/clip_guidance/merged_clip_guidance.jpg).
90
+
91
+ ### One Step Unet
92
+
93
+ The dummy "one-step-unet" can be run as follows:
94
+
95
+ ```python
96
+ from diffusers import DiffusionPipeline
97
+
98
+ pipe = DiffusionPipeline.from_pretrained("google/ddpm-cifar10-32", custom_pipeline="one_step_unet")
99
+ pipe()
100
+ ```
101
+
102
+ **Note**: This community pipeline is not useful as a feature, but rather just serves as an example of how community pipelines can be added (see https://github.com/huggingface/diffusers/issues/841).
103
+
104
+ ### Stable Diffusion Interpolation
105
+
106
+ The following code can be run on a GPU of at least 8GB VRAM and should take approximately 5 minutes.
107
+
108
+ ```python
109
+ from diffusers import DiffusionPipeline
110
+ import torch
111
+
112
+ pipe = DiffusionPipeline.from_pretrained(
113
+ "CompVis/stable-diffusion-v1-4",
114
+ revision='fp16',
115
+ torch_dtype=torch.float16,
116
+ safety_checker=None, # Very important for videos...lots of false positives while interpolating
117
+ custom_pipeline="interpolate_stable_diffusion",
118
+ ).to('cuda')
119
+ pipe.enable_attention_slicing()
120
+
121
+ frame_filepaths = pipe.walk(
122
+ prompts=['a dog', 'a cat', 'a horse'],
123
+ seeds=[42, 1337, 1234],
124
+ num_interpolation_steps=16,
125
+ output_dir='./dreams',
126
+ batch_size=4,
127
+ height=512,
128
+ width=512,
129
+ guidance_scale=8.5,
130
+ num_inference_steps=50,
131
+ )
132
+ ```
133
+
134
+ The output of the `walk(...)` function returns a list of images saved under the folder as defined in `output_dir`. You can use these images to create videos of stable diffusion.
135
+
136
+ > **Please have a look at https://github.com/nateraw/stable-diffusion-videos for more in-detail information on how to create videos using stable diffusion as well as more feature-complete functionality.**
137
+
138
+ ### Stable Diffusion Mega
139
+
140
+ The Stable Diffusion Mega Pipeline lets you use the main use cases of the stable diffusion pipeline in a single class.
141
+
142
+ ```python
143
+ #!/usr/bin/env python3
144
+ from diffusers import DiffusionPipeline
145
+ import PIL
146
+ import requests
147
+ from io import BytesIO
148
+ import torch
149
+
150
+
151
+ def download_image(url):
152
+ response = requests.get(url)
153
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
154
+
155
+ pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", custom_pipeline="stable_diffusion_mega", torch_dtype=torch.float16, revision="fp16")
156
+ pipe.to("cuda")
157
+ pipe.enable_attention_slicing()
158
+
159
+
160
+ ### Text-to-Image
161
+
162
+ images = pipe.text2img("An astronaut riding a horse").images
163
+
164
+ ### Image-to-Image
165
+
166
+ init_image = download_image("https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg")
167
+
168
+ prompt = "A fantasy landscape, trending on artstation"
169
+
170
+ images = pipe.img2img(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
171
+
172
+ ### Inpainting
173
+
174
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
175
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
176
+ init_image = download_image(img_url).resize((512, 512))
177
+ mask_image = download_image(mask_url).resize((512, 512))
178
+
179
+ prompt = "a cat sitting on a bench"
180
+ images = pipe.inpaint(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.75).images
181
+ ```
182
+
183
+ As shown above this one pipeline can run all both "text-to-image", "image-to-image", and "inpainting" in one pipeline.
184
+
185
+ ### Long Prompt Weighting Stable Diffusion
186
+ Features of this custom pipeline:
187
+ - Input a prompt without the 77 token length limit.
188
+ - Includes tx2img, img2img. and inpainting pipelines.
189
+ - Emphasize/weigh part of your prompt with parentheses as so: `a baby deer with (big eyes)`
190
+ - De-emphasize part of your prompt as so: `a [baby] deer with big eyes`
191
+ - Precisely weigh part of your prompt as so: `a baby deer with (big eyes:1.3)`
192
+
193
+ Prompt weighting equivalents:
194
+ - `a baby deer with` == `(a baby deer with:1.0)`
195
+ - `(big eyes)` == `(big eyes:1.1)`
196
+ - `((big eyes))` == `(big eyes:1.21)`
197
+ - `[big eyes]` == `(big eyes:0.91)`
198
+
199
+ You can run this custom pipeline as so:
200
+
201
+ #### pytorch
202
+
203
+ ```python
204
+ from diffusers import DiffusionPipeline
205
+ import torch
206
+
207
+ pipe = DiffusionPipeline.from_pretrained(
208
+ 'hakurei/waifu-diffusion',
209
+ custom_pipeline="lpw_stable_diffusion",
210
+ revision="fp16",
211
+ torch_dtype=torch.float16
212
+ )
213
+ pipe=pipe.to("cuda")
214
+
215
+ prompt = "best_quality (1girl:1.3) bow bride brown_hair closed_mouth frilled_bow frilled_hair_tubes frills (full_body:1.3) fox_ear hair_bow hair_tubes happy hood japanese_clothes kimono long_sleeves red_bow smile solo tabi uchikake white_kimono wide_sleeves cherry_blossoms"
216
+ neg_prompt = "lowres, bad_anatomy, error_body, error_hair, error_arm, error_hands, bad_hands, error_fingers, bad_fingers, missing_fingers, error_legs, bad_legs, multiple_legs, missing_legs, error_lighting, error_shadow, error_reflection, text, error, extra_digit, fewer_digits, cropped, worst_quality, low_quality, normal_quality, jpeg_artifacts, signature, watermark, username, blurry"
217
+
218
+ pipe.text2img(prompt, negative_prompt=neg_prompt, width=512,height=512,max_embeddings_multiples=3).images[0]
219
+
220
+ ```
221
+
222
+ #### onnxruntime
223
+
224
+ ```python
225
+ from diffusers import DiffusionPipeline
226
+ import torch
227
+
228
+ pipe = DiffusionPipeline.from_pretrained(
229
+ 'CompVis/stable-diffusion-v1-4',
230
+ custom_pipeline="lpw_stable_diffusion_onnx",
231
+ revision="onnx",
232
+ provider="CUDAExecutionProvider"
233
+ )
234
+
235
+ prompt = "a photo of an astronaut riding a horse on mars, best quality"
236
+ neg_prompt = "lowres, bad anatomy, error body, error hair, error arm, error hands, bad hands, error fingers, bad fingers, missing fingers, error legs, bad legs, multiple legs, missing legs, error lighting, error shadow, error reflection, text, error, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry"
237
+
238
+ pipe.text2img(prompt,negative_prompt=neg_prompt, width=512, height=512, max_embeddings_multiples=3).images[0]
239
+
240
+ ```
241
+
242
+ if you see `Token indices sequence length is longer than the specified maximum sequence length for this model ( *** > 77 ) . Running this sequence through the model will result in indexing errors`. Do not worry, it is normal.
243
+
244
+ ### Speech to Image
245
+
246
+ The following code can generate an image from an audio sample using pre-trained OpenAI whisper-small and Stable Diffusion.
247
+
248
+ ```Python
249
+ import torch
250
+
251
+ import matplotlib.pyplot as plt
252
+ from datasets import load_dataset
253
+ from diffusers import DiffusionPipeline
254
+ from transformers import (
255
+ WhisperForConditionalGeneration,
256
+ WhisperProcessor,
257
+ )
258
+
259
+
260
+ device = "cuda" if torch.cuda.is_available() else "cpu"
261
+
262
+ ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
263
+
264
+ audio_sample = ds[3]
265
+
266
+ text = audio_sample["text"].lower()
267
+ speech_data = audio_sample["audio"]["array"]
268
+
269
+ model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small").to(device)
270
+ processor = WhisperProcessor.from_pretrained("openai/whisper-small")
271
+
272
+ diffuser_pipeline = DiffusionPipeline.from_pretrained(
273
+ "CompVis/stable-diffusion-v1-4",
274
+ custom_pipeline="speech_to_image_diffusion",
275
+ speech_model=model,
276
+ speech_processor=processor,
277
+ revision="fp16",
278
+ torch_dtype=torch.float16,
279
+ )
280
+
281
+ diffuser_pipeline.enable_attention_slicing()
282
+ diffuser_pipeline = diffuser_pipeline.to(device)
283
+
284
+ output = diffuser_pipeline(speech_data)
285
+ plt.imshow(output.images[0])
286
+ ```
287
+ This example produces the following image:
288
+
289
+ ![image](https://user-images.githubusercontent.com/45072645/196901736-77d9c6fc-63ee-4072-90b0-dc8b903d63e3.png)
290
+
291
+ ### Wildcard Stable Diffusion
292
+ Following the great examples from https://github.com/jtkelm2/stable-diffusion-webui-1/blob/master/scripts/wildcards.py and https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Custom-Scripts#wildcards, here's a minimal implementation that allows for users to add "wildcards", denoted by `__wildcard__` to prompts that are used as placeholders for randomly sampled values given by either a dictionary or a `.txt` file. For example:
293
+
294
+ Say we have a prompt:
295
+
296
+ ```
297
+ prompt = "__animal__ sitting on a __object__ wearing a __clothing__"
298
+ ```
299
+
300
+ We can then define possible values to be sampled for `animal`, `object`, and `clothing`. These can either be from a `.txt` with the same name as the category.
301
+
302
+ The possible values can also be defined / combined by using a dictionary like: `{"animal":["dog", "cat", mouse"]}`.
303
+
304
+ The actual pipeline works just like `StableDiffusionPipeline`, except the `__call__` method takes in:
305
+
306
+ `wildcard_files`: list of file paths for wild card replacement
307
+ `wildcard_option_dict`: dict with key as `wildcard` and values as a list of possible replacements
308
+ `num_prompt_samples`: number of prompts to sample, uniformly sampling wildcards
309
+
310
+ A full example:
311
+
312
+ create `animal.txt`, with contents like:
313
+
314
+ ```
315
+ dog
316
+ cat
317
+ mouse
318
+ ```
319
+
320
+ create `object.txt`, with contents like:
321
+
322
+ ```
323
+ chair
324
+ sofa
325
+ bench
326
+ ```
327
+
328
+ ```python
329
+ from diffusers import DiffusionPipeline
330
+ import torch
331
+
332
+ pipe = DiffusionPipeline.from_pretrained(
333
+ "CompVis/stable-diffusion-v1-4",
334
+ custom_pipeline="wildcard_stable_diffusion",
335
+ revision="fp16",
336
+ torch_dtype=torch.float16,
337
+ )
338
+ prompt = "__animal__ sitting on a __object__ wearing a __clothing__"
339
+ out = pipe(
340
+ prompt,
341
+ wildcard_option_dict={
342
+ "clothing":["hat", "shirt", "scarf", "beret"]
343
+ },
344
+ wildcard_files=["object.txt", "animal.txt"],
345
+ num_prompt_samples=1
346
+ )
347
+ ```
348
+
349
+ ### Composable Stable diffusion
350
+
351
+ [Composable Stable Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/) proposes conjunction and negation (negative prompts) operators for compositional generation with conditional diffusion models.
352
+
353
+ ```python
354
+ import torch as th
355
+ import numpy as np
356
+ import torchvision.utils as tvu
357
+ from diffusers import DiffusionPipeline
358
+
359
+ has_cuda = th.cuda.is_available()
360
+ device = th.device('cpu' if not has_cuda else 'cuda')
361
+
362
+ pipe = DiffusionPipeline.from_pretrained(
363
+ "CompVis/stable-diffusion-v1-4",
364
+ use_auth_token=True,
365
+ custom_pipeline="composable_stable_diffusion",
366
+ ).to(device)
367
+
368
+
369
+ def dummy(images, **kwargs):
370
+ return images, False
371
+
372
+ pipe.safety_checker = dummy
373
+
374
+ images = []
375
+ generator = torch.Generator("cuda").manual_seed(0)
376
+
377
+ seed = 0
378
+ prompt = "a forest | a camel"
379
+ weights = " 1 | 1" # Equal weight to each prompt. Can be negative
380
+
381
+ images = []
382
+ for i in range(4):
383
+ res = pipe(
384
+ prompt,
385
+ guidance_scale=7.5,
386
+ num_inference_steps=50,
387
+ weights=weights,
388
+ generator=generator)
389
+ image = res.images[0]
390
+ images.append(image)
391
+
392
+ for i, img in enumerate(images):
393
+ img.save(f"./composable_diffusion/image_{i}.png")
394
+ ```
395
+
396
+ ### Imagic Stable Diffusion
397
+ Allows you to edit an image using stable diffusion.
398
+
399
+ ```python
400
+ import requests
401
+ from PIL import Image
402
+ from io import BytesIO
403
+ import torch
404
+ import os
405
+ from diffusers import DiffusionPipeline, DDIMScheduler
406
+ has_cuda = torch.cuda.is_available()
407
+ device = torch.device('cpu' if not has_cuda else 'cuda')
408
+ pipe = DiffusionPipeline.from_pretrained(
409
+ "CompVis/stable-diffusion-v1-4",
410
+ safety_checker=None,
411
+ use_auth_token=True,
412
+ custom_pipeline="imagic_stable_diffusion",
413
+ scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False, set_alpha_to_one=False)
414
+ ).to(device)
415
+ generator = torch.Generator("cuda").manual_seed(0)
416
+ seed = 0
417
+ prompt = "A photo of Barack Obama smiling with a big grin"
418
+ url = 'https://www.dropbox.com/s/6tlwzr73jd1r9yk/obama.png?dl=1'
419
+ response = requests.get(url)
420
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
421
+ init_image = init_image.resize((512, 512))
422
+ res = pipe.train(
423
+ prompt,
424
+ image=init_image,
425
+ generator=generator)
426
+ res = pipe(alpha=1, guidance_scale=7.5, num_inference_steps=50)
427
+ os.makedirs("imagic", exist_ok=True)
428
+ image = res.images[0]
429
+ image.save('./imagic/imagic_image_alpha_1.png')
430
+ res = pipe(alpha=1.5, guidance_scale=7.5, num_inference_steps=50)
431
+ image = res.images[0]
432
+ image.save('./imagic/imagic_image_alpha_1_5.png')
433
+ res = pipe(alpha=2, guidance_scale=7.5, num_inference_steps=50)
434
+ image = res.images[0]
435
+ image.save('./imagic/imagic_image_alpha_2.png')
436
+ ```
437
+
438
+ ### Seed Resizing
439
+ Test seed resizing. Originally generate an image in 512 by 512, then generate image with same seed at 512 by 592 using seed resizing. Finally, generate 512 by 592 using original stable diffusion pipeline.
440
+
441
+ ```python
442
+ import torch as th
443
+ import numpy as np
444
+ from diffusers import DiffusionPipeline
445
+
446
+ has_cuda = th.cuda.is_available()
447
+ device = th.device('cpu' if not has_cuda else 'cuda')
448
+
449
+ pipe = DiffusionPipeline.from_pretrained(
450
+ "CompVis/stable-diffusion-v1-4",
451
+ use_auth_token=True,
452
+ custom_pipeline="seed_resize_stable_diffusion"
453
+ ).to(device)
454
+
455
+ def dummy(images, **kwargs):
456
+ return images, False
457
+
458
+ pipe.safety_checker = dummy
459
+
460
+
461
+ images = []
462
+ th.manual_seed(0)
463
+ generator = th.Generator("cuda").manual_seed(0)
464
+
465
+ seed = 0
466
+ prompt = "A painting of a futuristic cop"
467
+
468
+ width = 512
469
+ height = 512
470
+
471
+ res = pipe(
472
+ prompt,
473
+ guidance_scale=7.5,
474
+ num_inference_steps=50,
475
+ height=height,
476
+ width=width,
477
+ generator=generator)
478
+ image = res.images[0]
479
+ image.save('./seed_resize/seed_resize_{w}_{h}_image.png'.format(w=width, h=height))
480
+
481
+
482
+ th.manual_seed(0)
483
+ generator = th.Generator("cuda").manual_seed(0)
484
+
485
+ pipe = DiffusionPipeline.from_pretrained(
486
+ "CompVis/stable-diffusion-v1-4",
487
+ use_auth_token=True,
488
+ custom_pipeline="/home/mark/open_source/diffusers/examples/community/"
489
+ ).to(device)
490
+
491
+ width = 512
492
+ height = 592
493
+
494
+ res = pipe(
495
+ prompt,
496
+ guidance_scale=7.5,
497
+ num_inference_steps=50,
498
+ height=height,
499
+ width=width,
500
+ generator=generator)
501
+ image = res.images[0]
502
+ image.save('./seed_resize/seed_resize_{w}_{h}_image.png'.format(w=width, h=height))
503
+
504
+ pipe_compare = DiffusionPipeline.from_pretrained(
505
+ "CompVis/stable-diffusion-v1-4",
506
+ use_auth_token=True,
507
+ custom_pipeline="/home/mark/open_source/diffusers/examples/community/"
508
+ ).to(device)
509
+
510
+ res = pipe_compare(
511
+ prompt,
512
+ guidance_scale=7.5,
513
+ num_inference_steps=50,
514
+ height=height,
515
+ width=width,
516
+ generator=generator
517
+ )
518
+
519
+ image = res.images[0]
520
+ image.save('./seed_resize/seed_resize_{w}_{h}_image_compare.png'.format(w=width, h=height))
521
+ ```
522
+
523
+ ### Multilingual Stable Diffusion Pipeline
524
+
525
+ The following code can generate an images from texts in different languages using the pre-trained [mBART-50 many-to-one multilingual machine translation model](https://huggingface.co/facebook/mbart-large-50-many-to-one-mmt) and Stable Diffusion.
526
+
527
+ ```python
528
+ from PIL import Image
529
+
530
+ import torch
531
+
532
+ from diffusers import DiffusionPipeline
533
+ from transformers import (
534
+ pipeline,
535
+ MBart50TokenizerFast,
536
+ MBartForConditionalGeneration,
537
+ )
538
+ device = "cuda" if torch.cuda.is_available() else "cpu"
539
+ device_dict = {"cuda": 0, "cpu": -1}
540
+
541
+ # helper function taken from: https://huggingface.co/blog/stable_diffusion
542
+ def image_grid(imgs, rows, cols):
543
+ assert len(imgs) == rows*cols
544
+
545
+ w, h = imgs[0].size
546
+ grid = Image.new('RGB', size=(cols*w, rows*h))
547
+ grid_w, grid_h = grid.size
548
+
549
+ for i, img in enumerate(imgs):
550
+ grid.paste(img, box=(i%cols*w, i//cols*h))
551
+ return grid
552
+
553
+ # Add language detection pipeline
554
+ language_detection_model_ckpt = "papluca/xlm-roberta-base-language-detection"
555
+ language_detection_pipeline = pipeline("text-classification",
556
+ model=language_detection_model_ckpt,
557
+ device=device_dict[device])
558
+
559
+ # Add model for language translation
560
+ trans_tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-one-mmt")
561
+ trans_model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-one-mmt").to(device)
562
+
563
+ diffuser_pipeline = DiffusionPipeline.from_pretrained(
564
+ "CompVis/stable-diffusion-v1-4",
565
+ custom_pipeline="multilingual_stable_diffusion",
566
+ detection_pipeline=language_detection_pipeline,
567
+ translation_model=trans_model,
568
+ translation_tokenizer=trans_tokenizer,
569
+ revision="fp16",
570
+ torch_dtype=torch.float16,
571
+ )
572
+
573
+ diffuser_pipeline.enable_attention_slicing()
574
+ diffuser_pipeline = diffuser_pipeline.to(device)
575
+
576
+ prompt = ["a photograph of an astronaut riding a horse",
577
+ "Una casa en la playa",
578
+ "Ein Hund, der Orange isst",
579
+ "Un restaurant parisien"]
580
+
581
+ output = diffuser_pipeline(prompt)
582
+
583
+ images = output.images
584
+
585
+ grid = image_grid(images, rows=2, cols=2)
586
+ ```
587
+
588
+ This example produces the following images:
589
+ ![image](https://user-images.githubusercontent.com/4313860/198328706-295824a4-9856-4ce5-8e66-278ceb42fd29.png)
590
+
591
+ ### Image to Image Inpainting Stable Diffusion
592
+
593
+ Similar to the standard stable diffusion inpainting example, except with the addition of an `inner_image` argument.
594
+
595
+ `image`, `inner_image`, and `mask` should have the same dimensions. `inner_image` should have an alpha (transparency) channel.
596
+
597
+ The aim is to overlay two images, then mask out the boundary between `image` and `inner_image` to allow stable diffusion to make the connection more seamless.
598
+ For example, this could be used to place a logo on a shirt and make it blend seamlessly.
599
+
600
+ ```python
601
+ import PIL
602
+ import torch
603
+
604
+ from diffusers import DiffusionPipeline
605
+
606
+ image_path = "./path-to-image.png"
607
+ inner_image_path = "./path-to-inner-image.png"
608
+ mask_path = "./path-to-mask.png"
609
+
610
+ init_image = PIL.Image.open(image_path).convert("RGB").resize((512, 512))
611
+ inner_image = PIL.Image.open(inner_image_path).convert("RGBA").resize((512, 512))
612
+ mask_image = PIL.Image.open(mask_path).convert("RGB").resize((512, 512))
613
+
614
+ pipe = DiffusionPipeline.from_pretrained(
615
+ "runwayml/stable-diffusion-inpainting",
616
+ custom_pipeline="img2img_inpainting",
617
+ revision="fp16",
618
+ torch_dtype=torch.float16
619
+ )
620
+ pipe = pipe.to("cuda")
621
+
622
+ prompt = "Your prompt here!"
623
+ image = pipe(prompt=prompt, image=init_image, inner_image=inner_image, mask_image=mask_image).images[0]
624
+ ```
625
+
626
+ ![2 by 2 grid demonstrating image to image inpainting.](https://user-images.githubusercontent.com/44398246/203506577-ec303be4-887e-4ebd-a773-c83fcb3dd01a.png)
627
+
628
+ ### Text Based Inpainting Stable Diffusion
629
+
630
+ Use a text prompt to generate the mask for the area to be inpainted.
631
+ Currently uses the CLIPSeg model for mask generation, then calls the standard Stable Diffusion Inpainting pipeline to perform the inpainting.
632
+
633
+ ```python
634
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
635
+ from diffusers import DiffusionPipeline
636
+
637
+ from PIL import Image
638
+ import requests
639
+ from torch import autocast
640
+
641
+ processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
642
+ model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")
643
+
644
+ pipe = DiffusionPipeline.from_pretrained(
645
+ "runwayml/stable-diffusion-inpainting",
646
+ custom_pipeline="text_inpainting",
647
+ segmentation_model=model,
648
+ segmentation_processor=processor
649
+ )
650
+ pipe = pipe.to("cuda")
651
+
652
+
653
+ url = "https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true"
654
+ image = Image.open(requests.get(url, stream=True).raw).resize((512, 512))
655
+ text = "a glass" # will mask out this text
656
+ prompt = "a cup" # the masked out region will be replaced with this
657
+
658
+ with autocast("cuda"):
659
+ image = pipe(image=image, text=text, prompt=prompt).images[0]
660
+ ```
661
+
662
+ ### Bit Diffusion
663
+ Based https://arxiv.org/abs/2208.04202, this is used for diffusion on discrete data - eg, discreate image data, DNA sequence data. An unconditional discreate image can be generated like this:
664
+
665
+ ```python
666
+ from diffusers import DiffusionPipeline
667
+ pipe = DiffusionPipeline.from_pretrained("google/ddpm-cifar10-32", custom_pipeline="bit_diffusion")
668
+ image = pipe().images[0]
669
+
670
+ ```
671
+
672
+ ### Stable Diffusion with K Diffusion
673
+
674
+ Make sure you have @crowsonkb's https://github.com/crowsonkb/k-diffusion installed:
675
+
676
+ ```
677
+ pip install k-diffusion
678
+ ```
679
+
680
+ You can use the community pipeline as follows:
681
+
682
+ ```python
683
+ from diffusers import DiffusionPipeline
684
+
685
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="sd_text2img_k_diffusion")
686
+ pipe = pipe.to("cuda")
687
+
688
+ prompt = "an astronaut riding a horse on mars"
689
+ pipe.set_scheduler("sample_heun")
690
+ generator = torch.Generator(device="cuda").manual_seed(seed)
691
+ image = pipe(prompt, generator=generator, num_inference_steps=20).images[0]
692
+
693
+ image.save("./astronaut_heun_k_diffusion.png")
694
+ ```
695
+
696
+ To make sure that K Diffusion and `diffusers` yield the same results:
697
+
698
+ **Diffusers**:
699
+ ```python
700
+ from diffusers import DiffusionPipeline, EulerDiscreteScheduler
701
+
702
+ seed = 33
703
+
704
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
705
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
706
+ pipe = pipe.to("cuda")
707
+
708
+ generator = torch.Generator(device="cuda").manual_seed(seed)
709
+ image = pipe(prompt, generator=generator, num_inference_steps=50).images[0]
710
+ ```
711
+
712
+ ![diffusers_euler](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/k_diffusion/astronaut_euler.png)
713
+
714
+ **K Diffusion**:
715
+ ```python
716
+ from diffusers import DiffusionPipeline, EulerDiscreteScheduler
717
+
718
+ seed = 33
719
+
720
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="sd_text2img_k_diffusion")
721
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
722
+ pipe = pipe.to("cuda")
723
+
724
+ pipe.set_scheduler("sample_euler")
725
+ generator = torch.Generator(device="cuda").manual_seed(seed)
726
+ image = pipe(prompt, generator=generator, num_inference_steps=50).images[0]
727
+ ```
728
+
729
+ ![diffusers_euler](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/k_diffusion/astronaut_euler_k_diffusion.png)
730
+
731
+ ### Checkpoint Merger Pipeline
732
+ Based on the AUTOMATIC1111/webui for checkpoint merging. This is a custom pipeline that merges upto 3 pretrained model checkpoints as long as they are in the HuggingFace model_index.json format.
733
+
734
+ The checkpoint merging is currently memory intensive as it modifies the weights of a DiffusionPipeline object in place. Expect atleast 13GB RAM Usage on Kaggle GPU kernels and
735
+ on colab you might run out of the 12GB memory even while merging two checkpoints.
736
+
737
+ Usage:-
738
+ ```python
739
+ from diffusers import DiffusionPipeline
740
+
741
+ #Return a CheckpointMergerPipeline class that allows you to merge checkpoints.
742
+ #The checkpoint passed here is ignored. But still pass one of the checkpoints you plan to
743
+ #merge for convenience
744
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger")
745
+
746
+ #There are multiple possible scenarios:
747
+ #The pipeline with the merged checkpoints is returned in all the scenarios
748
+
749
+ #Compatible checkpoints a.k.a matched model_index.json files. Ignores the meta attributes in model_index.json during comparision.( attrs with _ as prefix )
750
+ merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","CompVis/stable-diffusion-v1-2"], interp = "sigmoid", alpha = 0.4)
751
+
752
+ #Incompatible checkpoints in model_index.json but merge might be possible. Use force = True to ignore model_index.json compatibility
753
+ merged_pipe_1 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion"], force = True, interp = "sigmoid", alpha = 0.4)
754
+
755
+ #Three checkpoint merging. Only "add_difference" method actually works on all three checkpoints. Using any other options will ignore the 3rd checkpoint.
756
+ merged_pipe_2 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion","prompthero/openjourney"], force = True, interp = "add_difference", alpha = 0.4)
757
+
758
+ prompt = "An astronaut riding a horse on Mars"
759
+
760
+ image = merged_pipe(prompt).images[0]
761
+
762
+ ```
763
+ Some examples along with the merge details:
764
+
765
+ 1. "CompVis/stable-diffusion-v1-4" + "hakurei/waifu-diffusion" ; Sigmoid interpolation; alpha = 0.8
766
+
767
+ ![Stable plus Waifu Sigmoid 0.8](https://huggingface.co/datasets/NagaSaiAbhinay/CheckpointMergerSamples/resolve/main/stability_v1_4_waifu_sig_0.8.png)
768
+
769
+ 2. "hakurei/waifu-diffusion" + "prompthero/openjourney" ; Inverse Sigmoid interpolation; alpha = 0.8
770
+
771
+ ![Stable plus Waifu Sigmoid 0.8](https://huggingface.co/datasets/NagaSaiAbhinay/CheckpointMergerSamples/resolve/main/waifu_openjourney_inv_sig_0.8.png)
772
+
773
+
774
+ 3. "CompVis/stable-diffusion-v1-4" + "hakurei/waifu-diffusion" + "prompthero/openjourney"; Add Difference interpolation; alpha = 0.5
775
+
776
+ ![Stable plus Waifu plus openjourney add_diff 0.5](https://huggingface.co/datasets/NagaSaiAbhinay/CheckpointMergerSamples/resolve/main/stable_waifu_openjourney_add_diff_0.5.png)
v0.10.1/bit_diffusion.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+
5
+ from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, UNet2DConditionModel
6
+ from diffusers.pipeline_utils import ImagePipelineOutput
7
+ from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
8
+ from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
9
+ from einops import rearrange, reduce
10
+
11
+
12
+ BITS = 8
13
+
14
+
15
+ # convert to bit representations and back taken from https://github.com/lucidrains/bit-diffusion/blob/main/bit_diffusion/bit_diffusion.py
16
+ def decimal_to_bits(x, bits=BITS):
17
+ """expects image tensor ranging from 0 to 1, outputs bit tensor ranging from -1 to 1"""
18
+ device = x.device
19
+
20
+ x = (x * 255).int().clamp(0, 255)
21
+
22
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device)
23
+ mask = rearrange(mask, "d -> d 1 1")
24
+ x = rearrange(x, "b c h w -> b c 1 h w")
25
+
26
+ bits = ((x & mask) != 0).float()
27
+ bits = rearrange(bits, "b c d h w -> b (c d) h w")
28
+ bits = bits * 2 - 1
29
+ return bits
30
+
31
+
32
+ def bits_to_decimal(x, bits=BITS):
33
+ """expects bits from -1 to 1, outputs image tensor from 0 to 1"""
34
+ device = x.device
35
+
36
+ x = (x > 0).int()
37
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device, dtype=torch.int32)
38
+
39
+ mask = rearrange(mask, "d -> d 1 1")
40
+ x = rearrange(x, "b (c d) h w -> b c d h w", d=8)
41
+ dec = reduce(x * mask, "b c d h w -> b c h w", "sum")
42
+ return (dec / 255).clamp(0.0, 1.0)
43
+
44
+
45
+ # modified scheduler step functions for clamping the predicted x_0 between -bit_scale and +bit_scale
46
+ def ddim_bit_scheduler_step(
47
+ self,
48
+ model_output: torch.FloatTensor,
49
+ timestep: int,
50
+ sample: torch.FloatTensor,
51
+ eta: float = 0.0,
52
+ use_clipped_model_output: bool = True,
53
+ generator=None,
54
+ return_dict: bool = True,
55
+ ) -> Union[DDIMSchedulerOutput, Tuple]:
56
+ """
57
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
58
+ process from the learned model outputs (most often the predicted noise).
59
+ Args:
60
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
61
+ timestep (`int`): current discrete timestep in the diffusion chain.
62
+ sample (`torch.FloatTensor`):
63
+ current instance of sample being created by diffusion process.
64
+ eta (`float`): weight of noise for added noise in diffusion step.
65
+ use_clipped_model_output (`bool`): TODO
66
+ generator: random number generator.
67
+ return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class
68
+ Returns:
69
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:
70
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
71
+ returning a tuple, the first element is the sample tensor.
72
+ """
73
+ if self.num_inference_steps is None:
74
+ raise ValueError(
75
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
76
+ )
77
+
78
+ # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
79
+ # Ideally, read DDIM paper in-detail understanding
80
+
81
+ # Notation (<variable name> -> <name in paper>
82
+ # - pred_noise_t -> e_theta(x_t, t)
83
+ # - pred_original_sample -> f_theta(x_t, t) or x_0
84
+ # - std_dev_t -> sigma_t
85
+ # - eta -> η
86
+ # - pred_sample_direction -> "direction pointing to x_t"
87
+ # - pred_prev_sample -> "x_t-1"
88
+
89
+ # 1. get previous step value (=t-1)
90
+ prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
91
+
92
+ # 2. compute alphas, betas
93
+ alpha_prod_t = self.alphas_cumprod[timestep]
94
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
95
+
96
+ beta_prod_t = 1 - alpha_prod_t
97
+
98
+ # 3. compute predicted original sample from predicted noise also called
99
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
100
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
101
+
102
+ # 4. Clip "predicted x_0"
103
+ scale = self.bit_scale
104
+ if self.config.clip_sample:
105
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
106
+
107
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
108
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
109
+ variance = self._get_variance(timestep, prev_timestep)
110
+ std_dev_t = eta * variance ** (0.5)
111
+
112
+ if use_clipped_model_output:
113
+ # the model_output is always re-derived from the clipped x_0 in Glide
114
+ model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
115
+
116
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
117
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output
118
+
119
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
120
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
121
+
122
+ if eta > 0:
123
+ # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
124
+ device = model_output.device if torch.is_tensor(model_output) else "cpu"
125
+ noise = torch.randn(model_output.shape, dtype=model_output.dtype, generator=generator).to(device)
126
+ variance = self._get_variance(timestep, prev_timestep) ** (0.5) * eta * noise
127
+
128
+ prev_sample = prev_sample + variance
129
+
130
+ if not return_dict:
131
+ return (prev_sample,)
132
+
133
+ return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
134
+
135
+
136
+ def ddpm_bit_scheduler_step(
137
+ self,
138
+ model_output: torch.FloatTensor,
139
+ timestep: int,
140
+ sample: torch.FloatTensor,
141
+ prediction_type="epsilon",
142
+ generator=None,
143
+ return_dict: bool = True,
144
+ ) -> Union[DDPMSchedulerOutput, Tuple]:
145
+ """
146
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
147
+ process from the learned model outputs (most often the predicted noise).
148
+ Args:
149
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
150
+ timestep (`int`): current discrete timestep in the diffusion chain.
151
+ sample (`torch.FloatTensor`):
152
+ current instance of sample being created by diffusion process.
153
+ prediction_type (`str`, default `epsilon`):
154
+ indicates whether the model predicts the noise (epsilon), or the samples (`sample`).
155
+ generator: random number generator.
156
+ return_dict (`bool`): option for returning tuple rather than DDPMSchedulerOutput class
157
+ Returns:
158
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] or `tuple`:
159
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
160
+ returning a tuple, the first element is the sample tensor.
161
+ """
162
+ t = timestep
163
+
164
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
165
+ model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1)
166
+ else:
167
+ predicted_variance = None
168
+
169
+ # 1. compute alphas, betas
170
+ alpha_prod_t = self.alphas_cumprod[t]
171
+ alpha_prod_t_prev = self.alphas_cumprod[t - 1] if t > 0 else self.one
172
+ beta_prod_t = 1 - alpha_prod_t
173
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
174
+
175
+ # 2. compute predicted original sample from predicted noise also called
176
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
177
+ if prediction_type == "epsilon":
178
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
179
+ elif prediction_type == "sample":
180
+ pred_original_sample = model_output
181
+ else:
182
+ raise ValueError(f"Unsupported prediction_type {prediction_type}.")
183
+
184
+ # 3. Clip "predicted x_0"
185
+ scale = self.bit_scale
186
+ if self.config.clip_sample:
187
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
188
+
189
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
190
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
191
+ pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * self.betas[t]) / beta_prod_t
192
+ current_sample_coeff = self.alphas[t] ** (0.5) * beta_prod_t_prev / beta_prod_t
193
+
194
+ # 5. Compute predicted previous sample µ_t
195
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
196
+ pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
197
+
198
+ # 6. Add noise
199
+ variance = 0
200
+ if t > 0:
201
+ noise = torch.randn(
202
+ model_output.size(), dtype=model_output.dtype, layout=model_output.layout, generator=generator
203
+ ).to(model_output.device)
204
+ variance = (self._get_variance(t, predicted_variance=predicted_variance) ** 0.5) * noise
205
+
206
+ pred_prev_sample = pred_prev_sample + variance
207
+
208
+ if not return_dict:
209
+ return (pred_prev_sample,)
210
+
211
+ return DDPMSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
212
+
213
+
214
+ class BitDiffusion(DiffusionPipeline):
215
+ def __init__(
216
+ self,
217
+ unet: UNet2DConditionModel,
218
+ scheduler: Union[DDIMScheduler, DDPMScheduler],
219
+ bit_scale: Optional[float] = 1.0,
220
+ ):
221
+ super().__init__()
222
+ self.bit_scale = bit_scale
223
+ self.scheduler.step = (
224
+ ddim_bit_scheduler_step if isinstance(scheduler, DDIMScheduler) else ddpm_bit_scheduler_step
225
+ )
226
+
227
+ self.register_modules(unet=unet, scheduler=scheduler)
228
+
229
+ @torch.no_grad()
230
+ def __call__(
231
+ self,
232
+ height: Optional[int] = 256,
233
+ width: Optional[int] = 256,
234
+ num_inference_steps: Optional[int] = 50,
235
+ generator: Optional[torch.Generator] = None,
236
+ batch_size: Optional[int] = 1,
237
+ output_type: Optional[str] = "pil",
238
+ return_dict: bool = True,
239
+ **kwargs,
240
+ ) -> Union[Tuple, ImagePipelineOutput]:
241
+ latents = torch.randn(
242
+ (batch_size, self.unet.in_channels, height, width),
243
+ generator=generator,
244
+ )
245
+ latents = decimal_to_bits(latents) * self.bit_scale
246
+ latents = latents.to(self.device)
247
+
248
+ self.scheduler.set_timesteps(num_inference_steps)
249
+
250
+ for t in self.progress_bar(self.scheduler.timesteps):
251
+ # predict the noise residual
252
+ noise_pred = self.unet(latents, t).sample
253
+
254
+ # compute the previous noisy sample x_t -> x_t-1
255
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
256
+
257
+ image = bits_to_decimal(latents)
258
+
259
+ if output_type == "pil":
260
+ image = self.numpy_to_pil(image)
261
+
262
+ if not return_dict:
263
+ return (image,)
264
+
265
+ return ImagePipelineOutput(images=image)
v0.10.1/checkpoint_merger.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from typing import Dict, List, Union
4
+
5
+ import torch
6
+
7
+ from diffusers import DiffusionPipeline, __version__
8
+ from diffusers.pipeline_utils import (
9
+ CONFIG_NAME,
10
+ DIFFUSERS_CACHE,
11
+ ONNX_WEIGHTS_NAME,
12
+ SCHEDULER_CONFIG_NAME,
13
+ WEIGHTS_NAME,
14
+ )
15
+ from huggingface_hub import snapshot_download
16
+
17
+
18
+ class CheckpointMergerPipeline(DiffusionPipeline):
19
+ """
20
+ A class that that supports merging diffusion models based on the discussion here:
21
+ https://github.com/huggingface/diffusers/issues/877
22
+
23
+ Example usage:-
24
+
25
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger.py")
26
+
27
+ merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","prompthero/openjourney"], interp = 'inv_sigmoid', alpha = 0.8, force = True)
28
+
29
+ merged_pipe.to('cuda')
30
+
31
+ prompt = "An astronaut riding a unicycle on Mars"
32
+
33
+ results = merged_pipe(prompt)
34
+
35
+ ## For more details, see the docstring for the merge method.
36
+
37
+ """
38
+
39
+ def __init__(self):
40
+ super().__init__()
41
+
42
+ def _compare_model_configs(self, dict0, dict1):
43
+ if dict0 == dict1:
44
+ return True
45
+ else:
46
+ config0, meta_keys0 = self._remove_meta_keys(dict0)
47
+ config1, meta_keys1 = self._remove_meta_keys(dict1)
48
+ if config0 == config1:
49
+ print(f"Warning !: Mismatch in keys {meta_keys0} and {meta_keys1}.")
50
+ return True
51
+ return False
52
+
53
+ def _remove_meta_keys(self, config_dict: Dict):
54
+ meta_keys = []
55
+ temp_dict = config_dict.copy()
56
+ for key in config_dict.keys():
57
+ if key.startswith("_"):
58
+ temp_dict.pop(key)
59
+ meta_keys.append(key)
60
+ return (temp_dict, meta_keys)
61
+
62
+ @torch.no_grad()
63
+ def merge(self, pretrained_model_name_or_path_list: List[Union[str, os.PathLike]], **kwargs):
64
+ """
65
+ Returns a new pipeline object of the class 'DiffusionPipeline' with the merged checkpoints(weights) of the models passed
66
+ in the argument 'pretrained_model_name_or_path_list' as a list.
67
+
68
+ Parameters:
69
+ -----------
70
+ pretrained_model_name_or_path_list : A list of valid pretrained model names in the HuggingFace hub or paths to locally stored models in the HuggingFace format.
71
+
72
+ **kwargs:
73
+ Supports all the default DiffusionPipeline.get_config_dict kwargs viz..
74
+
75
+ cache_dir, resume_download, force_download, proxies, local_files_only, use_auth_token, revision, torch_dtype, device_map.
76
+
77
+ alpha - The interpolation parameter. Ranges from 0 to 1. It affects the ratio in which the checkpoints are merged. A 0.8 alpha
78
+ would mean that the first model checkpoints would affect the final result far less than an alpha of 0.2
79
+
80
+ interp - The interpolation method to use for the merging. Supports "sigmoid", "inv_sigmoid", "add_difference" and None.
81
+ Passing None uses the default interpolation which is weighted sum interpolation. For merging three checkpoints, only "add_difference" is supported.
82
+
83
+ force - Whether to ignore mismatch in model_config.json for the current models. Defaults to False.
84
+
85
+ """
86
+ # Default kwargs from DiffusionPipeline
87
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
88
+ resume_download = kwargs.pop("resume_download", False)
89
+ force_download = kwargs.pop("force_download", False)
90
+ proxies = kwargs.pop("proxies", None)
91
+ local_files_only = kwargs.pop("local_files_only", False)
92
+ use_auth_token = kwargs.pop("use_auth_token", None)
93
+ revision = kwargs.pop("revision", None)
94
+ torch_dtype = kwargs.pop("torch_dtype", None)
95
+ device_map = kwargs.pop("device_map", None)
96
+
97
+ alpha = kwargs.pop("alpha", 0.5)
98
+ interp = kwargs.pop("interp", None)
99
+
100
+ print("Recieved list", pretrained_model_name_or_path_list)
101
+
102
+ checkpoint_count = len(pretrained_model_name_or_path_list)
103
+ # Ignore result from model_index_json comparision of the two checkpoints
104
+ force = kwargs.pop("force", False)
105
+
106
+ # If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
107
+ if checkpoint_count > 3 or checkpoint_count < 2:
108
+ raise ValueError(
109
+ "Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being"
110
+ " passed."
111
+ )
112
+
113
+ print("Received the right number of checkpoints")
114
+ # chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
115
+ # chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None
116
+
117
+ # Validate that the checkpoints can be merged
118
+ # Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
119
+ config_dicts = []
120
+ for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
121
+ if not os.path.isdir(pretrained_model_name_or_path):
122
+ config_dict = DiffusionPipeline.get_config_dict(
123
+ pretrained_model_name_or_path,
124
+ cache_dir=cache_dir,
125
+ resume_download=resume_download,
126
+ force_download=force_download,
127
+ proxies=proxies,
128
+ local_files_only=local_files_only,
129
+ use_auth_token=use_auth_token,
130
+ revision=revision,
131
+ )
132
+ config_dicts.append(config_dict)
133
+
134
+ comparison_result = True
135
+ for idx in range(1, len(config_dicts)):
136
+ comparison_result &= self._compare_model_configs(config_dicts[idx - 1], config_dicts[idx])
137
+ if not force and comparison_result is False:
138
+ raise ValueError("Incompatible checkpoints. Please check model_index.json for the models.")
139
+ print(config_dicts[0], config_dicts[1])
140
+ print("Compatible model_index.json files found")
141
+ # Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
142
+ cached_folders = []
143
+ for pretrained_model_name_or_path, config_dict in zip(pretrained_model_name_or_path_list, config_dicts):
144
+ folder_names = [k for k in config_dict.keys() if not k.startswith("_")]
145
+ allow_patterns = [os.path.join(k, "*") for k in folder_names]
146
+ allow_patterns += [
147
+ WEIGHTS_NAME,
148
+ SCHEDULER_CONFIG_NAME,
149
+ CONFIG_NAME,
150
+ ONNX_WEIGHTS_NAME,
151
+ DiffusionPipeline.config_name,
152
+ ]
153
+ requested_pipeline_class = config_dict.get("_class_name")
154
+ user_agent = {"diffusers": __version__, "pipeline_class": requested_pipeline_class}
155
+
156
+ cached_folder = snapshot_download(
157
+ pretrained_model_name_or_path,
158
+ cache_dir=cache_dir,
159
+ resume_download=resume_download,
160
+ proxies=proxies,
161
+ local_files_only=local_files_only,
162
+ use_auth_token=use_auth_token,
163
+ revision=revision,
164
+ allow_patterns=allow_patterns,
165
+ user_agent=user_agent,
166
+ )
167
+ print("Cached Folder", cached_folder)
168
+ cached_folders.append(cached_folder)
169
+
170
+ # Step 3:-
171
+ # Load the first checkpoint as a diffusion pipeline and modify it's module state_dict in place
172
+ final_pipe = DiffusionPipeline.from_pretrained(
173
+ cached_folders[0], torch_dtype=torch_dtype, device_map=device_map
174
+ )
175
+
176
+ checkpoint_path_2 = None
177
+ if len(cached_folders) > 2:
178
+ checkpoint_path_2 = os.path.join(cached_folders[2])
179
+
180
+ if interp == "sigmoid":
181
+ theta_func = CheckpointMergerPipeline.sigmoid
182
+ elif interp == "inv_sigmoid":
183
+ theta_func = CheckpointMergerPipeline.inv_sigmoid
184
+ elif interp == "add_diff":
185
+ theta_func = CheckpointMergerPipeline.add_difference
186
+ else:
187
+ theta_func = CheckpointMergerPipeline.weighted_sum
188
+
189
+ # Find each module's state dict.
190
+ for attr in final_pipe.config.keys():
191
+ if not attr.startswith("_"):
192
+ checkpoint_path_1 = os.path.join(cached_folders[1], attr)
193
+ if os.path.exists(checkpoint_path_1):
194
+ files = glob.glob(os.path.join(checkpoint_path_1, "*.bin"))
195
+ checkpoint_path_1 = files[0] if len(files) > 0 else None
196
+ if checkpoint_path_2 is not None and os.path.exists(checkpoint_path_2):
197
+ files = glob.glob(os.path.join(checkpoint_path_2, "*.bin"))
198
+ checkpoint_path_2 = files[0] if len(files) > 0 else None
199
+ # For an attr if both checkpoint_path_1 and 2 are None, ignore.
200
+ # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
201
+ if checkpoint_path_1 is None and checkpoint_path_2 is None:
202
+ print("SKIPPING ATTR ", attr)
203
+ continue
204
+ try:
205
+ module = getattr(final_pipe, attr)
206
+ theta_0 = getattr(module, "state_dict")
207
+ theta_0 = theta_0()
208
+
209
+ update_theta_0 = getattr(module, "load_state_dict")
210
+ theta_1 = torch.load(checkpoint_path_1)
211
+
212
+ theta_2 = torch.load(checkpoint_path_2) if checkpoint_path_2 else None
213
+
214
+ if not theta_0.keys() == theta_1.keys():
215
+ print("SKIPPING ATTR ", attr, " DUE TO MISMATCH")
216
+ continue
217
+ if theta_2 and not theta_1.keys() == theta_2.keys():
218
+ print("SKIPPING ATTR ", attr, " DUE TO MISMATCH")
219
+ except:
220
+ print("SKIPPING ATTR ", attr)
221
+ continue
222
+ print("Found dicts for")
223
+ print(attr)
224
+ print(checkpoint_path_1)
225
+ print(checkpoint_path_2)
226
+
227
+ for key in theta_0.keys():
228
+ if theta_2:
229
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], theta_2[key], alpha)
230
+ else:
231
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], None, alpha)
232
+
233
+ del theta_1
234
+ del theta_2
235
+ update_theta_0(theta_0)
236
+
237
+ del theta_0
238
+ print("Diffusion pipeline successfully updated with merged weights")
239
+
240
+ return final_pipe
241
+
242
+ @staticmethod
243
+ def weighted_sum(theta0, theta1, theta2, alpha):
244
+ return ((1 - alpha) * theta0) + (alpha * theta1)
245
+
246
+ # Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
247
+ @staticmethod
248
+ def sigmoid(theta0, theta1, theta2, alpha):
249
+ alpha = alpha * alpha * (3 - (2 * alpha))
250
+ return theta0 + ((theta1 - theta0) * alpha)
251
+
252
+ # Inverse Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
253
+ @staticmethod
254
+ def inv_sigmoid(theta0, theta1, theta2, alpha):
255
+ import math
256
+
257
+ alpha = 0.5 - math.sin(math.asin(1.0 - 2.0 * alpha) / 3.0)
258
+ return theta0 + ((theta1 - theta0) * alpha)
259
+
260
+ @staticmethod
261
+ def add_difference(theta0, theta1, theta2, alpha):
262
+ return theta0 + (theta1 - theta2) * (1.0 - alpha)
v0.10.1/clip_guided_stable_diffusion.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ from diffusers import (
9
+ AutoencoderKL,
10
+ DDIMScheduler,
11
+ DiffusionPipeline,
12
+ LMSDiscreteScheduler,
13
+ PNDMScheduler,
14
+ UNet2DConditionModel,
15
+ )
16
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
17
+ from torchvision import transforms
18
+ from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
19
+
20
+
21
+ class MakeCutouts(nn.Module):
22
+ def __init__(self, cut_size, cut_power=1.0):
23
+ super().__init__()
24
+
25
+ self.cut_size = cut_size
26
+ self.cut_power = cut_power
27
+
28
+ def forward(self, pixel_values, num_cutouts):
29
+ sideY, sideX = pixel_values.shape[2:4]
30
+ max_size = min(sideX, sideY)
31
+ min_size = min(sideX, sideY, self.cut_size)
32
+ cutouts = []
33
+ for _ in range(num_cutouts):
34
+ size = int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size)
35
+ offsetx = torch.randint(0, sideX - size + 1, ())
36
+ offsety = torch.randint(0, sideY - size + 1, ())
37
+ cutout = pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
38
+ cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
39
+ return torch.cat(cutouts)
40
+
41
+
42
+ def spherical_dist_loss(x, y):
43
+ x = F.normalize(x, dim=-1)
44
+ y = F.normalize(y, dim=-1)
45
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
46
+
47
+
48
+ def set_requires_grad(model, value):
49
+ for param in model.parameters():
50
+ param.requires_grad = value
51
+
52
+
53
+ class CLIPGuidedStableDiffusion(DiffusionPipeline):
54
+ """CLIP guided stable diffusion based on the amazing repo by @crowsonkb and @Jack000
55
+ - https://github.com/Jack000/glid-3-xl
56
+ - https://github.dev/crowsonkb/k-diffusion
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ vae: AutoencoderKL,
62
+ text_encoder: CLIPTextModel,
63
+ clip_model: CLIPModel,
64
+ tokenizer: CLIPTokenizer,
65
+ unet: UNet2DConditionModel,
66
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler],
67
+ feature_extractor: CLIPFeatureExtractor,
68
+ ):
69
+ super().__init__()
70
+ self.register_modules(
71
+ vae=vae,
72
+ text_encoder=text_encoder,
73
+ clip_model=clip_model,
74
+ tokenizer=tokenizer,
75
+ unet=unet,
76
+ scheduler=scheduler,
77
+ feature_extractor=feature_extractor,
78
+ )
79
+
80
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
81
+ cut_out_size = (
82
+ feature_extractor.size
83
+ if isinstance(feature_extractor.size, int)
84
+ else feature_extractor.size["shortest_edge"]
85
+ )
86
+ self.make_cutouts = MakeCutouts(cut_out_size)
87
+
88
+ set_requires_grad(self.text_encoder, False)
89
+ set_requires_grad(self.clip_model, False)
90
+
91
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
92
+ if slice_size == "auto":
93
+ # half the attention head size is usually a good trade-off between
94
+ # speed and memory
95
+ slice_size = self.unet.config.attention_head_dim // 2
96
+ self.unet.set_attention_slice(slice_size)
97
+
98
+ def disable_attention_slicing(self):
99
+ self.enable_attention_slicing(None)
100
+
101
+ def freeze_vae(self):
102
+ set_requires_grad(self.vae, False)
103
+
104
+ def unfreeze_vae(self):
105
+ set_requires_grad(self.vae, True)
106
+
107
+ def freeze_unet(self):
108
+ set_requires_grad(self.unet, False)
109
+
110
+ def unfreeze_unet(self):
111
+ set_requires_grad(self.unet, True)
112
+
113
+ @torch.enable_grad()
114
+ def cond_fn(
115
+ self,
116
+ latents,
117
+ timestep,
118
+ index,
119
+ text_embeddings,
120
+ noise_pred_original,
121
+ text_embeddings_clip,
122
+ clip_guidance_scale,
123
+ num_cutouts,
124
+ use_cutouts=True,
125
+ ):
126
+ latents = latents.detach().requires_grad_()
127
+
128
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
129
+ sigma = self.scheduler.sigmas[index]
130
+ # the model input needs to be scaled to match the continuous ODE formulation in K-LMS
131
+ latent_model_input = latents / ((sigma**2 + 1) ** 0.5)
132
+ else:
133
+ latent_model_input = latents
134
+
135
+ # predict the noise residual
136
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
137
+
138
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler)):
139
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
140
+ beta_prod_t = 1 - alpha_prod_t
141
+ # compute predicted original sample from predicted noise also called
142
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
143
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
144
+
145
+ fac = torch.sqrt(beta_prod_t)
146
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
147
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
148
+ sigma = self.scheduler.sigmas[index]
149
+ sample = latents - sigma * noise_pred
150
+ else:
151
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
152
+
153
+ sample = 1 / 0.18215 * sample
154
+ image = self.vae.decode(sample).sample
155
+ image = (image / 2 + 0.5).clamp(0, 1)
156
+
157
+ if use_cutouts:
158
+ image = self.make_cutouts(image, num_cutouts)
159
+ else:
160
+ image = transforms.Resize(self.feature_extractor.size)(image)
161
+ image = self.normalize(image).to(latents.dtype)
162
+
163
+ image_embeddings_clip = self.clip_model.get_image_features(image)
164
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
165
+
166
+ if use_cutouts:
167
+ dists = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip)
168
+ dists = dists.view([num_cutouts, sample.shape[0], -1])
169
+ loss = dists.sum(2).mean(0).sum() * clip_guidance_scale
170
+ else:
171
+ loss = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip).mean() * clip_guidance_scale
172
+
173
+ grads = -torch.autograd.grad(loss, latents)[0]
174
+
175
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
176
+ latents = latents.detach() + grads * (sigma**2)
177
+ noise_pred = noise_pred_original
178
+ else:
179
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
180
+ return noise_pred, latents
181
+
182
+ @torch.no_grad()
183
+ def __call__(
184
+ self,
185
+ prompt: Union[str, List[str]],
186
+ height: Optional[int] = 512,
187
+ width: Optional[int] = 512,
188
+ num_inference_steps: Optional[int] = 50,
189
+ guidance_scale: Optional[float] = 7.5,
190
+ num_images_per_prompt: Optional[int] = 1,
191
+ eta: float = 0.0,
192
+ clip_guidance_scale: Optional[float] = 100,
193
+ clip_prompt: Optional[Union[str, List[str]]] = None,
194
+ num_cutouts: Optional[int] = 4,
195
+ use_cutouts: Optional[bool] = True,
196
+ generator: Optional[torch.Generator] = None,
197
+ latents: Optional[torch.FloatTensor] = None,
198
+ output_type: Optional[str] = "pil",
199
+ return_dict: bool = True,
200
+ ):
201
+ if isinstance(prompt, str):
202
+ batch_size = 1
203
+ elif isinstance(prompt, list):
204
+ batch_size = len(prompt)
205
+ else:
206
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
207
+
208
+ if height % 8 != 0 or width % 8 != 0:
209
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
210
+
211
+ # get prompt text embeddings
212
+ text_input = self.tokenizer(
213
+ prompt,
214
+ padding="max_length",
215
+ max_length=self.tokenizer.model_max_length,
216
+ truncation=True,
217
+ return_tensors="pt",
218
+ )
219
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
220
+ # duplicate text embeddings for each generation per prompt
221
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
222
+
223
+ if clip_guidance_scale > 0:
224
+ if clip_prompt is not None:
225
+ clip_text_input = self.tokenizer(
226
+ clip_prompt,
227
+ padding="max_length",
228
+ max_length=self.tokenizer.model_max_length,
229
+ truncation=True,
230
+ return_tensors="pt",
231
+ ).input_ids.to(self.device)
232
+ else:
233
+ clip_text_input = text_input.input_ids.to(self.device)
234
+ text_embeddings_clip = self.clip_model.get_text_features(clip_text_input)
235
+ text_embeddings_clip = text_embeddings_clip / text_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
236
+ # duplicate text embeddings clip for each generation per prompt
237
+ text_embeddings_clip = text_embeddings_clip.repeat_interleave(num_images_per_prompt, dim=0)
238
+
239
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
240
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
241
+ # corresponds to doing no classifier free guidance.
242
+ do_classifier_free_guidance = guidance_scale > 1.0
243
+ # get unconditional embeddings for classifier free guidance
244
+ if do_classifier_free_guidance:
245
+ max_length = text_input.input_ids.shape[-1]
246
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
247
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
248
+ # duplicate unconditional embeddings for each generation per prompt
249
+ uncond_embeddings = uncond_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
250
+
251
+ # For classifier free guidance, we need to do two forward passes.
252
+ # Here we concatenate the unconditional and text embeddings into a single batch
253
+ # to avoid doing two forward passes
254
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
255
+
256
+ # get the initial random noise unless the user supplied it
257
+
258
+ # Unlike in other pipelines, latents need to be generated in the target device
259
+ # for 1-to-1 results reproducibility with the CompVis implementation.
260
+ # However this currently doesn't work in `mps`.
261
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
262
+ latents_dtype = text_embeddings.dtype
263
+ if latents is None:
264
+ if self.device.type == "mps":
265
+ # randn does not work reproducibly on mps
266
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
267
+ self.device
268
+ )
269
+ else:
270
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
271
+ else:
272
+ if latents.shape != latents_shape:
273
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
274
+ latents = latents.to(self.device)
275
+
276
+ # set timesteps
277
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
278
+ extra_set_kwargs = {}
279
+ if accepts_offset:
280
+ extra_set_kwargs["offset"] = 1
281
+
282
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
283
+
284
+ # Some schedulers like PNDM have timesteps as arrays
285
+ # It's more optimized to move all timesteps to correct device beforehand
286
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
287
+
288
+ # scale the initial noise by the standard deviation required by the scheduler
289
+ latents = latents * self.scheduler.init_noise_sigma
290
+
291
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
292
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
293
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
294
+ # and should be between [0, 1]
295
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
296
+ extra_step_kwargs = {}
297
+ if accepts_eta:
298
+ extra_step_kwargs["eta"] = eta
299
+
300
+ # check if the scheduler accepts generator
301
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
302
+ if accepts_generator:
303
+ extra_step_kwargs["generator"] = generator
304
+
305
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
306
+ # expand the latents if we are doing classifier free guidance
307
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
308
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
309
+
310
+ # predict the noise residual
311
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
312
+
313
+ # perform classifier free guidance
314
+ if do_classifier_free_guidance:
315
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
316
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
317
+
318
+ # perform clip guidance
319
+ if clip_guidance_scale > 0:
320
+ text_embeddings_for_guidance = (
321
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
322
+ )
323
+ noise_pred, latents = self.cond_fn(
324
+ latents,
325
+ t,
326
+ i,
327
+ text_embeddings_for_guidance,
328
+ noise_pred,
329
+ text_embeddings_clip,
330
+ clip_guidance_scale,
331
+ num_cutouts,
332
+ use_cutouts,
333
+ )
334
+
335
+ # compute the previous noisy sample x_t -> x_t-1
336
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
337
+
338
+ # scale and decode the image latents with vae
339
+ latents = 1 / 0.18215 * latents
340
+ image = self.vae.decode(latents).sample
341
+
342
+ image = (image / 2 + 0.5).clamp(0, 1)
343
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
344
+
345
+ if output_type == "pil":
346
+ image = self.numpy_to_pil(image)
347
+
348
+ if not return_dict:
349
+ return (image, None)
350
+
351
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.10.1/composable_stable_diffusion.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modified based on diffusion library from Huggingface: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
3
+ """
4
+ import inspect
5
+ import warnings
6
+ from typing import List, Optional, Union
7
+
8
+ import torch
9
+
10
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
11
+ from diffusers.pipeline_utils import DiffusionPipeline
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
15
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
16
+
17
+
18
+ class ComposableStableDiffusionPipeline(DiffusionPipeline):
19
+ r"""
20
+ Pipeline for text-to-image generation using Stable Diffusion.
21
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
22
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
23
+ Args:
24
+ vae ([`AutoencoderKL`]):
25
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
26
+ text_encoder ([`CLIPTextModel`]):
27
+ Frozen text-encoder. Stable Diffusion uses the text portion of
28
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
29
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
30
+ tokenizer (`CLIPTokenizer`):
31
+ Tokenizer of class
32
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
33
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
34
+ scheduler ([`SchedulerMixin`]):
35
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
36
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
37
+ safety_checker ([`StableDiffusionSafetyChecker`]):
38
+ Classification module that estimates whether generated images could be considered offsensive or harmful.
39
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
40
+ feature_extractor ([`CLIPFeatureExtractor`]):
41
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ vae: AutoencoderKL,
47
+ text_encoder: CLIPTextModel,
48
+ tokenizer: CLIPTokenizer,
49
+ unet: UNet2DConditionModel,
50
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
51
+ safety_checker: StableDiffusionSafetyChecker,
52
+ feature_extractor: CLIPFeatureExtractor,
53
+ ):
54
+ super().__init__()
55
+ self.register_modules(
56
+ vae=vae,
57
+ text_encoder=text_encoder,
58
+ tokenizer=tokenizer,
59
+ unet=unet,
60
+ scheduler=scheduler,
61
+ safety_checker=safety_checker,
62
+ feature_extractor=feature_extractor,
63
+ )
64
+
65
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
66
+ r"""
67
+ Enable sliced attention computation.
68
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
69
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
70
+ Args:
71
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
72
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
73
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
74
+ `attention_head_dim` must be a multiple of `slice_size`.
75
+ """
76
+ if slice_size == "auto":
77
+ # half the attention head size is usually a good trade-off between
78
+ # speed and memory
79
+ slice_size = self.unet.config.attention_head_dim // 2
80
+ self.unet.set_attention_slice(slice_size)
81
+
82
+ def disable_attention_slicing(self):
83
+ r"""
84
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
85
+ back to computing attention in one step.
86
+ """
87
+ # set slice_size = `None` to disable `attention slicing`
88
+ self.enable_attention_slicing(None)
89
+
90
+ @torch.no_grad()
91
+ def __call__(
92
+ self,
93
+ prompt: Union[str, List[str]],
94
+ height: Optional[int] = 512,
95
+ width: Optional[int] = 512,
96
+ num_inference_steps: Optional[int] = 50,
97
+ guidance_scale: Optional[float] = 7.5,
98
+ eta: Optional[float] = 0.0,
99
+ generator: Optional[torch.Generator] = None,
100
+ latents: Optional[torch.FloatTensor] = None,
101
+ output_type: Optional[str] = "pil",
102
+ return_dict: bool = True,
103
+ weights: Optional[str] = "",
104
+ **kwargs,
105
+ ):
106
+ r"""
107
+ Function invoked when calling the pipeline for generation.
108
+ Args:
109
+ prompt (`str` or `List[str]`):
110
+ The prompt or prompts to guide the image generation.
111
+ height (`int`, *optional*, defaults to 512):
112
+ The height in pixels of the generated image.
113
+ width (`int`, *optional*, defaults to 512):
114
+ The width in pixels of the generated image.
115
+ num_inference_steps (`int`, *optional*, defaults to 50):
116
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
117
+ expense of slower inference.
118
+ guidance_scale (`float`, *optional*, defaults to 7.5):
119
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
120
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
121
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
122
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
123
+ usually at the expense of lower image quality.
124
+ eta (`float`, *optional*, defaults to 0.0):
125
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
126
+ [`schedulers.DDIMScheduler`], will be ignored for others.
127
+ generator (`torch.Generator`, *optional*):
128
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
129
+ deterministic.
130
+ latents (`torch.FloatTensor`, *optional*):
131
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
132
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
133
+ tensor will ge generated by sampling using the supplied random `generator`.
134
+ output_type (`str`, *optional*, defaults to `"pil"`):
135
+ The output format of the generate image. Choose between
136
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
137
+ return_dict (`bool`, *optional*, defaults to `True`):
138
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
139
+ plain tuple.
140
+ Returns:
141
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
142
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
143
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
144
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
145
+ (nsfw) content, according to the `safety_checker`.
146
+ """
147
+
148
+ if "torch_device" in kwargs:
149
+ device = kwargs.pop("torch_device")
150
+ warnings.warn(
151
+ "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
152
+ " Consider using `pipe.to(torch_device)` instead."
153
+ )
154
+
155
+ # Set device as before (to be removed in 0.3.0)
156
+ if device is None:
157
+ device = "cuda" if torch.cuda.is_available() else "cpu"
158
+ self.to(device)
159
+
160
+ if isinstance(prompt, str):
161
+ batch_size = 1
162
+ elif isinstance(prompt, list):
163
+ batch_size = len(prompt)
164
+ else:
165
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
166
+
167
+ if height % 8 != 0 or width % 8 != 0:
168
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
169
+
170
+ if "|" in prompt:
171
+ prompt = [x.strip() for x in prompt.split("|")]
172
+ print(f"composing {prompt}...")
173
+
174
+ # get prompt text embeddings
175
+ text_input = self.tokenizer(
176
+ prompt,
177
+ padding="max_length",
178
+ max_length=self.tokenizer.model_max_length,
179
+ truncation=True,
180
+ return_tensors="pt",
181
+ )
182
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
183
+
184
+ if not weights:
185
+ # specify weights for prompts (excluding the unconditional score)
186
+ print("using equal weights for all prompts...")
187
+ pos_weights = torch.tensor(
188
+ [1 / (text_embeddings.shape[0] - 1)] * (text_embeddings.shape[0] - 1), device=self.device
189
+ ).reshape(-1, 1, 1, 1)
190
+ neg_weights = torch.tensor([1.0], device=self.device).reshape(-1, 1, 1, 1)
191
+ mask = torch.tensor([False] + [True] * pos_weights.shape[0], dtype=torch.bool)
192
+ else:
193
+ # set prompt weight for each
194
+ num_prompts = len(prompt) if isinstance(prompt, list) else 1
195
+ weights = [float(w.strip()) for w in weights.split("|")]
196
+ if len(weights) < num_prompts:
197
+ weights.append(1.0)
198
+ weights = torch.tensor(weights, device=self.device)
199
+ assert len(weights) == text_embeddings.shape[0], "weights specified are not equal to the number of prompts"
200
+ pos_weights = []
201
+ neg_weights = []
202
+ mask = [] # first one is unconditional score
203
+ for w in weights:
204
+ if w > 0:
205
+ pos_weights.append(w)
206
+ mask.append(True)
207
+ else:
208
+ neg_weights.append(abs(w))
209
+ mask.append(False)
210
+ # normalize the weights
211
+ pos_weights = torch.tensor(pos_weights, device=self.device).reshape(-1, 1, 1, 1)
212
+ pos_weights = pos_weights / pos_weights.sum()
213
+ neg_weights = torch.tensor(neg_weights, device=self.device).reshape(-1, 1, 1, 1)
214
+ neg_weights = neg_weights / neg_weights.sum()
215
+ mask = torch.tensor(mask, device=self.device, dtype=torch.bool)
216
+
217
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
218
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
219
+ # corresponds to doing no classifier free guidance.
220
+ do_classifier_free_guidance = guidance_scale > 1.0
221
+ # get unconditional embeddings for classifier free guidance
222
+ if do_classifier_free_guidance:
223
+ max_length = text_input.input_ids.shape[-1]
224
+
225
+ if torch.all(mask):
226
+ # no negative prompts, so we use empty string as the negative prompt
227
+ uncond_input = self.tokenizer(
228
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
229
+ )
230
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
231
+
232
+ # For classifier free guidance, we need to do two forward passes.
233
+ # Here we concatenate the unconditional and text embeddings into a single batch
234
+ # to avoid doing two forward passes
235
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
236
+
237
+ # update negative weights
238
+ neg_weights = torch.tensor([1.0], device=self.device)
239
+ mask = torch.tensor([False] + mask.detach().tolist(), device=self.device, dtype=torch.bool)
240
+
241
+ # get the initial random noise unless the user supplied it
242
+
243
+ # Unlike in other pipelines, latents need to be generated in the target device
244
+ # for 1-to-1 results reproducibility with the CompVis implementation.
245
+ # However this currently doesn't work in `mps`.
246
+ latents_device = "cpu" if self.device.type == "mps" else self.device
247
+ latents_shape = (batch_size, self.unet.in_channels, height // 8, width // 8)
248
+ if latents is None:
249
+ latents = torch.randn(
250
+ latents_shape,
251
+ generator=generator,
252
+ device=latents_device,
253
+ )
254
+ else:
255
+ if latents.shape != latents_shape:
256
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
257
+ latents = latents.to(self.device)
258
+
259
+ # set timesteps
260
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
261
+ extra_set_kwargs = {}
262
+ if accepts_offset:
263
+ extra_set_kwargs["offset"] = 1
264
+
265
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
266
+
267
+ # if we use LMSDiscreteScheduler, let's make sure latents are multiplied by sigmas
268
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
269
+ latents = latents * self.scheduler.sigmas[0]
270
+
271
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
272
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
273
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
274
+ # and should be between [0, 1]
275
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
276
+ extra_step_kwargs = {}
277
+ if accepts_eta:
278
+ extra_step_kwargs["eta"] = eta
279
+
280
+ for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
281
+ # expand the latents if we are doing classifier free guidance
282
+ latent_model_input = (
283
+ torch.cat([latents] * text_embeddings.shape[0]) if do_classifier_free_guidance else latents
284
+ )
285
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
286
+ sigma = self.scheduler.sigmas[i]
287
+ # the model input needs to be scaled to match the continuous ODE formulation in K-LMS
288
+ latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5)
289
+
290
+ # reduce memory by predicting each score sequentially
291
+ noise_preds = []
292
+ # predict the noise residual
293
+ for latent_in, text_embedding_in in zip(
294
+ torch.chunk(latent_model_input, chunks=latent_model_input.shape[0], dim=0),
295
+ torch.chunk(text_embeddings, chunks=text_embeddings.shape[0], dim=0),
296
+ ):
297
+ noise_preds.append(self.unet(latent_in, t, encoder_hidden_states=text_embedding_in).sample)
298
+ noise_preds = torch.cat(noise_preds, dim=0)
299
+
300
+ # perform guidance
301
+ if do_classifier_free_guidance:
302
+ noise_pred_uncond = (noise_preds[~mask] * neg_weights).sum(dim=0, keepdims=True)
303
+ noise_pred_text = (noise_preds[mask] * pos_weights).sum(dim=0, keepdims=True)
304
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
305
+
306
+ # compute the previous noisy sample x_t -> x_t-1
307
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
308
+ latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs).prev_sample
309
+ else:
310
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
311
+
312
+ # scale and decode the image latents with vae
313
+ latents = 1 / 0.18215 * latents
314
+ image = self.vae.decode(latents).sample
315
+
316
+ image = (image / 2 + 0.5).clamp(0, 1)
317
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
318
+
319
+ # run safety checker
320
+ safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
321
+ image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_cheker_input.pixel_values)
322
+
323
+ if output_type == "pil":
324
+ image = self.numpy_to_pil(image)
325
+
326
+ if not return_dict:
327
+ return (image, has_nsfw_concept)
328
+
329
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.10.1/imagic_stable_diffusion.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modeled after the textual_inversion.py / train_dreambooth.py and the work
3
+ of justinpinkney here: https://github.com/justinpinkney/stable-diffusion/blob/main/notebooks/imagic.ipynb
4
+ """
5
+ import inspect
6
+ import warnings
7
+ from typing import List, Optional, Union
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+
13
+ import PIL
14
+ from accelerate import Accelerator
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.pipeline_utils import DiffusionPipeline
17
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
18
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
19
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
20
+ from diffusers.utils import deprecate, logging
21
+
22
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
23
+ from packaging import version
24
+ from tqdm.auto import tqdm
25
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
26
+
27
+
28
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
29
+ PIL_INTERPOLATION = {
30
+ "linear": PIL.Image.Resampling.BILINEAR,
31
+ "bilinear": PIL.Image.Resampling.BILINEAR,
32
+ "bicubic": PIL.Image.Resampling.BICUBIC,
33
+ "lanczos": PIL.Image.Resampling.LANCZOS,
34
+ "nearest": PIL.Image.Resampling.NEAREST,
35
+ }
36
+ else:
37
+ PIL_INTERPOLATION = {
38
+ "linear": PIL.Image.LINEAR,
39
+ "bilinear": PIL.Image.BILINEAR,
40
+ "bicubic": PIL.Image.BICUBIC,
41
+ "lanczos": PIL.Image.LANCZOS,
42
+ "nearest": PIL.Image.NEAREST,
43
+ }
44
+ # ------------------------------------------------------------------------------
45
+
46
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
47
+
48
+
49
+ def preprocess(image):
50
+ w, h = image.size
51
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
52
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
53
+ image = np.array(image).astype(np.float32) / 255.0
54
+ image = image[None].transpose(0, 3, 1, 2)
55
+ image = torch.from_numpy(image)
56
+ return 2.0 * image - 1.0
57
+
58
+
59
+ class ImagicStableDiffusionPipeline(DiffusionPipeline):
60
+ r"""
61
+ Pipeline for imagic image editing.
62
+ See paper here: https://arxiv.org/pdf/2210.09276.pdf
63
+
64
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
65
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
66
+ Args:
67
+ vae ([`AutoencoderKL`]):
68
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
69
+ text_encoder ([`CLIPTextModel`]):
70
+ Frozen text-encoder. Stable Diffusion uses the text portion of
71
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
72
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
73
+ tokenizer (`CLIPTokenizer`):
74
+ Tokenizer of class
75
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
76
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
77
+ scheduler ([`SchedulerMixin`]):
78
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
79
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
80
+ safety_checker ([`StableDiffusionSafetyChecker`]):
81
+ Classification module that estimates whether generated images could be considered offsensive or harmful.
82
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
83
+ feature_extractor ([`CLIPFeatureExtractor`]):
84
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ vae: AutoencoderKL,
90
+ text_encoder: CLIPTextModel,
91
+ tokenizer: CLIPTokenizer,
92
+ unet: UNet2DConditionModel,
93
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
94
+ safety_checker: StableDiffusionSafetyChecker,
95
+ feature_extractor: CLIPFeatureExtractor,
96
+ ):
97
+ super().__init__()
98
+ self.register_modules(
99
+ vae=vae,
100
+ text_encoder=text_encoder,
101
+ tokenizer=tokenizer,
102
+ unet=unet,
103
+ scheduler=scheduler,
104
+ safety_checker=safety_checker,
105
+ feature_extractor=feature_extractor,
106
+ )
107
+
108
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
109
+ r"""
110
+ Enable sliced attention computation.
111
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
112
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
113
+ Args:
114
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
115
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
116
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
117
+ `attention_head_dim` must be a multiple of `slice_size`.
118
+ """
119
+ if slice_size == "auto":
120
+ # half the attention head size is usually a good trade-off between
121
+ # speed and memory
122
+ slice_size = self.unet.config.attention_head_dim // 2
123
+ self.unet.set_attention_slice(slice_size)
124
+
125
+ def disable_attention_slicing(self):
126
+ r"""
127
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
128
+ back to computing attention in one step.
129
+ """
130
+ # set slice_size = `None` to disable `attention slicing`
131
+ self.enable_attention_slicing(None)
132
+
133
+ def train(
134
+ self,
135
+ prompt: Union[str, List[str]],
136
+ image: Union[torch.FloatTensor, PIL.Image.Image],
137
+ height: Optional[int] = 512,
138
+ width: Optional[int] = 512,
139
+ generator: Optional[torch.Generator] = None,
140
+ embedding_learning_rate: float = 0.001,
141
+ diffusion_model_learning_rate: float = 2e-6,
142
+ text_embedding_optimization_steps: int = 500,
143
+ model_fine_tuning_optimization_steps: int = 1000,
144
+ **kwargs,
145
+ ):
146
+ r"""
147
+ Function invoked when calling the pipeline for generation.
148
+ Args:
149
+ prompt (`str` or `List[str]`):
150
+ The prompt or prompts to guide the image generation.
151
+ height (`int`, *optional*, defaults to 512):
152
+ The height in pixels of the generated image.
153
+ width (`int`, *optional*, defaults to 512):
154
+ The width in pixels of the generated image.
155
+ num_inference_steps (`int`, *optional*, defaults to 50):
156
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
157
+ expense of slower inference.
158
+ guidance_scale (`float`, *optional*, defaults to 7.5):
159
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
160
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
161
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
162
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
163
+ usually at the expense of lower image quality.
164
+ eta (`float`, *optional*, defaults to 0.0):
165
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
166
+ [`schedulers.DDIMScheduler`], will be ignored for others.
167
+ generator (`torch.Generator`, *optional*):
168
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
169
+ deterministic.
170
+ latents (`torch.FloatTensor`, *optional*):
171
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
172
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
173
+ tensor will ge generated by sampling using the supplied random `generator`.
174
+ output_type (`str`, *optional*, defaults to `"pil"`):
175
+ The output format of the generate image. Choose between
176
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
177
+ return_dict (`bool`, *optional*, defaults to `True`):
178
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
179
+ plain tuple.
180
+ Returns:
181
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
182
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
183
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
184
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
185
+ (nsfw) content, according to the `safety_checker`.
186
+ """
187
+ message = "Please use `image` instead of `init_image`."
188
+ init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)
189
+ image = init_image or image
190
+
191
+ accelerator = Accelerator(
192
+ gradient_accumulation_steps=1,
193
+ mixed_precision="fp16",
194
+ )
195
+
196
+ if "torch_device" in kwargs:
197
+ device = kwargs.pop("torch_device")
198
+ warnings.warn(
199
+ "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
200
+ " Consider using `pipe.to(torch_device)` instead."
201
+ )
202
+
203
+ if device is None:
204
+ device = "cuda" if torch.cuda.is_available() else "cpu"
205
+ self.to(device)
206
+
207
+ if height % 8 != 0 or width % 8 != 0:
208
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
209
+
210
+ # Freeze vae and unet
211
+ self.vae.requires_grad_(False)
212
+ self.unet.requires_grad_(False)
213
+ self.text_encoder.requires_grad_(False)
214
+ self.unet.eval()
215
+ self.vae.eval()
216
+ self.text_encoder.eval()
217
+
218
+ if accelerator.is_main_process:
219
+ accelerator.init_trackers(
220
+ "imagic",
221
+ config={
222
+ "embedding_learning_rate": embedding_learning_rate,
223
+ "text_embedding_optimization_steps": text_embedding_optimization_steps,
224
+ },
225
+ )
226
+
227
+ # get text embeddings for prompt
228
+ text_input = self.tokenizer(
229
+ prompt,
230
+ padding="max_length",
231
+ max_length=self.tokenizer.model_max_length,
232
+ truncaton=True,
233
+ return_tensors="pt",
234
+ )
235
+ text_embeddings = torch.nn.Parameter(
236
+ self.text_encoder(text_input.input_ids.to(self.device))[0], requires_grad=True
237
+ )
238
+ text_embeddings = text_embeddings.detach()
239
+ text_embeddings.requires_grad_()
240
+ text_embeddings_orig = text_embeddings.clone()
241
+
242
+ # Initialize the optimizer
243
+ optimizer = torch.optim.Adam(
244
+ [text_embeddings], # only optimize the embeddings
245
+ lr=embedding_learning_rate,
246
+ )
247
+
248
+ if isinstance(image, PIL.Image.Image):
249
+ image = preprocess(image)
250
+
251
+ latents_dtype = text_embeddings.dtype
252
+ image = image.to(device=self.device, dtype=latents_dtype)
253
+ init_latent_image_dist = self.vae.encode(image).latent_dist
254
+ image_latents = init_latent_image_dist.sample(generator=generator)
255
+ image_latents = 0.18215 * image_latents
256
+
257
+ progress_bar = tqdm(range(text_embedding_optimization_steps), disable=not accelerator.is_local_main_process)
258
+ progress_bar.set_description("Steps")
259
+
260
+ global_step = 0
261
+
262
+ logger.info("First optimizing the text embedding to better reconstruct the init image")
263
+ for _ in range(text_embedding_optimization_steps):
264
+ with accelerator.accumulate(text_embeddings):
265
+ # Sample noise that we'll add to the latents
266
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
267
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
268
+
269
+ # Add noise to the latents according to the noise magnitude at each timestep
270
+ # (this is the forward diffusion process)
271
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
272
+
273
+ # Predict the noise residual
274
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
275
+
276
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
277
+ accelerator.backward(loss)
278
+
279
+ optimizer.step()
280
+ optimizer.zero_grad()
281
+
282
+ # Checks if the accelerator has performed an optimization step behind the scenes
283
+ if accelerator.sync_gradients:
284
+ progress_bar.update(1)
285
+ global_step += 1
286
+
287
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
288
+ progress_bar.set_postfix(**logs)
289
+ accelerator.log(logs, step=global_step)
290
+
291
+ accelerator.wait_for_everyone()
292
+
293
+ text_embeddings.requires_grad_(False)
294
+
295
+ # Now we fine tune the unet to better reconstruct the image
296
+ self.unet.requires_grad_(True)
297
+ self.unet.train()
298
+ optimizer = torch.optim.Adam(
299
+ self.unet.parameters(), # only optimize unet
300
+ lr=diffusion_model_learning_rate,
301
+ )
302
+ progress_bar = tqdm(range(model_fine_tuning_optimization_steps), disable=not accelerator.is_local_main_process)
303
+
304
+ logger.info("Next fine tuning the entire model to better reconstruct the init image")
305
+ for _ in range(model_fine_tuning_optimization_steps):
306
+ with accelerator.accumulate(self.unet.parameters()):
307
+ # Sample noise that we'll add to the latents
308
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
309
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
310
+
311
+ # Add noise to the latents according to the noise magnitude at each timestep
312
+ # (this is the forward diffusion process)
313
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
314
+
315
+ # Predict the noise residual
316
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
317
+
318
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
319
+ accelerator.backward(loss)
320
+
321
+ optimizer.step()
322
+ optimizer.zero_grad()
323
+
324
+ # Checks if the accelerator has performed an optimization step behind the scenes
325
+ if accelerator.sync_gradients:
326
+ progress_bar.update(1)
327
+ global_step += 1
328
+
329
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
330
+ progress_bar.set_postfix(**logs)
331
+ accelerator.log(logs, step=global_step)
332
+
333
+ accelerator.wait_for_everyone()
334
+ self.text_embeddings_orig = text_embeddings_orig
335
+ self.text_embeddings = text_embeddings
336
+
337
+ @torch.no_grad()
338
+ def __call__(
339
+ self,
340
+ alpha: float = 1.2,
341
+ height: Optional[int] = 512,
342
+ width: Optional[int] = 512,
343
+ num_inference_steps: Optional[int] = 50,
344
+ generator: Optional[torch.Generator] = None,
345
+ output_type: Optional[str] = "pil",
346
+ return_dict: bool = True,
347
+ guidance_scale: float = 7.5,
348
+ eta: float = 0.0,
349
+ **kwargs,
350
+ ):
351
+ r"""
352
+ Function invoked when calling the pipeline for generation.
353
+ Args:
354
+ prompt (`str` or `List[str]`):
355
+ The prompt or prompts to guide the image generation.
356
+ height (`int`, *optional*, defaults to 512):
357
+ The height in pixels of the generated image.
358
+ width (`int`, *optional*, defaults to 512):
359
+ The width in pixels of the generated image.
360
+ num_inference_steps (`int`, *optional*, defaults to 50):
361
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
362
+ expense of slower inference.
363
+ guidance_scale (`float`, *optional*, defaults to 7.5):
364
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
365
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
366
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
367
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
368
+ usually at the expense of lower image quality.
369
+ eta (`float`, *optional*, defaults to 0.0):
370
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
371
+ [`schedulers.DDIMScheduler`], will be ignored for others.
372
+ generator (`torch.Generator`, *optional*):
373
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
374
+ deterministic.
375
+ latents (`torch.FloatTensor`, *optional*):
376
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
377
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
378
+ tensor will ge generated by sampling using the supplied random `generator`.
379
+ output_type (`str`, *optional*, defaults to `"pil"`):
380
+ The output format of the generate image. Choose between
381
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
382
+ return_dict (`bool`, *optional*, defaults to `True`):
383
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
384
+ plain tuple.
385
+ Returns:
386
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
387
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
388
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
389
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
390
+ (nsfw) content, according to the `safety_checker`.
391
+ """
392
+ if height % 8 != 0 or width % 8 != 0:
393
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
394
+ if self.text_embeddings is None:
395
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
396
+ if self.text_embeddings_orig is None:
397
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
398
+
399
+ text_embeddings = alpha * self.text_embeddings_orig + (1 - alpha) * self.text_embeddings
400
+
401
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
402
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
403
+ # corresponds to doing no classifier free guidance.
404
+ do_classifier_free_guidance = guidance_scale > 1.0
405
+ # get unconditional embeddings for classifier free guidance
406
+ if do_classifier_free_guidance:
407
+ uncond_tokens = [""]
408
+ max_length = self.tokenizer.model_max_length
409
+ uncond_input = self.tokenizer(
410
+ uncond_tokens,
411
+ padding="max_length",
412
+ max_length=max_length,
413
+ truncation=True,
414
+ return_tensors="pt",
415
+ )
416
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
417
+
418
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
419
+ seq_len = uncond_embeddings.shape[1]
420
+ uncond_embeddings = uncond_embeddings.view(1, seq_len, -1)
421
+
422
+ # For classifier free guidance, we need to do two forward passes.
423
+ # Here we concatenate the unconditional and text embeddings into a single batch
424
+ # to avoid doing two forward passes
425
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
426
+
427
+ # get the initial random noise unless the user supplied it
428
+
429
+ # Unlike in other pipelines, latents need to be generated in the target device
430
+ # for 1-to-1 results reproducibility with the CompVis implementation.
431
+ # However this currently doesn't work in `mps`.
432
+ latents_shape = (1, self.unet.in_channels, height // 8, width // 8)
433
+ latents_dtype = text_embeddings.dtype
434
+ if self.device.type == "mps":
435
+ # randn does not exist on mps
436
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
437
+ self.device
438
+ )
439
+ else:
440
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
441
+
442
+ # set timesteps
443
+ self.scheduler.set_timesteps(num_inference_steps)
444
+
445
+ # Some schedulers like PNDM have timesteps as arrays
446
+ # It's more optimized to move all timesteps to correct device beforehand
447
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
448
+
449
+ # scale the initial noise by the standard deviation required by the scheduler
450
+ latents = latents * self.scheduler.init_noise_sigma
451
+
452
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
453
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
454
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
455
+ # and should be between [0, 1]
456
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
457
+ extra_step_kwargs = {}
458
+ if accepts_eta:
459
+ extra_step_kwargs["eta"] = eta
460
+
461
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
462
+ # expand the latents if we are doing classifier free guidance
463
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
464
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
465
+
466
+ # predict the noise residual
467
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
468
+
469
+ # perform guidance
470
+ if do_classifier_free_guidance:
471
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
472
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
473
+
474
+ # compute the previous noisy sample x_t -> x_t-1
475
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
476
+
477
+ latents = 1 / 0.18215 * latents
478
+ image = self.vae.decode(latents).sample
479
+
480
+ image = (image / 2 + 0.5).clamp(0, 1)
481
+
482
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
483
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
484
+
485
+ if self.safety_checker is not None:
486
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
487
+ self.device
488
+ )
489
+ image, has_nsfw_concept = self.safety_checker(
490
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
491
+ )
492
+ else:
493
+ has_nsfw_concept = None
494
+
495
+ if output_type == "pil":
496
+ image = self.numpy_to_pil(image)
497
+
498
+ if not return_dict:
499
+ return (image, has_nsfw_concept)
500
+
501
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.10.1/img2img_inpainting.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+
7
+ import PIL
8
+ from diffusers.configuration_utils import FrozenDict
9
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
10
+ from diffusers.pipeline_utils import DiffusionPipeline
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
12
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
13
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
14
+ from diffusers.utils import deprecate, logging
15
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+
21
+ def prepare_mask_and_masked_image(image, mask):
22
+ image = np.array(image.convert("RGB"))
23
+ image = image[None].transpose(0, 3, 1, 2)
24
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
25
+
26
+ mask = np.array(mask.convert("L"))
27
+ mask = mask.astype(np.float32) / 255.0
28
+ mask = mask[None, None]
29
+ mask[mask < 0.5] = 0
30
+ mask[mask >= 0.5] = 1
31
+ mask = torch.from_numpy(mask)
32
+
33
+ masked_image = image * (mask < 0.5)
34
+
35
+ return mask, masked_image
36
+
37
+
38
+ def check_size(image, height, width):
39
+ if isinstance(image, PIL.Image.Image):
40
+ w, h = image.size
41
+ elif isinstance(image, torch.Tensor):
42
+ *_, h, w = image.shape
43
+
44
+ if h != height or w != width:
45
+ raise ValueError(f"Image size should be {height}x{width}, but got {h}x{w}")
46
+
47
+
48
+ def overlay_inner_image(image, inner_image, paste_offset: Tuple[int] = (0, 0)):
49
+ inner_image = inner_image.convert("RGBA")
50
+ image = image.convert("RGB")
51
+
52
+ image.paste(inner_image, paste_offset, inner_image)
53
+ image = image.convert("RGB")
54
+
55
+ return image
56
+
57
+
58
+ class ImageToImageInpaintingPipeline(DiffusionPipeline):
59
+ r"""
60
+ Pipeline for text-guided image-to-image inpainting using Stable Diffusion. *This is an experimental feature*.
61
+
62
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
63
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
64
+
65
+ Args:
66
+ vae ([`AutoencoderKL`]):
67
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
68
+ text_encoder ([`CLIPTextModel`]):
69
+ Frozen text-encoder. Stable Diffusion uses the text portion of
70
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
71
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
72
+ tokenizer (`CLIPTokenizer`):
73
+ Tokenizer of class
74
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
75
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
76
+ scheduler ([`SchedulerMixin`]):
77
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
78
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
79
+ safety_checker ([`StableDiffusionSafetyChecker`]):
80
+ Classification module that estimates whether generated images could be considered offensive or harmful.
81
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
82
+ feature_extractor ([`CLIPFeatureExtractor`]):
83
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ vae: AutoencoderKL,
89
+ text_encoder: CLIPTextModel,
90
+ tokenizer: CLIPTokenizer,
91
+ unet: UNet2DConditionModel,
92
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
93
+ safety_checker: StableDiffusionSafetyChecker,
94
+ feature_extractor: CLIPFeatureExtractor,
95
+ ):
96
+ super().__init__()
97
+
98
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
99
+ deprecation_message = (
100
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
101
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
102
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
103
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
104
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
105
+ " file"
106
+ )
107
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
108
+ new_config = dict(scheduler.config)
109
+ new_config["steps_offset"] = 1
110
+ scheduler._internal_dict = FrozenDict(new_config)
111
+
112
+ if safety_checker is None:
113
+ logger.warning(
114
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
115
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
116
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
117
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
118
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
119
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
120
+ )
121
+
122
+ self.register_modules(
123
+ vae=vae,
124
+ text_encoder=text_encoder,
125
+ tokenizer=tokenizer,
126
+ unet=unet,
127
+ scheduler=scheduler,
128
+ safety_checker=safety_checker,
129
+ feature_extractor=feature_extractor,
130
+ )
131
+
132
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
133
+ r"""
134
+ Enable sliced attention computation.
135
+
136
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
137
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
138
+
139
+ Args:
140
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
141
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
142
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
143
+ `attention_head_dim` must be a multiple of `slice_size`.
144
+ """
145
+ if slice_size == "auto":
146
+ # half the attention head size is usually a good trade-off between
147
+ # speed and memory
148
+ slice_size = self.unet.config.attention_head_dim // 2
149
+ self.unet.set_attention_slice(slice_size)
150
+
151
+ def disable_attention_slicing(self):
152
+ r"""
153
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
154
+ back to computing attention in one step.
155
+ """
156
+ # set slice_size = `None` to disable `attention slicing`
157
+ self.enable_attention_slicing(None)
158
+
159
+ @torch.no_grad()
160
+ def __call__(
161
+ self,
162
+ prompt: Union[str, List[str]],
163
+ image: Union[torch.FloatTensor, PIL.Image.Image],
164
+ inner_image: Union[torch.FloatTensor, PIL.Image.Image],
165
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
166
+ height: int = 512,
167
+ width: int = 512,
168
+ num_inference_steps: int = 50,
169
+ guidance_scale: float = 7.5,
170
+ negative_prompt: Optional[Union[str, List[str]]] = None,
171
+ num_images_per_prompt: Optional[int] = 1,
172
+ eta: float = 0.0,
173
+ generator: Optional[torch.Generator] = None,
174
+ latents: Optional[torch.FloatTensor] = None,
175
+ output_type: Optional[str] = "pil",
176
+ return_dict: bool = True,
177
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
178
+ callback_steps: Optional[int] = 1,
179
+ **kwargs,
180
+ ):
181
+ r"""
182
+ Function invoked when calling the pipeline for generation.
183
+
184
+ Args:
185
+ prompt (`str` or `List[str]`):
186
+ The prompt or prompts to guide the image generation.
187
+ image (`torch.Tensor` or `PIL.Image.Image`):
188
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
189
+ be masked out with `mask_image` and repainted according to `prompt`.
190
+ inner_image (`torch.Tensor` or `PIL.Image.Image`):
191
+ `Image`, or tensor representing an image batch which will be overlayed onto `image`. Non-transparent
192
+ regions of `inner_image` must fit inside white pixels in `mask_image`. Expects four channels, with
193
+ the last channel representing the alpha channel, which will be used to blend `inner_image` with
194
+ `image`. If not provided, it will be forcibly cast to RGBA.
195
+ mask_image (`PIL.Image.Image`):
196
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
197
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
198
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
199
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
200
+ height (`int`, *optional*, defaults to 512):
201
+ The height in pixels of the generated image.
202
+ width (`int`, *optional*, defaults to 512):
203
+ The width in pixels of the generated image.
204
+ num_inference_steps (`int`, *optional*, defaults to 50):
205
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
206
+ expense of slower inference.
207
+ guidance_scale (`float`, *optional*, defaults to 7.5):
208
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
209
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
210
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
211
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
212
+ usually at the expense of lower image quality.
213
+ negative_prompt (`str` or `List[str]`, *optional*):
214
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
215
+ if `guidance_scale` is less than `1`).
216
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
217
+ The number of images to generate per prompt.
218
+ eta (`float`, *optional*, defaults to 0.0):
219
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
220
+ [`schedulers.DDIMScheduler`], will be ignored for others.
221
+ generator (`torch.Generator`, *optional*):
222
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
223
+ deterministic.
224
+ latents (`torch.FloatTensor`, *optional*):
225
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
226
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
227
+ tensor will ge generated by sampling using the supplied random `generator`.
228
+ output_type (`str`, *optional*, defaults to `"pil"`):
229
+ The output format of the generate image. Choose between
230
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
231
+ return_dict (`bool`, *optional*, defaults to `True`):
232
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
233
+ plain tuple.
234
+ callback (`Callable`, *optional*):
235
+ A function that will be called every `callback_steps` steps during inference. The function will be
236
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
237
+ callback_steps (`int`, *optional*, defaults to 1):
238
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
239
+ called at every step.
240
+
241
+ Returns:
242
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
243
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
244
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
245
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
246
+ (nsfw) content, according to the `safety_checker`.
247
+ """
248
+
249
+ if isinstance(prompt, str):
250
+ batch_size = 1
251
+ elif isinstance(prompt, list):
252
+ batch_size = len(prompt)
253
+ else:
254
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
255
+
256
+ if height % 8 != 0 or width % 8 != 0:
257
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
258
+
259
+ if (callback_steps is None) or (
260
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
261
+ ):
262
+ raise ValueError(
263
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
264
+ f" {type(callback_steps)}."
265
+ )
266
+
267
+ # check if input sizes are correct
268
+ check_size(image, height, width)
269
+ check_size(inner_image, height, width)
270
+ check_size(mask_image, height, width)
271
+
272
+ # get prompt text embeddings
273
+ text_inputs = self.tokenizer(
274
+ prompt,
275
+ padding="max_length",
276
+ max_length=self.tokenizer.model_max_length,
277
+ return_tensors="pt",
278
+ )
279
+ text_input_ids = text_inputs.input_ids
280
+
281
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
282
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
283
+ logger.warning(
284
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
285
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
286
+ )
287
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
288
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
289
+
290
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
291
+ bs_embed, seq_len, _ = text_embeddings.shape
292
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
293
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
294
+
295
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
296
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
297
+ # corresponds to doing no classifier free guidance.
298
+ do_classifier_free_guidance = guidance_scale > 1.0
299
+ # get unconditional embeddings for classifier free guidance
300
+ if do_classifier_free_guidance:
301
+ uncond_tokens: List[str]
302
+ if negative_prompt is None:
303
+ uncond_tokens = [""]
304
+ elif type(prompt) is not type(negative_prompt):
305
+ raise TypeError(
306
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
307
+ f" {type(prompt)}."
308
+ )
309
+ elif isinstance(negative_prompt, str):
310
+ uncond_tokens = [negative_prompt]
311
+ elif batch_size != len(negative_prompt):
312
+ raise ValueError(
313
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
314
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
315
+ " the batch size of `prompt`."
316
+ )
317
+ else:
318
+ uncond_tokens = negative_prompt
319
+
320
+ max_length = text_input_ids.shape[-1]
321
+ uncond_input = self.tokenizer(
322
+ uncond_tokens,
323
+ padding="max_length",
324
+ max_length=max_length,
325
+ truncation=True,
326
+ return_tensors="pt",
327
+ )
328
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
329
+
330
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
331
+ seq_len = uncond_embeddings.shape[1]
332
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
333
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
334
+
335
+ # For classifier free guidance, we need to do two forward passes.
336
+ # Here we concatenate the unconditional and text embeddings into a single batch
337
+ # to avoid doing two forward passes
338
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
339
+
340
+ # get the initial random noise unless the user supplied it
341
+ # Unlike in other pipelines, latents need to be generated in the target device
342
+ # for 1-to-1 results reproducibility with the CompVis implementation.
343
+ # However this currently doesn't work in `mps`.
344
+ num_channels_latents = self.vae.config.latent_channels
345
+ latents_shape = (batch_size * num_images_per_prompt, num_channels_latents, height // 8, width // 8)
346
+ latents_dtype = text_embeddings.dtype
347
+ if latents is None:
348
+ if self.device.type == "mps":
349
+ # randn does not exist on mps
350
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
351
+ self.device
352
+ )
353
+ else:
354
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
355
+ else:
356
+ if latents.shape != latents_shape:
357
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
358
+ latents = latents.to(self.device)
359
+
360
+ # overlay the inner image
361
+ image = overlay_inner_image(image, inner_image)
362
+
363
+ # prepare mask and masked_image
364
+ mask, masked_image = prepare_mask_and_masked_image(image, mask_image)
365
+ mask = mask.to(device=self.device, dtype=text_embeddings.dtype)
366
+ masked_image = masked_image.to(device=self.device, dtype=text_embeddings.dtype)
367
+
368
+ # resize the mask to latents shape as we concatenate the mask to the latents
369
+ mask = torch.nn.functional.interpolate(mask, size=(height // 8, width // 8))
370
+
371
+ # encode the mask image into latents space so we can concatenate it to the latents
372
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
373
+ masked_image_latents = 0.18215 * masked_image_latents
374
+
375
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
376
+ mask = mask.repeat(batch_size * num_images_per_prompt, 1, 1, 1)
377
+ masked_image_latents = masked_image_latents.repeat(batch_size * num_images_per_prompt, 1, 1, 1)
378
+
379
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
380
+ masked_image_latents = (
381
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
382
+ )
383
+
384
+ num_channels_mask = mask.shape[1]
385
+ num_channels_masked_image = masked_image_latents.shape[1]
386
+
387
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
388
+ raise ValueError(
389
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
390
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
391
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
392
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
393
+ " `pipeline.unet` or your `mask_image` or `image` input."
394
+ )
395
+
396
+ # set timesteps
397
+ self.scheduler.set_timesteps(num_inference_steps)
398
+
399
+ # Some schedulers like PNDM have timesteps as arrays
400
+ # It's more optimized to move all timesteps to correct device beforehand
401
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
402
+
403
+ # scale the initial noise by the standard deviation required by the scheduler
404
+ latents = latents * self.scheduler.init_noise_sigma
405
+
406
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
407
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
408
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
409
+ # and should be between [0, 1]
410
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
411
+ extra_step_kwargs = {}
412
+ if accepts_eta:
413
+ extra_step_kwargs["eta"] = eta
414
+
415
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
416
+ # expand the latents if we are doing classifier free guidance
417
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
418
+
419
+ # concat latents, mask, masked_image_latents in the channel dimension
420
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
421
+
422
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
423
+
424
+ # predict the noise residual
425
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
426
+
427
+ # perform guidance
428
+ if do_classifier_free_guidance:
429
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
430
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
431
+
432
+ # compute the previous noisy sample x_t -> x_t-1
433
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
434
+
435
+ # call the callback, if provided
436
+ if callback is not None and i % callback_steps == 0:
437
+ callback(i, t, latents)
438
+
439
+ latents = 1 / 0.18215 * latents
440
+ image = self.vae.decode(latents).sample
441
+
442
+ image = (image / 2 + 0.5).clamp(0, 1)
443
+
444
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
445
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
446
+
447
+ if self.safety_checker is not None:
448
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
449
+ self.device
450
+ )
451
+ image, has_nsfw_concept = self.safety_checker(
452
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
453
+ )
454
+ else:
455
+ has_nsfw_concept = None
456
+
457
+ if output_type == "pil":
458
+ image = self.numpy_to_pil(image)
459
+
460
+ if not return_dict:
461
+ return (image, has_nsfw_concept)
462
+
463
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.10.1/interpolate_stable_diffusion.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Callable, List, Optional, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+
9
+ from diffusers.configuration_utils import FrozenDict
10
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
11
+ from diffusers.pipeline_utils import DiffusionPipeline
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
15
+ from diffusers.utils import deprecate, logging
16
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
17
+
18
+
19
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
20
+
21
+
22
+ def slerp(t, v0, v1, DOT_THRESHOLD=0.9995):
23
+ """helper function to spherically interpolate two arrays v1 v2"""
24
+
25
+ if not isinstance(v0, np.ndarray):
26
+ inputs_are_torch = True
27
+ input_device = v0.device
28
+ v0 = v0.cpu().numpy()
29
+ v1 = v1.cpu().numpy()
30
+
31
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
32
+ if np.abs(dot) > DOT_THRESHOLD:
33
+ v2 = (1 - t) * v0 + t * v1
34
+ else:
35
+ theta_0 = np.arccos(dot)
36
+ sin_theta_0 = np.sin(theta_0)
37
+ theta_t = theta_0 * t
38
+ sin_theta_t = np.sin(theta_t)
39
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
40
+ s1 = sin_theta_t / sin_theta_0
41
+ v2 = s0 * v0 + s1 * v1
42
+
43
+ if inputs_are_torch:
44
+ v2 = torch.from_numpy(v2).to(input_device)
45
+
46
+ return v2
47
+
48
+
49
+ class StableDiffusionWalkPipeline(DiffusionPipeline):
50
+ r"""
51
+ Pipeline for text-to-image generation using Stable Diffusion.
52
+
53
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
54
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
55
+
56
+ Args:
57
+ vae ([`AutoencoderKL`]):
58
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
59
+ text_encoder ([`CLIPTextModel`]):
60
+ Frozen text-encoder. Stable Diffusion uses the text portion of
61
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
62
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
63
+ tokenizer (`CLIPTokenizer`):
64
+ Tokenizer of class
65
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
66
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
67
+ scheduler ([`SchedulerMixin`]):
68
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
69
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
70
+ safety_checker ([`StableDiffusionSafetyChecker`]):
71
+ Classification module that estimates whether generated images could be considered offensive or harmful.
72
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
73
+ feature_extractor ([`CLIPFeatureExtractor`]):
74
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ vae: AutoencoderKL,
80
+ text_encoder: CLIPTextModel,
81
+ tokenizer: CLIPTokenizer,
82
+ unet: UNet2DConditionModel,
83
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
84
+ safety_checker: StableDiffusionSafetyChecker,
85
+ feature_extractor: CLIPFeatureExtractor,
86
+ ):
87
+ super().__init__()
88
+
89
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
90
+ deprecation_message = (
91
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
92
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
93
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
94
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
95
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
96
+ " file"
97
+ )
98
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
99
+ new_config = dict(scheduler.config)
100
+ new_config["steps_offset"] = 1
101
+ scheduler._internal_dict = FrozenDict(new_config)
102
+
103
+ if safety_checker is None:
104
+ logger.warning(
105
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
106
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
107
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
108
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
109
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
110
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
111
+ )
112
+
113
+ self.register_modules(
114
+ vae=vae,
115
+ text_encoder=text_encoder,
116
+ tokenizer=tokenizer,
117
+ unet=unet,
118
+ scheduler=scheduler,
119
+ safety_checker=safety_checker,
120
+ feature_extractor=feature_extractor,
121
+ )
122
+
123
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
124
+ r"""
125
+ Enable sliced attention computation.
126
+
127
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
128
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
129
+
130
+ Args:
131
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
132
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
133
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
134
+ `attention_head_dim` must be a multiple of `slice_size`.
135
+ """
136
+ if slice_size == "auto":
137
+ # half the attention head size is usually a good trade-off between
138
+ # speed and memory
139
+ slice_size = self.unet.config.attention_head_dim // 2
140
+ self.unet.set_attention_slice(slice_size)
141
+
142
+ def disable_attention_slicing(self):
143
+ r"""
144
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
145
+ back to computing attention in one step.
146
+ """
147
+ # set slice_size = `None` to disable `attention slicing`
148
+ self.enable_attention_slicing(None)
149
+
150
+ @torch.no_grad()
151
+ def __call__(
152
+ self,
153
+ prompt: Optional[Union[str, List[str]]] = None,
154
+ height: int = 512,
155
+ width: int = 512,
156
+ num_inference_steps: int = 50,
157
+ guidance_scale: float = 7.5,
158
+ negative_prompt: Optional[Union[str, List[str]]] = None,
159
+ num_images_per_prompt: Optional[int] = 1,
160
+ eta: float = 0.0,
161
+ generator: Optional[torch.Generator] = None,
162
+ latents: Optional[torch.FloatTensor] = None,
163
+ output_type: Optional[str] = "pil",
164
+ return_dict: bool = True,
165
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
166
+ callback_steps: Optional[int] = 1,
167
+ text_embeddings: Optional[torch.FloatTensor] = None,
168
+ **kwargs,
169
+ ):
170
+ r"""
171
+ Function invoked when calling the pipeline for generation.
172
+
173
+ Args:
174
+ prompt (`str` or `List[str]`, *optional*, defaults to `None`):
175
+ The prompt or prompts to guide the image generation. If not provided, `text_embeddings` is required.
176
+ height (`int`, *optional*, defaults to 512):
177
+ The height in pixels of the generated image.
178
+ width (`int`, *optional*, defaults to 512):
179
+ The width in pixels of the generated image.
180
+ num_inference_steps (`int`, *optional*, defaults to 50):
181
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
182
+ expense of slower inference.
183
+ guidance_scale (`float`, *optional*, defaults to 7.5):
184
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
185
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
186
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
187
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
188
+ usually at the expense of lower image quality.
189
+ negative_prompt (`str` or `List[str]`, *optional*):
190
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
191
+ if `guidance_scale` is less than `1`).
192
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
193
+ The number of images to generate per prompt.
194
+ eta (`float`, *optional*, defaults to 0.0):
195
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
196
+ [`schedulers.DDIMScheduler`], will be ignored for others.
197
+ generator (`torch.Generator`, *optional*):
198
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
199
+ deterministic.
200
+ latents (`torch.FloatTensor`, *optional*):
201
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
202
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
203
+ tensor will ge generated by sampling using the supplied random `generator`.
204
+ output_type (`str`, *optional*, defaults to `"pil"`):
205
+ The output format of the generate image. Choose between
206
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
207
+ return_dict (`bool`, *optional*, defaults to `True`):
208
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
209
+ plain tuple.
210
+ callback (`Callable`, *optional*):
211
+ A function that will be called every `callback_steps` steps during inference. The function will be
212
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
213
+ callback_steps (`int`, *optional*, defaults to 1):
214
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
215
+ called at every step.
216
+ text_embeddings (`torch.FloatTensor`, *optional*, defaults to `None`):
217
+ Pre-generated text embeddings to be used as inputs for image generation. Can be used in place of
218
+ `prompt` to avoid re-computing the embeddings. If not provided, the embeddings will be generated from
219
+ the supplied `prompt`.
220
+
221
+ Returns:
222
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
223
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
224
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
225
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
226
+ (nsfw) content, according to the `safety_checker`.
227
+ """
228
+
229
+ if height % 8 != 0 or width % 8 != 0:
230
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
231
+
232
+ if (callback_steps is None) or (
233
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
234
+ ):
235
+ raise ValueError(
236
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
237
+ f" {type(callback_steps)}."
238
+ )
239
+
240
+ if text_embeddings is None:
241
+ if isinstance(prompt, str):
242
+ batch_size = 1
243
+ elif isinstance(prompt, list):
244
+ batch_size = len(prompt)
245
+ else:
246
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
247
+
248
+ # get prompt text embeddings
249
+ text_inputs = self.tokenizer(
250
+ prompt,
251
+ padding="max_length",
252
+ max_length=self.tokenizer.model_max_length,
253
+ return_tensors="pt",
254
+ )
255
+ text_input_ids = text_inputs.input_ids
256
+
257
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
258
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
259
+ print(
260
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
261
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
262
+ )
263
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
264
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
265
+ else:
266
+ batch_size = text_embeddings.shape[0]
267
+
268
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
269
+ bs_embed, seq_len, _ = text_embeddings.shape
270
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
271
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
272
+
273
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
274
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
275
+ # corresponds to doing no classifier free guidance.
276
+ do_classifier_free_guidance = guidance_scale > 1.0
277
+ # get unconditional embeddings for classifier free guidance
278
+ if do_classifier_free_guidance:
279
+ uncond_tokens: List[str]
280
+ if negative_prompt is None:
281
+ uncond_tokens = [""] * batch_size
282
+ elif type(prompt) is not type(negative_prompt):
283
+ raise TypeError(
284
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
285
+ f" {type(prompt)}."
286
+ )
287
+ elif isinstance(negative_prompt, str):
288
+ uncond_tokens = [negative_prompt]
289
+ elif batch_size != len(negative_prompt):
290
+ raise ValueError(
291
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
292
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
293
+ " the batch size of `prompt`."
294
+ )
295
+ else:
296
+ uncond_tokens = negative_prompt
297
+
298
+ max_length = self.tokenizer.model_max_length
299
+ uncond_input = self.tokenizer(
300
+ uncond_tokens,
301
+ padding="max_length",
302
+ max_length=max_length,
303
+ truncation=True,
304
+ return_tensors="pt",
305
+ )
306
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
307
+
308
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
309
+ seq_len = uncond_embeddings.shape[1]
310
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
311
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
312
+
313
+ # For classifier free guidance, we need to do two forward passes.
314
+ # Here we concatenate the unconditional and text embeddings into a single batch
315
+ # to avoid doing two forward passes
316
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
317
+
318
+ # get the initial random noise unless the user supplied it
319
+
320
+ # Unlike in other pipelines, latents need to be generated in the target device
321
+ # for 1-to-1 results reproducibility with the CompVis implementation.
322
+ # However this currently doesn't work in `mps`.
323
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
324
+ latents_dtype = text_embeddings.dtype
325
+ if latents is None:
326
+ if self.device.type == "mps":
327
+ # randn does not work reproducibly on mps
328
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
329
+ self.device
330
+ )
331
+ else:
332
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
333
+ else:
334
+ if latents.shape != latents_shape:
335
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
336
+ latents = latents.to(self.device)
337
+
338
+ # set timesteps
339
+ self.scheduler.set_timesteps(num_inference_steps)
340
+
341
+ # Some schedulers like PNDM have timesteps as arrays
342
+ # It's more optimized to move all timesteps to correct device beforehand
343
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
344
+
345
+ # scale the initial noise by the standard deviation required by the scheduler
346
+ latents = latents * self.scheduler.init_noise_sigma
347
+
348
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
349
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
350
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
351
+ # and should be between [0, 1]
352
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
353
+ extra_step_kwargs = {}
354
+ if accepts_eta:
355
+ extra_step_kwargs["eta"] = eta
356
+
357
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
358
+ # expand the latents if we are doing classifier free guidance
359
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
360
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
361
+
362
+ # predict the noise residual
363
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
364
+
365
+ # perform guidance
366
+ if do_classifier_free_guidance:
367
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
368
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
369
+
370
+ # compute the previous noisy sample x_t -> x_t-1
371
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
372
+
373
+ # call the callback, if provided
374
+ if callback is not None and i % callback_steps == 0:
375
+ callback(i, t, latents)
376
+
377
+ latents = 1 / 0.18215 * latents
378
+ image = self.vae.decode(latents).sample
379
+
380
+ image = (image / 2 + 0.5).clamp(0, 1)
381
+
382
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
383
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
384
+
385
+ if self.safety_checker is not None:
386
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
387
+ self.device
388
+ )
389
+ image, has_nsfw_concept = self.safety_checker(
390
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
391
+ )
392
+ else:
393
+ has_nsfw_concept = None
394
+
395
+ if output_type == "pil":
396
+ image = self.numpy_to_pil(image)
397
+
398
+ if not return_dict:
399
+ return (image, has_nsfw_concept)
400
+
401
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
402
+
403
+ def embed_text(self, text):
404
+ """takes in text and turns it into text embeddings"""
405
+ text_input = self.tokenizer(
406
+ text,
407
+ padding="max_length",
408
+ max_length=self.tokenizer.model_max_length,
409
+ truncation=True,
410
+ return_tensors="pt",
411
+ )
412
+ with torch.no_grad():
413
+ embed = self.text_encoder(text_input.input_ids.to(self.device))[0]
414
+ return embed
415
+
416
+ def get_noise(self, seed, dtype=torch.float32, height=512, width=512):
417
+ """Takes in random seed and returns corresponding noise vector"""
418
+ return torch.randn(
419
+ (1, self.unet.in_channels, height // 8, width // 8),
420
+ generator=torch.Generator(device=self.device).manual_seed(seed),
421
+ device=self.device,
422
+ dtype=dtype,
423
+ )
424
+
425
+ def walk(
426
+ self,
427
+ prompts: List[str],
428
+ seeds: List[int],
429
+ num_interpolation_steps: Optional[int] = 6,
430
+ output_dir: Optional[str] = "./dreams",
431
+ name: Optional[str] = None,
432
+ batch_size: Optional[int] = 1,
433
+ height: Optional[int] = 512,
434
+ width: Optional[int] = 512,
435
+ guidance_scale: Optional[float] = 7.5,
436
+ num_inference_steps: Optional[int] = 50,
437
+ eta: Optional[float] = 0.0,
438
+ ) -> List[str]:
439
+ """
440
+ Walks through a series of prompts and seeds, interpolating between them and saving the results to disk.
441
+
442
+ Args:
443
+ prompts (`List[str]`):
444
+ List of prompts to generate images for.
445
+ seeds (`List[int]`):
446
+ List of seeds corresponding to provided prompts. Must be the same length as prompts.
447
+ num_interpolation_steps (`int`, *optional*, defaults to 6):
448
+ Number of interpolation steps to take between prompts.
449
+ output_dir (`str`, *optional*, defaults to `./dreams`):
450
+ Directory to save the generated images to.
451
+ name (`str`, *optional*, defaults to `None`):
452
+ Subdirectory of `output_dir` to save the generated images to. If `None`, the name will
453
+ be the current time.
454
+ batch_size (`int`, *optional*, defaults to 1):
455
+ Number of images to generate at once.
456
+ height (`int`, *optional*, defaults to 512):
457
+ Height of the generated images.
458
+ width (`int`, *optional*, defaults to 512):
459
+ Width of the generated images.
460
+ guidance_scale (`float`, *optional*, defaults to 7.5):
461
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
462
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
463
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
464
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
465
+ usually at the expense of lower image quality.
466
+ num_inference_steps (`int`, *optional*, defaults to 50):
467
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
468
+ expense of slower inference.
469
+ eta (`float`, *optional*, defaults to 0.0):
470
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
471
+ [`schedulers.DDIMScheduler`], will be ignored for others.
472
+
473
+ Returns:
474
+ `List[str]`: List of paths to the generated images.
475
+ """
476
+ if not len(prompts) == len(seeds):
477
+ raise ValueError(
478
+ f"Number of prompts and seeds must be equalGot {len(prompts)} prompts and {len(seeds)} seeds"
479
+ )
480
+
481
+ name = name or time.strftime("%Y%m%d-%H%M%S")
482
+ save_path = Path(output_dir) / name
483
+ save_path.mkdir(exist_ok=True, parents=True)
484
+
485
+ frame_idx = 0
486
+ frame_filepaths = []
487
+ for prompt_a, prompt_b, seed_a, seed_b in zip(prompts, prompts[1:], seeds, seeds[1:]):
488
+ # Embed Text
489
+ embed_a = self.embed_text(prompt_a)
490
+ embed_b = self.embed_text(prompt_b)
491
+
492
+ # Get Noise
493
+ noise_dtype = embed_a.dtype
494
+ noise_a = self.get_noise(seed_a, noise_dtype, height, width)
495
+ noise_b = self.get_noise(seed_b, noise_dtype, height, width)
496
+
497
+ noise_batch, embeds_batch = None, None
498
+ T = np.linspace(0.0, 1.0, num_interpolation_steps)
499
+ for i, t in enumerate(T):
500
+ noise = slerp(float(t), noise_a, noise_b)
501
+ embed = torch.lerp(embed_a, embed_b, t)
502
+
503
+ noise_batch = noise if noise_batch is None else torch.cat([noise_batch, noise], dim=0)
504
+ embeds_batch = embed if embeds_batch is None else torch.cat([embeds_batch, embed], dim=0)
505
+
506
+ batch_is_ready = embeds_batch.shape[0] == batch_size or i + 1 == T.shape[0]
507
+ if batch_is_ready:
508
+ outputs = self(
509
+ latents=noise_batch,
510
+ text_embeddings=embeds_batch,
511
+ height=height,
512
+ width=width,
513
+ guidance_scale=guidance_scale,
514
+ eta=eta,
515
+ num_inference_steps=num_inference_steps,
516
+ )
517
+ noise_batch, embeds_batch = None, None
518
+
519
+ for image in outputs["images"]:
520
+ frame_filepath = str(save_path / f"frame_{frame_idx:06d}.png")
521
+ image.save(frame_filepath)
522
+ frame_filepaths.append(frame_filepath)
523
+ frame_idx += 1
524
+ return frame_filepaths
v0.10.1/lpw_stable_diffusion.py ADDED
@@ -0,0 +1,1095 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+ import PIL
9
+ from diffusers import SchedulerMixin, StableDiffusionPipeline
10
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
12
+ from diffusers.utils import PIL_INTERPOLATION, deprecate, logging
13
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
14
+
15
+
16
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
17
+
18
+ re_attention = re.compile(
19
+ r"""
20
+ \\\(|
21
+ \\\)|
22
+ \\\[|
23
+ \\]|
24
+ \\\\|
25
+ \\|
26
+ \(|
27
+ \[|
28
+ :([+-]?[.\d]+)\)|
29
+ \)|
30
+ ]|
31
+ [^\\()\[\]:]+|
32
+ :
33
+ """,
34
+ re.X,
35
+ )
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 associated 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(pipe: StableDiffusionPipeline, prompt: List[str], max_length: int):
125
+ r"""
126
+ Tokenize a list of prompts and return its tokens with weights of each token.
127
+
128
+ No padding, starting or ending token is included.
129
+ """
130
+ tokens = []
131
+ weights = []
132
+ truncated = False
133
+ for text in prompt:
134
+ texts_and_weights = parse_prompt_attention(text)
135
+ text_token = []
136
+ text_weight = []
137
+ for word, weight in texts_and_weights:
138
+ # tokenize and discard the starting and the ending token
139
+ token = pipe.tokenizer(word).input_ids[1:-1]
140
+ text_token += token
141
+ # copy the weight by length of token
142
+ text_weight += [weight] * len(token)
143
+ # stop if the text is too long (longer than truncation limit)
144
+ if len(text_token) > max_length:
145
+ truncated = True
146
+ break
147
+ # truncate
148
+ if len(text_token) > max_length:
149
+ truncated = True
150
+ text_token = text_token[:max_length]
151
+ text_weight = text_weight[:max_length]
152
+ tokens.append(text_token)
153
+ weights.append(text_weight)
154
+ if truncated:
155
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
156
+ return tokens, weights
157
+
158
+
159
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, no_boseos_middle=True, chunk_length=77):
160
+ r"""
161
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
162
+ """
163
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
164
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
165
+ for i in range(len(tokens)):
166
+ tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i]))
167
+ if no_boseos_middle:
168
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
169
+ else:
170
+ w = []
171
+ if len(weights[i]) == 0:
172
+ w = [1.0] * weights_length
173
+ else:
174
+ for j in range(max_embeddings_multiples):
175
+ w.append(1.0) # weight for starting token in this chunk
176
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
177
+ w.append(1.0) # weight for ending token in this chunk
178
+ w += [1.0] * (weights_length - len(w))
179
+ weights[i] = w[:]
180
+
181
+ return tokens, weights
182
+
183
+
184
+ def get_unweighted_text_embeddings(
185
+ pipe: StableDiffusionPipeline,
186
+ text_input: torch.Tensor,
187
+ chunk_length: int,
188
+ no_boseos_middle: Optional[bool] = True,
189
+ ):
190
+ """
191
+ When the length of tokens is a multiple of the capacity of the text encoder,
192
+ it should be split into chunks and sent to the text encoder individually.
193
+ """
194
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
195
+ if max_embeddings_multiples > 1:
196
+ text_embeddings = []
197
+ for i in range(max_embeddings_multiples):
198
+ # extract the i-th chunk
199
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].clone()
200
+
201
+ # cover the head and the tail by the starting and the ending tokens
202
+ text_input_chunk[:, 0] = text_input[0, 0]
203
+ text_input_chunk[:, -1] = text_input[0, -1]
204
+ text_embedding = pipe.text_encoder(text_input_chunk)[0]
205
+
206
+ if no_boseos_middle:
207
+ if i == 0:
208
+ # discard the ending token
209
+ text_embedding = text_embedding[:, :-1]
210
+ elif i == max_embeddings_multiples - 1:
211
+ # discard the starting token
212
+ text_embedding = text_embedding[:, 1:]
213
+ else:
214
+ # discard both starting and ending tokens
215
+ text_embedding = text_embedding[:, 1:-1]
216
+
217
+ text_embeddings.append(text_embedding)
218
+ text_embeddings = torch.concat(text_embeddings, axis=1)
219
+ else:
220
+ text_embeddings = pipe.text_encoder(text_input)[0]
221
+ return text_embeddings
222
+
223
+
224
+ def get_weighted_text_embeddings(
225
+ pipe: StableDiffusionPipeline,
226
+ prompt: Union[str, List[str]],
227
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
228
+ max_embeddings_multiples: Optional[int] = 3,
229
+ no_boseos_middle: Optional[bool] = False,
230
+ skip_parsing: Optional[bool] = False,
231
+ skip_weighting: Optional[bool] = False,
232
+ **kwargs,
233
+ ):
234
+ r"""
235
+ Prompts can be assigned with local weights using brackets. For example,
236
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
237
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
238
+
239
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
240
+
241
+ Args:
242
+ pipe (`StableDiffusionPipeline`):
243
+ Pipe to provide access to the tokenizer and the text encoder.
244
+ prompt (`str` or `List[str]`):
245
+ The prompt or prompts to guide the image generation.
246
+ uncond_prompt (`str` or `List[str]`):
247
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
248
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
249
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
250
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
251
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
252
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
253
+ ending token in each of the chunk in the middle.
254
+ skip_parsing (`bool`, *optional*, defaults to `False`):
255
+ Skip the parsing of brackets.
256
+ skip_weighting (`bool`, *optional*, defaults to `False`):
257
+ Skip the weighting. When the parsing is skipped, it is forced True.
258
+ """
259
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
260
+ if isinstance(prompt, str):
261
+ prompt = [prompt]
262
+
263
+ if not skip_parsing:
264
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
265
+ if uncond_prompt is not None:
266
+ if isinstance(uncond_prompt, str):
267
+ uncond_prompt = [uncond_prompt]
268
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
269
+ else:
270
+ prompt_tokens = [
271
+ token[1:-1] for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True).input_ids
272
+ ]
273
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
274
+ if uncond_prompt is not None:
275
+ if isinstance(uncond_prompt, str):
276
+ uncond_prompt = [uncond_prompt]
277
+ uncond_tokens = [
278
+ token[1:-1]
279
+ for token in pipe.tokenizer(uncond_prompt, max_length=max_length, truncation=True).input_ids
280
+ ]
281
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
282
+
283
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
284
+ max_length = max([len(token) for token in prompt_tokens])
285
+ if uncond_prompt is not None:
286
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
287
+
288
+ max_embeddings_multiples = min(
289
+ max_embeddings_multiples,
290
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
291
+ )
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(
299
+ prompt_tokens,
300
+ prompt_weights,
301
+ max_length,
302
+ bos,
303
+ eos,
304
+ no_boseos_middle=no_boseos_middle,
305
+ chunk_length=pipe.tokenizer.model_max_length,
306
+ )
307
+ prompt_tokens = torch.tensor(prompt_tokens, dtype=torch.long, device=pipe.device)
308
+ if uncond_prompt is not None:
309
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
310
+ uncond_tokens,
311
+ uncond_weights,
312
+ max_length,
313
+ bos,
314
+ eos,
315
+ no_boseos_middle=no_boseos_middle,
316
+ chunk_length=pipe.tokenizer.model_max_length,
317
+ )
318
+ uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=pipe.device)
319
+
320
+ # get the embeddings
321
+ text_embeddings = get_unweighted_text_embeddings(
322
+ pipe,
323
+ prompt_tokens,
324
+ pipe.tokenizer.model_max_length,
325
+ no_boseos_middle=no_boseos_middle,
326
+ )
327
+ prompt_weights = torch.tensor(prompt_weights, dtype=text_embeddings.dtype, device=pipe.device)
328
+ if uncond_prompt is not None:
329
+ uncond_embeddings = get_unweighted_text_embeddings(
330
+ pipe,
331
+ uncond_tokens,
332
+ pipe.tokenizer.model_max_length,
333
+ no_boseos_middle=no_boseos_middle,
334
+ )
335
+ uncond_weights = torch.tensor(uncond_weights, dtype=uncond_embeddings.dtype, device=pipe.device)
336
+
337
+ # assign weights to the prompts and normalize in the sense of mean
338
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
339
+ if (not skip_parsing) and (not skip_weighting):
340
+ previous_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
341
+ text_embeddings *= prompt_weights.unsqueeze(-1)
342
+ current_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
343
+ text_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
344
+ if uncond_prompt is not None:
345
+ previous_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
346
+ uncond_embeddings *= uncond_weights.unsqueeze(-1)
347
+ current_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
348
+ uncond_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
349
+
350
+ if uncond_prompt is not None:
351
+ return text_embeddings, uncond_embeddings
352
+ return text_embeddings, None
353
+
354
+
355
+ def preprocess_image(image):
356
+ w, h = image.size
357
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
358
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
359
+ image = np.array(image).astype(np.float32) / 255.0
360
+ image = image[None].transpose(0, 3, 1, 2)
361
+ image = torch.from_numpy(image)
362
+ return 2.0 * image - 1.0
363
+
364
+
365
+ def preprocess_mask(mask, scale_factor=8):
366
+ mask = mask.convert("L")
367
+ w, h = mask.size
368
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
369
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
370
+ mask = np.array(mask).astype(np.float32) / 255.0
371
+ mask = np.tile(mask, (4, 1, 1))
372
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
373
+ mask = 1 - mask # repaint white, keep black
374
+ mask = torch.from_numpy(mask)
375
+ return mask
376
+
377
+
378
+ class StableDiffusionLongPromptWeightingPipeline(StableDiffusionPipeline):
379
+ r"""
380
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
381
+ weighting in prompt.
382
+
383
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
384
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
385
+
386
+ Args:
387
+ vae ([`AutoencoderKL`]):
388
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
389
+ text_encoder ([`CLIPTextModel`]):
390
+ Frozen text-encoder. Stable Diffusion uses the text portion of
391
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
392
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
393
+ tokenizer (`CLIPTokenizer`):
394
+ Tokenizer of class
395
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
396
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
397
+ scheduler ([`SchedulerMixin`]):
398
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
399
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
400
+ safety_checker ([`StableDiffusionSafetyChecker`]):
401
+ Classification module that estimates whether generated images could be considered offensive or harmful.
402
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
403
+ feature_extractor ([`CLIPFeatureExtractor`]):
404
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
405
+ """
406
+
407
+ def __init__(
408
+ self,
409
+ vae: AutoencoderKL,
410
+ text_encoder: CLIPTextModel,
411
+ tokenizer: CLIPTokenizer,
412
+ unet: UNet2DConditionModel,
413
+ scheduler: SchedulerMixin,
414
+ safety_checker: StableDiffusionSafetyChecker,
415
+ feature_extractor: CLIPFeatureExtractor,
416
+ requires_safety_checker: bool = True,
417
+ ):
418
+ super().__init__(
419
+ vae=vae,
420
+ text_encoder=text_encoder,
421
+ tokenizer=tokenizer,
422
+ unet=unet,
423
+ scheduler=scheduler,
424
+ safety_checker=safety_checker,
425
+ feature_extractor=feature_extractor,
426
+ requires_safety_checker=requires_safety_checker,
427
+ )
428
+
429
+ def _encode_prompt(
430
+ self,
431
+ prompt,
432
+ device,
433
+ num_images_per_prompt,
434
+ do_classifier_free_guidance,
435
+ negative_prompt,
436
+ max_embeddings_multiples,
437
+ ):
438
+ r"""
439
+ Encodes the prompt into text encoder hidden states.
440
+
441
+ Args:
442
+ prompt (`str` or `list(int)`):
443
+ prompt to be encoded
444
+ device: (`torch.device`):
445
+ torch device
446
+ num_images_per_prompt (`int`):
447
+ number of images that should be generated per prompt
448
+ do_classifier_free_guidance (`bool`):
449
+ whether to use classifier free guidance or not
450
+ negative_prompt (`str` or `List[str]`):
451
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
452
+ if `guidance_scale` is less than `1`).
453
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
454
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
455
+ """
456
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
457
+
458
+ if negative_prompt is None:
459
+ negative_prompt = [""] * batch_size
460
+ elif isinstance(negative_prompt, str):
461
+ negative_prompt = [negative_prompt] * batch_size
462
+ if batch_size != len(negative_prompt):
463
+ raise ValueError(
464
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
465
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
466
+ " the batch size of `prompt`."
467
+ )
468
+
469
+ text_embeddings, uncond_embeddings = get_weighted_text_embeddings(
470
+ pipe=self,
471
+ prompt=prompt,
472
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
473
+ max_embeddings_multiples=max_embeddings_multiples,
474
+ )
475
+ bs_embed, seq_len, _ = text_embeddings.shape
476
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
477
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
478
+
479
+ if do_classifier_free_guidance:
480
+ bs_embed, seq_len, _ = uncond_embeddings.shape
481
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
482
+ uncond_embeddings = uncond_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
483
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
484
+
485
+ return text_embeddings
486
+
487
+ def check_inputs(self, prompt, height, width, strength, callback_steps):
488
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
489
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
490
+
491
+ if strength < 0 or strength > 1:
492
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
493
+
494
+ if height % 8 != 0 or width % 8 != 0:
495
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
496
+
497
+ if (callback_steps is None) or (
498
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
499
+ ):
500
+ raise ValueError(
501
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
502
+ f" {type(callback_steps)}."
503
+ )
504
+
505
+ def get_timesteps(self, num_inference_steps, strength, device, is_text2img):
506
+ if is_text2img:
507
+ return self.scheduler.timesteps.to(device), num_inference_steps
508
+ else:
509
+ # get the original timestep using init_timestep
510
+ offset = self.scheduler.config.get("steps_offset", 0)
511
+ init_timestep = int(num_inference_steps * strength) + offset
512
+ init_timestep = min(init_timestep, num_inference_steps)
513
+
514
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
515
+ timesteps = self.scheduler.timesteps[t_start:].to(device)
516
+ return timesteps, num_inference_steps - t_start
517
+
518
+ def run_safety_checker(self, image, device, dtype):
519
+ if self.safety_checker is not None:
520
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
521
+ image, has_nsfw_concept = self.safety_checker(
522
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
523
+ )
524
+ else:
525
+ has_nsfw_concept = None
526
+ return image, has_nsfw_concept
527
+
528
+ def decode_latents(self, latents):
529
+ latents = 1 / 0.18215 * latents
530
+ image = self.vae.decode(latents).sample
531
+ image = (image / 2 + 0.5).clamp(0, 1)
532
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
533
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
534
+ return image
535
+
536
+ def prepare_extra_step_kwargs(self, generator, eta):
537
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
538
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
539
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
540
+ # and should be between [0, 1]
541
+
542
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
543
+ extra_step_kwargs = {}
544
+ if accepts_eta:
545
+ extra_step_kwargs["eta"] = eta
546
+
547
+ # check if the scheduler accepts generator
548
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
549
+ if accepts_generator:
550
+ extra_step_kwargs["generator"] = generator
551
+ return extra_step_kwargs
552
+
553
+ def prepare_latents(self, image, timestep, batch_size, height, width, dtype, device, generator, latents=None):
554
+ if image is None:
555
+ shape = (
556
+ batch_size,
557
+ self.unet.in_channels,
558
+ height // self.vae_scale_factor,
559
+ width // self.vae_scale_factor,
560
+ )
561
+
562
+ if latents is None:
563
+ if device.type == "mps":
564
+ # randn does not work reproducibly on mps
565
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
566
+ else:
567
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
568
+ else:
569
+ if latents.shape != shape:
570
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
571
+ latents = latents.to(device)
572
+
573
+ # scale the initial noise by the standard deviation required by the scheduler
574
+ latents = latents * self.scheduler.init_noise_sigma
575
+ return latents, None, None
576
+ else:
577
+ init_latent_dist = self.vae.encode(image).latent_dist
578
+ init_latents = init_latent_dist.sample(generator=generator)
579
+ init_latents = 0.18215 * init_latents
580
+ init_latents = torch.cat([init_latents] * batch_size, dim=0)
581
+ init_latents_orig = init_latents
582
+ shape = init_latents.shape
583
+
584
+ # add noise to latents using the timesteps
585
+ if device.type == "mps":
586
+ noise = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
587
+ else:
588
+ noise = torch.randn(shape, generator=generator, device=device, dtype=dtype)
589
+ latents = self.scheduler.add_noise(init_latents, noise, timestep)
590
+ return latents, init_latents_orig, noise
591
+
592
+ @torch.no_grad()
593
+ def __call__(
594
+ self,
595
+ prompt: Union[str, List[str]],
596
+ negative_prompt: Optional[Union[str, List[str]]] = None,
597
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
598
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
599
+ height: int = 512,
600
+ width: int = 512,
601
+ num_inference_steps: int = 50,
602
+ guidance_scale: float = 7.5,
603
+ strength: float = 0.8,
604
+ num_images_per_prompt: Optional[int] = 1,
605
+ eta: float = 0.0,
606
+ generator: Optional[torch.Generator] = None,
607
+ latents: Optional[torch.FloatTensor] = None,
608
+ max_embeddings_multiples: Optional[int] = 3,
609
+ output_type: Optional[str] = "pil",
610
+ return_dict: bool = True,
611
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
612
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
613
+ callback_steps: Optional[int] = 1,
614
+ **kwargs,
615
+ ):
616
+ r"""
617
+ Function invoked when calling the pipeline for generation.
618
+
619
+ Args:
620
+ prompt (`str` or `List[str]`):
621
+ The prompt or prompts to guide the image generation.
622
+ negative_prompt (`str` or `List[str]`, *optional*):
623
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
624
+ if `guidance_scale` is less than `1`).
625
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
626
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
627
+ process.
628
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
629
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
630
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
631
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
632
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
633
+ height (`int`, *optional*, defaults to 512):
634
+ The height in pixels of the generated image.
635
+ width (`int`, *optional*, defaults to 512):
636
+ The width in pixels of the generated image.
637
+ num_inference_steps (`int`, *optional*, defaults to 50):
638
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
639
+ expense of slower inference.
640
+ guidance_scale (`float`, *optional*, defaults to 7.5):
641
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
642
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
643
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
644
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
645
+ usually at the expense of lower image quality.
646
+ strength (`float`, *optional*, defaults to 0.8):
647
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
648
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
649
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
650
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
651
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
652
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
653
+ The number of images to generate per prompt.
654
+ eta (`float`, *optional*, defaults to 0.0):
655
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
656
+ [`schedulers.DDIMScheduler`], will be ignored for others.
657
+ generator (`torch.Generator`, *optional*):
658
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
659
+ deterministic.
660
+ latents (`torch.FloatTensor`, *optional*):
661
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
662
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
663
+ tensor will ge generated by sampling using the supplied random `generator`.
664
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
665
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
666
+ output_type (`str`, *optional*, defaults to `"pil"`):
667
+ The output format of the generate image. Choose between
668
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
669
+ return_dict (`bool`, *optional*, defaults to `True`):
670
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
671
+ plain tuple.
672
+ callback (`Callable`, *optional*):
673
+ A function that will be called every `callback_steps` steps during inference. The function will be
674
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
675
+ is_cancelled_callback (`Callable`, *optional*):
676
+ A function that will be called every `callback_steps` steps during inference. If the function returns
677
+ `True`, the inference will be cancelled.
678
+ callback_steps (`int`, *optional*, defaults to 1):
679
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
680
+ called at every step.
681
+
682
+ Returns:
683
+ `None` if cancelled by `is_cancelled_callback`,
684
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
685
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
686
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
687
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
688
+ (nsfw) content, according to the `safety_checker`.
689
+ """
690
+ message = "Please use `image` instead of `init_image`."
691
+ init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)
692
+ image = init_image or image
693
+
694
+ # 0. Default height and width to unet
695
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
696
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
697
+
698
+ # 1. Check inputs. Raise error if not correct
699
+ self.check_inputs(prompt, height, width, strength, callback_steps)
700
+
701
+ # 2. Define call parameters
702
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
703
+ device = self._execution_device
704
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
705
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
706
+ # corresponds to doing no classifier free guidance.
707
+ do_classifier_free_guidance = guidance_scale > 1.0
708
+
709
+ # 3. Encode input prompt
710
+ text_embeddings = self._encode_prompt(
711
+ prompt,
712
+ device,
713
+ num_images_per_prompt,
714
+ do_classifier_free_guidance,
715
+ negative_prompt,
716
+ max_embeddings_multiples,
717
+ )
718
+ dtype = text_embeddings.dtype
719
+
720
+ # 4. Preprocess image and mask
721
+ if isinstance(image, PIL.Image.Image):
722
+ image = preprocess_image(image)
723
+ if image is not None:
724
+ image = image.to(device=self.device, dtype=dtype)
725
+ if isinstance(mask_image, PIL.Image.Image):
726
+ mask_image = preprocess_mask(mask_image, self.vae_scale_factor)
727
+ if mask_image is not None:
728
+ mask = mask_image.to(device=self.device, dtype=dtype)
729
+ mask = torch.cat([mask] * batch_size * num_images_per_prompt)
730
+ else:
731
+ mask = None
732
+
733
+ # 5. set timesteps
734
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
735
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device, image is None)
736
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
737
+
738
+ # 6. Prepare latent variables
739
+ latents, init_latents_orig, noise = self.prepare_latents(
740
+ image,
741
+ latent_timestep,
742
+ batch_size * num_images_per_prompt,
743
+ height,
744
+ width,
745
+ dtype,
746
+ device,
747
+ generator,
748
+ latents,
749
+ )
750
+
751
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
752
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
753
+
754
+ # 8. Denoising loop
755
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
756
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
757
+ for i, t in enumerate(timesteps):
758
+ # expand the latents if we are doing classifier free guidance
759
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
760
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
761
+
762
+ # predict the noise residual
763
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
764
+
765
+ # perform guidance
766
+ if do_classifier_free_guidance:
767
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
768
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
769
+
770
+ # compute the previous noisy sample x_t -> x_t-1
771
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
772
+
773
+ if mask is not None:
774
+ # masking
775
+ init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, torch.tensor([t]))
776
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
777
+
778
+ # call the callback, if provided
779
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
780
+ progress_bar.update()
781
+ if i % callback_steps == 0:
782
+ if callback is not None:
783
+ callback(i, t, latents)
784
+ if is_cancelled_callback is not None and is_cancelled_callback():
785
+ return None
786
+
787
+ # 9. Post-processing
788
+ image = self.decode_latents(latents)
789
+
790
+ # 10. Run safety checker
791
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
792
+
793
+ # 11. Convert to PIL
794
+ if output_type == "pil":
795
+ image = self.numpy_to_pil(image)
796
+
797
+ if not return_dict:
798
+ return image, has_nsfw_concept
799
+
800
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
801
+
802
+ def text2img(
803
+ self,
804
+ prompt: Union[str, List[str]],
805
+ negative_prompt: Optional[Union[str, List[str]]] = None,
806
+ height: int = 512,
807
+ width: int = 512,
808
+ num_inference_steps: int = 50,
809
+ guidance_scale: float = 7.5,
810
+ num_images_per_prompt: Optional[int] = 1,
811
+ eta: float = 0.0,
812
+ generator: Optional[torch.Generator] = None,
813
+ latents: Optional[torch.FloatTensor] = None,
814
+ max_embeddings_multiples: Optional[int] = 3,
815
+ output_type: Optional[str] = "pil",
816
+ return_dict: bool = True,
817
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
818
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
819
+ callback_steps: Optional[int] = 1,
820
+ **kwargs,
821
+ ):
822
+ r"""
823
+ Function for text-to-image generation.
824
+ Args:
825
+ prompt (`str` or `List[str]`):
826
+ The prompt or prompts to guide the image generation.
827
+ negative_prompt (`str` or `List[str]`, *optional*):
828
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
829
+ if `guidance_scale` is less than `1`).
830
+ height (`int`, *optional*, defaults to 512):
831
+ The height in pixels of the generated image.
832
+ width (`int`, *optional*, defaults to 512):
833
+ The width in pixels of the generated image.
834
+ num_inference_steps (`int`, *optional*, defaults to 50):
835
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
836
+ expense of slower inference.
837
+ guidance_scale (`float`, *optional*, defaults to 7.5):
838
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
839
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
840
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
841
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
842
+ usually at the expense of lower image quality.
843
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
844
+ The number of images to generate per prompt.
845
+ eta (`float`, *optional*, defaults to 0.0):
846
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
847
+ [`schedulers.DDIMScheduler`], will be ignored for others.
848
+ generator (`torch.Generator`, *optional*):
849
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
850
+ deterministic.
851
+ latents (`torch.FloatTensor`, *optional*):
852
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
853
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
854
+ tensor will ge generated by sampling using the supplied random `generator`.
855
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
856
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
857
+ output_type (`str`, *optional*, defaults to `"pil"`):
858
+ The output format of the generate image. Choose between
859
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
860
+ return_dict (`bool`, *optional*, defaults to `True`):
861
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
862
+ plain tuple.
863
+ callback (`Callable`, *optional*):
864
+ A function that will be called every `callback_steps` steps during inference. The function will be
865
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
866
+ is_cancelled_callback (`Callable`, *optional*):
867
+ A function that will be called every `callback_steps` steps during inference. If the function returns
868
+ `True`, the inference will be cancelled.
869
+ callback_steps (`int`, *optional*, defaults to 1):
870
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
871
+ called at every step.
872
+ Returns:
873
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
874
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
875
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
876
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
877
+ (nsfw) content, according to the `safety_checker`.
878
+ """
879
+ return self.__call__(
880
+ prompt=prompt,
881
+ negative_prompt=negative_prompt,
882
+ height=height,
883
+ width=width,
884
+ num_inference_steps=num_inference_steps,
885
+ guidance_scale=guidance_scale,
886
+ num_images_per_prompt=num_images_per_prompt,
887
+ eta=eta,
888
+ generator=generator,
889
+ latents=latents,
890
+ max_embeddings_multiples=max_embeddings_multiples,
891
+ output_type=output_type,
892
+ return_dict=return_dict,
893
+ callback=callback,
894
+ is_cancelled_callback=is_cancelled_callback,
895
+ callback_steps=callback_steps,
896
+ **kwargs,
897
+ )
898
+
899
+ def img2img(
900
+ self,
901
+ image: Union[torch.FloatTensor, PIL.Image.Image],
902
+ prompt: Union[str, List[str]],
903
+ negative_prompt: Optional[Union[str, List[str]]] = None,
904
+ strength: float = 0.8,
905
+ num_inference_steps: Optional[int] = 50,
906
+ guidance_scale: Optional[float] = 7.5,
907
+ num_images_per_prompt: Optional[int] = 1,
908
+ eta: Optional[float] = 0.0,
909
+ generator: Optional[torch.Generator] = None,
910
+ max_embeddings_multiples: Optional[int] = 3,
911
+ output_type: Optional[str] = "pil",
912
+ return_dict: bool = True,
913
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
914
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
915
+ callback_steps: Optional[int] = 1,
916
+ **kwargs,
917
+ ):
918
+ r"""
919
+ Function for image-to-image generation.
920
+ Args:
921
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
922
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
923
+ process.
924
+ prompt (`str` or `List[str]`):
925
+ The prompt or prompts to guide the image generation.
926
+ negative_prompt (`str` or `List[str]`, *optional*):
927
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
928
+ if `guidance_scale` is less than `1`).
929
+ strength (`float`, *optional*, defaults to 0.8):
930
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
931
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
932
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
933
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
934
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
935
+ num_inference_steps (`int`, *optional*, defaults to 50):
936
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
937
+ expense of slower inference. This parameter will be modulated by `strength`.
938
+ guidance_scale (`float`, *optional*, defaults to 7.5):
939
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
940
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
941
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
942
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
943
+ usually at the expense of lower image quality.
944
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
945
+ The number of images to generate per prompt.
946
+ eta (`float`, *optional*, defaults to 0.0):
947
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
948
+ [`schedulers.DDIMScheduler`], will be ignored for others.
949
+ generator (`torch.Generator`, *optional*):
950
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
951
+ deterministic.
952
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
953
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
954
+ output_type (`str`, *optional*, defaults to `"pil"`):
955
+ The output format of the generate image. Choose between
956
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
957
+ return_dict (`bool`, *optional*, defaults to `True`):
958
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
959
+ plain tuple.
960
+ callback (`Callable`, *optional*):
961
+ A function that will be called every `callback_steps` steps during inference. The function will be
962
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
963
+ is_cancelled_callback (`Callable`, *optional*):
964
+ A function that will be called every `callback_steps` steps during inference. If the function returns
965
+ `True`, the inference will be cancelled.
966
+ callback_steps (`int`, *optional*, defaults to 1):
967
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
968
+ called at every step.
969
+ Returns:
970
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
971
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
972
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
973
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
974
+ (nsfw) content, according to the `safety_checker`.
975
+ """
976
+ return self.__call__(
977
+ prompt=prompt,
978
+ negative_prompt=negative_prompt,
979
+ image=image,
980
+ num_inference_steps=num_inference_steps,
981
+ guidance_scale=guidance_scale,
982
+ strength=strength,
983
+ num_images_per_prompt=num_images_per_prompt,
984
+ eta=eta,
985
+ generator=generator,
986
+ max_embeddings_multiples=max_embeddings_multiples,
987
+ output_type=output_type,
988
+ return_dict=return_dict,
989
+ callback=callback,
990
+ is_cancelled_callback=is_cancelled_callback,
991
+ callback_steps=callback_steps,
992
+ **kwargs,
993
+ )
994
+
995
+ def inpaint(
996
+ self,
997
+ image: Union[torch.FloatTensor, PIL.Image.Image],
998
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
999
+ prompt: Union[str, List[str]],
1000
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1001
+ strength: float = 0.8,
1002
+ num_inference_steps: Optional[int] = 50,
1003
+ guidance_scale: Optional[float] = 7.5,
1004
+ num_images_per_prompt: Optional[int] = 1,
1005
+ eta: Optional[float] = 0.0,
1006
+ generator: Optional[torch.Generator] = None,
1007
+ max_embeddings_multiples: Optional[int] = 3,
1008
+ output_type: Optional[str] = "pil",
1009
+ return_dict: bool = True,
1010
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1011
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1012
+ callback_steps: Optional[int] = 1,
1013
+ **kwargs,
1014
+ ):
1015
+ r"""
1016
+ Function for inpaint.
1017
+ Args:
1018
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
1019
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1020
+ process. This is the image whose masked region will be inpainted.
1021
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
1022
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1023
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1024
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1025
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1026
+ prompt (`str` or `List[str]`):
1027
+ The prompt or prompts to guide the image generation.
1028
+ negative_prompt (`str` or `List[str]`, *optional*):
1029
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1030
+ if `guidance_scale` is less than `1`).
1031
+ strength (`float`, *optional*, defaults to 0.8):
1032
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1033
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1034
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1035
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1036
+ num_inference_steps (`int`, *optional*, defaults to 50):
1037
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1038
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1039
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1040
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1041
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1042
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1043
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1044
+ usually at the expense of lower image quality.
1045
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1046
+ The number of images to generate per prompt.
1047
+ eta (`float`, *optional*, defaults to 0.0):
1048
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1049
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1050
+ generator (`torch.Generator`, *optional*):
1051
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1052
+ deterministic.
1053
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1054
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1055
+ output_type (`str`, *optional*, defaults to `"pil"`):
1056
+ The output format of the generate image. Choose between
1057
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1058
+ return_dict (`bool`, *optional*, defaults to `True`):
1059
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1060
+ plain tuple.
1061
+ callback (`Callable`, *optional*):
1062
+ A function that will be called every `callback_steps` steps during inference. The function will be
1063
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1064
+ is_cancelled_callback (`Callable`, *optional*):
1065
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1066
+ `True`, the inference will be cancelled.
1067
+ callback_steps (`int`, *optional*, defaults to 1):
1068
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1069
+ called at every step.
1070
+ Returns:
1071
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1072
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1073
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1074
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1075
+ (nsfw) content, according to the `safety_checker`.
1076
+ """
1077
+ return self.__call__(
1078
+ prompt=prompt,
1079
+ negative_prompt=negative_prompt,
1080
+ image=image,
1081
+ mask_image=mask_image,
1082
+ num_inference_steps=num_inference_steps,
1083
+ guidance_scale=guidance_scale,
1084
+ strength=strength,
1085
+ num_images_per_prompt=num_images_per_prompt,
1086
+ eta=eta,
1087
+ generator=generator,
1088
+ max_embeddings_multiples=max_embeddings_multiples,
1089
+ output_type=output_type,
1090
+ return_dict=return_dict,
1091
+ callback=callback,
1092
+ is_cancelled_callback=is_cancelled_callback,
1093
+ callback_steps=callback_steps,
1094
+ **kwargs,
1095
+ )
v0.10.1/lpw_stable_diffusion_onnx.py ADDED
@@ -0,0 +1,1080 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+ import PIL
9
+ from diffusers import OnnxStableDiffusionPipeline, SchedulerMixin
10
+ from diffusers.onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
12
+ from diffusers.utils import PIL_INTERPOLATION, deprecate, logging
13
+ from transformers import CLIPFeatureExtractor, CLIPTokenizer
14
+
15
+
16
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
17
+
18
+ re_attention = re.compile(
19
+ r"""
20
+ \\\(|
21
+ \\\)|
22
+ \\\[|
23
+ \\]|
24
+ \\\\|
25
+ \\|
26
+ \(|
27
+ \[|
28
+ :([+-]?[.\d]+)\)|
29
+ \)|
30
+ ]|
31
+ [^\\()\[\]:]+|
32
+ :
33
+ """,
34
+ re.X,
35
+ )
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 associated 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(pipe, prompt: List[str], max_length: int):
125
+ r"""
126
+ Tokenize a list of prompts and return its tokens with weights of each token.
127
+
128
+ No padding, starting or ending token is included.
129
+ """
130
+ tokens = []
131
+ weights = []
132
+ truncated = False
133
+ for text in prompt:
134
+ texts_and_weights = parse_prompt_attention(text)
135
+ text_token = []
136
+ text_weight = []
137
+ for word, weight in texts_and_weights:
138
+ # tokenize and discard the starting and the ending token
139
+ token = pipe.tokenizer(word, return_tensors="np").input_ids[0, 1:-1]
140
+ text_token += list(token)
141
+ # copy the weight by length of token
142
+ text_weight += [weight] * len(token)
143
+ # stop if the text is too long (longer than truncation limit)
144
+ if len(text_token) > max_length:
145
+ truncated = True
146
+ break
147
+ # truncate
148
+ if len(text_token) > max_length:
149
+ truncated = True
150
+ text_token = text_token[:max_length]
151
+ text_weight = text_weight[:max_length]
152
+ tokens.append(text_token)
153
+ weights.append(text_weight)
154
+ if truncated:
155
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
156
+ return tokens, weights
157
+
158
+
159
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, no_boseos_middle=True, chunk_length=77):
160
+ r"""
161
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
162
+ """
163
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
164
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
165
+ for i in range(len(tokens)):
166
+ tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i]))
167
+ if no_boseos_middle:
168
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
169
+ else:
170
+ w = []
171
+ if len(weights[i]) == 0:
172
+ w = [1.0] * weights_length
173
+ else:
174
+ for j in range(max_embeddings_multiples):
175
+ w.append(1.0) # weight for starting token in this chunk
176
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
177
+ w.append(1.0) # weight for ending token in this chunk
178
+ w += [1.0] * (weights_length - len(w))
179
+ weights[i] = w[:]
180
+
181
+ return tokens, weights
182
+
183
+
184
+ def get_unweighted_text_embeddings(
185
+ pipe,
186
+ text_input: np.array,
187
+ chunk_length: int,
188
+ no_boseos_middle: Optional[bool] = True,
189
+ ):
190
+ """
191
+ When the length of tokens is a multiple of the capacity of the text encoder,
192
+ it should be split into chunks and sent to the text encoder individually.
193
+ """
194
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
195
+ if max_embeddings_multiples > 1:
196
+ text_embeddings = []
197
+ for i in range(max_embeddings_multiples):
198
+ # extract the i-th chunk
199
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].copy()
200
+
201
+ # cover the head and the tail by the starting and the ending tokens
202
+ text_input_chunk[:, 0] = text_input[0, 0]
203
+ text_input_chunk[:, -1] = text_input[0, -1]
204
+
205
+ text_embedding = pipe.text_encoder(input_ids=text_input_chunk)[0]
206
+
207
+ if no_boseos_middle:
208
+ if i == 0:
209
+ # discard the ending token
210
+ text_embedding = text_embedding[:, :-1]
211
+ elif i == max_embeddings_multiples - 1:
212
+ # discard the starting token
213
+ text_embedding = text_embedding[:, 1:]
214
+ else:
215
+ # discard both starting and ending tokens
216
+ text_embedding = text_embedding[:, 1:-1]
217
+
218
+ text_embeddings.append(text_embedding)
219
+ text_embeddings = np.concatenate(text_embeddings, axis=1)
220
+ else:
221
+ text_embeddings = pipe.text_encoder(input_ids=text_input)[0]
222
+ return text_embeddings
223
+
224
+
225
+ def get_weighted_text_embeddings(
226
+ pipe,
227
+ prompt: Union[str, List[str]],
228
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
229
+ max_embeddings_multiples: Optional[int] = 4,
230
+ no_boseos_middle: Optional[bool] = False,
231
+ skip_parsing: Optional[bool] = False,
232
+ skip_weighting: Optional[bool] = False,
233
+ **kwargs,
234
+ ):
235
+ r"""
236
+ Prompts can be assigned with local weights using brackets. For example,
237
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
238
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
239
+
240
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
241
+
242
+ Args:
243
+ pipe (`OnnxStableDiffusionPipeline`):
244
+ Pipe to provide access to the tokenizer and the text encoder.
245
+ prompt (`str` or `List[str]`):
246
+ The prompt or prompts to guide the image generation.
247
+ uncond_prompt (`str` or `List[str]`):
248
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
249
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
250
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
251
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
252
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
253
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
254
+ ending token in each of the chunk in the middle.
255
+ skip_parsing (`bool`, *optional*, defaults to `False`):
256
+ Skip the parsing of brackets.
257
+ skip_weighting (`bool`, *optional*, defaults to `False`):
258
+ Skip the weighting. When the parsing is skipped, it is forced True.
259
+ """
260
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
261
+ if isinstance(prompt, str):
262
+ prompt = [prompt]
263
+
264
+ if not skip_parsing:
265
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
266
+ if uncond_prompt is not None:
267
+ if isinstance(uncond_prompt, str):
268
+ uncond_prompt = [uncond_prompt]
269
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
270
+ else:
271
+ prompt_tokens = [
272
+ token[1:-1]
273
+ for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True, return_tensors="np").input_ids
274
+ ]
275
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
276
+ if uncond_prompt is not None:
277
+ if isinstance(uncond_prompt, str):
278
+ uncond_prompt = [uncond_prompt]
279
+ uncond_tokens = [
280
+ token[1:-1]
281
+ for token in pipe.tokenizer(
282
+ uncond_prompt,
283
+ max_length=max_length,
284
+ truncation=True,
285
+ return_tensors="np",
286
+ ).input_ids
287
+ ]
288
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
289
+
290
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
291
+ max_length = max([len(token) for token in prompt_tokens])
292
+ if uncond_prompt is not None:
293
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
294
+
295
+ max_embeddings_multiples = min(
296
+ max_embeddings_multiples,
297
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
298
+ )
299
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
300
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
301
+
302
+ # pad the length of tokens and weights
303
+ bos = pipe.tokenizer.bos_token_id
304
+ eos = pipe.tokenizer.eos_token_id
305
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
306
+ prompt_tokens,
307
+ prompt_weights,
308
+ max_length,
309
+ bos,
310
+ eos,
311
+ no_boseos_middle=no_boseos_middle,
312
+ chunk_length=pipe.tokenizer.model_max_length,
313
+ )
314
+ prompt_tokens = np.array(prompt_tokens, dtype=np.int32)
315
+ if uncond_prompt is not None:
316
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
317
+ uncond_tokens,
318
+ uncond_weights,
319
+ max_length,
320
+ bos,
321
+ eos,
322
+ no_boseos_middle=no_boseos_middle,
323
+ chunk_length=pipe.tokenizer.model_max_length,
324
+ )
325
+ uncond_tokens = np.array(uncond_tokens, dtype=np.int32)
326
+
327
+ # get the embeddings
328
+ text_embeddings = get_unweighted_text_embeddings(
329
+ pipe,
330
+ prompt_tokens,
331
+ pipe.tokenizer.model_max_length,
332
+ no_boseos_middle=no_boseos_middle,
333
+ )
334
+ prompt_weights = np.array(prompt_weights, dtype=text_embeddings.dtype)
335
+ if uncond_prompt is not None:
336
+ uncond_embeddings = get_unweighted_text_embeddings(
337
+ pipe,
338
+ uncond_tokens,
339
+ pipe.tokenizer.model_max_length,
340
+ no_boseos_middle=no_boseos_middle,
341
+ )
342
+ uncond_weights = np.array(uncond_weights, dtype=uncond_embeddings.dtype)
343
+
344
+ # assign weights to the prompts and normalize in the sense of mean
345
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
346
+ if (not skip_parsing) and (not skip_weighting):
347
+ previous_mean = text_embeddings.mean(axis=(-2, -1))
348
+ text_embeddings *= prompt_weights[:, :, None]
349
+ text_embeddings *= (previous_mean / text_embeddings.mean(axis=(-2, -1)))[:, None, None]
350
+ if uncond_prompt is not None:
351
+ previous_mean = uncond_embeddings.mean(axis=(-2, -1))
352
+ uncond_embeddings *= uncond_weights[:, :, None]
353
+ uncond_embeddings *= (previous_mean / uncond_embeddings.mean(axis=(-2, -1)))[:, None, None]
354
+
355
+ # For classifier free guidance, we need to do two forward passes.
356
+ # Here we concatenate the unconditional and text embeddings into a single batch
357
+ # to avoid doing two forward passes
358
+ if uncond_prompt is not None:
359
+ return text_embeddings, uncond_embeddings
360
+
361
+ return text_embeddings
362
+
363
+
364
+ def preprocess_image(image):
365
+ w, h = image.size
366
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
367
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
368
+ image = np.array(image).astype(np.float32) / 255.0
369
+ image = image[None].transpose(0, 3, 1, 2)
370
+ return 2.0 * image - 1.0
371
+
372
+
373
+ def preprocess_mask(mask, scale_factor=8):
374
+ mask = mask.convert("L")
375
+ w, h = mask.size
376
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
377
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
378
+ mask = np.array(mask).astype(np.float32) / 255.0
379
+ mask = np.tile(mask, (4, 1, 1))
380
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
381
+ mask = 1 - mask # repaint white, keep black
382
+ return mask
383
+
384
+
385
+ class OnnxStableDiffusionLongPromptWeightingPipeline(OnnxStableDiffusionPipeline):
386
+ r"""
387
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
388
+ weighting in prompt.
389
+
390
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
391
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
392
+ """
393
+
394
+ def __init__(
395
+ self,
396
+ vae_encoder: OnnxRuntimeModel,
397
+ vae_decoder: OnnxRuntimeModel,
398
+ text_encoder: OnnxRuntimeModel,
399
+ tokenizer: CLIPTokenizer,
400
+ unet: OnnxRuntimeModel,
401
+ scheduler: SchedulerMixin,
402
+ safety_checker: OnnxRuntimeModel,
403
+ feature_extractor: CLIPFeatureExtractor,
404
+ requires_safety_checker: bool = True,
405
+ ):
406
+ super().__init__(
407
+ vae_encoder=vae_encoder,
408
+ vae_decoder=vae_decoder,
409
+ text_encoder=text_encoder,
410
+ tokenizer=tokenizer,
411
+ unet=unet,
412
+ scheduler=scheduler,
413
+ safety_checker=safety_checker,
414
+ feature_extractor=feature_extractor,
415
+ requires_safety_checker=requires_safety_checker,
416
+ )
417
+ self.unet_in_channels = 4
418
+ self.vae_scale_factor = 8
419
+
420
+ def _encode_prompt(
421
+ self,
422
+ prompt,
423
+ num_images_per_prompt,
424
+ do_classifier_free_guidance,
425
+ negative_prompt,
426
+ max_embeddings_multiples,
427
+ ):
428
+ r"""
429
+ Encodes the prompt into text encoder hidden states.
430
+
431
+ Args:
432
+ prompt (`str` or `list(int)`):
433
+ prompt to be encoded
434
+ num_images_per_prompt (`int`):
435
+ number of images that should be generated per prompt
436
+ do_classifier_free_guidance (`bool`):
437
+ whether to use classifier free guidance or not
438
+ negative_prompt (`str` or `List[str]`):
439
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
440
+ if `guidance_scale` is less than `1`).
441
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
442
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
443
+ """
444
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
445
+
446
+ if negative_prompt is None:
447
+ negative_prompt = [""] * batch_size
448
+ elif isinstance(negative_prompt, str):
449
+ negative_prompt = [negative_prompt] * batch_size
450
+ if batch_size != len(negative_prompt):
451
+ raise ValueError(
452
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
453
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
454
+ " the batch size of `prompt`."
455
+ )
456
+
457
+ text_embeddings, uncond_embeddings = get_weighted_text_embeddings(
458
+ pipe=self,
459
+ prompt=prompt,
460
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
461
+ max_embeddings_multiples=max_embeddings_multiples,
462
+ )
463
+
464
+ text_embeddings = text_embeddings.repeat(num_images_per_prompt, 0)
465
+ if do_classifier_free_guidance:
466
+ uncond_embeddings = uncond_embeddings.repeat(num_images_per_prompt, 0)
467
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
468
+
469
+ return text_embeddings
470
+
471
+ def check_inputs(self, prompt, height, width, strength, callback_steps):
472
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
473
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
474
+
475
+ if strength < 0 or strength > 1:
476
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
477
+
478
+ if height % 8 != 0 or width % 8 != 0:
479
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
480
+
481
+ if (callback_steps is None) or (
482
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
483
+ ):
484
+ raise ValueError(
485
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
486
+ f" {type(callback_steps)}."
487
+ )
488
+
489
+ def get_timesteps(self, num_inference_steps, strength, is_text2img):
490
+ if is_text2img:
491
+ return self.scheduler.timesteps, num_inference_steps
492
+ else:
493
+ # get the original timestep using init_timestep
494
+ offset = self.scheduler.config.get("steps_offset", 0)
495
+ init_timestep = int(num_inference_steps * strength) + offset
496
+ init_timestep = min(init_timestep, num_inference_steps)
497
+
498
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
499
+ timesteps = self.scheduler.timesteps[t_start:]
500
+ return timesteps, num_inference_steps - t_start
501
+
502
+ def run_safety_checker(self, image):
503
+ if self.safety_checker is not None:
504
+ safety_checker_input = self.feature_extractor(
505
+ self.numpy_to_pil(image), return_tensors="np"
506
+ ).pixel_values.astype(image.dtype)
507
+ # There will throw an error if use safety_checker directly and batchsize>1
508
+ images, has_nsfw_concept = [], []
509
+ for i in range(image.shape[0]):
510
+ image_i, has_nsfw_concept_i = self.safety_checker(
511
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
512
+ )
513
+ images.append(image_i)
514
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
515
+ image = np.concatenate(images)
516
+ else:
517
+ has_nsfw_concept = None
518
+ return image, has_nsfw_concept
519
+
520
+ def decode_latents(self, latents):
521
+ latents = 1 / 0.18215 * latents
522
+ # image = self.vae_decoder(latent_sample=latents)[0]
523
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
524
+ image = np.concatenate(
525
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
526
+ )
527
+ image = np.clip(image / 2 + 0.5, 0, 1)
528
+ image = image.transpose((0, 2, 3, 1))
529
+ return image
530
+
531
+ def prepare_extra_step_kwargs(self, generator, eta):
532
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
533
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
534
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
535
+ # and should be between [0, 1]
536
+
537
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
538
+ extra_step_kwargs = {}
539
+ if accepts_eta:
540
+ extra_step_kwargs["eta"] = eta
541
+
542
+ # check if the scheduler accepts generator
543
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
544
+ if accepts_generator:
545
+ extra_step_kwargs["generator"] = generator
546
+ return extra_step_kwargs
547
+
548
+ def prepare_latents(self, image, timestep, batch_size, height, width, dtype, generator, latents=None):
549
+ if image is None:
550
+ shape = (
551
+ batch_size,
552
+ self.unet_in_channels,
553
+ height // self.vae_scale_factor,
554
+ width // self.vae_scale_factor,
555
+ )
556
+
557
+ if latents is None:
558
+ latents = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
559
+ else:
560
+ if latents.shape != shape:
561
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
562
+
563
+ # scale the initial noise by the standard deviation required by the scheduler
564
+ latents = (torch.from_numpy(latents) * self.scheduler.init_noise_sigma).numpy()
565
+ return latents, None, None
566
+ else:
567
+ init_latents = self.vae_encoder(sample=image)[0]
568
+ init_latents = 0.18215 * init_latents
569
+ init_latents = np.concatenate([init_latents] * batch_size, axis=0)
570
+ init_latents_orig = init_latents
571
+ shape = init_latents.shape
572
+
573
+ # add noise to latents using the timesteps
574
+ noise = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
575
+ latents = self.scheduler.add_noise(
576
+ torch.from_numpy(init_latents), torch.from_numpy(noise), timestep
577
+ ).numpy()
578
+ return latents, init_latents_orig, noise
579
+
580
+ @torch.no_grad()
581
+ def __call__(
582
+ self,
583
+ prompt: Union[str, List[str]],
584
+ negative_prompt: Optional[Union[str, List[str]]] = None,
585
+ image: Union[np.ndarray, PIL.Image.Image] = None,
586
+ mask_image: Union[np.ndarray, PIL.Image.Image] = None,
587
+ height: int = 512,
588
+ width: int = 512,
589
+ num_inference_steps: int = 50,
590
+ guidance_scale: float = 7.5,
591
+ strength: float = 0.8,
592
+ num_images_per_prompt: Optional[int] = 1,
593
+ eta: float = 0.0,
594
+ generator: Optional[torch.Generator] = None,
595
+ latents: Optional[np.ndarray] = None,
596
+ max_embeddings_multiples: Optional[int] = 3,
597
+ output_type: Optional[str] = "pil",
598
+ return_dict: bool = True,
599
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
600
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
601
+ callback_steps: Optional[int] = 1,
602
+ **kwargs,
603
+ ):
604
+ r"""
605
+ Function invoked when calling the pipeline for generation.
606
+
607
+ Args:
608
+ prompt (`str` or `List[str]`):
609
+ The prompt or prompts to guide the image generation.
610
+ negative_prompt (`str` or `List[str]`, *optional*):
611
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
612
+ if `guidance_scale` is less than `1`).
613
+ image (`np.ndarray` or `PIL.Image.Image`):
614
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
615
+ process.
616
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
617
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
618
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
619
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
620
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
621
+ height (`int`, *optional*, defaults to 512):
622
+ The height in pixels of the generated image.
623
+ width (`int`, *optional*, defaults to 512):
624
+ The width in pixels of the generated image.
625
+ num_inference_steps (`int`, *optional*, defaults to 50):
626
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
627
+ expense of slower inference.
628
+ guidance_scale (`float`, *optional*, defaults to 7.5):
629
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
630
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
631
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
632
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
633
+ usually at the expense of lower image quality.
634
+ strength (`float`, *optional*, defaults to 0.8):
635
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
636
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
637
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
638
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
639
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
640
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
641
+ The number of images to generate per prompt.
642
+ eta (`float`, *optional*, defaults to 0.0):
643
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
644
+ [`schedulers.DDIMScheduler`], will be ignored for others.
645
+ generator (`torch.Generator`, *optional*):
646
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
647
+ deterministic.
648
+ latents (`np.ndarray`, *optional*):
649
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
650
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
651
+ tensor will ge generated by sampling using the supplied random `generator`.
652
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
653
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
654
+ output_type (`str`, *optional*, defaults to `"pil"`):
655
+ The output format of the generate image. Choose between
656
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
657
+ return_dict (`bool`, *optional*, defaults to `True`):
658
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
659
+ plain tuple.
660
+ callback (`Callable`, *optional*):
661
+ A function that will be called every `callback_steps` steps during inference. The function will be
662
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
663
+ is_cancelled_callback (`Callable`, *optional*):
664
+ A function that will be called every `callback_steps` steps during inference. If the function returns
665
+ `True`, the inference will be cancelled.
666
+ callback_steps (`int`, *optional*, defaults to 1):
667
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
668
+ called at every step.
669
+
670
+ Returns:
671
+ `None` if cancelled by `is_cancelled_callback`,
672
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
673
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
674
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
675
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
676
+ (nsfw) content, according to the `safety_checker`.
677
+ """
678
+ message = "Please use `image` instead of `init_image`."
679
+ init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)
680
+ image = init_image or image
681
+
682
+ # 0. Default height and width to unet
683
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
684
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
685
+
686
+ # 1. Check inputs. Raise error if not correct
687
+ self.check_inputs(prompt, height, width, strength, callback_steps)
688
+
689
+ # 2. Define call parameters
690
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
691
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
692
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
693
+ # corresponds to doing no classifier free guidance.
694
+ do_classifier_free_guidance = guidance_scale > 1.0
695
+
696
+ # 3. Encode input prompt
697
+ text_embeddings = self._encode_prompt(
698
+ prompt,
699
+ num_images_per_prompt,
700
+ do_classifier_free_guidance,
701
+ negative_prompt,
702
+ max_embeddings_multiples,
703
+ )
704
+ dtype = text_embeddings.dtype
705
+
706
+ # 4. Preprocess image and mask
707
+ if isinstance(image, PIL.Image.Image):
708
+ image = preprocess_image(image)
709
+ if image is not None:
710
+ image = image.astype(dtype)
711
+ if isinstance(mask_image, PIL.Image.Image):
712
+ mask_image = preprocess_mask(mask_image, self.vae_scale_factor)
713
+ if mask_image is not None:
714
+ mask = mask_image.astype(dtype)
715
+ mask = np.concatenate([mask] * batch_size * num_images_per_prompt)
716
+ else:
717
+ mask = None
718
+
719
+ # 5. set timesteps
720
+ self.scheduler.set_timesteps(num_inference_steps)
721
+ timestep_dtype = next(
722
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
723
+ )
724
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
725
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, image is None)
726
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
727
+
728
+ # 6. Prepare latent variables
729
+ latents, init_latents_orig, noise = self.prepare_latents(
730
+ image,
731
+ latent_timestep,
732
+ batch_size * num_images_per_prompt,
733
+ height,
734
+ width,
735
+ dtype,
736
+ generator,
737
+ latents,
738
+ )
739
+
740
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
741
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
742
+
743
+ # 8. Denoising loop
744
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
745
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
746
+ for i, t in enumerate(timesteps):
747
+ # expand the latents if we are doing classifier free guidance
748
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
749
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
750
+ latent_model_input = latent_model_input.numpy()
751
+
752
+ # predict the noise residual
753
+ noise_pred = self.unet(
754
+ sample=latent_model_input,
755
+ timestep=np.array([t], dtype=timestep_dtype),
756
+ encoder_hidden_states=text_embeddings,
757
+ )
758
+ noise_pred = noise_pred[0]
759
+
760
+ # perform guidance
761
+ if do_classifier_free_guidance:
762
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
763
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
764
+
765
+ # compute the previous noisy sample x_t -> x_t-1
766
+ scheduler_output = self.scheduler.step(
767
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
768
+ )
769
+ latents = scheduler_output.prev_sample.numpy()
770
+
771
+ if mask is not None:
772
+ # masking
773
+ init_latents_proper = self.scheduler.add_noise(
774
+ torch.from_numpy(init_latents_orig),
775
+ torch.from_numpy(noise),
776
+ t,
777
+ ).numpy()
778
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
779
+
780
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
781
+ progress_bar.update()
782
+ if i % callback_steps == 0:
783
+ if callback is not None:
784
+ callback(i, t, latents)
785
+ if is_cancelled_callback is not None and is_cancelled_callback():
786
+ return None
787
+ # 9. Post-processing
788
+ image = self.decode_latents(latents)
789
+
790
+ # 10. Run safety checker
791
+ image, has_nsfw_concept = self.run_safety_checker(image)
792
+
793
+ # 11. Convert to PIL
794
+ if output_type == "pil":
795
+ image = self.numpy_to_pil(image)
796
+
797
+ if not return_dict:
798
+ return image, has_nsfw_concept
799
+
800
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
801
+
802
+ def text2img(
803
+ self,
804
+ prompt: Union[str, List[str]],
805
+ negative_prompt: Optional[Union[str, List[str]]] = None,
806
+ height: int = 512,
807
+ width: int = 512,
808
+ num_inference_steps: int = 50,
809
+ guidance_scale: float = 7.5,
810
+ num_images_per_prompt: Optional[int] = 1,
811
+ eta: float = 0.0,
812
+ generator: Optional[torch.Generator] = None,
813
+ latents: Optional[np.ndarray] = None,
814
+ max_embeddings_multiples: Optional[int] = 3,
815
+ output_type: Optional[str] = "pil",
816
+ return_dict: bool = True,
817
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
818
+ callback_steps: Optional[int] = 1,
819
+ **kwargs,
820
+ ):
821
+ r"""
822
+ Function for text-to-image generation.
823
+ Args:
824
+ prompt (`str` or `List[str]`):
825
+ The prompt or prompts to guide the image generation.
826
+ negative_prompt (`str` or `List[str]`, *optional*):
827
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
828
+ if `guidance_scale` is less than `1`).
829
+ height (`int`, *optional*, defaults to 512):
830
+ The height in pixels of the generated image.
831
+ width (`int`, *optional*, defaults to 512):
832
+ The width in pixels of the generated image.
833
+ num_inference_steps (`int`, *optional*, defaults to 50):
834
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
835
+ expense of slower inference.
836
+ guidance_scale (`float`, *optional*, defaults to 7.5):
837
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
838
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
839
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
840
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
841
+ usually at the expense of lower image quality.
842
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
843
+ The number of images to generate per prompt.
844
+ eta (`float`, *optional*, defaults to 0.0):
845
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
846
+ [`schedulers.DDIMScheduler`], will be ignored for others.
847
+ generator (`torch.Generator`, *optional*):
848
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
849
+ deterministic.
850
+ latents (`np.ndarray`, *optional*):
851
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
852
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
853
+ tensor will ge generated by sampling using the supplied random `generator`.
854
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
855
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
856
+ output_type (`str`, *optional*, defaults to `"pil"`):
857
+ The output format of the generate image. Choose between
858
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
859
+ return_dict (`bool`, *optional*, defaults to `True`):
860
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
861
+ plain tuple.
862
+ callback (`Callable`, *optional*):
863
+ A function that will be called every `callback_steps` steps during inference. The function will be
864
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
865
+ callback_steps (`int`, *optional*, defaults to 1):
866
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
867
+ called at every step.
868
+ Returns:
869
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
870
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
871
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
872
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
873
+ (nsfw) content, according to the `safety_checker`.
874
+ """
875
+ return self.__call__(
876
+ prompt=prompt,
877
+ negative_prompt=negative_prompt,
878
+ height=height,
879
+ width=width,
880
+ num_inference_steps=num_inference_steps,
881
+ guidance_scale=guidance_scale,
882
+ num_images_per_prompt=num_images_per_prompt,
883
+ eta=eta,
884
+ generator=generator,
885
+ latents=latents,
886
+ max_embeddings_multiples=max_embeddings_multiples,
887
+ output_type=output_type,
888
+ return_dict=return_dict,
889
+ callback=callback,
890
+ callback_steps=callback_steps,
891
+ **kwargs,
892
+ )
893
+
894
+ def img2img(
895
+ self,
896
+ image: Union[np.ndarray, PIL.Image.Image],
897
+ prompt: Union[str, List[str]],
898
+ negative_prompt: Optional[Union[str, List[str]]] = None,
899
+ strength: float = 0.8,
900
+ num_inference_steps: Optional[int] = 50,
901
+ guidance_scale: Optional[float] = 7.5,
902
+ num_images_per_prompt: Optional[int] = 1,
903
+ eta: Optional[float] = 0.0,
904
+ generator: Optional[torch.Generator] = None,
905
+ max_embeddings_multiples: Optional[int] = 3,
906
+ output_type: Optional[str] = "pil",
907
+ return_dict: bool = True,
908
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
909
+ callback_steps: Optional[int] = 1,
910
+ **kwargs,
911
+ ):
912
+ r"""
913
+ Function for image-to-image generation.
914
+ Args:
915
+ image (`np.ndarray` or `PIL.Image.Image`):
916
+ `Image`, or ndarray representing an image batch, that will be used as the starting point for the
917
+ process.
918
+ prompt (`str` or `List[str]`):
919
+ The prompt or prompts to guide the image generation.
920
+ negative_prompt (`str` or `List[str]`, *optional*):
921
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
922
+ if `guidance_scale` is less than `1`).
923
+ strength (`float`, *optional*, defaults to 0.8):
924
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
925
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
926
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
927
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
928
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
929
+ num_inference_steps (`int`, *optional*, defaults to 50):
930
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
931
+ expense of slower inference. This parameter will be modulated by `strength`.
932
+ guidance_scale (`float`, *optional*, defaults to 7.5):
933
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
934
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
935
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
936
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
937
+ usually at the expense of lower image quality.
938
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
939
+ The number of images to generate per prompt.
940
+ eta (`float`, *optional*, defaults to 0.0):
941
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
942
+ [`schedulers.DDIMScheduler`], will be ignored for others.
943
+ generator (`torch.Generator`, *optional*):
944
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
945
+ deterministic.
946
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
947
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
948
+ output_type (`str`, *optional*, defaults to `"pil"`):
949
+ The output format of the generate image. Choose between
950
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
951
+ return_dict (`bool`, *optional*, defaults to `True`):
952
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
953
+ plain tuple.
954
+ callback (`Callable`, *optional*):
955
+ A function that will be called every `callback_steps` steps during inference. The function will be
956
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
957
+ callback_steps (`int`, *optional*, defaults to 1):
958
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
959
+ called at every step.
960
+ Returns:
961
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
962
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
963
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
964
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
965
+ (nsfw) content, according to the `safety_checker`.
966
+ """
967
+ return self.__call__(
968
+ prompt=prompt,
969
+ negative_prompt=negative_prompt,
970
+ image=image,
971
+ num_inference_steps=num_inference_steps,
972
+ guidance_scale=guidance_scale,
973
+ strength=strength,
974
+ num_images_per_prompt=num_images_per_prompt,
975
+ eta=eta,
976
+ generator=generator,
977
+ max_embeddings_multiples=max_embeddings_multiples,
978
+ output_type=output_type,
979
+ return_dict=return_dict,
980
+ callback=callback,
981
+ callback_steps=callback_steps,
982
+ **kwargs,
983
+ )
984
+
985
+ def inpaint(
986
+ self,
987
+ image: Union[np.ndarray, PIL.Image.Image],
988
+ mask_image: Union[np.ndarray, PIL.Image.Image],
989
+ prompt: Union[str, List[str]],
990
+ negative_prompt: Optional[Union[str, List[str]]] = None,
991
+ strength: float = 0.8,
992
+ num_inference_steps: Optional[int] = 50,
993
+ guidance_scale: Optional[float] = 7.5,
994
+ num_images_per_prompt: Optional[int] = 1,
995
+ eta: Optional[float] = 0.0,
996
+ generator: Optional[torch.Generator] = None,
997
+ max_embeddings_multiples: Optional[int] = 3,
998
+ output_type: Optional[str] = "pil",
999
+ return_dict: bool = True,
1000
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
1001
+ callback_steps: Optional[int] = 1,
1002
+ **kwargs,
1003
+ ):
1004
+ r"""
1005
+ Function for inpaint.
1006
+ Args:
1007
+ image (`np.ndarray` or `PIL.Image.Image`):
1008
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1009
+ process. This is the image whose masked region will be inpainted.
1010
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
1011
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1012
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1013
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1014
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1015
+ prompt (`str` or `List[str]`):
1016
+ The prompt or prompts to guide the image generation.
1017
+ negative_prompt (`str` or `List[str]`, *optional*):
1018
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1019
+ if `guidance_scale` is less than `1`).
1020
+ strength (`float`, *optional*, defaults to 0.8):
1021
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1022
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1023
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1024
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1025
+ num_inference_steps (`int`, *optional*, defaults to 50):
1026
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1027
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1028
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1029
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1030
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1031
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1032
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1033
+ usually at the expense of lower image quality.
1034
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1035
+ The number of images to generate per prompt.
1036
+ eta (`float`, *optional*, defaults to 0.0):
1037
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1038
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1039
+ generator (`torch.Generator`, *optional*):
1040
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1041
+ deterministic.
1042
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1043
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1044
+ output_type (`str`, *optional*, defaults to `"pil"`):
1045
+ The output format of the generate image. Choose between
1046
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1047
+ return_dict (`bool`, *optional*, defaults to `True`):
1048
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1049
+ plain tuple.
1050
+ callback (`Callable`, *optional*):
1051
+ A function that will be called every `callback_steps` steps during inference. The function will be
1052
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1053
+ callback_steps (`int`, *optional*, defaults to 1):
1054
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1055
+ called at every step.
1056
+ Returns:
1057
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1058
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1059
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1060
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1061
+ (nsfw) content, according to the `safety_checker`.
1062
+ """
1063
+ return self.__call__(
1064
+ prompt=prompt,
1065
+ negative_prompt=negative_prompt,
1066
+ image=image,
1067
+ mask_image=mask_image,
1068
+ num_inference_steps=num_inference_steps,
1069
+ guidance_scale=guidance_scale,
1070
+ strength=strength,
1071
+ num_images_per_prompt=num_images_per_prompt,
1072
+ eta=eta,
1073
+ generator=generator,
1074
+ max_embeddings_multiples=max_embeddings_multiples,
1075
+ output_type=output_type,
1076
+ return_dict=return_dict,
1077
+ callback=callback,
1078
+ callback_steps=callback_steps,
1079
+ **kwargs,
1080
+ )
v0.10.1/multilingual_stable_diffusion.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Union
3
+
4
+ import torch
5
+
6
+ from diffusers.configuration_utils import FrozenDict
7
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
8
+ from diffusers.pipeline_utils import DiffusionPipeline
9
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
10
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
11
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
12
+ from diffusers.utils import deprecate, logging
13
+ from transformers import (
14
+ CLIPFeatureExtractor,
15
+ CLIPTextModel,
16
+ CLIPTokenizer,
17
+ MBart50TokenizerFast,
18
+ MBartForConditionalGeneration,
19
+ pipeline,
20
+ )
21
+
22
+
23
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
24
+
25
+
26
+ def detect_language(pipe, prompt, batch_size):
27
+ """helper function to detect language(s) of prompt"""
28
+
29
+ if batch_size == 1:
30
+ preds = pipe(prompt, top_k=1, truncation=True, max_length=128)
31
+ return preds[0]["label"]
32
+ else:
33
+ detected_languages = []
34
+ for p in prompt:
35
+ preds = pipe(p, top_k=1, truncation=True, max_length=128)
36
+ detected_languages.append(preds[0]["label"])
37
+
38
+ return detected_languages
39
+
40
+
41
+ def translate_prompt(prompt, translation_tokenizer, translation_model, device):
42
+ """helper function to translate prompt to English"""
43
+
44
+ encoded_prompt = translation_tokenizer(prompt, return_tensors="pt").to(device)
45
+ generated_tokens = translation_model.generate(**encoded_prompt, max_new_tokens=1000)
46
+ en_trans = translation_tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
47
+
48
+ return en_trans[0]
49
+
50
+
51
+ class MultilingualStableDiffusion(DiffusionPipeline):
52
+ r"""
53
+ Pipeline for text-to-image generation using Stable Diffusion in different languages.
54
+
55
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
56
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
57
+
58
+ Args:
59
+ detection_pipeline ([`pipeline`]):
60
+ Transformers pipeline to detect prompt's language.
61
+ translation_model ([`MBartForConditionalGeneration`]):
62
+ Model to translate prompt to English, if necessary. Please refer to the
63
+ [model card](https://huggingface.co/docs/transformers/model_doc/mbart) for details.
64
+ translation_tokenizer ([`MBart50TokenizerFast`]):
65
+ Tokenizer of the translation model.
66
+ vae ([`AutoencoderKL`]):
67
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
68
+ text_encoder ([`CLIPTextModel`]):
69
+ Frozen text-encoder. Stable Diffusion uses the text portion of
70
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
71
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
72
+ tokenizer (`CLIPTokenizer`):
73
+ Tokenizer of class
74
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
75
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
76
+ scheduler ([`SchedulerMixin`]):
77
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
78
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
79
+ safety_checker ([`StableDiffusionSafetyChecker`]):
80
+ Classification module that estimates whether generated images could be considered offensive or harmful.
81
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
82
+ feature_extractor ([`CLIPFeatureExtractor`]):
83
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ detection_pipeline: pipeline,
89
+ translation_model: MBartForConditionalGeneration,
90
+ translation_tokenizer: MBart50TokenizerFast,
91
+ vae: AutoencoderKL,
92
+ text_encoder: CLIPTextModel,
93
+ tokenizer: CLIPTokenizer,
94
+ unet: UNet2DConditionModel,
95
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
96
+ safety_checker: StableDiffusionSafetyChecker,
97
+ feature_extractor: CLIPFeatureExtractor,
98
+ ):
99
+ super().__init__()
100
+
101
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
102
+ deprecation_message = (
103
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
104
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
105
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
106
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
107
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
108
+ " file"
109
+ )
110
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
111
+ new_config = dict(scheduler.config)
112
+ new_config["steps_offset"] = 1
113
+ scheduler._internal_dict = FrozenDict(new_config)
114
+
115
+ if safety_checker is None:
116
+ logger.warning(
117
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
118
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
119
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
120
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
121
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
122
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
123
+ )
124
+
125
+ self.register_modules(
126
+ detection_pipeline=detection_pipeline,
127
+ translation_model=translation_model,
128
+ translation_tokenizer=translation_tokenizer,
129
+ vae=vae,
130
+ text_encoder=text_encoder,
131
+ tokenizer=tokenizer,
132
+ unet=unet,
133
+ scheduler=scheduler,
134
+ safety_checker=safety_checker,
135
+ feature_extractor=feature_extractor,
136
+ )
137
+
138
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
139
+ r"""
140
+ Enable sliced attention computation.
141
+
142
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
143
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
144
+
145
+ Args:
146
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
147
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
148
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
149
+ `attention_head_dim` must be a multiple of `slice_size`.
150
+ """
151
+ if slice_size == "auto":
152
+ # half the attention head size is usually a good trade-off between
153
+ # speed and memory
154
+ slice_size = self.unet.config.attention_head_dim // 2
155
+ self.unet.set_attention_slice(slice_size)
156
+
157
+ def disable_attention_slicing(self):
158
+ r"""
159
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
160
+ back to computing attention in one step.
161
+ """
162
+ # set slice_size = `None` to disable `attention slicing`
163
+ self.enable_attention_slicing(None)
164
+
165
+ @torch.no_grad()
166
+ def __call__(
167
+ self,
168
+ prompt: Union[str, List[str]],
169
+ height: int = 512,
170
+ width: int = 512,
171
+ num_inference_steps: int = 50,
172
+ guidance_scale: float = 7.5,
173
+ negative_prompt: Optional[Union[str, List[str]]] = None,
174
+ num_images_per_prompt: Optional[int] = 1,
175
+ eta: float = 0.0,
176
+ generator: Optional[torch.Generator] = None,
177
+ latents: Optional[torch.FloatTensor] = None,
178
+ output_type: Optional[str] = "pil",
179
+ return_dict: bool = True,
180
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
181
+ callback_steps: Optional[int] = 1,
182
+ **kwargs,
183
+ ):
184
+ r"""
185
+ Function invoked when calling the pipeline for generation.
186
+
187
+ Args:
188
+ prompt (`str` or `List[str]`):
189
+ The prompt or prompts to guide the image generation. Can be in different languages.
190
+ height (`int`, *optional*, defaults to 512):
191
+ The height in pixels of the generated image.
192
+ width (`int`, *optional*, defaults to 512):
193
+ The width in pixels of the generated image.
194
+ num_inference_steps (`int`, *optional*, defaults to 50):
195
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
196
+ expense of slower inference.
197
+ guidance_scale (`float`, *optional*, defaults to 7.5):
198
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
199
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
200
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
201
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
202
+ usually at the expense of lower image quality.
203
+ negative_prompt (`str` or `List[str]`, *optional*):
204
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
205
+ if `guidance_scale` is less than `1`).
206
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
207
+ The number of images to generate per prompt.
208
+ eta (`float`, *optional*, defaults to 0.0):
209
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
210
+ [`schedulers.DDIMScheduler`], will be ignored for others.
211
+ generator (`torch.Generator`, *optional*):
212
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
213
+ deterministic.
214
+ latents (`torch.FloatTensor`, *optional*):
215
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
216
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
217
+ tensor will ge generated by sampling using the supplied random `generator`.
218
+ output_type (`str`, *optional*, defaults to `"pil"`):
219
+ The output format of the generate image. Choose between
220
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
221
+ return_dict (`bool`, *optional*, defaults to `True`):
222
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
223
+ plain tuple.
224
+ callback (`Callable`, *optional*):
225
+ A function that will be called every `callback_steps` steps during inference. The function will be
226
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
227
+ callback_steps (`int`, *optional*, defaults to 1):
228
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
229
+ called at every step.
230
+
231
+ Returns:
232
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
233
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
234
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
235
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
236
+ (nsfw) content, according to the `safety_checker`.
237
+ """
238
+ if isinstance(prompt, str):
239
+ batch_size = 1
240
+ elif isinstance(prompt, list):
241
+ batch_size = len(prompt)
242
+ else:
243
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
244
+
245
+ if height % 8 != 0 or width % 8 != 0:
246
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
247
+
248
+ if (callback_steps is None) or (
249
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
250
+ ):
251
+ raise ValueError(
252
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
253
+ f" {type(callback_steps)}."
254
+ )
255
+
256
+ # detect language and translate if necessary
257
+ prompt_language = detect_language(self.detection_pipeline, prompt, batch_size)
258
+ if batch_size == 1 and prompt_language != "en":
259
+ prompt = translate_prompt(prompt, self.translation_tokenizer, self.translation_model, self.device)
260
+
261
+ if isinstance(prompt, list):
262
+ for index in range(batch_size):
263
+ if prompt_language[index] != "en":
264
+ p = translate_prompt(
265
+ prompt[index], self.translation_tokenizer, self.translation_model, self.device
266
+ )
267
+ prompt[index] = p
268
+
269
+ # get prompt text embeddings
270
+ text_inputs = self.tokenizer(
271
+ prompt,
272
+ padding="max_length",
273
+ max_length=self.tokenizer.model_max_length,
274
+ return_tensors="pt",
275
+ )
276
+ text_input_ids = text_inputs.input_ids
277
+
278
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
279
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
280
+ logger.warning(
281
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
282
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
283
+ )
284
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
285
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
286
+
287
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
288
+ bs_embed, seq_len, _ = text_embeddings.shape
289
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
290
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
291
+
292
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
293
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
294
+ # corresponds to doing no classifier free guidance.
295
+ do_classifier_free_guidance = guidance_scale > 1.0
296
+ # get unconditional embeddings for classifier free guidance
297
+ if do_classifier_free_guidance:
298
+ uncond_tokens: List[str]
299
+ if negative_prompt is None:
300
+ uncond_tokens = [""] * batch_size
301
+ elif type(prompt) is not type(negative_prompt):
302
+ raise TypeError(
303
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
304
+ f" {type(prompt)}."
305
+ )
306
+ elif isinstance(negative_prompt, str):
307
+ # detect language and translate it if necessary
308
+ negative_prompt_language = detect_language(self.detection_pipeline, negative_prompt, batch_size)
309
+ if negative_prompt_language != "en":
310
+ negative_prompt = translate_prompt(
311
+ negative_prompt, self.translation_tokenizer, self.translation_model, self.device
312
+ )
313
+ if isinstance(negative_prompt, str):
314
+ uncond_tokens = [negative_prompt]
315
+ elif batch_size != len(negative_prompt):
316
+ raise ValueError(
317
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
318
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
319
+ " the batch size of `prompt`."
320
+ )
321
+ else:
322
+ # detect language and translate it if necessary
323
+ if isinstance(negative_prompt, list):
324
+ negative_prompt_languages = detect_language(self.detection_pipeline, negative_prompt, batch_size)
325
+ for index in range(batch_size):
326
+ if negative_prompt_languages[index] != "en":
327
+ p = translate_prompt(
328
+ negative_prompt[index], self.translation_tokenizer, self.translation_model, self.device
329
+ )
330
+ negative_prompt[index] = p
331
+ uncond_tokens = negative_prompt
332
+
333
+ max_length = text_input_ids.shape[-1]
334
+ uncond_input = self.tokenizer(
335
+ uncond_tokens,
336
+ padding="max_length",
337
+ max_length=max_length,
338
+ truncation=True,
339
+ return_tensors="pt",
340
+ )
341
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
342
+
343
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
344
+ seq_len = uncond_embeddings.shape[1]
345
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
346
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
347
+
348
+ # For classifier free guidance, we need to do two forward passes.
349
+ # Here we concatenate the unconditional and text embeddings into a single batch
350
+ # to avoid doing two forward passes
351
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
352
+
353
+ # get the initial random noise unless the user supplied it
354
+
355
+ # Unlike in other pipelines, latents need to be generated in the target device
356
+ # for 1-to-1 results reproducibility with the CompVis implementation.
357
+ # However this currently doesn't work in `mps`.
358
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
359
+ latents_dtype = text_embeddings.dtype
360
+ if latents is None:
361
+ if self.device.type == "mps":
362
+ # randn does not work reproducibly on mps
363
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
364
+ self.device
365
+ )
366
+ else:
367
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
368
+ else:
369
+ if latents.shape != latents_shape:
370
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
371
+ latents = latents.to(self.device)
372
+
373
+ # set timesteps
374
+ self.scheduler.set_timesteps(num_inference_steps)
375
+
376
+ # Some schedulers like PNDM have timesteps as arrays
377
+ # It's more optimized to move all timesteps to correct device beforehand
378
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
379
+
380
+ # scale the initial noise by the standard deviation required by the scheduler
381
+ latents = latents * self.scheduler.init_noise_sigma
382
+
383
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
384
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
385
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
386
+ # and should be between [0, 1]
387
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
388
+ extra_step_kwargs = {}
389
+ if accepts_eta:
390
+ extra_step_kwargs["eta"] = eta
391
+
392
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
393
+ # expand the latents if we are doing classifier free guidance
394
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
395
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
396
+
397
+ # predict the noise residual
398
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
399
+
400
+ # perform guidance
401
+ if do_classifier_free_guidance:
402
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
403
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
404
+
405
+ # compute the previous noisy sample x_t -> x_t-1
406
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
407
+
408
+ # call the callback, if provided
409
+ if callback is not None and i % callback_steps == 0:
410
+ callback(i, t, latents)
411
+
412
+ latents = 1 / 0.18215 * latents
413
+ image = self.vae.decode(latents).sample
414
+
415
+ image = (image / 2 + 0.5).clamp(0, 1)
416
+
417
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
418
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
419
+
420
+ if self.safety_checker is not None:
421
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
422
+ self.device
423
+ )
424
+ image, has_nsfw_concept = self.safety_checker(
425
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
426
+ )
427
+ else:
428
+ has_nsfw_concept = None
429
+
430
+ if output_type == "pil":
431
+ image = self.numpy_to_pil(image)
432
+
433
+ if not return_dict:
434
+ return (image, has_nsfw_concept)
435
+
436
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.10.1/one_step_unet.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+
4
+ from diffusers import DiffusionPipeline
5
+
6
+
7
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
8
+ def __init__(self, unet, scheduler):
9
+ super().__init__()
10
+
11
+ self.register_modules(unet=unet, scheduler=scheduler)
12
+
13
+ def __call__(self):
14
+ image = torch.randn(
15
+ (1, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size),
16
+ )
17
+ timestep = 1
18
+
19
+ model_output = self.unet(image, timestep).sample
20
+ scheduler_output = self.scheduler.step(model_output, timestep, image).prev_sample
21
+
22
+ return scheduler_output
v0.10.1/sd_text2img_k_diffusion.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import importlib
16
+ import warnings
17
+ from typing import Callable, List, Optional, Union
18
+
19
+ import torch
20
+
21
+ from diffusers import LMSDiscreteScheduler
22
+ from diffusers.pipeline_utils import DiffusionPipeline
23
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
24
+ from diffusers.utils import is_accelerate_available, logging
25
+ from k_diffusion.external import CompVisDenoiser, CompVisVDenoiser
26
+
27
+
28
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
29
+
30
+
31
+ class ModelWrapper:
32
+ def __init__(self, model, alphas_cumprod):
33
+ self.model = model
34
+ self.alphas_cumprod = alphas_cumprod
35
+
36
+ def apply_model(self, *args, **kwargs):
37
+ if len(args) == 3:
38
+ encoder_hidden_states = args[-1]
39
+ args = args[:2]
40
+ if kwargs.get("cond", None) is not None:
41
+ encoder_hidden_states = kwargs.pop("cond")
42
+ return self.model(*args, encoder_hidden_states=encoder_hidden_states, **kwargs).sample
43
+
44
+
45
+ class StableDiffusionPipeline(DiffusionPipeline):
46
+ r"""
47
+ Pipeline for text-to-image generation using Stable Diffusion.
48
+
49
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
50
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
51
+
52
+ Args:
53
+ vae ([`AutoencoderKL`]):
54
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
55
+ text_encoder ([`CLIPTextModel`]):
56
+ Frozen text-encoder. Stable Diffusion uses the text portion of
57
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
58
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
59
+ tokenizer (`CLIPTokenizer`):
60
+ Tokenizer of class
61
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
62
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
63
+ scheduler ([`SchedulerMixin`]):
64
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
65
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
66
+ safety_checker ([`StableDiffusionSafetyChecker`]):
67
+ Classification module that estimates whether generated images could be considered offensive or harmful.
68
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
69
+ feature_extractor ([`CLIPFeatureExtractor`]):
70
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
71
+ """
72
+ _optional_components = ["safety_checker", "feature_extractor"]
73
+
74
+ def __init__(
75
+ self,
76
+ vae,
77
+ text_encoder,
78
+ tokenizer,
79
+ unet,
80
+ scheduler,
81
+ safety_checker,
82
+ feature_extractor,
83
+ ):
84
+ super().__init__()
85
+
86
+ if safety_checker is None:
87
+ logger.warning(
88
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
89
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
90
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
91
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
92
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
93
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
94
+ )
95
+
96
+ # get correct sigmas from LMS
97
+ scheduler = LMSDiscreteScheduler.from_config(scheduler.config)
98
+ self.register_modules(
99
+ vae=vae,
100
+ text_encoder=text_encoder,
101
+ tokenizer=tokenizer,
102
+ unet=unet,
103
+ scheduler=scheduler,
104
+ safety_checker=safety_checker,
105
+ feature_extractor=feature_extractor,
106
+ )
107
+
108
+ model = ModelWrapper(unet, scheduler.alphas_cumprod)
109
+ if scheduler.prediction_type == "v_prediction":
110
+ self.k_diffusion_model = CompVisVDenoiser(model)
111
+ else:
112
+ self.k_diffusion_model = CompVisDenoiser(model)
113
+
114
+ def set_sampler(self, scheduler_type: str):
115
+ warnings.warn("The `set_sampler` method is deprecated, please use `set_scheduler` instead.")
116
+ return self.set_scheduler(scheduler_type)
117
+
118
+ def set_scheduler(self, scheduler_type: str):
119
+ library = importlib.import_module("k_diffusion")
120
+ sampling = getattr(library, "sampling")
121
+ self.sampler = getattr(sampling, scheduler_type)
122
+
123
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
124
+ r"""
125
+ Enable sliced attention computation.
126
+
127
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
128
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
129
+
130
+ Args:
131
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
132
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
133
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
134
+ `attention_head_dim` must be a multiple of `slice_size`.
135
+ """
136
+ if slice_size == "auto":
137
+ # half the attention head size is usually a good trade-off between
138
+ # speed and memory
139
+ slice_size = self.unet.config.attention_head_dim // 2
140
+ self.unet.set_attention_slice(slice_size)
141
+
142
+ def disable_attention_slicing(self):
143
+ r"""
144
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
145
+ back to computing attention in one step.
146
+ """
147
+ # set slice_size = `None` to disable `attention slicing`
148
+ self.enable_attention_slicing(None)
149
+
150
+ def enable_sequential_cpu_offload(self, gpu_id=0):
151
+ r"""
152
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
153
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
154
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
155
+ """
156
+ if is_accelerate_available():
157
+ from accelerate import cpu_offload
158
+ else:
159
+ raise ImportError("Please install accelerate via `pip install accelerate`")
160
+
161
+ device = torch.device(f"cuda:{gpu_id}")
162
+
163
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
164
+ if cpu_offloaded_model is not None:
165
+ cpu_offload(cpu_offloaded_model, device)
166
+
167
+ @property
168
+ def _execution_device(self):
169
+ r"""
170
+ Returns the device on which the pipeline's models will be executed. After calling
171
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
172
+ hooks.
173
+ """
174
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
175
+ return self.device
176
+ for module in self.unet.modules():
177
+ if (
178
+ hasattr(module, "_hf_hook")
179
+ and hasattr(module._hf_hook, "execution_device")
180
+ and module._hf_hook.execution_device is not None
181
+ ):
182
+ return torch.device(module._hf_hook.execution_device)
183
+ return self.device
184
+
185
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
186
+ r"""
187
+ Encodes the prompt into text encoder hidden states.
188
+
189
+ Args:
190
+ prompt (`str` or `list(int)`):
191
+ prompt to be encoded
192
+ device: (`torch.device`):
193
+ torch device
194
+ num_images_per_prompt (`int`):
195
+ number of images that should be generated per prompt
196
+ do_classifier_free_guidance (`bool`):
197
+ whether to use classifier free guidance or not
198
+ negative_prompt (`str` or `List[str]`):
199
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
200
+ if `guidance_scale` is less than `1`).
201
+ """
202
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
203
+
204
+ text_inputs = self.tokenizer(
205
+ prompt,
206
+ padding="max_length",
207
+ max_length=self.tokenizer.model_max_length,
208
+ truncation=True,
209
+ return_tensors="pt",
210
+ )
211
+ text_input_ids = text_inputs.input_ids
212
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="pt").input_ids
213
+
214
+ if not torch.equal(text_input_ids, untruncated_ids):
215
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
216
+ logger.warning(
217
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
218
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
219
+ )
220
+
221
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
222
+ attention_mask = text_inputs.attention_mask.to(device)
223
+ else:
224
+ attention_mask = None
225
+
226
+ text_embeddings = self.text_encoder(
227
+ text_input_ids.to(device),
228
+ attention_mask=attention_mask,
229
+ )
230
+ text_embeddings = text_embeddings[0]
231
+
232
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
233
+ bs_embed, seq_len, _ = text_embeddings.shape
234
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
235
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
236
+
237
+ # get unconditional embeddings for classifier free guidance
238
+ if do_classifier_free_guidance:
239
+ uncond_tokens: List[str]
240
+ if negative_prompt is None:
241
+ uncond_tokens = [""] * batch_size
242
+ elif type(prompt) is not type(negative_prompt):
243
+ raise TypeError(
244
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
245
+ f" {type(prompt)}."
246
+ )
247
+ elif isinstance(negative_prompt, str):
248
+ uncond_tokens = [negative_prompt]
249
+ elif batch_size != len(negative_prompt):
250
+ raise ValueError(
251
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
252
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
253
+ " the batch size of `prompt`."
254
+ )
255
+ else:
256
+ uncond_tokens = negative_prompt
257
+
258
+ max_length = text_input_ids.shape[-1]
259
+ uncond_input = self.tokenizer(
260
+ uncond_tokens,
261
+ padding="max_length",
262
+ max_length=max_length,
263
+ truncation=True,
264
+ return_tensors="pt",
265
+ )
266
+
267
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
268
+ attention_mask = uncond_input.attention_mask.to(device)
269
+ else:
270
+ attention_mask = None
271
+
272
+ uncond_embeddings = self.text_encoder(
273
+ uncond_input.input_ids.to(device),
274
+ attention_mask=attention_mask,
275
+ )
276
+ uncond_embeddings = uncond_embeddings[0]
277
+
278
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
279
+ seq_len = uncond_embeddings.shape[1]
280
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
281
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
282
+
283
+ # For classifier free guidance, we need to do two forward passes.
284
+ # Here we concatenate the unconditional and text embeddings into a single batch
285
+ # to avoid doing two forward passes
286
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
287
+
288
+ return text_embeddings
289
+
290
+ def run_safety_checker(self, image, device, dtype):
291
+ if self.safety_checker is not None:
292
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
293
+ image, has_nsfw_concept = self.safety_checker(
294
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
295
+ )
296
+ else:
297
+ has_nsfw_concept = None
298
+ return image, has_nsfw_concept
299
+
300
+ def decode_latents(self, latents):
301
+ latents = 1 / 0.18215 * latents
302
+ image = self.vae.decode(latents).sample
303
+ image = (image / 2 + 0.5).clamp(0, 1)
304
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
305
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
306
+ return image
307
+
308
+ def check_inputs(self, prompt, height, width, callback_steps):
309
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
310
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
311
+
312
+ if height % 8 != 0 or width % 8 != 0:
313
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
314
+
315
+ if (callback_steps is None) or (
316
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
317
+ ):
318
+ raise ValueError(
319
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
320
+ f" {type(callback_steps)}."
321
+ )
322
+
323
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
324
+ shape = (batch_size, num_channels_latents, height // 8, width // 8)
325
+ if latents is None:
326
+ if device.type == "mps":
327
+ # randn does not work reproducibly on mps
328
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
329
+ else:
330
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
331
+ else:
332
+ if latents.shape != shape:
333
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
334
+ latents = latents.to(device)
335
+
336
+ # scale the initial noise by the standard deviation required by the scheduler
337
+ return latents
338
+
339
+ @torch.no_grad()
340
+ def __call__(
341
+ self,
342
+ prompt: Union[str, List[str]],
343
+ height: int = 512,
344
+ width: int = 512,
345
+ num_inference_steps: int = 50,
346
+ guidance_scale: float = 7.5,
347
+ negative_prompt: Optional[Union[str, List[str]]] = None,
348
+ num_images_per_prompt: Optional[int] = 1,
349
+ eta: float = 0.0,
350
+ generator: Optional[torch.Generator] = None,
351
+ latents: Optional[torch.FloatTensor] = None,
352
+ output_type: Optional[str] = "pil",
353
+ return_dict: bool = True,
354
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
355
+ callback_steps: Optional[int] = 1,
356
+ **kwargs,
357
+ ):
358
+ r"""
359
+ Function invoked when calling the pipeline for generation.
360
+
361
+ Args:
362
+ prompt (`str` or `List[str]`):
363
+ The prompt or prompts to guide the image generation.
364
+ height (`int`, *optional*, defaults to 512):
365
+ The height in pixels of the generated image.
366
+ width (`int`, *optional*, defaults to 512):
367
+ The width in pixels of the generated image.
368
+ num_inference_steps (`int`, *optional*, defaults to 50):
369
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
370
+ expense of slower inference.
371
+ guidance_scale (`float`, *optional*, defaults to 7.5):
372
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
373
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
374
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
375
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
376
+ usually at the expense of lower image quality.
377
+ negative_prompt (`str` or `List[str]`, *optional*):
378
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
379
+ if `guidance_scale` is less than `1`).
380
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
381
+ The number of images to generate per prompt.
382
+ eta (`float`, *optional*, defaults to 0.0):
383
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
384
+ [`schedulers.DDIMScheduler`], will be ignored for others.
385
+ generator (`torch.Generator`, *optional*):
386
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
387
+ deterministic.
388
+ latents (`torch.FloatTensor`, *optional*):
389
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
390
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
391
+ tensor will ge generated by sampling using the supplied random `generator`.
392
+ output_type (`str`, *optional*, defaults to `"pil"`):
393
+ The output format of the generate image. Choose between
394
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
395
+ return_dict (`bool`, *optional*, defaults to `True`):
396
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
397
+ plain tuple.
398
+ callback (`Callable`, *optional*):
399
+ A function that will be called every `callback_steps` steps during inference. The function will be
400
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
401
+ callback_steps (`int`, *optional*, defaults to 1):
402
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
403
+ called at every step.
404
+
405
+ Returns:
406
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
407
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
408
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
409
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
410
+ (nsfw) content, according to the `safety_checker`.
411
+ """
412
+
413
+ # 1. Check inputs. Raise error if not correct
414
+ self.check_inputs(prompt, height, width, callback_steps)
415
+
416
+ # 2. Define call parameters
417
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
418
+ device = self._execution_device
419
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
420
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
421
+ # corresponds to doing no classifier free guidance.
422
+ do_classifier_free_guidance = True
423
+ if guidance_scale <= 1.0:
424
+ raise ValueError("has to use guidance_scale")
425
+
426
+ # 3. Encode input prompt
427
+ text_embeddings = self._encode_prompt(
428
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
429
+ )
430
+
431
+ # 4. Prepare timesteps
432
+ self.scheduler.set_timesteps(num_inference_steps, device=text_embeddings.device)
433
+ sigmas = self.scheduler.sigmas
434
+ sigmas = sigmas.to(text_embeddings.dtype)
435
+
436
+ # 5. Prepare latent variables
437
+ num_channels_latents = self.unet.in_channels
438
+ latents = self.prepare_latents(
439
+ batch_size * num_images_per_prompt,
440
+ num_channels_latents,
441
+ height,
442
+ width,
443
+ text_embeddings.dtype,
444
+ device,
445
+ generator,
446
+ latents,
447
+ )
448
+ latents = latents * sigmas[0]
449
+ self.k_diffusion_model.sigmas = self.k_diffusion_model.sigmas.to(latents.device)
450
+ self.k_diffusion_model.log_sigmas = self.k_diffusion_model.log_sigmas.to(latents.device)
451
+
452
+ def model_fn(x, t):
453
+ latent_model_input = torch.cat([x] * 2)
454
+
455
+ noise_pred = self.k_diffusion_model(latent_model_input, t, cond=text_embeddings)
456
+
457
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
458
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
459
+ return noise_pred
460
+
461
+ latents = self.sampler(model_fn, latents, sigmas)
462
+
463
+ # 8. Post-processing
464
+ image = self.decode_latents(latents)
465
+
466
+ # 9. Run safety checker
467
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
468
+
469
+ # 10. Convert to PIL
470
+ if output_type == "pil":
471
+ image = self.numpy_to_pil(image)
472
+
473
+ if not return_dict:
474
+ return (image, has_nsfw_concept)
475
+
476
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.10.1/seed_resize_stable_diffusion.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modified based on diffusion library from Huggingface: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
3
+ """
4
+ import inspect
5
+ from typing import Callable, List, Optional, Union
6
+
7
+ import torch
8
+
9
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
10
+ from diffusers.pipeline_utils import DiffusionPipeline
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
12
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
13
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
14
+ from diffusers.utils import logging
15
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+
21
+ class SeedResizeStableDiffusionPipeline(DiffusionPipeline):
22
+ r"""
23
+ Pipeline for text-to-image generation using Stable Diffusion.
24
+
25
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
26
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
27
+
28
+ Args:
29
+ vae ([`AutoencoderKL`]):
30
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
31
+ text_encoder ([`CLIPTextModel`]):
32
+ Frozen text-encoder. Stable Diffusion uses the text portion of
33
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
34
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
35
+ tokenizer (`CLIPTokenizer`):
36
+ Tokenizer of class
37
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
38
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
39
+ scheduler ([`SchedulerMixin`]):
40
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
41
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
42
+ safety_checker ([`StableDiffusionSafetyChecker`]):
43
+ Classification module that estimates whether generated images could be considered offensive or harmful.
44
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
45
+ feature_extractor ([`CLIPFeatureExtractor`]):
46
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ vae: AutoencoderKL,
52
+ text_encoder: CLIPTextModel,
53
+ tokenizer: CLIPTokenizer,
54
+ unet: UNet2DConditionModel,
55
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
56
+ safety_checker: StableDiffusionSafetyChecker,
57
+ feature_extractor: CLIPFeatureExtractor,
58
+ ):
59
+ super().__init__()
60
+ self.register_modules(
61
+ vae=vae,
62
+ text_encoder=text_encoder,
63
+ tokenizer=tokenizer,
64
+ unet=unet,
65
+ scheduler=scheduler,
66
+ safety_checker=safety_checker,
67
+ feature_extractor=feature_extractor,
68
+ )
69
+
70
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
71
+ r"""
72
+ Enable sliced attention computation.
73
+
74
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
75
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
76
+
77
+ Args:
78
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
79
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
80
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
81
+ `attention_head_dim` must be a multiple of `slice_size`.
82
+ """
83
+ if slice_size == "auto":
84
+ # half the attention head size is usually a good trade-off between
85
+ # speed and memory
86
+ slice_size = self.unet.config.attention_head_dim // 2
87
+ self.unet.set_attention_slice(slice_size)
88
+
89
+ def disable_attention_slicing(self):
90
+ r"""
91
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
92
+ back to computing attention in one step.
93
+ """
94
+ # set slice_size = `None` to disable `attention slicing`
95
+ self.enable_attention_slicing(None)
96
+
97
+ @torch.no_grad()
98
+ def __call__(
99
+ self,
100
+ prompt: Union[str, List[str]],
101
+ height: int = 512,
102
+ width: int = 512,
103
+ num_inference_steps: int = 50,
104
+ guidance_scale: float = 7.5,
105
+ negative_prompt: Optional[Union[str, List[str]]] = None,
106
+ num_images_per_prompt: Optional[int] = 1,
107
+ eta: float = 0.0,
108
+ generator: Optional[torch.Generator] = None,
109
+ latents: Optional[torch.FloatTensor] = None,
110
+ output_type: Optional[str] = "pil",
111
+ return_dict: bool = True,
112
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
113
+ callback_steps: Optional[int] = 1,
114
+ text_embeddings: Optional[torch.FloatTensor] = None,
115
+ **kwargs,
116
+ ):
117
+ r"""
118
+ Function invoked when calling the pipeline for generation.
119
+
120
+ Args:
121
+ prompt (`str` or `List[str]`):
122
+ The prompt or prompts to guide the image generation.
123
+ height (`int`, *optional*, defaults to 512):
124
+ The height in pixels of the generated image.
125
+ width (`int`, *optional*, defaults to 512):
126
+ The width in pixels of the generated image.
127
+ num_inference_steps (`int`, *optional*, defaults to 50):
128
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
129
+ expense of slower inference.
130
+ guidance_scale (`float`, *optional*, defaults to 7.5):
131
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
132
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
133
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
134
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
135
+ usually at the expense of lower image quality.
136
+ negative_prompt (`str` or `List[str]`, *optional*):
137
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
138
+ if `guidance_scale` is less than `1`).
139
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
140
+ The number of images to generate per prompt.
141
+ eta (`float`, *optional*, defaults to 0.0):
142
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
143
+ [`schedulers.DDIMScheduler`], will be ignored for others.
144
+ generator (`torch.Generator`, *optional*):
145
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
146
+ deterministic.
147
+ latents (`torch.FloatTensor`, *optional*):
148
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
149
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
150
+ tensor will ge generated by sampling using the supplied random `generator`.
151
+ output_type (`str`, *optional*, defaults to `"pil"`):
152
+ The output format of the generate image. Choose between
153
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
154
+ return_dict (`bool`, *optional*, defaults to `True`):
155
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
156
+ plain tuple.
157
+ callback (`Callable`, *optional*):
158
+ A function that will be called every `callback_steps` steps during inference. The function will be
159
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
160
+ callback_steps (`int`, *optional*, defaults to 1):
161
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
162
+ called at every step.
163
+
164
+ Returns:
165
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
166
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
167
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
168
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
169
+ (nsfw) content, according to the `safety_checker`.
170
+ """
171
+
172
+ if isinstance(prompt, str):
173
+ batch_size = 1
174
+ elif isinstance(prompt, list):
175
+ batch_size = len(prompt)
176
+ else:
177
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
178
+
179
+ if height % 8 != 0 or width % 8 != 0:
180
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
181
+
182
+ if (callback_steps is None) or (
183
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
184
+ ):
185
+ raise ValueError(
186
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
187
+ f" {type(callback_steps)}."
188
+ )
189
+
190
+ # get prompt text embeddings
191
+ text_inputs = self.tokenizer(
192
+ prompt,
193
+ padding="max_length",
194
+ max_length=self.tokenizer.model_max_length,
195
+ return_tensors="pt",
196
+ )
197
+ text_input_ids = text_inputs.input_ids
198
+
199
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
200
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
201
+ logger.warning(
202
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
203
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
204
+ )
205
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
206
+
207
+ if text_embeddings is None:
208
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
209
+
210
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
211
+ bs_embed, seq_len, _ = text_embeddings.shape
212
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
213
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
214
+
215
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
216
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
217
+ # corresponds to doing no classifier free guidance.
218
+ do_classifier_free_guidance = guidance_scale > 1.0
219
+ # get unconditional embeddings for classifier free guidance
220
+ if do_classifier_free_guidance:
221
+ uncond_tokens: List[str]
222
+ if negative_prompt is None:
223
+ uncond_tokens = [""]
224
+ elif type(prompt) is not type(negative_prompt):
225
+ raise TypeError(
226
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
227
+ f" {type(prompt)}."
228
+ )
229
+ elif isinstance(negative_prompt, str):
230
+ uncond_tokens = [negative_prompt]
231
+ elif batch_size != len(negative_prompt):
232
+ raise ValueError(
233
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
234
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
235
+ " the batch size of `prompt`."
236
+ )
237
+ else:
238
+ uncond_tokens = negative_prompt
239
+
240
+ max_length = text_input_ids.shape[-1]
241
+ uncond_input = self.tokenizer(
242
+ uncond_tokens,
243
+ padding="max_length",
244
+ max_length=max_length,
245
+ truncation=True,
246
+ return_tensors="pt",
247
+ )
248
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
249
+
250
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
251
+ seq_len = uncond_embeddings.shape[1]
252
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
253
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
254
+
255
+ # For classifier free guidance, we need to do two forward passes.
256
+ # Here we concatenate the unconditional and text embeddings into a single batch
257
+ # to avoid doing two forward passes
258
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
259
+
260
+ # get the initial random noise unless the user supplied it
261
+
262
+ # Unlike in other pipelines, latents need to be generated in the target device
263
+ # for 1-to-1 results reproducibility with the CompVis implementation.
264
+ # However this currently doesn't work in `mps`.
265
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
266
+ latents_shape_reference = (batch_size * num_images_per_prompt, self.unet.in_channels, 64, 64)
267
+ latents_dtype = text_embeddings.dtype
268
+ if latents is None:
269
+ if self.device.type == "mps":
270
+ # randn does not exist on mps
271
+ latents_reference = torch.randn(
272
+ latents_shape_reference, generator=generator, device="cpu", dtype=latents_dtype
273
+ ).to(self.device)
274
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
275
+ self.device
276
+ )
277
+ else:
278
+ latents_reference = torch.randn(
279
+ latents_shape_reference, generator=generator, device=self.device, dtype=latents_dtype
280
+ )
281
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
282
+ else:
283
+ if latents_reference.shape != latents_shape:
284
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
285
+ latents_reference = latents_reference.to(self.device)
286
+ latents = latents.to(self.device)
287
+
288
+ # This is the key part of the pipeline where we
289
+ # try to ensure that the generated images w/ the same seed
290
+ # but different sizes actually result in similar images
291
+ dx = (latents_shape[3] - latents_shape_reference[3]) // 2
292
+ dy = (latents_shape[2] - latents_shape_reference[2]) // 2
293
+ w = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
294
+ h = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
295
+ tx = 0 if dx < 0 else dx
296
+ ty = 0 if dy < 0 else dy
297
+ dx = max(-dx, 0)
298
+ dy = max(-dy, 0)
299
+ # import pdb
300
+ # pdb.set_trace()
301
+ latents[:, :, ty : ty + h, tx : tx + w] = latents_reference[:, :, dy : dy + h, dx : dx + w]
302
+
303
+ # set timesteps
304
+ self.scheduler.set_timesteps(num_inference_steps)
305
+
306
+ # Some schedulers like PNDM have timesteps as arrays
307
+ # It's more optimized to move all timesteps to correct device beforehand
308
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
309
+
310
+ # scale the initial noise by the standard deviation required by the scheduler
311
+ latents = latents * self.scheduler.init_noise_sigma
312
+
313
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
314
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
315
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
316
+ # and should be between [0, 1]
317
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
318
+ extra_step_kwargs = {}
319
+ if accepts_eta:
320
+ extra_step_kwargs["eta"] = eta
321
+
322
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
323
+ # expand the latents if we are doing classifier free guidance
324
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
325
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
326
+
327
+ # predict the noise residual
328
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
329
+
330
+ # perform guidance
331
+ if do_classifier_free_guidance:
332
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
333
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
334
+
335
+ # compute the previous noisy sample x_t -> x_t-1
336
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
337
+
338
+ # call the callback, if provided
339
+ if callback is not None and i % callback_steps == 0:
340
+ callback(i, t, latents)
341
+
342
+ latents = 1 / 0.18215 * latents
343
+ image = self.vae.decode(latents).sample
344
+
345
+ image = (image / 2 + 0.5).clamp(0, 1)
346
+
347
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
348
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
349
+
350
+ if self.safety_checker is not None:
351
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
352
+ self.device
353
+ )
354
+ image, has_nsfw_concept = self.safety_checker(
355
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
356
+ )
357
+ else:
358
+ has_nsfw_concept = None
359
+
360
+ if output_type == "pil":
361
+ image = self.numpy_to_pil(image)
362
+
363
+ if not return_dict:
364
+ return (image, has_nsfw_concept)
365
+
366
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.10.1/speech_to_image_diffusion.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Union
3
+
4
+ import torch
5
+
6
+ from diffusers import (
7
+ AutoencoderKL,
8
+ DDIMScheduler,
9
+ DiffusionPipeline,
10
+ LMSDiscreteScheduler,
11
+ PNDMScheduler,
12
+ UNet2DConditionModel,
13
+ )
14
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
15
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
16
+ from diffusers.utils import logging
17
+ from transformers import (
18
+ CLIPFeatureExtractor,
19
+ CLIPTextModel,
20
+ CLIPTokenizer,
21
+ WhisperForConditionalGeneration,
22
+ WhisperProcessor,
23
+ )
24
+
25
+
26
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
27
+
28
+
29
+ class SpeechToImagePipeline(DiffusionPipeline):
30
+ def __init__(
31
+ self,
32
+ speech_model: WhisperForConditionalGeneration,
33
+ speech_processor: WhisperProcessor,
34
+ vae: AutoencoderKL,
35
+ text_encoder: CLIPTextModel,
36
+ tokenizer: CLIPTokenizer,
37
+ unet: UNet2DConditionModel,
38
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
39
+ safety_checker: StableDiffusionSafetyChecker,
40
+ feature_extractor: CLIPFeatureExtractor,
41
+ ):
42
+ super().__init__()
43
+
44
+ if safety_checker is None:
45
+ logger.warning(
46
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
47
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
48
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
49
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
50
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
51
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
52
+ )
53
+
54
+ self.register_modules(
55
+ speech_model=speech_model,
56
+ speech_processor=speech_processor,
57
+ vae=vae,
58
+ text_encoder=text_encoder,
59
+ tokenizer=tokenizer,
60
+ unet=unet,
61
+ scheduler=scheduler,
62
+ feature_extractor=feature_extractor,
63
+ )
64
+
65
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
66
+ if slice_size == "auto":
67
+ slice_size = self.unet.config.attention_head_dim // 2
68
+ self.unet.set_attention_slice(slice_size)
69
+
70
+ def disable_attention_slicing(self):
71
+ self.enable_attention_slicing(None)
72
+
73
+ @torch.no_grad()
74
+ def __call__(
75
+ self,
76
+ audio,
77
+ sampling_rate=16_000,
78
+ height: int = 512,
79
+ width: int = 512,
80
+ num_inference_steps: int = 50,
81
+ guidance_scale: float = 7.5,
82
+ negative_prompt: Optional[Union[str, List[str]]] = None,
83
+ num_images_per_prompt: Optional[int] = 1,
84
+ eta: float = 0.0,
85
+ generator: Optional[torch.Generator] = None,
86
+ latents: Optional[torch.FloatTensor] = None,
87
+ output_type: Optional[str] = "pil",
88
+ return_dict: bool = True,
89
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
90
+ callback_steps: Optional[int] = 1,
91
+ **kwargs,
92
+ ):
93
+ inputs = self.speech_processor.feature_extractor(
94
+ audio, return_tensors="pt", sampling_rate=sampling_rate
95
+ ).input_features.to(self.device)
96
+ predicted_ids = self.speech_model.generate(inputs, max_length=480_000)
97
+
98
+ prompt = self.speech_processor.tokenizer.batch_decode(predicted_ids, skip_special_tokens=True, normalize=True)[
99
+ 0
100
+ ]
101
+
102
+ if isinstance(prompt, str):
103
+ batch_size = 1
104
+ elif isinstance(prompt, list):
105
+ batch_size = len(prompt)
106
+ else:
107
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
108
+
109
+ if height % 8 != 0 or width % 8 != 0:
110
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
111
+
112
+ if (callback_steps is None) or (
113
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
114
+ ):
115
+ raise ValueError(
116
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
117
+ f" {type(callback_steps)}."
118
+ )
119
+
120
+ # get prompt text embeddings
121
+ text_inputs = self.tokenizer(
122
+ prompt,
123
+ padding="max_length",
124
+ max_length=self.tokenizer.model_max_length,
125
+ return_tensors="pt",
126
+ )
127
+ text_input_ids = text_inputs.input_ids
128
+
129
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
130
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
131
+ logger.warning(
132
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
133
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
134
+ )
135
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
136
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
137
+
138
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
139
+ bs_embed, seq_len, _ = text_embeddings.shape
140
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
141
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
142
+
143
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
144
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
145
+ # corresponds to doing no classifier free guidance.
146
+ do_classifier_free_guidance = guidance_scale > 1.0
147
+ # get unconditional embeddings for classifier free guidance
148
+ if do_classifier_free_guidance:
149
+ uncond_tokens: List[str]
150
+ if negative_prompt is None:
151
+ uncond_tokens = [""] * batch_size
152
+ elif type(prompt) is not type(negative_prompt):
153
+ raise TypeError(
154
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
155
+ f" {type(prompt)}."
156
+ )
157
+ elif isinstance(negative_prompt, str):
158
+ uncond_tokens = [negative_prompt]
159
+ elif batch_size != len(negative_prompt):
160
+ raise ValueError(
161
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
162
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
163
+ " the batch size of `prompt`."
164
+ )
165
+ else:
166
+ uncond_tokens = negative_prompt
167
+
168
+ max_length = text_input_ids.shape[-1]
169
+ uncond_input = self.tokenizer(
170
+ uncond_tokens,
171
+ padding="max_length",
172
+ max_length=max_length,
173
+ truncation=True,
174
+ return_tensors="pt",
175
+ )
176
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
177
+
178
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
179
+ seq_len = uncond_embeddings.shape[1]
180
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
181
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
182
+
183
+ # For classifier free guidance, we need to do two forward passes.
184
+ # Here we concatenate the unconditional and text embeddings into a single batch
185
+ # to avoid doing two forward passes
186
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
187
+
188
+ # get the initial random noise unless the user supplied it
189
+
190
+ # Unlike in other pipelines, latents need to be generated in the target device
191
+ # for 1-to-1 results reproducibility with the CompVis implementation.
192
+ # However this currently doesn't work in `mps`.
193
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
194
+ latents_dtype = text_embeddings.dtype
195
+ if latents is None:
196
+ if self.device.type == "mps":
197
+ # randn does not exist on mps
198
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
199
+ self.device
200
+ )
201
+ else:
202
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
203
+ else:
204
+ if latents.shape != latents_shape:
205
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
206
+ latents = latents.to(self.device)
207
+
208
+ # set timesteps
209
+ self.scheduler.set_timesteps(num_inference_steps)
210
+
211
+ # Some schedulers like PNDM have timesteps as arrays
212
+ # It's more optimized to move all timesteps to correct device beforehand
213
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
214
+
215
+ # scale the initial noise by the standard deviation required by the scheduler
216
+ latents = latents * self.scheduler.init_noise_sigma
217
+
218
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
219
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
220
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
221
+ # and should be between [0, 1]
222
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
223
+ extra_step_kwargs = {}
224
+ if accepts_eta:
225
+ extra_step_kwargs["eta"] = eta
226
+
227
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
228
+ # expand the latents if we are doing classifier free guidance
229
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
230
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
231
+
232
+ # predict the noise residual
233
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
234
+
235
+ # perform guidance
236
+ if do_classifier_free_guidance:
237
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
238
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
239
+
240
+ # compute the previous noisy sample x_t -> x_t-1
241
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
242
+
243
+ # call the callback, if provided
244
+ if callback is not None and i % callback_steps == 0:
245
+ callback(i, t, latents)
246
+
247
+ latents = 1 / 0.18215 * latents
248
+ image = self.vae.decode(latents).sample
249
+
250
+ image = (image / 2 + 0.5).clamp(0, 1)
251
+
252
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
253
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
254
+
255
+ if output_type == "pil":
256
+ image = self.numpy_to_pil(image)
257
+
258
+ if not return_dict:
259
+ return image
260
+
261
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.10.1/stable_diffusion_mega.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import torch
4
+
5
+ import PIL.Image
6
+ from diffusers import (
7
+ AutoencoderKL,
8
+ DDIMScheduler,
9
+ DiffusionPipeline,
10
+ LMSDiscreteScheduler,
11
+ PNDMScheduler,
12
+ StableDiffusionImg2ImgPipeline,
13
+ StableDiffusionInpaintPipelineLegacy,
14
+ StableDiffusionPipeline,
15
+ UNet2DConditionModel,
16
+ )
17
+ from diffusers.configuration_utils import FrozenDict
18
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
19
+ from diffusers.utils import deprecate, logging
20
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
21
+
22
+
23
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
24
+
25
+
26
+ class StableDiffusionMegaPipeline(DiffusionPipeline):
27
+ r"""
28
+ Pipeline for text-to-image generation using Stable Diffusion.
29
+
30
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
31
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
32
+
33
+ Args:
34
+ vae ([`AutoencoderKL`]):
35
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
36
+ text_encoder ([`CLIPTextModel`]):
37
+ Frozen text-encoder. Stable Diffusion uses the text portion of
38
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
39
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
40
+ tokenizer (`CLIPTokenizer`):
41
+ Tokenizer of class
42
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
43
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
44
+ scheduler ([`SchedulerMixin`]):
45
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
46
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
47
+ safety_checker ([`StableDiffusionMegaSafetyChecker`]):
48
+ Classification module that estimates whether generated images could be considered offensive or harmful.
49
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
50
+ feature_extractor ([`CLIPFeatureExtractor`]):
51
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
52
+ """
53
+ _optional_components = ["safety_checker", "feature_extractor"]
54
+
55
+ def __init__(
56
+ self,
57
+ vae: AutoencoderKL,
58
+ text_encoder: CLIPTextModel,
59
+ tokenizer: CLIPTokenizer,
60
+ unet: UNet2DConditionModel,
61
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
62
+ safety_checker: StableDiffusionSafetyChecker,
63
+ feature_extractor: CLIPFeatureExtractor,
64
+ requires_safety_checker: bool = True,
65
+ ):
66
+ super().__init__()
67
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
68
+ deprecation_message = (
69
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
70
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
71
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
72
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
73
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
74
+ " file"
75
+ )
76
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
77
+ new_config = dict(scheduler.config)
78
+ new_config["steps_offset"] = 1
79
+ scheduler._internal_dict = FrozenDict(new_config)
80
+
81
+ self.register_modules(
82
+ vae=vae,
83
+ text_encoder=text_encoder,
84
+ tokenizer=tokenizer,
85
+ unet=unet,
86
+ scheduler=scheduler,
87
+ safety_checker=safety_checker,
88
+ feature_extractor=feature_extractor,
89
+ )
90
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
91
+
92
+ @property
93
+ def components(self) -> Dict[str, Any]:
94
+ return {k: getattr(self, k) for k in self.config.keys() if not k.startswith("_")}
95
+
96
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
97
+ r"""
98
+ Enable sliced attention computation.
99
+
100
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
101
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
102
+
103
+ Args:
104
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
105
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
106
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
107
+ `attention_head_dim` must be a multiple of `slice_size`.
108
+ """
109
+ if slice_size == "auto":
110
+ # half the attention head size is usually a good trade-off between
111
+ # speed and memory
112
+ slice_size = self.unet.config.attention_head_dim // 2
113
+ self.unet.set_attention_slice(slice_size)
114
+
115
+ def disable_attention_slicing(self):
116
+ r"""
117
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
118
+ back to computing attention in one step.
119
+ """
120
+ # set slice_size = `None` to disable `attention slicing`
121
+ self.enable_attention_slicing(None)
122
+
123
+ @torch.no_grad()
124
+ def inpaint(
125
+ self,
126
+ prompt: Union[str, List[str]],
127
+ image: Union[torch.FloatTensor, PIL.Image.Image],
128
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
129
+ strength: float = 0.8,
130
+ num_inference_steps: Optional[int] = 50,
131
+ guidance_scale: Optional[float] = 7.5,
132
+ negative_prompt: Optional[Union[str, List[str]]] = None,
133
+ num_images_per_prompt: Optional[int] = 1,
134
+ eta: Optional[float] = 0.0,
135
+ generator: Optional[torch.Generator] = None,
136
+ output_type: Optional[str] = "pil",
137
+ return_dict: bool = True,
138
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
139
+ callback_steps: Optional[int] = 1,
140
+ ):
141
+ # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
142
+ return StableDiffusionInpaintPipelineLegacy(**self.components)(
143
+ prompt=prompt,
144
+ image=image,
145
+ mask_image=mask_image,
146
+ strength=strength,
147
+ num_inference_steps=num_inference_steps,
148
+ guidance_scale=guidance_scale,
149
+ negative_prompt=negative_prompt,
150
+ num_images_per_prompt=num_images_per_prompt,
151
+ eta=eta,
152
+ generator=generator,
153
+ output_type=output_type,
154
+ return_dict=return_dict,
155
+ callback=callback,
156
+ )
157
+
158
+ @torch.no_grad()
159
+ def img2img(
160
+ self,
161
+ prompt: Union[str, List[str]],
162
+ image: Union[torch.FloatTensor, PIL.Image.Image],
163
+ strength: float = 0.8,
164
+ num_inference_steps: Optional[int] = 50,
165
+ guidance_scale: Optional[float] = 7.5,
166
+ negative_prompt: Optional[Union[str, List[str]]] = None,
167
+ num_images_per_prompt: Optional[int] = 1,
168
+ eta: Optional[float] = 0.0,
169
+ generator: Optional[torch.Generator] = None,
170
+ output_type: Optional[str] = "pil",
171
+ return_dict: bool = True,
172
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
173
+ callback_steps: Optional[int] = 1,
174
+ **kwargs,
175
+ ):
176
+ # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
177
+ return StableDiffusionImg2ImgPipeline(**self.components)(
178
+ prompt=prompt,
179
+ image=image,
180
+ strength=strength,
181
+ num_inference_steps=num_inference_steps,
182
+ guidance_scale=guidance_scale,
183
+ negative_prompt=negative_prompt,
184
+ num_images_per_prompt=num_images_per_prompt,
185
+ eta=eta,
186
+ generator=generator,
187
+ output_type=output_type,
188
+ return_dict=return_dict,
189
+ callback=callback,
190
+ callback_steps=callback_steps,
191
+ )
192
+
193
+ @torch.no_grad()
194
+ def text2img(
195
+ self,
196
+ prompt: Union[str, List[str]],
197
+ height: int = 512,
198
+ width: int = 512,
199
+ num_inference_steps: int = 50,
200
+ guidance_scale: float = 7.5,
201
+ negative_prompt: Optional[Union[str, List[str]]] = None,
202
+ num_images_per_prompt: Optional[int] = 1,
203
+ eta: float = 0.0,
204
+ generator: Optional[torch.Generator] = None,
205
+ latents: Optional[torch.FloatTensor] = None,
206
+ output_type: Optional[str] = "pil",
207
+ return_dict: bool = True,
208
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
209
+ callback_steps: Optional[int] = 1,
210
+ ):
211
+ # For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
212
+ return StableDiffusionPipeline(**self.components)(
213
+ prompt=prompt,
214
+ height=height,
215
+ width=width,
216
+ num_inference_steps=num_inference_steps,
217
+ guidance_scale=guidance_scale,
218
+ negative_prompt=negative_prompt,
219
+ num_images_per_prompt=num_images_per_prompt,
220
+ eta=eta,
221
+ generator=generator,
222
+ latents=latents,
223
+ output_type=output_type,
224
+ return_dict=return_dict,
225
+ callback=callback,
226
+ callback_steps=callback_steps,
227
+ )
v0.10.1/text_inpainting.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Union
2
+
3
+ import torch
4
+
5
+ import PIL
6
+ from diffusers.configuration_utils import FrozenDict
7
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
8
+ from diffusers.pipeline_utils import DiffusionPipeline
9
+ from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
10
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
11
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
12
+ from diffusers.utils import deprecate, is_accelerate_available, logging
13
+ from transformers import (
14
+ CLIPFeatureExtractor,
15
+ CLIPSegForImageSegmentation,
16
+ CLIPSegProcessor,
17
+ CLIPTextModel,
18
+ CLIPTokenizer,
19
+ )
20
+
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+
25
+ class TextInpainting(DiffusionPipeline):
26
+ r"""
27
+ Pipeline for text based inpainting using Stable Diffusion.
28
+ Uses CLIPSeg to get a mask from the given text, then calls the Inpainting pipeline with the generated mask
29
+
30
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
31
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
32
+
33
+ Args:
34
+ segmentation_model ([`CLIPSegForImageSegmentation`]):
35
+ CLIPSeg Model to generate mask from the given text. Please refer to the [model card]() for details.
36
+ segmentation_processor ([`CLIPSegProcessor`]):
37
+ CLIPSeg processor to get image, text features to translate prompt to English, if necessary. Please refer to the
38
+ [model card](https://huggingface.co/docs/transformers/model_doc/clipseg) for details.
39
+ vae ([`AutoencoderKL`]):
40
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
41
+ text_encoder ([`CLIPTextModel`]):
42
+ Frozen text-encoder. Stable Diffusion uses the text portion of
43
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
44
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
45
+ tokenizer (`CLIPTokenizer`):
46
+ Tokenizer of class
47
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
48
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
49
+ scheduler ([`SchedulerMixin`]):
50
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
51
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
52
+ safety_checker ([`StableDiffusionSafetyChecker`]):
53
+ Classification module that estimates whether generated images could be considered offensive or harmful.
54
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
55
+ feature_extractor ([`CLIPFeatureExtractor`]):
56
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ segmentation_model: CLIPSegForImageSegmentation,
62
+ segmentation_processor: CLIPSegProcessor,
63
+ vae: AutoencoderKL,
64
+ text_encoder: CLIPTextModel,
65
+ tokenizer: CLIPTokenizer,
66
+ unet: UNet2DConditionModel,
67
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
68
+ safety_checker: StableDiffusionSafetyChecker,
69
+ feature_extractor: CLIPFeatureExtractor,
70
+ ):
71
+ super().__init__()
72
+
73
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
74
+ deprecation_message = (
75
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
76
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
77
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
78
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
79
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
80
+ " file"
81
+ )
82
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
83
+ new_config = dict(scheduler.config)
84
+ new_config["steps_offset"] = 1
85
+ scheduler._internal_dict = FrozenDict(new_config)
86
+
87
+ if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
88
+ deprecation_message = (
89
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration"
90
+ " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
91
+ " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
92
+ " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
93
+ " Hub, it would be very nice if you could open a Pull request for the"
94
+ " `scheduler/scheduler_config.json` file"
95
+ )
96
+ deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False)
97
+ new_config = dict(scheduler.config)
98
+ new_config["skip_prk_steps"] = True
99
+ scheduler._internal_dict = FrozenDict(new_config)
100
+
101
+ if safety_checker is None:
102
+ logger.warning(
103
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
104
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
105
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
106
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
107
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
108
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
109
+ )
110
+
111
+ self.register_modules(
112
+ segmentation_model=segmentation_model,
113
+ segmentation_processor=segmentation_processor,
114
+ vae=vae,
115
+ text_encoder=text_encoder,
116
+ tokenizer=tokenizer,
117
+ unet=unet,
118
+ scheduler=scheduler,
119
+ safety_checker=safety_checker,
120
+ feature_extractor=feature_extractor,
121
+ )
122
+
123
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
124
+ r"""
125
+ Enable sliced attention computation.
126
+
127
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
128
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
129
+
130
+ Args:
131
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
132
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
133
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
134
+ `attention_head_dim` must be a multiple of `slice_size`.
135
+ """
136
+ if slice_size == "auto":
137
+ # half the attention head size is usually a good trade-off between
138
+ # speed and memory
139
+ slice_size = self.unet.config.attention_head_dim // 2
140
+ self.unet.set_attention_slice(slice_size)
141
+
142
+ def disable_attention_slicing(self):
143
+ r"""
144
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
145
+ back to computing attention in one step.
146
+ """
147
+ # set slice_size = `None` to disable `attention slicing`
148
+ self.enable_attention_slicing(None)
149
+
150
+ def enable_sequential_cpu_offload(self):
151
+ r"""
152
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
153
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
154
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
155
+ """
156
+ if is_accelerate_available():
157
+ from accelerate import cpu_offload
158
+ else:
159
+ raise ImportError("Please install accelerate via `pip install accelerate`")
160
+
161
+ device = torch.device("cuda")
162
+
163
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
164
+ if cpu_offloaded_model is not None:
165
+ cpu_offload(cpu_offloaded_model, device)
166
+
167
+ @property
168
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
169
+ def _execution_device(self):
170
+ r"""
171
+ Returns the device on which the pipeline's models will be executed. After calling
172
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
173
+ hooks.
174
+ """
175
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
176
+ return self.device
177
+ for module in self.unet.modules():
178
+ if (
179
+ hasattr(module, "_hf_hook")
180
+ and hasattr(module._hf_hook, "execution_device")
181
+ and module._hf_hook.execution_device is not None
182
+ ):
183
+ return torch.device(module._hf_hook.execution_device)
184
+ return self.device
185
+
186
+ @torch.no_grad()
187
+ def __call__(
188
+ self,
189
+ prompt: Union[str, List[str]],
190
+ image: Union[torch.FloatTensor, PIL.Image.Image],
191
+ text: str,
192
+ height: int = 512,
193
+ width: int = 512,
194
+ num_inference_steps: int = 50,
195
+ guidance_scale: float = 7.5,
196
+ negative_prompt: Optional[Union[str, List[str]]] = None,
197
+ num_images_per_prompt: Optional[int] = 1,
198
+ eta: float = 0.0,
199
+ generator: Optional[torch.Generator] = None,
200
+ latents: Optional[torch.FloatTensor] = None,
201
+ output_type: Optional[str] = "pil",
202
+ return_dict: bool = True,
203
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
204
+ callback_steps: Optional[int] = 1,
205
+ **kwargs,
206
+ ):
207
+ r"""
208
+ Function invoked when calling the pipeline for generation.
209
+
210
+ Args:
211
+ prompt (`str` or `List[str]`):
212
+ The prompt or prompts to guide the image generation.
213
+ image (`PIL.Image.Image`):
214
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
215
+ be masked out with `mask_image` and repainted according to `prompt`.
216
+ text (`str``):
217
+ The text to use to generate the mask.
218
+ height (`int`, *optional*, defaults to 512):
219
+ The height in pixels of the generated image.
220
+ width (`int`, *optional*, defaults to 512):
221
+ The width in pixels of the generated image.
222
+ num_inference_steps (`int`, *optional*, defaults to 50):
223
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
224
+ expense of slower inference.
225
+ guidance_scale (`float`, *optional*, defaults to 7.5):
226
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
227
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
228
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
229
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
230
+ usually at the expense of lower image quality.
231
+ negative_prompt (`str` or `List[str]`, *optional*):
232
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
233
+ if `guidance_scale` is less than `1`).
234
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
235
+ The number of images to generate per prompt.
236
+ eta (`float`, *optional*, defaults to 0.0):
237
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
238
+ [`schedulers.DDIMScheduler`], will be ignored for others.
239
+ generator (`torch.Generator`, *optional*):
240
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
241
+ deterministic.
242
+ latents (`torch.FloatTensor`, *optional*):
243
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
244
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
245
+ tensor will ge generated by sampling using the supplied random `generator`.
246
+ output_type (`str`, *optional*, defaults to `"pil"`):
247
+ The output format of the generate image. Choose between
248
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
249
+ return_dict (`bool`, *optional*, defaults to `True`):
250
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
251
+ plain tuple.
252
+ callback (`Callable`, *optional*):
253
+ A function that will be called every `callback_steps` steps during inference. The function will be
254
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
255
+ callback_steps (`int`, *optional*, defaults to 1):
256
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
257
+ called at every step.
258
+
259
+ Returns:
260
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
261
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
262
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
263
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
264
+ (nsfw) content, according to the `safety_checker`.
265
+ """
266
+
267
+ # We use the input text to generate the mask
268
+ inputs = self.segmentation_processor(
269
+ text=[text], images=[image], padding="max_length", return_tensors="pt"
270
+ ).to(self.device)
271
+ outputs = self.segmentation_model(**inputs)
272
+ mask = torch.sigmoid(outputs.logits).cpu().detach().unsqueeze(-1).numpy()
273
+ mask_pil = self.numpy_to_pil(mask)[0].resize(image.size)
274
+
275
+ # Run inpainting pipeline with the generated mask
276
+ inpainting_pipeline = StableDiffusionInpaintPipeline(
277
+ vae=self.vae,
278
+ text_encoder=self.text_encoder,
279
+ tokenizer=self.tokenizer,
280
+ unet=self.unet,
281
+ scheduler=self.scheduler,
282
+ safety_checker=self.safety_checker,
283
+ feature_extractor=self.feature_extractor,
284
+ )
285
+ return inpainting_pipeline(
286
+ prompt=prompt,
287
+ image=image,
288
+ mask_image=mask_pil,
289
+ height=height,
290
+ width=width,
291
+ num_inference_steps=num_inference_steps,
292
+ guidance_scale=guidance_scale,
293
+ negative_prompt=negative_prompt,
294
+ num_images_per_prompt=num_images_per_prompt,
295
+ eta=eta,
296
+ generator=generator,
297
+ latents=latents,
298
+ output_type=output_type,
299
+ return_dict=return_dict,
300
+ callback=callback,
301
+ callback_steps=callback_steps,
302
+ )
v0.10.1/wildcard_stable_diffusion.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+ import random
4
+ import re
5
+ from dataclasses import dataclass
6
+ from typing import Callable, Dict, List, Optional, Union
7
+
8
+ import torch
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.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
15
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
16
+ from diffusers.utils import deprecate, logging
17
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
18
+
19
+
20
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
21
+
22
+ global_re_wildcard = re.compile(r"__([^_]*)__")
23
+
24
+
25
+ def get_filename(path: str):
26
+ # this doesn't work on Windows
27
+ return os.path.basename(path).split(".txt")[0]
28
+
29
+
30
+ def read_wildcard_values(path: str):
31
+ with open(path, encoding="utf8") as f:
32
+ return f.read().splitlines()
33
+
34
+
35
+ def grab_wildcard_values(wildcard_option_dict: Dict[str, List[str]] = {}, wildcard_files: List[str] = []):
36
+ for wildcard_file in wildcard_files:
37
+ filename = get_filename(wildcard_file)
38
+ read_values = read_wildcard_values(wildcard_file)
39
+ if filename not in wildcard_option_dict:
40
+ wildcard_option_dict[filename] = []
41
+ wildcard_option_dict[filename].extend(read_values)
42
+ return wildcard_option_dict
43
+
44
+
45
+ def replace_prompt_with_wildcards(
46
+ prompt: str, wildcard_option_dict: Dict[str, List[str]] = {}, wildcard_files: List[str] = []
47
+ ):
48
+ new_prompt = prompt
49
+
50
+ # get wildcard options
51
+ wildcard_option_dict = grab_wildcard_values(wildcard_option_dict, wildcard_files)
52
+
53
+ for m in global_re_wildcard.finditer(new_prompt):
54
+ wildcard_value = m.group()
55
+ replace_value = random.choice(wildcard_option_dict[wildcard_value.strip("__")])
56
+ new_prompt = new_prompt.replace(wildcard_value, replace_value, 1)
57
+
58
+ return new_prompt
59
+
60
+
61
+ @dataclass
62
+ class WildcardStableDiffusionOutput(StableDiffusionPipelineOutput):
63
+ prompts: List[str]
64
+
65
+
66
+ class WildcardStableDiffusionPipeline(DiffusionPipeline):
67
+ r"""
68
+ Example Usage:
69
+ pipe = WildcardStableDiffusionPipeline.from_pretrained(
70
+ "CompVis/stable-diffusion-v1-4",
71
+ revision="fp16",
72
+ torch_dtype=torch.float16,
73
+ )
74
+ prompt = "__animal__ sitting on a __object__ wearing a __clothing__"
75
+ out = pipe(
76
+ prompt,
77
+ wildcard_option_dict={
78
+ "clothing":["hat", "shirt", "scarf", "beret"]
79
+ },
80
+ wildcard_files=["object.txt", "animal.txt"],
81
+ num_prompt_samples=1
82
+ )
83
+
84
+
85
+ Pipeline for text-to-image generation with wild cards using Stable Diffusion.
86
+
87
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
88
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
89
+
90
+ Args:
91
+ vae ([`AutoencoderKL`]):
92
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
93
+ text_encoder ([`CLIPTextModel`]):
94
+ Frozen text-encoder. Stable Diffusion uses the text portion of
95
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
96
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
97
+ tokenizer (`CLIPTokenizer`):
98
+ Tokenizer of class
99
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
100
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
101
+ scheduler ([`SchedulerMixin`]):
102
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
103
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
104
+ safety_checker ([`StableDiffusionSafetyChecker`]):
105
+ Classification module that estimates whether generated images could be considered offensive or harmful.
106
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
107
+ feature_extractor ([`CLIPFeatureExtractor`]):
108
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
109
+ """
110
+
111
+ def __init__(
112
+ self,
113
+ vae: AutoencoderKL,
114
+ text_encoder: CLIPTextModel,
115
+ tokenizer: CLIPTokenizer,
116
+ unet: UNet2DConditionModel,
117
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
118
+ safety_checker: StableDiffusionSafetyChecker,
119
+ feature_extractor: CLIPFeatureExtractor,
120
+ ):
121
+ super().__init__()
122
+
123
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
124
+ deprecation_message = (
125
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
126
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
127
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
128
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
129
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
130
+ " file"
131
+ )
132
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
133
+ new_config = dict(scheduler.config)
134
+ new_config["steps_offset"] = 1
135
+ scheduler._internal_dict = FrozenDict(new_config)
136
+
137
+ if safety_checker is None:
138
+ logger.warning(
139
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
140
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
141
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
142
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
143
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
144
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
145
+ )
146
+
147
+ self.register_modules(
148
+ vae=vae,
149
+ text_encoder=text_encoder,
150
+ tokenizer=tokenizer,
151
+ unet=unet,
152
+ scheduler=scheduler,
153
+ safety_checker=safety_checker,
154
+ feature_extractor=feature_extractor,
155
+ )
156
+
157
+ @torch.no_grad()
158
+ def __call__(
159
+ self,
160
+ prompt: Union[str, List[str]],
161
+ height: int = 512,
162
+ width: int = 512,
163
+ num_inference_steps: int = 50,
164
+ guidance_scale: float = 7.5,
165
+ negative_prompt: Optional[Union[str, List[str]]] = None,
166
+ num_images_per_prompt: Optional[int] = 1,
167
+ eta: float = 0.0,
168
+ generator: Optional[torch.Generator] = None,
169
+ latents: Optional[torch.FloatTensor] = None,
170
+ output_type: Optional[str] = "pil",
171
+ return_dict: bool = True,
172
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
173
+ callback_steps: Optional[int] = 1,
174
+ wildcard_option_dict: Dict[str, List[str]] = {},
175
+ wildcard_files: List[str] = [],
176
+ num_prompt_samples: Optional[int] = 1,
177
+ **kwargs,
178
+ ):
179
+ r"""
180
+ Function invoked when calling the pipeline for generation.
181
+
182
+ Args:
183
+ prompt (`str` or `List[str]`):
184
+ The prompt or prompts to guide the image generation.
185
+ height (`int`, *optional*, defaults to 512):
186
+ The height in pixels of the generated image.
187
+ width (`int`, *optional*, defaults to 512):
188
+ The width in pixels of the generated image.
189
+ num_inference_steps (`int`, *optional*, defaults to 50):
190
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
191
+ expense of slower inference.
192
+ guidance_scale (`float`, *optional*, defaults to 7.5):
193
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
194
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
195
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
196
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
197
+ usually at the expense of lower image quality.
198
+ negative_prompt (`str` or `List[str]`, *optional*):
199
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
200
+ if `guidance_scale` is less than `1`).
201
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
202
+ The number of images to generate per prompt.
203
+ eta (`float`, *optional*, defaults to 0.0):
204
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
205
+ [`schedulers.DDIMScheduler`], will be ignored for others.
206
+ generator (`torch.Generator`, *optional*):
207
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
208
+ deterministic.
209
+ latents (`torch.FloatTensor`, *optional*):
210
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
211
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
212
+ tensor will ge generated by sampling using the supplied random `generator`.
213
+ output_type (`str`, *optional*, defaults to `"pil"`):
214
+ The output format of the generate image. Choose between
215
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
216
+ return_dict (`bool`, *optional*, defaults to `True`):
217
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
218
+ plain tuple.
219
+ callback (`Callable`, *optional*):
220
+ A function that will be called every `callback_steps` steps during inference. The function will be
221
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
222
+ callback_steps (`int`, *optional*, defaults to 1):
223
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
224
+ called at every step.
225
+ wildcard_option_dict (Dict[str, List[str]]):
226
+ dict with key as `wildcard` and values as a list of possible replacements. For example if a prompt, "A __animal__ sitting on a chair". A wildcard_option_dict can provide possible values for "animal" like this: {"animal":["dog", "cat", "fox"]}
227
+ wildcard_files: (List[str])
228
+ List of filenames of txt files for wildcard replacements. For example if a prompt, "A __animal__ sitting on a chair". A file can be provided ["animal.txt"]
229
+ num_prompt_samples: int
230
+ Number of times to sample wildcards for each prompt provided
231
+
232
+ Returns:
233
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
234
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
235
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
236
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
237
+ (nsfw) content, according to the `safety_checker`.
238
+ """
239
+
240
+ if isinstance(prompt, str):
241
+ prompt = [
242
+ replace_prompt_with_wildcards(prompt, wildcard_option_dict, wildcard_files)
243
+ for i in range(num_prompt_samples)
244
+ ]
245
+ batch_size = len(prompt)
246
+ elif isinstance(prompt, list):
247
+ prompt_list = []
248
+ for p in prompt:
249
+ for i in range(num_prompt_samples):
250
+ prompt_list.append(replace_prompt_with_wildcards(p, wildcard_option_dict, wildcard_files))
251
+ prompt = prompt_list
252
+ batch_size = len(prompt)
253
+ else:
254
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
255
+
256
+ if height % 8 != 0 or width % 8 != 0:
257
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
258
+
259
+ if (callback_steps is None) or (
260
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
261
+ ):
262
+ raise ValueError(
263
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
264
+ f" {type(callback_steps)}."
265
+ )
266
+
267
+ # get prompt text embeddings
268
+ text_inputs = self.tokenizer(
269
+ prompt,
270
+ padding="max_length",
271
+ max_length=self.tokenizer.model_max_length,
272
+ return_tensors="pt",
273
+ )
274
+ text_input_ids = text_inputs.input_ids
275
+
276
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
277
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
278
+ logger.warning(
279
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
280
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
281
+ )
282
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
283
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
284
+
285
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
286
+ bs_embed, seq_len, _ = text_embeddings.shape
287
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
288
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
289
+
290
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
291
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
292
+ # corresponds to doing no classifier free guidance.
293
+ do_classifier_free_guidance = guidance_scale > 1.0
294
+ # get unconditional embeddings for classifier free guidance
295
+ if do_classifier_free_guidance:
296
+ uncond_tokens: List[str]
297
+ if negative_prompt is None:
298
+ uncond_tokens = [""] * batch_size
299
+ elif type(prompt) is not type(negative_prompt):
300
+ raise TypeError(
301
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
302
+ f" {type(prompt)}."
303
+ )
304
+ elif isinstance(negative_prompt, str):
305
+ uncond_tokens = [negative_prompt]
306
+ elif batch_size != len(negative_prompt):
307
+ raise ValueError(
308
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
309
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
310
+ " the batch size of `prompt`."
311
+ )
312
+ else:
313
+ uncond_tokens = negative_prompt
314
+
315
+ max_length = text_input_ids.shape[-1]
316
+ uncond_input = self.tokenizer(
317
+ uncond_tokens,
318
+ padding="max_length",
319
+ max_length=max_length,
320
+ truncation=True,
321
+ return_tensors="pt",
322
+ )
323
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
324
+
325
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
326
+ seq_len = uncond_embeddings.shape[1]
327
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
328
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
329
+
330
+ # For classifier free guidance, we need to do two forward passes.
331
+ # Here we concatenate the unconditional and text embeddings into a single batch
332
+ # to avoid doing two forward passes
333
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
334
+
335
+ # get the initial random noise unless the user supplied it
336
+
337
+ # Unlike in other pipelines, latents need to be generated in the target device
338
+ # for 1-to-1 results reproducibility with the CompVis implementation.
339
+ # However this currently doesn't work in `mps`.
340
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)
341
+ latents_dtype = text_embeddings.dtype
342
+ if latents is None:
343
+ if self.device.type == "mps":
344
+ # randn does not exist on mps
345
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
346
+ self.device
347
+ )
348
+ else:
349
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
350
+ else:
351
+ if latents.shape != latents_shape:
352
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
353
+ latents = latents.to(self.device)
354
+
355
+ # set timesteps
356
+ self.scheduler.set_timesteps(num_inference_steps)
357
+
358
+ # Some schedulers like PNDM have timesteps as arrays
359
+ # It's more optimized to move all timesteps to correct device beforehand
360
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
361
+
362
+ # scale the initial noise by the standard deviation required by the scheduler
363
+ latents = latents * self.scheduler.init_noise_sigma
364
+
365
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
366
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
367
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
368
+ # and should be between [0, 1]
369
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
370
+ extra_step_kwargs = {}
371
+ if accepts_eta:
372
+ extra_step_kwargs["eta"] = eta
373
+
374
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
375
+ # expand the latents if we are doing classifier free guidance
376
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
377
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
378
+
379
+ # predict the noise residual
380
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
381
+
382
+ # perform guidance
383
+ if do_classifier_free_guidance:
384
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
385
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
386
+
387
+ # compute the previous noisy sample x_t -> x_t-1
388
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
389
+
390
+ # call the callback, if provided
391
+ if callback is not None and i % callback_steps == 0:
392
+ callback(i, t, latents)
393
+
394
+ latents = 1 / 0.18215 * latents
395
+ image = self.vae.decode(latents).sample
396
+
397
+ image = (image / 2 + 0.5).clamp(0, 1)
398
+
399
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
400
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
401
+
402
+ if self.safety_checker is not None:
403
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
404
+ self.device
405
+ )
406
+ image, has_nsfw_concept = self.safety_checker(
407
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
408
+ )
409
+ else:
410
+ has_nsfw_concept = None
411
+
412
+ if output_type == "pil":
413
+ image = self.numpy_to_pil(image)
414
+
415
+ if not return_dict:
416
+ return (image, has_nsfw_concept)
417
+
418
+ return WildcardStableDiffusionOutput(images=image, nsfw_content_detected=has_nsfw_concept, prompts=prompt)