Datasets:

ArXiv:
diffusers-bot commited on
Commit
6bfed78
1 Parent(s): ee03b6f

Upload folder using huggingface_hub

Browse files
v0.14.0/README.md ADDED
@@ -0,0 +1,991 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Stable Diffusion v1.1-1.4 Comparison | Run all 4 model checkpoints for Stable Diffusion and compare their results together | [Stable Diffusion Comparison](#stable-diffusion-comparisons) | - | [Suvaditya Mukherjee](https://github.com/suvadityamuk) |
28
+ MagicMix | Diffusion Pipeline for semantic mixing of an image and a text prompt | [MagicMix](#magic-mix) | - | [Partho Das](https://github.com/daspartho) |
29
+ | Stable UnCLIP | Diffusion Pipeline for combining prior model (generate clip image embedding from text, UnCLIPPipeline `"kakaobrain/karlo-v1-alpha"`) and decoder pipeline (decode clip image embedding to image, StableDiffusionImageVariationPipeline `"lambdalabs/sd-image-variations-diffusers"` ). | [Stable UnCLIP](#stable-unclip) | - |[Ray Wang](https://wrong.wang) |
30
+ | UnCLIP Text Interpolation Pipeline | Diffusion Pipeline that allows passing two prompts and produces images while interpolating between the text-embeddings of the two prompts | [UnCLIP Text Interpolation Pipeline](#unclip-text-interpolation-pipeline) | - | [Naga Sai Abhinay Devarinti](https://github.com/Abhinay1997/) |
31
+
32
+
33
+
34
+
35
+ 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.
36
+ ```py
37
+ pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", custom_pipeline="filename_in_the_community_folder")
38
+ ```
39
+
40
+ ## Example usages
41
+
42
+ ### CLIP Guided Stable Diffusion
43
+
44
+ CLIP guided stable diffusion can help to generate more realistic images
45
+ by guiding stable diffusion at every denoising step with an additional CLIP model.
46
+
47
+ The following code requires roughly 12GB of GPU RAM.
48
+
49
+ ```python
50
+ from diffusers import DiffusionPipeline
51
+ from transformers import CLIPFeatureExtractor, CLIPModel
52
+ import torch
53
+
54
+
55
+ feature_extractor = CLIPFeatureExtractor.from_pretrained("laion/CLIP-ViT-B-32-laion2B-s34B-b79K")
56
+ clip_model = CLIPModel.from_pretrained("laion/CLIP-ViT-B-32-laion2B-s34B-b79K", torch_dtype=torch.float16)
57
+
58
+
59
+ guided_pipeline = DiffusionPipeline.from_pretrained(
60
+ "runwayml/stable-diffusion-v1-5",
61
+ custom_pipeline="clip_guided_stable_diffusion",
62
+ clip_model=clip_model,
63
+ feature_extractor=feature_extractor,
64
+
65
+ torch_dtype=torch.float16,
66
+ )
67
+ guided_pipeline.enable_attention_slicing()
68
+ guided_pipeline = guided_pipeline.to("cuda")
69
+
70
+ 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"
71
+
72
+ generator = torch.Generator(device="cuda").manual_seed(0)
73
+ images = []
74
+ for i in range(4):
75
+ image = guided_pipeline(
76
+ prompt,
77
+ num_inference_steps=50,
78
+ guidance_scale=7.5,
79
+ clip_guidance_scale=100,
80
+ num_cutouts=4,
81
+ use_cutouts=False,
82
+ generator=generator,
83
+ ).images[0]
84
+ images.append(image)
85
+
86
+ # save images locally
87
+ for i, img in enumerate(images):
88
+ img.save(f"./clip_guided_sd/image_{i}.png")
89
+ ```
90
+
91
+ The `images` list contains a list of PIL images that can be saved locally or displayed directly in a google colab.
92
+ Generated images tend to be of higher qualtiy than natively using stable diffusion. E.g. the above script generates the following images:
93
+
94
+ ![clip_guidance](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/clip_guidance/merged_clip_guidance.jpg).
95
+
96
+ ### One Step Unet
97
+
98
+ The dummy "one-step-unet" can be run as follows:
99
+
100
+ ```python
101
+ from diffusers import DiffusionPipeline
102
+
103
+ pipe = DiffusionPipeline.from_pretrained("google/ddpm-cifar10-32", custom_pipeline="one_step_unet")
104
+ pipe()
105
+ ```
106
+
107
+ **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).
108
+
109
+ ### Stable Diffusion Interpolation
110
+
111
+ The following code can be run on a GPU of at least 8GB VRAM and should take approximately 5 minutes.
112
+
113
+ ```python
114
+ from diffusers import DiffusionPipeline
115
+ import torch
116
+
117
+ pipe = DiffusionPipeline.from_pretrained(
118
+ "CompVis/stable-diffusion-v1-4",
119
+ revision='fp16',
120
+ torch_dtype=torch.float16,
121
+ safety_checker=None, # Very important for videos...lots of false positives while interpolating
122
+ custom_pipeline="interpolate_stable_diffusion",
123
+ ).to('cuda')
124
+ pipe.enable_attention_slicing()
125
+
126
+ frame_filepaths = pipe.walk(
127
+ prompts=['a dog', 'a cat', 'a horse'],
128
+ seeds=[42, 1337, 1234],
129
+ num_interpolation_steps=16,
130
+ output_dir='./dreams',
131
+ batch_size=4,
132
+ height=512,
133
+ width=512,
134
+ guidance_scale=8.5,
135
+ num_inference_steps=50,
136
+ )
137
+ ```
138
+
139
+ 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.
140
+
141
+ > **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.**
142
+
143
+ ### Stable Diffusion Mega
144
+
145
+ The Stable Diffusion Mega Pipeline lets you use the main use cases of the stable diffusion pipeline in a single class.
146
+
147
+ ```python
148
+ #!/usr/bin/env python3
149
+ from diffusers import DiffusionPipeline
150
+ import PIL
151
+ import requests
152
+ from io import BytesIO
153
+ import torch
154
+
155
+
156
+ def download_image(url):
157
+ response = requests.get(url)
158
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
159
+
160
+ pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", custom_pipeline="stable_diffusion_mega", torch_dtype=torch.float16, revision="fp16")
161
+ pipe.to("cuda")
162
+ pipe.enable_attention_slicing()
163
+
164
+
165
+ ### Text-to-Image
166
+
167
+ images = pipe.text2img("An astronaut riding a horse").images
168
+
169
+ ### Image-to-Image
170
+
171
+ init_image = download_image("https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg")
172
+
173
+ prompt = "A fantasy landscape, trending on artstation"
174
+
175
+ images = pipe.img2img(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
176
+
177
+ ### Inpainting
178
+
179
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
180
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
181
+ init_image = download_image(img_url).resize((512, 512))
182
+ mask_image = download_image(mask_url).resize((512, 512))
183
+
184
+ prompt = "a cat sitting on a bench"
185
+ images = pipe.inpaint(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.75).images
186
+ ```
187
+
188
+ As shown above this one pipeline can run all both "text-to-image", "image-to-image", and "inpainting" in one pipeline.
189
+
190
+ ### Long Prompt Weighting Stable Diffusion
191
+ Features of this custom pipeline:
192
+ - Input a prompt without the 77 token length limit.
193
+ - Includes tx2img, img2img. and inpainting pipelines.
194
+ - Emphasize/weigh part of your prompt with parentheses as so: `a baby deer with (big eyes)`
195
+ - De-emphasize part of your prompt as so: `a [baby] deer with big eyes`
196
+ - Precisely weigh part of your prompt as so: `a baby deer with (big eyes:1.3)`
197
+
198
+ Prompt weighting equivalents:
199
+ - `a baby deer with` == `(a baby deer with:1.0)`
200
+ - `(big eyes)` == `(big eyes:1.1)`
201
+ - `((big eyes))` == `(big eyes:1.21)`
202
+ - `[big eyes]` == `(big eyes:0.91)`
203
+
204
+ You can run this custom pipeline as so:
205
+
206
+ #### pytorch
207
+
208
+ ```python
209
+ from diffusers import DiffusionPipeline
210
+ import torch
211
+
212
+ pipe = DiffusionPipeline.from_pretrained(
213
+ 'hakurei/waifu-diffusion',
214
+ custom_pipeline="lpw_stable_diffusion",
215
+
216
+ torch_dtype=torch.float16
217
+ )
218
+ pipe=pipe.to("cuda")
219
+
220
+ 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"
221
+ 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"
222
+
223
+ pipe.text2img(prompt, negative_prompt=neg_prompt, width=512,height=512,max_embeddings_multiples=3).images[0]
224
+
225
+ ```
226
+
227
+ #### onnxruntime
228
+
229
+ ```python
230
+ from diffusers import DiffusionPipeline
231
+ import torch
232
+
233
+ pipe = DiffusionPipeline.from_pretrained(
234
+ 'CompVis/stable-diffusion-v1-4',
235
+ custom_pipeline="lpw_stable_diffusion_onnx",
236
+ revision="onnx",
237
+ provider="CUDAExecutionProvider"
238
+ )
239
+
240
+ prompt = "a photo of an astronaut riding a horse on mars, best quality"
241
+ 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"
242
+
243
+ pipe.text2img(prompt,negative_prompt=neg_prompt, width=512, height=512, max_embeddings_multiples=3).images[0]
244
+
245
+ ```
246
+
247
+ 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.
248
+
249
+ ### Speech to Image
250
+
251
+ The following code can generate an image from an audio sample using pre-trained OpenAI whisper-small and Stable Diffusion.
252
+
253
+ ```Python
254
+ import torch
255
+
256
+ import matplotlib.pyplot as plt
257
+ from datasets import load_dataset
258
+ from diffusers import DiffusionPipeline
259
+ from transformers import (
260
+ WhisperForConditionalGeneration,
261
+ WhisperProcessor,
262
+ )
263
+
264
+
265
+ device = "cuda" if torch.cuda.is_available() else "cpu"
266
+
267
+ ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
268
+
269
+ audio_sample = ds[3]
270
+
271
+ text = audio_sample["text"].lower()
272
+ speech_data = audio_sample["audio"]["array"]
273
+
274
+ model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small").to(device)
275
+ processor = WhisperProcessor.from_pretrained("openai/whisper-small")
276
+
277
+ diffuser_pipeline = DiffusionPipeline.from_pretrained(
278
+ "CompVis/stable-diffusion-v1-4",
279
+ custom_pipeline="speech_to_image_diffusion",
280
+ speech_model=model,
281
+ speech_processor=processor,
282
+
283
+ torch_dtype=torch.float16,
284
+ )
285
+
286
+ diffuser_pipeline.enable_attention_slicing()
287
+ diffuser_pipeline = diffuser_pipeline.to(device)
288
+
289
+ output = diffuser_pipeline(speech_data)
290
+ plt.imshow(output.images[0])
291
+ ```
292
+ This example produces the following image:
293
+
294
+ ![image](https://user-images.githubusercontent.com/45072645/196901736-77d9c6fc-63ee-4072-90b0-dc8b903d63e3.png)
295
+
296
+ ### Wildcard Stable Diffusion
297
+ 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:
298
+
299
+ Say we have a prompt:
300
+
301
+ ```
302
+ prompt = "__animal__ sitting on a __object__ wearing a __clothing__"
303
+ ```
304
+
305
+ 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.
306
+
307
+ The possible values can also be defined / combined by using a dictionary like: `{"animal":["dog", "cat", mouse"]}`.
308
+
309
+ The actual pipeline works just like `StableDiffusionPipeline`, except the `__call__` method takes in:
310
+
311
+ `wildcard_files`: list of file paths for wild card replacement
312
+ `wildcard_option_dict`: dict with key as `wildcard` and values as a list of possible replacements
313
+ `num_prompt_samples`: number of prompts to sample, uniformly sampling wildcards
314
+
315
+ A full example:
316
+
317
+ create `animal.txt`, with contents like:
318
+
319
+ ```
320
+ dog
321
+ cat
322
+ mouse
323
+ ```
324
+
325
+ create `object.txt`, with contents like:
326
+
327
+ ```
328
+ chair
329
+ sofa
330
+ bench
331
+ ```
332
+
333
+ ```python
334
+ from diffusers import DiffusionPipeline
335
+ import torch
336
+
337
+ pipe = DiffusionPipeline.from_pretrained(
338
+ "CompVis/stable-diffusion-v1-4",
339
+ custom_pipeline="wildcard_stable_diffusion",
340
+
341
+ torch_dtype=torch.float16,
342
+ )
343
+ prompt = "__animal__ sitting on a __object__ wearing a __clothing__"
344
+ out = pipe(
345
+ prompt,
346
+ wildcard_option_dict={
347
+ "clothing":["hat", "shirt", "scarf", "beret"]
348
+ },
349
+ wildcard_files=["object.txt", "animal.txt"],
350
+ num_prompt_samples=1
351
+ )
352
+ ```
353
+
354
+ ### Composable Stable diffusion
355
+
356
+ [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.
357
+
358
+ ```python
359
+ import torch as th
360
+ import numpy as np
361
+ import torchvision.utils as tvu
362
+
363
+ from diffusers import DiffusionPipeline
364
+
365
+ import argparse
366
+
367
+ parser = argparse.ArgumentParser()
368
+ parser.add_argument("--prompt", type=str, default="mystical trees | A magical pond | dark",
369
+ help="use '|' as the delimiter to compose separate sentences.")
370
+ parser.add_argument("--steps", type=int, default=50)
371
+ parser.add_argument("--scale", type=float, default=7.5)
372
+ parser.add_argument("--weights", type=str, default="7.5 | 7.5 | -7.5")
373
+ parser.add_argument("--seed", type=int, default=2)
374
+ parser.add_argument("--model_path", type=str, default="CompVis/stable-diffusion-v1-4")
375
+ parser.add_argument("--num_images", type=int, default=1)
376
+ args = parser.parse_args()
377
+
378
+ has_cuda = th.cuda.is_available()
379
+ device = th.device('cpu' if not has_cuda else 'cuda')
380
+
381
+ prompt = args.prompt
382
+ scale = args.scale
383
+ steps = args.steps
384
+
385
+ pipe = DiffusionPipeline.from_pretrained(
386
+ args.model_path,
387
+ custom_pipeline="composable_stable_diffusion",
388
+ ).to(device)
389
+
390
+ pipe.safety_checker = None
391
+
392
+ images = []
393
+ generator = th.Generator("cuda").manual_seed(args.seed)
394
+ for i in range(args.num_images):
395
+ image = pipe(prompt, guidance_scale=scale, num_inference_steps=steps,
396
+ weights=args.weights, generator=generator).images[0]
397
+ images.append(th.from_numpy(np.array(image)).permute(2, 0, 1) / 255.)
398
+ grid = tvu.make_grid(th.stack(images, dim=0), nrow=4, padding=0)
399
+ tvu.save_image(grid, f'{prompt}_{args.weights}' + '.png')
400
+
401
+ ```
402
+
403
+ ### Imagic Stable Diffusion
404
+ Allows you to edit an image using stable diffusion.
405
+
406
+ ```python
407
+ import requests
408
+ from PIL import Image
409
+ from io import BytesIO
410
+ import torch
411
+ import os
412
+ from diffusers import DiffusionPipeline, DDIMScheduler
413
+ has_cuda = torch.cuda.is_available()
414
+ device = torch.device('cpu' if not has_cuda else 'cuda')
415
+ pipe = DiffusionPipeline.from_pretrained(
416
+ "CompVis/stable-diffusion-v1-4",
417
+ safety_checker=None,
418
+ use_auth_token=True,
419
+ custom_pipeline="imagic_stable_diffusion",
420
+ scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False, set_alpha_to_one=False)
421
+ ).to(device)
422
+ generator = torch.Generator("cuda").manual_seed(0)
423
+ seed = 0
424
+ prompt = "A photo of Barack Obama smiling with a big grin"
425
+ url = 'https://www.dropbox.com/s/6tlwzr73jd1r9yk/obama.png?dl=1'
426
+ response = requests.get(url)
427
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
428
+ init_image = init_image.resize((512, 512))
429
+ res = pipe.train(
430
+ prompt,
431
+ image=init_image,
432
+ generator=generator)
433
+ res = pipe(alpha=1, guidance_scale=7.5, num_inference_steps=50)
434
+ os.makedirs("imagic", exist_ok=True)
435
+ image = res.images[0]
436
+ image.save('./imagic/imagic_image_alpha_1.png')
437
+ res = pipe(alpha=1.5, guidance_scale=7.5, num_inference_steps=50)
438
+ image = res.images[0]
439
+ image.save('./imagic/imagic_image_alpha_1_5.png')
440
+ res = pipe(alpha=2, guidance_scale=7.5, num_inference_steps=50)
441
+ image = res.images[0]
442
+ image.save('./imagic/imagic_image_alpha_2.png')
443
+ ```
444
+
445
+ ### Seed Resizing
446
+ 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.
447
+
448
+ ```python
449
+ import torch as th
450
+ import numpy as np
451
+ from diffusers import DiffusionPipeline
452
+
453
+ has_cuda = th.cuda.is_available()
454
+ device = th.device('cpu' if not has_cuda else 'cuda')
455
+
456
+ pipe = DiffusionPipeline.from_pretrained(
457
+ "CompVis/stable-diffusion-v1-4",
458
+ use_auth_token=True,
459
+ custom_pipeline="seed_resize_stable_diffusion"
460
+ ).to(device)
461
+
462
+ def dummy(images, **kwargs):
463
+ return images, False
464
+
465
+ pipe.safety_checker = dummy
466
+
467
+
468
+ images = []
469
+ th.manual_seed(0)
470
+ generator = th.Generator("cuda").manual_seed(0)
471
+
472
+ seed = 0
473
+ prompt = "A painting of a futuristic cop"
474
+
475
+ width = 512
476
+ height = 512
477
+
478
+ res = pipe(
479
+ prompt,
480
+ guidance_scale=7.5,
481
+ num_inference_steps=50,
482
+ height=height,
483
+ width=width,
484
+ generator=generator)
485
+ image = res.images[0]
486
+ image.save('./seed_resize/seed_resize_{w}_{h}_image.png'.format(w=width, h=height))
487
+
488
+
489
+ th.manual_seed(0)
490
+ generator = th.Generator("cuda").manual_seed(0)
491
+
492
+ pipe = DiffusionPipeline.from_pretrained(
493
+ "CompVis/stable-diffusion-v1-4",
494
+ use_auth_token=True,
495
+ custom_pipeline="/home/mark/open_source/diffusers/examples/community/"
496
+ ).to(device)
497
+
498
+ width = 512
499
+ height = 592
500
+
501
+ res = pipe(
502
+ prompt,
503
+ guidance_scale=7.5,
504
+ num_inference_steps=50,
505
+ height=height,
506
+ width=width,
507
+ generator=generator)
508
+ image = res.images[0]
509
+ image.save('./seed_resize/seed_resize_{w}_{h}_image.png'.format(w=width, h=height))
510
+
511
+ pipe_compare = DiffusionPipeline.from_pretrained(
512
+ "CompVis/stable-diffusion-v1-4",
513
+ use_auth_token=True,
514
+ custom_pipeline="/home/mark/open_source/diffusers/examples/community/"
515
+ ).to(device)
516
+
517
+ res = pipe_compare(
518
+ prompt,
519
+ guidance_scale=7.5,
520
+ num_inference_steps=50,
521
+ height=height,
522
+ width=width,
523
+ generator=generator
524
+ )
525
+
526
+ image = res.images[0]
527
+ image.save('./seed_resize/seed_resize_{w}_{h}_image_compare.png'.format(w=width, h=height))
528
+ ```
529
+
530
+ ### Multilingual Stable Diffusion Pipeline
531
+
532
+ 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.
533
+
534
+ ```python
535
+ from PIL import Image
536
+
537
+ import torch
538
+
539
+ from diffusers import DiffusionPipeline
540
+ from transformers import (
541
+ pipeline,
542
+ MBart50TokenizerFast,
543
+ MBartForConditionalGeneration,
544
+ )
545
+ device = "cuda" if torch.cuda.is_available() else "cpu"
546
+ device_dict = {"cuda": 0, "cpu": -1}
547
+
548
+ # helper function taken from: https://huggingface.co/blog/stable_diffusion
549
+ def image_grid(imgs, rows, cols):
550
+ assert len(imgs) == rows*cols
551
+
552
+ w, h = imgs[0].size
553
+ grid = Image.new('RGB', size=(cols*w, rows*h))
554
+ grid_w, grid_h = grid.size
555
+
556
+ for i, img in enumerate(imgs):
557
+ grid.paste(img, box=(i%cols*w, i//cols*h))
558
+ return grid
559
+
560
+ # Add language detection pipeline
561
+ language_detection_model_ckpt = "papluca/xlm-roberta-base-language-detection"
562
+ language_detection_pipeline = pipeline("text-classification",
563
+ model=language_detection_model_ckpt,
564
+ device=device_dict[device])
565
+
566
+ # Add model for language translation
567
+ trans_tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-one-mmt")
568
+ trans_model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-one-mmt").to(device)
569
+
570
+ diffuser_pipeline = DiffusionPipeline.from_pretrained(
571
+ "CompVis/stable-diffusion-v1-4",
572
+ custom_pipeline="multilingual_stable_diffusion",
573
+ detection_pipeline=language_detection_pipeline,
574
+ translation_model=trans_model,
575
+ translation_tokenizer=trans_tokenizer,
576
+
577
+ torch_dtype=torch.float16,
578
+ )
579
+
580
+ diffuser_pipeline.enable_attention_slicing()
581
+ diffuser_pipeline = diffuser_pipeline.to(device)
582
+
583
+ prompt = ["a photograph of an astronaut riding a horse",
584
+ "Una casa en la playa",
585
+ "Ein Hund, der Orange isst",
586
+ "Un restaurant parisien"]
587
+
588
+ output = diffuser_pipeline(prompt)
589
+
590
+ images = output.images
591
+
592
+ grid = image_grid(images, rows=2, cols=2)
593
+ ```
594
+
595
+ This example produces the following images:
596
+ ![image](https://user-images.githubusercontent.com/4313860/198328706-295824a4-9856-4ce5-8e66-278ceb42fd29.png)
597
+
598
+ ### Image to Image Inpainting Stable Diffusion
599
+
600
+ Similar to the standard stable diffusion inpainting example, except with the addition of an `inner_image` argument.
601
+
602
+ `image`, `inner_image`, and `mask` should have the same dimensions. `inner_image` should have an alpha (transparency) channel.
603
+
604
+ 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.
605
+ For example, this could be used to place a logo on a shirt and make it blend seamlessly.
606
+
607
+ ```python
608
+ import PIL
609
+ import torch
610
+
611
+ from diffusers import DiffusionPipeline
612
+
613
+ image_path = "./path-to-image.png"
614
+ inner_image_path = "./path-to-inner-image.png"
615
+ mask_path = "./path-to-mask.png"
616
+
617
+ init_image = PIL.Image.open(image_path).convert("RGB").resize((512, 512))
618
+ inner_image = PIL.Image.open(inner_image_path).convert("RGBA").resize((512, 512))
619
+ mask_image = PIL.Image.open(mask_path).convert("RGB").resize((512, 512))
620
+
621
+ pipe = DiffusionPipeline.from_pretrained(
622
+ "runwayml/stable-diffusion-inpainting",
623
+ custom_pipeline="img2img_inpainting",
624
+
625
+ torch_dtype=torch.float16
626
+ )
627
+ pipe = pipe.to("cuda")
628
+
629
+ prompt = "Your prompt here!"
630
+ image = pipe(prompt=prompt, image=init_image, inner_image=inner_image, mask_image=mask_image).images[0]
631
+ ```
632
+
633
+ ![2 by 2 grid demonstrating image to image inpainting.](https://user-images.githubusercontent.com/44398246/203506577-ec303be4-887e-4ebd-a773-c83fcb3dd01a.png)
634
+
635
+ ### Text Based Inpainting Stable Diffusion
636
+
637
+ Use a text prompt to generate the mask for the area to be inpainted.
638
+ Currently uses the CLIPSeg model for mask generation, then calls the standard Stable Diffusion Inpainting pipeline to perform the inpainting.
639
+
640
+ ```python
641
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
642
+ from diffusers import DiffusionPipeline
643
+
644
+ from PIL import Image
645
+ import requests
646
+
647
+ processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
648
+ model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")
649
+
650
+ pipe = DiffusionPipeline.from_pretrained(
651
+ "runwayml/stable-diffusion-inpainting",
652
+ custom_pipeline="text_inpainting",
653
+ segmentation_model=model,
654
+ segmentation_processor=processor
655
+ )
656
+ pipe = pipe.to("cuda")
657
+
658
+
659
+ url = "https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true"
660
+ image = Image.open(requests.get(url, stream=True).raw).resize((512, 512))
661
+ text = "a glass" # will mask out this text
662
+ prompt = "a cup" # the masked out region will be replaced with this
663
+
664
+ image = pipe(image=image, text=text, prompt=prompt).images[0]
665
+ ```
666
+
667
+ ### Bit Diffusion
668
+ 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:
669
+
670
+ ```python
671
+ from diffusers import DiffusionPipeline
672
+ pipe = DiffusionPipeline.from_pretrained("google/ddpm-cifar10-32", custom_pipeline="bit_diffusion")
673
+ image = pipe().images[0]
674
+
675
+ ```
676
+
677
+ ### Stable Diffusion with K Diffusion
678
+
679
+ Make sure you have @crowsonkb's https://github.com/crowsonkb/k-diffusion installed:
680
+
681
+ ```
682
+ pip install k-diffusion
683
+ ```
684
+
685
+ You can use the community pipeline as follows:
686
+
687
+ ```python
688
+ from diffusers import DiffusionPipeline
689
+
690
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="sd_text2img_k_diffusion")
691
+ pipe = pipe.to("cuda")
692
+
693
+ prompt = "an astronaut riding a horse on mars"
694
+ pipe.set_scheduler("sample_heun")
695
+ generator = torch.Generator(device="cuda").manual_seed(seed)
696
+ image = pipe(prompt, generator=generator, num_inference_steps=20).images[0]
697
+
698
+ image.save("./astronaut_heun_k_diffusion.png")
699
+ ```
700
+
701
+ To make sure that K Diffusion and `diffusers` yield the same results:
702
+
703
+ **Diffusers**:
704
+ ```python
705
+ from diffusers import DiffusionPipeline, EulerDiscreteScheduler
706
+
707
+ seed = 33
708
+
709
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
710
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
711
+ pipe = pipe.to("cuda")
712
+
713
+ generator = torch.Generator(device="cuda").manual_seed(seed)
714
+ image = pipe(prompt, generator=generator, num_inference_steps=50).images[0]
715
+ ```
716
+
717
+ ![diffusers_euler](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/k_diffusion/astronaut_euler.png)
718
+
719
+ **K Diffusion**:
720
+ ```python
721
+ from diffusers import DiffusionPipeline, EulerDiscreteScheduler
722
+
723
+ seed = 33
724
+
725
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="sd_text2img_k_diffusion")
726
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
727
+ pipe = pipe.to("cuda")
728
+
729
+ pipe.set_scheduler("sample_euler")
730
+ generator = torch.Generator(device="cuda").manual_seed(seed)
731
+ image = pipe(prompt, generator=generator, num_inference_steps=50).images[0]
732
+ ```
733
+
734
+ ![diffusers_euler](https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/k_diffusion/astronaut_euler_k_diffusion.png)
735
+
736
+ ### Checkpoint Merger Pipeline
737
+ 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.
738
+
739
+ 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
740
+ on colab you might run out of the 12GB memory even while merging two checkpoints.
741
+
742
+ Usage:-
743
+ ```python
744
+ from diffusers import DiffusionPipeline
745
+
746
+ #Return a CheckpointMergerPipeline class that allows you to merge checkpoints.
747
+ #The checkpoint passed here is ignored. But still pass one of the checkpoints you plan to
748
+ #merge for convenience
749
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger")
750
+
751
+ #There are multiple possible scenarios:
752
+ #The pipeline with the merged checkpoints is returned in all the scenarios
753
+
754
+ #Compatible checkpoints a.k.a matched model_index.json files. Ignores the meta attributes in model_index.json during comparision.( attrs with _ as prefix )
755
+ merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","CompVis/stable-diffusion-v1-2"], interp = "sigmoid", alpha = 0.4)
756
+
757
+ #Incompatible checkpoints in model_index.json but merge might be possible. Use force = True to ignore model_index.json compatibility
758
+ merged_pipe_1 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion"], force = True, interp = "sigmoid", alpha = 0.4)
759
+
760
+ #Three checkpoint merging. Only "add_difference" method actually works on all three checkpoints. Using any other options will ignore the 3rd checkpoint.
761
+ merged_pipe_2 = pipe.merge(["CompVis/stable-diffusion-v1-4","hakurei/waifu-diffusion","prompthero/openjourney"], force = True, interp = "add_difference", alpha = 0.4)
762
+
763
+ prompt = "An astronaut riding a horse on Mars"
764
+
765
+ image = merged_pipe(prompt).images[0]
766
+
767
+ ```
768
+ Some examples along with the merge details:
769
+
770
+ 1. "CompVis/stable-diffusion-v1-4" + "hakurei/waifu-diffusion" ; Sigmoid interpolation; alpha = 0.8
771
+
772
+ ![Stable plus Waifu Sigmoid 0.8](https://huggingface.co/datasets/NagaSaiAbhinay/CheckpointMergerSamples/resolve/main/stability_v1_4_waifu_sig_0.8.png)
773
+
774
+ 2. "hakurei/waifu-diffusion" + "prompthero/openjourney" ; Inverse Sigmoid interpolation; alpha = 0.8
775
+
776
+ ![Stable plus Waifu Sigmoid 0.8](https://huggingface.co/datasets/NagaSaiAbhinay/CheckpointMergerSamples/resolve/main/waifu_openjourney_inv_sig_0.8.png)
777
+
778
+
779
+ 3. "CompVis/stable-diffusion-v1-4" + "hakurei/waifu-diffusion" + "prompthero/openjourney"; Add Difference interpolation; alpha = 0.5
780
+
781
+ ![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)
782
+
783
+
784
+ ### Stable Diffusion Comparisons
785
+
786
+ This Community Pipeline enables the comparison between the 4 checkpoints that exist for Stable Diffusion. They can be found through the following links:
787
+ 1. [Stable Diffusion v1.1](https://huggingface.co/CompVis/stable-diffusion-v1-1)
788
+ 2. [Stable Diffusion v1.2](https://huggingface.co/CompVis/stable-diffusion-v1-2)
789
+ 3. [Stable Diffusion v1.3](https://huggingface.co/CompVis/stable-diffusion-v1-3)
790
+ 4. [Stable Diffusion v1.4](https://huggingface.co/CompVis/stable-diffusion-v1-4)
791
+
792
+ ```python
793
+ from diffusers import DiffusionPipeline
794
+ import matplotlib.pyplot as plt
795
+
796
+ pipe = DiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4', custom_pipeline='suvadityamuk/StableDiffusionComparison')
797
+ pipe.enable_attention_slicing()
798
+ pipe = pipe.to('cuda')
799
+ prompt = "an astronaut riding a horse on mars"
800
+ output = pipe(prompt)
801
+
802
+ plt.subplots(2,2,1)
803
+ plt.imshow(output.images[0])
804
+ plt.title('Stable Diffusion v1.1')
805
+ plt.axis('off')
806
+ plt.subplots(2,2,2)
807
+ plt.imshow(output.images[1])
808
+ plt.title('Stable Diffusion v1.2')
809
+ plt.axis('off')
810
+ plt.subplots(2,2,3)
811
+ plt.imshow(output.images[2])
812
+ plt.title('Stable Diffusion v1.3')
813
+ plt.axis('off')
814
+ plt.subplots(2,2,4)
815
+ plt.imshow(output.images[3])
816
+ plt.title('Stable Diffusion v1.4')
817
+ plt.axis('off')
818
+
819
+ plt.show()
820
+ ```
821
+
822
+ As a result, you can look at a grid of all 4 generated images being shown together, that captures a difference the advancement of the training between the 4 checkpoints.
823
+
824
+ ### Magic Mix
825
+
826
+ Implementation of the [MagicMix: Semantic Mixing with Diffusion Models](https://arxiv.org/abs/2210.16056) paper. This is a Diffusion Pipeline for semantic mixing of an image and a text prompt to create a new concept while preserving the spatial layout and geometry of the subject in the image. The pipeline takes an image that provides the layout semantics and a prompt that provides the content semantics for the mixing process.
827
+
828
+ There are 3 parameters for the method-
829
+ - `mix_factor`: It is the interpolation constant used in the layout generation phase. The greater the value of `mix_factor`, the greater the influence of the prompt on the layout generation process.
830
+ - `kmax` and `kmin`: These determine the range for the layout and content generation process. A higher value of kmax results in loss of more information about the layout of the original image and a higher value of kmin results in more steps for content generation process.
831
+
832
+ Here is an example usage-
833
+
834
+ ```python
835
+ from diffusers import DiffusionPipeline, DDIMScheduler
836
+ from PIL import Image
837
+
838
+ pipe = DiffusionPipeline.from_pretrained(
839
+ "CompVis/stable-diffusion-v1-4",
840
+ custom_pipeline="magic_mix",
841
+ scheduler = DDIMScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler"),
842
+ ).to('cuda')
843
+
844
+ img = Image.open('phone.jpg')
845
+ mix_img = pipe(
846
+ img,
847
+ prompt = 'bed',
848
+ kmin = 0.3,
849
+ kmax = 0.5,
850
+ mix_factor = 0.5,
851
+ )
852
+ mix_img.save('phone_bed_mix.jpg')
853
+ ```
854
+ The `mix_img` is a PIL image that can be saved locally or displayed directly in a google colab. Generated image is a mix of the layout semantics of the given image and the content semantics of the prompt.
855
+
856
+ E.g. the above script generates the following image:
857
+
858
+ `phone.jpg`
859
+
860
+ ![206903102-34e79b9f-9ed2-4fac-bb38-82871343c655](https://user-images.githubusercontent.com/59410571/209578593-141467c7-d831-4792-8b9a-b17dc5e47816.jpg)
861
+
862
+ `phone_bed_mix.jpg`
863
+
864
+ ![206903104-913a671d-ef53-4ae4-919d-64c3059c8f67](https://user-images.githubusercontent.com/59410571/209578602-70f323fa-05b7-4dd6-b055-e40683e37914.jpg)
865
+
866
+ For more example generations check out this [demo notebook](https://github.com/daspartho/MagicMix/blob/main/demo.ipynb).
867
+
868
+
869
+ ### Stable UnCLIP
870
+
871
+ UnCLIPPipeline("kakaobrain/karlo-v1-alpha") provide a prior model that can generate clip image embedding from text.
872
+ StableDiffusionImageVariationPipeline("lambdalabs/sd-image-variations-diffusers") provide a decoder model than can generate images from clip image embedding.
873
+
874
+ ```python
875
+ import torch
876
+ from diffusers import DiffusionPipeline
877
+
878
+ device = torch.device("cpu" if not torch.cuda.is_available() else "cuda")
879
+
880
+ pipeline = DiffusionPipeline.from_pretrained(
881
+ "kakaobrain/karlo-v1-alpha",
882
+ torch_dtype=torch.float16,
883
+ custom_pipeline="stable_unclip",
884
+ decoder_pipe_kwargs=dict(
885
+ image_encoder=None,
886
+ ),
887
+ )
888
+ pipeline.to(device)
889
+
890
+ prompt = "a shiba inu wearing a beret and black turtleneck"
891
+ random_generator = torch.Generator(device=device).manual_seed(1000)
892
+ output = pipeline(
893
+ prompt=prompt,
894
+ width=512,
895
+ height=512,
896
+ generator=random_generator,
897
+ prior_guidance_scale=4,
898
+ prior_num_inference_steps=25,
899
+ decoder_guidance_scale=8,
900
+ decoder_num_inference_steps=50,
901
+ )
902
+
903
+ image = output.images[0]
904
+ image.save("./shiba-inu.jpg")
905
+
906
+ # debug
907
+
908
+ # `pipeline.decoder_pipe` is a regular StableDiffusionImageVariationPipeline instance.
909
+ # It is used to convert clip image embedding to latents, then fed into VAE decoder.
910
+ print(pipeline.decoder_pipe.__class__)
911
+ # <class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_image_variation.StableDiffusionImageVariationPipeline'>
912
+
913
+ # this pipeline only use prior module in "kakaobrain/karlo-v1-alpha"
914
+ # It is used to convert clip text embedding to clip image embedding.
915
+ print(pipeline)
916
+ # StableUnCLIPPipeline {
917
+ # "_class_name": "StableUnCLIPPipeline",
918
+ # "_diffusers_version": "0.12.0.dev0",
919
+ # "prior": [
920
+ # "diffusers",
921
+ # "PriorTransformer"
922
+ # ],
923
+ # "prior_scheduler": [
924
+ # "diffusers",
925
+ # "UnCLIPScheduler"
926
+ # ],
927
+ # "text_encoder": [
928
+ # "transformers",
929
+ # "CLIPTextModelWithProjection"
930
+ # ],
931
+ # "tokenizer": [
932
+ # "transformers",
933
+ # "CLIPTokenizer"
934
+ # ]
935
+ # }
936
+
937
+ # pipeline.prior_scheduler is the scheduler used for prior in UnCLIP.
938
+ print(pipeline.prior_scheduler)
939
+ # UnCLIPScheduler {
940
+ # "_class_name": "UnCLIPScheduler",
941
+ # "_diffusers_version": "0.12.0.dev0",
942
+ # "clip_sample": true,
943
+ # "clip_sample_range": 5.0,
944
+ # "num_train_timesteps": 1000,
945
+ # "prediction_type": "sample",
946
+ # "variance_type": "fixed_small_log"
947
+ # }
948
+ ```
949
+
950
+
951
+ `shiba-inu.jpg`
952
+
953
+
954
+ ![shiba-inu](https://user-images.githubusercontent.com/16448529/209185639-6e5ec794-ce9d-4883-aa29-bd6852a2abad.jpg)
955
+
956
+ ### UnCLIP Text Interpolation Pipeline
957
+
958
+ This Diffusion Pipeline takes two prompts and interpolates between the two input prompts using spherical interpolation ( slerp ). The input prompts are converted to text embeddings by the pipeline's text_encoder and the interpolation is done on the resulting text_embeddings over the number of steps specified. Defaults to 5 steps.
959
+
960
+ ```python
961
+ import torch
962
+ from diffusers import DiffusionPipeline
963
+
964
+ device = torch.device("cpu" if not torch.cuda.is_available() else "cuda")
965
+
966
+ pipe = DiffusionPipeline.from_pretrained(
967
+ "kakaobrain/karlo-v1-alpha",
968
+ torch_dtype=torch.float16,
969
+ custom_pipeline="unclip_text_interpolation"
970
+ )
971
+ pipe.to(device)
972
+
973
+ start_prompt = "A photograph of an adult lion"
974
+ end_prompt = "A photograph of a lion cub"
975
+ #For best results keep the prompts close in length to each other. Of course, feel free to try out with differing lengths.
976
+ generator = torch.Generator(device=device).manual_seed(42)
977
+
978
+ output = pipe(start_prompt, end_prompt, steps = 6, generator = generator, enable_sequential_cpu_offload=False)
979
+
980
+ for i,image in enumerate(output.images):
981
+ img.save('result%s.jpg' % i)
982
+ ```
983
+
984
+ The resulting images in order:-
985
+
986
+ ![result_0](https://huggingface.co/datasets/NagaSaiAbhinay/UnCLIPTextInterpolationSamples/resolve/main/lion_to_cub_0.png)
987
+ ![result_1](https://huggingface.co/datasets/NagaSaiAbhinay/UnCLIPTextInterpolationSamples/resolve/main/lion_to_cub_1.png)
988
+ ![result_2](https://huggingface.co/datasets/NagaSaiAbhinay/UnCLIPTextInterpolationSamples/resolve/main/lion_to_cub_2.png)
989
+ ![result_3](https://huggingface.co/datasets/NagaSaiAbhinay/UnCLIPTextInterpolationSamples/resolve/main/lion_to_cub_3.png)
990
+ ![result_4](https://huggingface.co/datasets/NagaSaiAbhinay/UnCLIPTextInterpolationSamples/resolve/main/lion_to_cub_4.png)
991
+ ![result_5](https://huggingface.co/datasets/NagaSaiAbhinay/UnCLIPTextInterpolationSamples/resolve/main/lion_to_cub_5.png)
v0.14.0/bit_diffusion.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+ from einops import rearrange, reduce
5
+
6
+ from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNet2DConditionModel
7
+ from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
8
+ from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
9
+
10
+
11
+ BITS = 8
12
+
13
+
14
+ # convert to bit representations and back taken from https://github.com/lucidrains/bit-diffusion/blob/main/bit_diffusion/bit_diffusion.py
15
+ def decimal_to_bits(x, bits=BITS):
16
+ """expects image tensor ranging from 0 to 1, outputs bit tensor ranging from -1 to 1"""
17
+ device = x.device
18
+
19
+ x = (x * 255).int().clamp(0, 255)
20
+
21
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device)
22
+ mask = rearrange(mask, "d -> d 1 1")
23
+ x = rearrange(x, "b c h w -> b c 1 h w")
24
+
25
+ bits = ((x & mask) != 0).float()
26
+ bits = rearrange(bits, "b c d h w -> b (c d) h w")
27
+ bits = bits * 2 - 1
28
+ return bits
29
+
30
+
31
+ def bits_to_decimal(x, bits=BITS):
32
+ """expects bits from -1 to 1, outputs image tensor from 0 to 1"""
33
+ device = x.device
34
+
35
+ x = (x > 0).int()
36
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device, dtype=torch.int32)
37
+
38
+ mask = rearrange(mask, "d -> d 1 1")
39
+ x = rearrange(x, "b (c d) h w -> b c d h w", d=8)
40
+ dec = reduce(x * mask, "b c d h w -> b c h w", "sum")
41
+ return (dec / 255).clamp(0.0, 1.0)
42
+
43
+
44
+ # modified scheduler step functions for clamping the predicted x_0 between -bit_scale and +bit_scale
45
+ def ddim_bit_scheduler_step(
46
+ self,
47
+ model_output: torch.FloatTensor,
48
+ timestep: int,
49
+ sample: torch.FloatTensor,
50
+ eta: float = 0.0,
51
+ use_clipped_model_output: bool = True,
52
+ generator=None,
53
+ return_dict: bool = True,
54
+ ) -> Union[DDIMSchedulerOutput, Tuple]:
55
+ """
56
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
57
+ process from the learned model outputs (most often the predicted noise).
58
+ Args:
59
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
60
+ timestep (`int`): current discrete timestep in the diffusion chain.
61
+ sample (`torch.FloatTensor`):
62
+ current instance of sample being created by diffusion process.
63
+ eta (`float`): weight of noise for added noise in diffusion step.
64
+ use_clipped_model_output (`bool`): TODO
65
+ generator: random number generator.
66
+ return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class
67
+ Returns:
68
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:
69
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
70
+ returning a tuple, the first element is the sample tensor.
71
+ """
72
+ if self.num_inference_steps is None:
73
+ raise ValueError(
74
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
75
+ )
76
+
77
+ # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
78
+ # Ideally, read DDIM paper in-detail understanding
79
+
80
+ # Notation (<variable name> -> <name in paper>
81
+ # - pred_noise_t -> e_theta(x_t, t)
82
+ # - pred_original_sample -> f_theta(x_t, t) or x_0
83
+ # - std_dev_t -> sigma_t
84
+ # - eta -> η
85
+ # - pred_sample_direction -> "direction pointing to x_t"
86
+ # - pred_prev_sample -> "x_t-1"
87
+
88
+ # 1. get previous step value (=t-1)
89
+ prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
90
+
91
+ # 2. compute alphas, betas
92
+ alpha_prod_t = self.alphas_cumprod[timestep]
93
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
94
+
95
+ beta_prod_t = 1 - alpha_prod_t
96
+
97
+ # 3. compute predicted original sample from predicted noise also called
98
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
99
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
100
+
101
+ # 4. Clip "predicted x_0"
102
+ scale = self.bit_scale
103
+ if self.config.clip_sample:
104
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
105
+
106
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
107
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
108
+ variance = self._get_variance(timestep, prev_timestep)
109
+ std_dev_t = eta * variance ** (0.5)
110
+
111
+ if use_clipped_model_output:
112
+ # the model_output is always re-derived from the clipped x_0 in Glide
113
+ model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
114
+
115
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
116
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output
117
+
118
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
119
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
120
+
121
+ if eta > 0:
122
+ # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
123
+ device = model_output.device if torch.is_tensor(model_output) else "cpu"
124
+ noise = torch.randn(model_output.shape, dtype=model_output.dtype, generator=generator).to(device)
125
+ variance = self._get_variance(timestep, prev_timestep) ** (0.5) * eta * noise
126
+
127
+ prev_sample = prev_sample + variance
128
+
129
+ if not return_dict:
130
+ return (prev_sample,)
131
+
132
+ return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
133
+
134
+
135
+ def ddpm_bit_scheduler_step(
136
+ self,
137
+ model_output: torch.FloatTensor,
138
+ timestep: int,
139
+ sample: torch.FloatTensor,
140
+ prediction_type="epsilon",
141
+ generator=None,
142
+ return_dict: bool = True,
143
+ ) -> Union[DDPMSchedulerOutput, Tuple]:
144
+ """
145
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
146
+ process from the learned model outputs (most often the predicted noise).
147
+ Args:
148
+ model_output (`torch.FloatTensor`): direct output from learned diffusion model.
149
+ timestep (`int`): current discrete timestep in the diffusion chain.
150
+ sample (`torch.FloatTensor`):
151
+ current instance of sample being created by diffusion process.
152
+ prediction_type (`str`, default `epsilon`):
153
+ indicates whether the model predicts the noise (epsilon), or the samples (`sample`).
154
+ generator: random number generator.
155
+ return_dict (`bool`): option for returning tuple rather than DDPMSchedulerOutput class
156
+ Returns:
157
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] or `tuple`:
158
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
159
+ returning a tuple, the first element is the sample tensor.
160
+ """
161
+ t = timestep
162
+
163
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
164
+ model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1)
165
+ else:
166
+ predicted_variance = None
167
+
168
+ # 1. compute alphas, betas
169
+ alpha_prod_t = self.alphas_cumprod[t]
170
+ alpha_prod_t_prev = self.alphas_cumprod[t - 1] if t > 0 else self.one
171
+ beta_prod_t = 1 - alpha_prod_t
172
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
173
+
174
+ # 2. compute predicted original sample from predicted noise also called
175
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
176
+ if prediction_type == "epsilon":
177
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
178
+ elif prediction_type == "sample":
179
+ pred_original_sample = model_output
180
+ else:
181
+ raise ValueError(f"Unsupported prediction_type {prediction_type}.")
182
+
183
+ # 3. Clip "predicted x_0"
184
+ scale = self.bit_scale
185
+ if self.config.clip_sample:
186
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
187
+
188
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
189
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
190
+ pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * self.betas[t]) / beta_prod_t
191
+ current_sample_coeff = self.alphas[t] ** (0.5) * beta_prod_t_prev / beta_prod_t
192
+
193
+ # 5. Compute predicted previous sample µ_t
194
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
195
+ pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
196
+
197
+ # 6. Add noise
198
+ variance = 0
199
+ if t > 0:
200
+ noise = torch.randn(
201
+ model_output.size(), dtype=model_output.dtype, layout=model_output.layout, generator=generator
202
+ ).to(model_output.device)
203
+ variance = (self._get_variance(t, predicted_variance=predicted_variance) ** 0.5) * noise
204
+
205
+ pred_prev_sample = pred_prev_sample + variance
206
+
207
+ if not return_dict:
208
+ return (pred_prev_sample,)
209
+
210
+ return DDPMSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
211
+
212
+
213
+ class BitDiffusion(DiffusionPipeline):
214
+ def __init__(
215
+ self,
216
+ unet: UNet2DConditionModel,
217
+ scheduler: Union[DDIMScheduler, DDPMScheduler],
218
+ bit_scale: Optional[float] = 1.0,
219
+ ):
220
+ super().__init__()
221
+ self.bit_scale = bit_scale
222
+ self.scheduler.step = (
223
+ ddim_bit_scheduler_step if isinstance(scheduler, DDIMScheduler) else ddpm_bit_scheduler_step
224
+ )
225
+
226
+ self.register_modules(unet=unet, scheduler=scheduler)
227
+
228
+ @torch.no_grad()
229
+ def __call__(
230
+ self,
231
+ height: Optional[int] = 256,
232
+ width: Optional[int] = 256,
233
+ num_inference_steps: Optional[int] = 50,
234
+ generator: Optional[torch.Generator] = None,
235
+ batch_size: Optional[int] = 1,
236
+ output_type: Optional[str] = "pil",
237
+ return_dict: bool = True,
238
+ **kwargs,
239
+ ) -> Union[Tuple, ImagePipelineOutput]:
240
+ latents = torch.randn(
241
+ (batch_size, self.unet.in_channels, height, width),
242
+ generator=generator,
243
+ )
244
+ latents = decimal_to_bits(latents) * self.bit_scale
245
+ latents = latents.to(self.device)
246
+
247
+ self.scheduler.set_timesteps(num_inference_steps)
248
+
249
+ for t in self.progress_bar(self.scheduler.timesteps):
250
+ # predict the noise residual
251
+ noise_pred = self.unet(latents, t).sample
252
+
253
+ # compute the previous noisy sample x_t -> x_t-1
254
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
255
+
256
+ image = bits_to_decimal(latents)
257
+
258
+ if output_type == "pil":
259
+ image = self.numpy_to_pil(image)
260
+
261
+ if not return_dict:
262
+ return (image,)
263
+
264
+ return ImagePipelineOutput(images=image)
v0.14.0/checkpoint_merger.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from typing import Dict, List, Union
4
+
5
+ import torch
6
+
7
+ from diffusers.utils import is_safetensors_available
8
+
9
+
10
+ if is_safetensors_available():
11
+ import safetensors.torch
12
+
13
+ from huggingface_hub import snapshot_download
14
+
15
+ from diffusers import DiffusionPipeline, __version__
16
+ from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
17
+ from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME
18
+
19
+
20
+ class CheckpointMergerPipeline(DiffusionPipeline):
21
+ """
22
+ A class that that supports merging diffusion models based on the discussion here:
23
+ https://github.com/huggingface/diffusers/issues/877
24
+
25
+ Example usage:-
26
+
27
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger.py")
28
+
29
+ merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","prompthero/openjourney"], interp = 'inv_sigmoid', alpha = 0.8, force = True)
30
+
31
+ merged_pipe.to('cuda')
32
+
33
+ prompt = "An astronaut riding a unicycle on Mars"
34
+
35
+ results = merged_pipe(prompt)
36
+
37
+ ## For more details, see the docstring for the merge method.
38
+
39
+ """
40
+
41
+ def __init__(self):
42
+ self.register_to_config()
43
+ super().__init__()
44
+
45
+ def _compare_model_configs(self, dict0, dict1):
46
+ if dict0 == dict1:
47
+ return True
48
+ else:
49
+ config0, meta_keys0 = self._remove_meta_keys(dict0)
50
+ config1, meta_keys1 = self._remove_meta_keys(dict1)
51
+ if config0 == config1:
52
+ print(f"Warning !: Mismatch in keys {meta_keys0} and {meta_keys1}.")
53
+ return True
54
+ return False
55
+
56
+ def _remove_meta_keys(self, config_dict: Dict):
57
+ meta_keys = []
58
+ temp_dict = config_dict.copy()
59
+ for key in config_dict.keys():
60
+ if key.startswith("_"):
61
+ temp_dict.pop(key)
62
+ meta_keys.append(key)
63
+ return (temp_dict, meta_keys)
64
+
65
+ @torch.no_grad()
66
+ def merge(self, pretrained_model_name_or_path_list: List[Union[str, os.PathLike]], **kwargs):
67
+ """
68
+ Returns a new pipeline object of the class 'DiffusionPipeline' with the merged checkpoints(weights) of the models passed
69
+ in the argument 'pretrained_model_name_or_path_list' as a list.
70
+
71
+ Parameters:
72
+ -----------
73
+ 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.
74
+
75
+ **kwargs:
76
+ Supports all the default DiffusionPipeline.get_config_dict kwargs viz..
77
+
78
+ cache_dir, resume_download, force_download, proxies, local_files_only, use_auth_token, revision, torch_dtype, device_map.
79
+
80
+ alpha - The interpolation parameter. Ranges from 0 to 1. It affects the ratio in which the checkpoints are merged. A 0.8 alpha
81
+ would mean that the first model checkpoints would affect the final result far less than an alpha of 0.2
82
+
83
+ interp - The interpolation method to use for the merging. Supports "sigmoid", "inv_sigmoid", "add_diff" and None.
84
+ Passing None uses the default interpolation which is weighted sum interpolation. For merging three checkpoints, only "add_diff" is supported.
85
+
86
+ force - Whether to ignore mismatch in model_config.json for the current models. Defaults to False.
87
+
88
+ """
89
+ # Default kwargs from DiffusionPipeline
90
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
91
+ resume_download = kwargs.pop("resume_download", False)
92
+ force_download = kwargs.pop("force_download", False)
93
+ proxies = kwargs.pop("proxies", None)
94
+ local_files_only = kwargs.pop("local_files_only", False)
95
+ use_auth_token = kwargs.pop("use_auth_token", None)
96
+ revision = kwargs.pop("revision", None)
97
+ torch_dtype = kwargs.pop("torch_dtype", None)
98
+ device_map = kwargs.pop("device_map", None)
99
+
100
+ alpha = kwargs.pop("alpha", 0.5)
101
+ interp = kwargs.pop("interp", None)
102
+
103
+ print("Received list", pretrained_model_name_or_path_list)
104
+ print(f"Combining with alpha={alpha}, interpolation mode={interp}")
105
+
106
+ checkpoint_count = len(pretrained_model_name_or_path_list)
107
+ # Ignore result from model_index_json comparision of the two checkpoints
108
+ force = kwargs.pop("force", False)
109
+
110
+ # If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
111
+ if checkpoint_count > 3 or checkpoint_count < 2:
112
+ raise ValueError(
113
+ "Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being"
114
+ " passed."
115
+ )
116
+
117
+ print("Received the right number of checkpoints")
118
+ # chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
119
+ # chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None
120
+
121
+ # Validate that the checkpoints can be merged
122
+ # Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
123
+ config_dicts = []
124
+ for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
125
+ config_dict = DiffusionPipeline.load_config(
126
+ pretrained_model_name_or_path,
127
+ cache_dir=cache_dir,
128
+ resume_download=resume_download,
129
+ force_download=force_download,
130
+ proxies=proxies,
131
+ local_files_only=local_files_only,
132
+ use_auth_token=use_auth_token,
133
+ revision=revision,
134
+ )
135
+ config_dicts.append(config_dict)
136
+
137
+ comparison_result = True
138
+ for idx in range(1, len(config_dicts)):
139
+ comparison_result &= self._compare_model_configs(config_dicts[idx - 1], config_dicts[idx])
140
+ if not force and comparison_result is False:
141
+ raise ValueError("Incompatible checkpoints. Please check model_index.json for the models.")
142
+ print(config_dicts[0], config_dicts[1])
143
+ print("Compatible model_index.json files found")
144
+ # Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
145
+ cached_folders = []
146
+ for pretrained_model_name_or_path, config_dict in zip(pretrained_model_name_or_path_list, config_dicts):
147
+ folder_names = [k for k in config_dict.keys() if not k.startswith("_")]
148
+ allow_patterns = [os.path.join(k, "*") for k in folder_names]
149
+ allow_patterns += [
150
+ WEIGHTS_NAME,
151
+ SCHEDULER_CONFIG_NAME,
152
+ CONFIG_NAME,
153
+ ONNX_WEIGHTS_NAME,
154
+ DiffusionPipeline.config_name,
155
+ ]
156
+ requested_pipeline_class = config_dict.get("_class_name")
157
+ user_agent = {"diffusers": __version__, "pipeline_class": requested_pipeline_class}
158
+
159
+ cached_folder = (
160
+ pretrained_model_name_or_path
161
+ if os.path.isdir(pretrained_model_name_or_path)
162
+ else snapshot_download(
163
+ pretrained_model_name_or_path,
164
+ cache_dir=cache_dir,
165
+ resume_download=resume_download,
166
+ proxies=proxies,
167
+ local_files_only=local_files_only,
168
+ use_auth_token=use_auth_token,
169
+ revision=revision,
170
+ allow_patterns=allow_patterns,
171
+ user_agent=user_agent,
172
+ )
173
+ )
174
+ print("Cached Folder", cached_folder)
175
+ cached_folders.append(cached_folder)
176
+
177
+ # Step 3:-
178
+ # Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
179
+ final_pipe = DiffusionPipeline.from_pretrained(
180
+ cached_folders[0], torch_dtype=torch_dtype, device_map=device_map
181
+ )
182
+ final_pipe.to(self.device)
183
+
184
+ checkpoint_path_2 = None
185
+ if len(cached_folders) > 2:
186
+ checkpoint_path_2 = os.path.join(cached_folders[2])
187
+
188
+ if interp == "sigmoid":
189
+ theta_func = CheckpointMergerPipeline.sigmoid
190
+ elif interp == "inv_sigmoid":
191
+ theta_func = CheckpointMergerPipeline.inv_sigmoid
192
+ elif interp == "add_diff":
193
+ theta_func = CheckpointMergerPipeline.add_difference
194
+ else:
195
+ theta_func = CheckpointMergerPipeline.weighted_sum
196
+
197
+ # Find each module's state dict.
198
+ for attr in final_pipe.config.keys():
199
+ if not attr.startswith("_"):
200
+ checkpoint_path_1 = os.path.join(cached_folders[1], attr)
201
+ if os.path.exists(checkpoint_path_1):
202
+ files = list(
203
+ (
204
+ *glob.glob(os.path.join(checkpoint_path_1, "*.safetensors")),
205
+ *glob.glob(os.path.join(checkpoint_path_1, "*.bin")),
206
+ )
207
+ )
208
+ checkpoint_path_1 = files[0] if len(files) > 0 else None
209
+ if len(cached_folders) < 3:
210
+ checkpoint_path_2 = None
211
+ else:
212
+ checkpoint_path_2 = os.path.join(cached_folders[2], attr)
213
+ if os.path.exists(checkpoint_path_2):
214
+ files = list(
215
+ (
216
+ *glob.glob(os.path.join(checkpoint_path_2, "*.safetensors")),
217
+ *glob.glob(os.path.join(checkpoint_path_2, "*.bin")),
218
+ )
219
+ )
220
+ checkpoint_path_2 = files[0] if len(files) > 0 else None
221
+ # For an attr if both checkpoint_path_1 and 2 are None, ignore.
222
+ # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
223
+ if checkpoint_path_1 is None and checkpoint_path_2 is None:
224
+ print(f"Skipping {attr}: not present in 2nd or 3d model")
225
+ continue
226
+ try:
227
+ module = getattr(final_pipe, attr)
228
+ if isinstance(module, bool): # ignore requires_safety_checker boolean
229
+ continue
230
+ theta_0 = getattr(module, "state_dict")
231
+ theta_0 = theta_0()
232
+
233
+ update_theta_0 = getattr(module, "load_state_dict")
234
+ theta_1 = (
235
+ safetensors.torch.load_file(checkpoint_path_1)
236
+ if (is_safetensors_available() and checkpoint_path_1.endswith(".safetensors"))
237
+ else torch.load(checkpoint_path_1, map_location="cpu")
238
+ )
239
+ theta_2 = None
240
+ if checkpoint_path_2:
241
+ theta_2 = (
242
+ safetensors.torch.load_file(checkpoint_path_2)
243
+ if (is_safetensors_available() and checkpoint_path_2.endswith(".safetensors"))
244
+ else torch.load(checkpoint_path_2, map_location="cpu")
245
+ )
246
+
247
+ if not theta_0.keys() == theta_1.keys():
248
+ print(f"Skipping {attr}: key mismatch")
249
+ continue
250
+ if theta_2 and not theta_1.keys() == theta_2.keys():
251
+ print(f"Skipping {attr}:y mismatch")
252
+ except Exception as e:
253
+ print(f"Skipping {attr} do to an unexpected error: {str(e)}")
254
+ continue
255
+ print(f"MERGING {attr}")
256
+
257
+ for key in theta_0.keys():
258
+ if theta_2:
259
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], theta_2[key], alpha)
260
+ else:
261
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], None, alpha)
262
+
263
+ del theta_1
264
+ del theta_2
265
+ update_theta_0(theta_0)
266
+
267
+ del theta_0
268
+ return final_pipe
269
+
270
+ @staticmethod
271
+ def weighted_sum(theta0, theta1, theta2, alpha):
272
+ return ((1 - alpha) * theta0) + (alpha * theta1)
273
+
274
+ # Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
275
+ @staticmethod
276
+ def sigmoid(theta0, theta1, theta2, alpha):
277
+ alpha = alpha * alpha * (3 - (2 * alpha))
278
+ return theta0 + ((theta1 - theta0) * alpha)
279
+
280
+ # Inverse Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
281
+ @staticmethod
282
+ def inv_sigmoid(theta0, theta1, theta2, alpha):
283
+ import math
284
+
285
+ alpha = 0.5 - math.sin(math.asin(1.0 - 2.0 * alpha) / 3.0)
286
+ return theta0 + ((theta1 - theta0) * alpha)
287
+
288
+ @staticmethod
289
+ def add_difference(theta0, theta1, theta2, alpha):
290
+ return theta0 + (theta1 - theta2) * (1.0 - alpha)
v0.14.0/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
+ from torchvision import transforms
8
+ from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import (
11
+ AutoencoderKL,
12
+ DDIMScheduler,
13
+ DiffusionPipeline,
14
+ LMSDiscreteScheduler,
15
+ PNDMScheduler,
16
+ UNet2DConditionModel,
17
+ )
18
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
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
+ self.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(self.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 / self.vae.config.scaling_factor * 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.cut_out_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 / self.vae.config.scaling_factor * 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.14.0/composable_stable_diffusion.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers import DiffusionPipeline
23
+ from diffusers.configuration_utils import FrozenDict
24
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
25
+ from diffusers.schedulers import (
26
+ DDIMScheduler,
27
+ DPMSolverMultistepScheduler,
28
+ EulerAncestralDiscreteScheduler,
29
+ EulerDiscreteScheduler,
30
+ LMSDiscreteScheduler,
31
+ PNDMScheduler,
32
+ )
33
+ from diffusers.utils import is_accelerate_available
34
+
35
+ from ...utils import deprecate, logging
36
+ from . import StableDiffusionPipelineOutput
37
+ from .safety_checker import StableDiffusionSafetyChecker
38
+
39
+
40
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
41
+
42
+
43
+ class ComposableStableDiffusionPipeline(DiffusionPipeline):
44
+ r"""
45
+ Pipeline for text-to-image generation using Stable Diffusion.
46
+
47
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
48
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
49
+
50
+ Args:
51
+ vae ([`AutoencoderKL`]):
52
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
53
+ text_encoder ([`CLIPTextModel`]):
54
+ Frozen text-encoder. Stable Diffusion uses the text portion of
55
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
56
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
57
+ tokenizer (`CLIPTokenizer`):
58
+ Tokenizer of class
59
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
60
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
61
+ scheduler ([`SchedulerMixin`]):
62
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
63
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
64
+ safety_checker ([`StableDiffusionSafetyChecker`]):
65
+ Classification module that estimates whether generated images could be considered offensive or harmful.
66
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
67
+ feature_extractor ([`CLIPFeatureExtractor`]):
68
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
69
+ """
70
+ _optional_components = ["safety_checker", "feature_extractor"]
71
+
72
+ def __init__(
73
+ self,
74
+ vae: AutoencoderKL,
75
+ text_encoder: CLIPTextModel,
76
+ tokenizer: CLIPTokenizer,
77
+ unet: UNet2DConditionModel,
78
+ scheduler: Union[
79
+ DDIMScheduler,
80
+ PNDMScheduler,
81
+ LMSDiscreteScheduler,
82
+ EulerDiscreteScheduler,
83
+ EulerAncestralDiscreteScheduler,
84
+ DPMSolverMultistepScheduler,
85
+ ],
86
+ safety_checker: StableDiffusionSafetyChecker,
87
+ feature_extractor: CLIPFeatureExtractor,
88
+ requires_safety_checker: bool = True,
89
+ ):
90
+ super().__init__()
91
+
92
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
93
+ deprecation_message = (
94
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
95
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
96
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
97
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
98
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
99
+ " file"
100
+ )
101
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
102
+ new_config = dict(scheduler.config)
103
+ new_config["steps_offset"] = 1
104
+ scheduler._internal_dict = FrozenDict(new_config)
105
+
106
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
107
+ deprecation_message = (
108
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
109
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
110
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
111
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
112
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
113
+ )
114
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
115
+ new_config = dict(scheduler.config)
116
+ new_config["clip_sample"] = False
117
+ scheduler._internal_dict = FrozenDict(new_config)
118
+
119
+ if safety_checker is None and requires_safety_checker:
120
+ logger.warning(
121
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
122
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
123
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
124
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
125
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
126
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
127
+ )
128
+
129
+ if safety_checker is not None and feature_extractor is None:
130
+ raise ValueError(
131
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
132
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
133
+ )
134
+
135
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
136
+ version.parse(unet.config._diffusers_version).base_version
137
+ ) < version.parse("0.9.0.dev0")
138
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
139
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
140
+ deprecation_message = (
141
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
142
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
143
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
144
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
145
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
146
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
147
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
148
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
149
+ " the `unet/config.json` file"
150
+ )
151
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
152
+ new_config = dict(unet.config)
153
+ new_config["sample_size"] = 64
154
+ unet._internal_dict = FrozenDict(new_config)
155
+
156
+ self.register_modules(
157
+ vae=vae,
158
+ text_encoder=text_encoder,
159
+ tokenizer=tokenizer,
160
+ unet=unet,
161
+ scheduler=scheduler,
162
+ safety_checker=safety_checker,
163
+ feature_extractor=feature_extractor,
164
+ )
165
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
166
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
167
+
168
+ def enable_vae_slicing(self):
169
+ r"""
170
+ Enable sliced VAE decoding.
171
+
172
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
173
+ steps. This is useful to save some memory and allow larger batch sizes.
174
+ """
175
+ self.vae.enable_slicing()
176
+
177
+ def disable_vae_slicing(self):
178
+ r"""
179
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
180
+ computing decoding in one step.
181
+ """
182
+ self.vae.disable_slicing()
183
+
184
+ def enable_sequential_cpu_offload(self, gpu_id=0):
185
+ r"""
186
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
187
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
188
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
189
+ """
190
+ if is_accelerate_available():
191
+ from accelerate import cpu_offload
192
+ else:
193
+ raise ImportError("Please install accelerate via `pip install accelerate`")
194
+
195
+ device = torch.device(f"cuda:{gpu_id}")
196
+
197
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
198
+ if cpu_offloaded_model is not None:
199
+ cpu_offload(cpu_offloaded_model, device)
200
+
201
+ if self.safety_checker is not None:
202
+ # TODO(Patrick) - there is currently a bug with cpu offload of nn.Parameter in accelerate
203
+ # fix by only offloading self.safety_checker for now
204
+ cpu_offload(self.safety_checker.vision_model, device)
205
+
206
+ @property
207
+ def _execution_device(self):
208
+ r"""
209
+ Returns the device on which the pipeline's models will be executed. After calling
210
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
211
+ hooks.
212
+ """
213
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
214
+ return self.device
215
+ for module in self.unet.modules():
216
+ if (
217
+ hasattr(module, "_hf_hook")
218
+ and hasattr(module._hf_hook, "execution_device")
219
+ and module._hf_hook.execution_device is not None
220
+ ):
221
+ return torch.device(module._hf_hook.execution_device)
222
+ return self.device
223
+
224
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
225
+ r"""
226
+ Encodes the prompt into text encoder hidden states.
227
+
228
+ Args:
229
+ prompt (`str` or `list(int)`):
230
+ prompt to be encoded
231
+ device: (`torch.device`):
232
+ torch device
233
+ num_images_per_prompt (`int`):
234
+ number of images that should be generated per prompt
235
+ do_classifier_free_guidance (`bool`):
236
+ whether to use classifier free guidance or not
237
+ negative_prompt (`str` or `List[str]`):
238
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
239
+ if `guidance_scale` is less than `1`).
240
+ """
241
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
242
+
243
+ text_inputs = self.tokenizer(
244
+ prompt,
245
+ padding="max_length",
246
+ max_length=self.tokenizer.model_max_length,
247
+ truncation=True,
248
+ return_tensors="pt",
249
+ )
250
+ text_input_ids = text_inputs.input_ids
251
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
252
+
253
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
254
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
255
+ logger.warning(
256
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
257
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
258
+ )
259
+
260
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
261
+ attention_mask = text_inputs.attention_mask.to(device)
262
+ else:
263
+ attention_mask = None
264
+
265
+ text_embeddings = self.text_encoder(
266
+ text_input_ids.to(device),
267
+ attention_mask=attention_mask,
268
+ )
269
+ text_embeddings = text_embeddings[0]
270
+
271
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
272
+ bs_embed, seq_len, _ = text_embeddings.shape
273
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
274
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
275
+
276
+ # get unconditional embeddings for classifier free guidance
277
+ if do_classifier_free_guidance:
278
+ uncond_tokens: List[str]
279
+ if negative_prompt is None:
280
+ uncond_tokens = [""] * batch_size
281
+ elif type(prompt) is not type(negative_prompt):
282
+ raise TypeError(
283
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
284
+ f" {type(prompt)}."
285
+ )
286
+ elif isinstance(negative_prompt, str):
287
+ uncond_tokens = [negative_prompt]
288
+ elif batch_size != len(negative_prompt):
289
+ raise ValueError(
290
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
291
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
292
+ " the batch size of `prompt`."
293
+ )
294
+ else:
295
+ uncond_tokens = negative_prompt
296
+
297
+ max_length = text_input_ids.shape[-1]
298
+ uncond_input = self.tokenizer(
299
+ uncond_tokens,
300
+ padding="max_length",
301
+ max_length=max_length,
302
+ truncation=True,
303
+ return_tensors="pt",
304
+ )
305
+
306
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
307
+ attention_mask = uncond_input.attention_mask.to(device)
308
+ else:
309
+ attention_mask = None
310
+
311
+ uncond_embeddings = self.text_encoder(
312
+ uncond_input.input_ids.to(device),
313
+ attention_mask=attention_mask,
314
+ )
315
+ uncond_embeddings = uncond_embeddings[0]
316
+
317
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
318
+ seq_len = uncond_embeddings.shape[1]
319
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
320
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
321
+
322
+ # For classifier free guidance, we need to do two forward passes.
323
+ # Here we concatenate the unconditional and text embeddings into a single batch
324
+ # to avoid doing two forward passes
325
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
326
+
327
+ return text_embeddings
328
+
329
+ def run_safety_checker(self, image, device, dtype):
330
+ if self.safety_checker is not None:
331
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
332
+ image, has_nsfw_concept = self.safety_checker(
333
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
334
+ )
335
+ else:
336
+ has_nsfw_concept = None
337
+ return image, has_nsfw_concept
338
+
339
+ def decode_latents(self, latents):
340
+ latents = 1 / 0.18215 * latents
341
+ image = self.vae.decode(latents).sample
342
+ image = (image / 2 + 0.5).clamp(0, 1)
343
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
344
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
345
+ return image
346
+
347
+ def prepare_extra_step_kwargs(self, generator, eta):
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
+
353
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
354
+ extra_step_kwargs = {}
355
+ if accepts_eta:
356
+ extra_step_kwargs["eta"] = eta
357
+
358
+ # check if the scheduler accepts generator
359
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
360
+ if accepts_generator:
361
+ extra_step_kwargs["generator"] = generator
362
+ return extra_step_kwargs
363
+
364
+ def check_inputs(self, prompt, height, width, callback_steps):
365
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
366
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
367
+
368
+ if height % 8 != 0 or width % 8 != 0:
369
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
370
+
371
+ if (callback_steps is None) or (
372
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
373
+ ):
374
+ raise ValueError(
375
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
376
+ f" {type(callback_steps)}."
377
+ )
378
+
379
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
380
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
381
+ if latents is None:
382
+ if device.type == "mps":
383
+ # randn does not work reproducibly on mps
384
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
385
+ else:
386
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
387
+ else:
388
+ if latents.shape != shape:
389
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
390
+ latents = latents.to(device)
391
+
392
+ # scale the initial noise by the standard deviation required by the scheduler
393
+ latents = latents * self.scheduler.init_noise_sigma
394
+ return latents
395
+
396
+ @torch.no_grad()
397
+ def __call__(
398
+ self,
399
+ prompt: Union[str, List[str]],
400
+ height: Optional[int] = None,
401
+ width: Optional[int] = None,
402
+ num_inference_steps: int = 50,
403
+ guidance_scale: float = 7.5,
404
+ negative_prompt: Optional[Union[str, List[str]]] = None,
405
+ num_images_per_prompt: Optional[int] = 1,
406
+ eta: float = 0.0,
407
+ generator: Optional[torch.Generator] = None,
408
+ latents: Optional[torch.FloatTensor] = None,
409
+ output_type: Optional[str] = "pil",
410
+ return_dict: bool = True,
411
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
412
+ callback_steps: int = 1,
413
+ weights: Optional[str] = "",
414
+ ):
415
+ r"""
416
+ Function invoked when calling the pipeline for generation.
417
+
418
+ Args:
419
+ prompt (`str` or `List[str]`):
420
+ The prompt or prompts to guide the image generation.
421
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
422
+ The height in pixels of the generated image.
423
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
424
+ The width in pixels of the generated image.
425
+ num_inference_steps (`int`, *optional*, defaults to 50):
426
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
427
+ expense of slower inference.
428
+ guidance_scale (`float`, *optional*, defaults to 7.5):
429
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
430
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
431
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
432
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
433
+ usually at the expense of lower image quality.
434
+ negative_prompt (`str` or `List[str]`, *optional*):
435
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
436
+ if `guidance_scale` is less than `1`).
437
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
438
+ The number of images to generate per prompt.
439
+ eta (`float`, *optional*, defaults to 0.0):
440
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
441
+ [`schedulers.DDIMScheduler`], will be ignored for others.
442
+ generator (`torch.Generator`, *optional*):
443
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
444
+ deterministic.
445
+ latents (`torch.FloatTensor`, *optional*):
446
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
447
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
448
+ tensor will ge generated by sampling using the supplied random `generator`.
449
+ output_type (`str`, *optional*, defaults to `"pil"`):
450
+ The output format of the generate image. Choose between
451
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
452
+ return_dict (`bool`, *optional*, defaults to `True`):
453
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
454
+ plain tuple.
455
+ callback (`Callable`, *optional*):
456
+ A function that will be called every `callback_steps` steps during inference. The function will be
457
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
458
+ callback_steps (`int`, *optional*, defaults to 1):
459
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
460
+ called at every step.
461
+
462
+ Returns:
463
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
464
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
465
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
466
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
467
+ (nsfw) content, according to the `safety_checker`.
468
+ """
469
+ # 0. Default height and width to unet
470
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
471
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
472
+
473
+ # 1. Check inputs. Raise error if not correct
474
+ self.check_inputs(prompt, height, width, callback_steps)
475
+
476
+ # 2. Define call parameters
477
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
478
+ device = self._execution_device
479
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
480
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
481
+ # corresponds to doing no classifier free guidance.
482
+ do_classifier_free_guidance = guidance_scale > 1.0
483
+
484
+ if "|" in prompt:
485
+ prompt = [x.strip() for x in prompt.split("|")]
486
+ print(f"composing {prompt}...")
487
+
488
+ if not weights:
489
+ # specify weights for prompts (excluding the unconditional score)
490
+ print("using equal positive weights (conjunction) for all prompts...")
491
+ weights = torch.tensor([guidance_scale] * len(prompt), device=self.device).reshape(-1, 1, 1, 1)
492
+ else:
493
+ # set prompt weight for each
494
+ num_prompts = len(prompt) if isinstance(prompt, list) else 1
495
+ weights = [float(w.strip()) for w in weights.split("|")]
496
+ # guidance scale as the default
497
+ if len(weights) < num_prompts:
498
+ weights.append(guidance_scale)
499
+ else:
500
+ weights = weights[:num_prompts]
501
+ assert len(weights) == len(prompt), "weights specified are not equal to the number of prompts"
502
+ weights = torch.tensor(weights, device=self.device).reshape(-1, 1, 1, 1)
503
+ else:
504
+ weights = guidance_scale
505
+
506
+ # 3. Encode input prompt
507
+ text_embeddings = self._encode_prompt(
508
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
509
+ )
510
+
511
+ # 4. Prepare timesteps
512
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
513
+ timesteps = self.scheduler.timesteps
514
+
515
+ # 5. Prepare latent variables
516
+ num_channels_latents = self.unet.in_channels
517
+ latents = self.prepare_latents(
518
+ batch_size * num_images_per_prompt,
519
+ num_channels_latents,
520
+ height,
521
+ width,
522
+ text_embeddings.dtype,
523
+ device,
524
+ generator,
525
+ latents,
526
+ )
527
+
528
+ # composable diffusion
529
+ if isinstance(prompt, list) and batch_size == 1:
530
+ # remove extra unconditional embedding
531
+ # N = one unconditional embed + conditional embeds
532
+ text_embeddings = text_embeddings[len(prompt) - 1 :]
533
+
534
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
535
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
536
+
537
+ # 7. Denoising loop
538
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
539
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
540
+ for i, t in enumerate(timesteps):
541
+ # expand the latents if we are doing classifier free guidance
542
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
543
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
544
+
545
+ # predict the noise residual
546
+ noise_pred = []
547
+ for j in range(text_embeddings.shape[0]):
548
+ noise_pred.append(
549
+ self.unet(latent_model_input[:1], t, encoder_hidden_states=text_embeddings[j : j + 1]).sample
550
+ )
551
+ noise_pred = torch.cat(noise_pred, dim=0)
552
+
553
+ # perform guidance
554
+ if do_classifier_free_guidance:
555
+ noise_pred_uncond, noise_pred_text = noise_pred[:1], noise_pred[1:]
556
+ noise_pred = noise_pred_uncond + (weights * (noise_pred_text - noise_pred_uncond)).sum(
557
+ dim=0, keepdims=True
558
+ )
559
+
560
+ # compute the previous noisy sample x_t -> x_t-1
561
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
562
+
563
+ # call the callback, if provided
564
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
565
+ progress_bar.update()
566
+ if callback is not None and i % callback_steps == 0:
567
+ callback(i, t, latents)
568
+
569
+ # 8. Post-processing
570
+ image = self.decode_latents(latents)
571
+
572
+ # 9. Run safety checker
573
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
574
+
575
+ # 10. Convert to PIL
576
+ if output_type == "pil":
577
+ image = self.numpy_to_pil(image)
578
+
579
+ if not return_dict:
580
+ return (image, has_nsfw_concept)
581
+
582
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.14.0/imagic_stable_diffusion.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PIL
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from accelerate import Accelerator
14
+
15
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
16
+ from packaging import version
17
+ from tqdm.auto import tqdm
18
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
19
+
20
+ from diffusers import DiffusionPipeline
21
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
22
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
23
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
24
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
25
+ from diffusers.utils import logging
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
+ accelerator = Accelerator(
188
+ gradient_accumulation_steps=1,
189
+ mixed_precision="fp16",
190
+ )
191
+
192
+ if "torch_device" in kwargs:
193
+ device = kwargs.pop("torch_device")
194
+ warnings.warn(
195
+ "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
196
+ " Consider using `pipe.to(torch_device)` instead."
197
+ )
198
+
199
+ if device is None:
200
+ device = "cuda" if torch.cuda.is_available() else "cpu"
201
+ self.to(device)
202
+
203
+ if height % 8 != 0 or width % 8 != 0:
204
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
205
+
206
+ # Freeze vae and unet
207
+ self.vae.requires_grad_(False)
208
+ self.unet.requires_grad_(False)
209
+ self.text_encoder.requires_grad_(False)
210
+ self.unet.eval()
211
+ self.vae.eval()
212
+ self.text_encoder.eval()
213
+
214
+ if accelerator.is_main_process:
215
+ accelerator.init_trackers(
216
+ "imagic",
217
+ config={
218
+ "embedding_learning_rate": embedding_learning_rate,
219
+ "text_embedding_optimization_steps": text_embedding_optimization_steps,
220
+ },
221
+ )
222
+
223
+ # get text embeddings for prompt
224
+ text_input = self.tokenizer(
225
+ prompt,
226
+ padding="max_length",
227
+ max_length=self.tokenizer.model_max_length,
228
+ truncation=True,
229
+ return_tensors="pt",
230
+ )
231
+ text_embeddings = torch.nn.Parameter(
232
+ self.text_encoder(text_input.input_ids.to(self.device))[0], requires_grad=True
233
+ )
234
+ text_embeddings = text_embeddings.detach()
235
+ text_embeddings.requires_grad_()
236
+ text_embeddings_orig = text_embeddings.clone()
237
+
238
+ # Initialize the optimizer
239
+ optimizer = torch.optim.Adam(
240
+ [text_embeddings], # only optimize the embeddings
241
+ lr=embedding_learning_rate,
242
+ )
243
+
244
+ if isinstance(image, PIL.Image.Image):
245
+ image = preprocess(image)
246
+
247
+ latents_dtype = text_embeddings.dtype
248
+ image = image.to(device=self.device, dtype=latents_dtype)
249
+ init_latent_image_dist = self.vae.encode(image).latent_dist
250
+ image_latents = init_latent_image_dist.sample(generator=generator)
251
+ image_latents = 0.18215 * image_latents
252
+
253
+ progress_bar = tqdm(range(text_embedding_optimization_steps), disable=not accelerator.is_local_main_process)
254
+ progress_bar.set_description("Steps")
255
+
256
+ global_step = 0
257
+
258
+ logger.info("First optimizing the text embedding to better reconstruct the init image")
259
+ for _ in range(text_embedding_optimization_steps):
260
+ with accelerator.accumulate(text_embeddings):
261
+ # Sample noise that we'll add to the latents
262
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
263
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
264
+
265
+ # Add noise to the latents according to the noise magnitude at each timestep
266
+ # (this is the forward diffusion process)
267
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
268
+
269
+ # Predict the noise residual
270
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
271
+
272
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
273
+ accelerator.backward(loss)
274
+
275
+ optimizer.step()
276
+ optimizer.zero_grad()
277
+
278
+ # Checks if the accelerator has performed an optimization step behind the scenes
279
+ if accelerator.sync_gradients:
280
+ progress_bar.update(1)
281
+ global_step += 1
282
+
283
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
284
+ progress_bar.set_postfix(**logs)
285
+ accelerator.log(logs, step=global_step)
286
+
287
+ accelerator.wait_for_everyone()
288
+
289
+ text_embeddings.requires_grad_(False)
290
+
291
+ # Now we fine tune the unet to better reconstruct the image
292
+ self.unet.requires_grad_(True)
293
+ self.unet.train()
294
+ optimizer = torch.optim.Adam(
295
+ self.unet.parameters(), # only optimize unet
296
+ lr=diffusion_model_learning_rate,
297
+ )
298
+ progress_bar = tqdm(range(model_fine_tuning_optimization_steps), disable=not accelerator.is_local_main_process)
299
+
300
+ logger.info("Next fine tuning the entire model to better reconstruct the init image")
301
+ for _ in range(model_fine_tuning_optimization_steps):
302
+ with accelerator.accumulate(self.unet.parameters()):
303
+ # Sample noise that we'll add to the latents
304
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
305
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
306
+
307
+ # Add noise to the latents according to the noise magnitude at each timestep
308
+ # (this is the forward diffusion process)
309
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
310
+
311
+ # Predict the noise residual
312
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
313
+
314
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
315
+ accelerator.backward(loss)
316
+
317
+ optimizer.step()
318
+ optimizer.zero_grad()
319
+
320
+ # Checks if the accelerator has performed an optimization step behind the scenes
321
+ if accelerator.sync_gradients:
322
+ progress_bar.update(1)
323
+ global_step += 1
324
+
325
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
326
+ progress_bar.set_postfix(**logs)
327
+ accelerator.log(logs, step=global_step)
328
+
329
+ accelerator.wait_for_everyone()
330
+ self.text_embeddings_orig = text_embeddings_orig
331
+ self.text_embeddings = text_embeddings
332
+
333
+ @torch.no_grad()
334
+ def __call__(
335
+ self,
336
+ alpha: float = 1.2,
337
+ height: Optional[int] = 512,
338
+ width: Optional[int] = 512,
339
+ num_inference_steps: Optional[int] = 50,
340
+ generator: Optional[torch.Generator] = None,
341
+ output_type: Optional[str] = "pil",
342
+ return_dict: bool = True,
343
+ guidance_scale: float = 7.5,
344
+ eta: float = 0.0,
345
+ ):
346
+ r"""
347
+ Function invoked when calling the pipeline for generation.
348
+ Args:
349
+ prompt (`str` or `List[str]`):
350
+ The prompt or prompts to guide the image generation.
351
+ height (`int`, *optional*, defaults to 512):
352
+ The height in pixels of the generated image.
353
+ width (`int`, *optional*, defaults to 512):
354
+ The width in pixels of the generated image.
355
+ num_inference_steps (`int`, *optional*, defaults to 50):
356
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
357
+ expense of slower inference.
358
+ guidance_scale (`float`, *optional*, defaults to 7.5):
359
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
360
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
361
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
362
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
363
+ usually at the expense of lower image quality.
364
+ eta (`float`, *optional*, defaults to 0.0):
365
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
366
+ [`schedulers.DDIMScheduler`], will be ignored for others.
367
+ generator (`torch.Generator`, *optional*):
368
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
369
+ deterministic.
370
+ latents (`torch.FloatTensor`, *optional*):
371
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
372
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
373
+ tensor will ge generated by sampling using the supplied random `generator`.
374
+ output_type (`str`, *optional*, defaults to `"pil"`):
375
+ The output format of the generate image. Choose between
376
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
377
+ return_dict (`bool`, *optional*, defaults to `True`):
378
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
379
+ plain tuple.
380
+ Returns:
381
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
382
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
383
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
384
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
385
+ (nsfw) content, according to the `safety_checker`.
386
+ """
387
+ if height % 8 != 0 or width % 8 != 0:
388
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
389
+ if self.text_embeddings is None:
390
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
391
+ if self.text_embeddings_orig is None:
392
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
393
+
394
+ text_embeddings = alpha * self.text_embeddings_orig + (1 - alpha) * self.text_embeddings
395
+
396
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
397
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
398
+ # corresponds to doing no classifier free guidance.
399
+ do_classifier_free_guidance = guidance_scale > 1.0
400
+ # get unconditional embeddings for classifier free guidance
401
+ if do_classifier_free_guidance:
402
+ uncond_tokens = [""]
403
+ max_length = self.tokenizer.model_max_length
404
+ uncond_input = self.tokenizer(
405
+ uncond_tokens,
406
+ padding="max_length",
407
+ max_length=max_length,
408
+ truncation=True,
409
+ return_tensors="pt",
410
+ )
411
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
412
+
413
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
414
+ seq_len = uncond_embeddings.shape[1]
415
+ uncond_embeddings = uncond_embeddings.view(1, seq_len, -1)
416
+
417
+ # For classifier free guidance, we need to do two forward passes.
418
+ # Here we concatenate the unconditional and text embeddings into a single batch
419
+ # to avoid doing two forward passes
420
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
421
+
422
+ # get the initial random noise unless the user supplied it
423
+
424
+ # Unlike in other pipelines, latents need to be generated in the target device
425
+ # for 1-to-1 results reproducibility with the CompVis implementation.
426
+ # However this currently doesn't work in `mps`.
427
+ latents_shape = (1, self.unet.in_channels, height // 8, width // 8)
428
+ latents_dtype = text_embeddings.dtype
429
+ if self.device.type == "mps":
430
+ # randn does not exist on mps
431
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
432
+ self.device
433
+ )
434
+ else:
435
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
436
+
437
+ # set timesteps
438
+ self.scheduler.set_timesteps(num_inference_steps)
439
+
440
+ # Some schedulers like PNDM have timesteps as arrays
441
+ # It's more optimized to move all timesteps to correct device beforehand
442
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
443
+
444
+ # scale the initial noise by the standard deviation required by the scheduler
445
+ latents = latents * self.scheduler.init_noise_sigma
446
+
447
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
448
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
449
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
450
+ # and should be between [0, 1]
451
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
452
+ extra_step_kwargs = {}
453
+ if accepts_eta:
454
+ extra_step_kwargs["eta"] = eta
455
+
456
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
457
+ # expand the latents if we are doing classifier free guidance
458
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
459
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
460
+
461
+ # predict the noise residual
462
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
463
+
464
+ # perform guidance
465
+ if do_classifier_free_guidance:
466
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
467
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
468
+
469
+ # compute the previous noisy sample x_t -> x_t-1
470
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
471
+
472
+ latents = 1 / 0.18215 * latents
473
+ image = self.vae.decode(latents).sample
474
+
475
+ image = (image / 2 + 0.5).clamp(0, 1)
476
+
477
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
478
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
479
+
480
+ if self.safety_checker is not None:
481
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
482
+ self.device
483
+ )
484
+ image, has_nsfw_concept = self.safety_checker(
485
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
486
+ )
487
+ else:
488
+ has_nsfw_concept = None
489
+
490
+ if output_type == "pil":
491
+ image = self.numpy_to_pil(image)
492
+
493
+ if not return_dict:
494
+ return (image, has_nsfw_concept)
495
+
496
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.14.0/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 PIL
6
+ import torch
7
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers import DiffusionPipeline
10
+ from diffusers.configuration_utils import FrozenDict
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
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
+
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: 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.14.0/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
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import DiffusionPipeline
11
+ from diffusers.configuration_utils import FrozenDict
12
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
13
+ from diffusers.pipelines.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
+
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: 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 bfloat16
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.14.0/lpw_stable_diffusion.py ADDED
@@ -0,0 +1,1150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL
7
+ import torch
8
+ from packaging import version
9
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
10
+
11
+ import diffusers
12
+ from diffusers import SchedulerMixin, StableDiffusionPipeline
13
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
14
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
15
+ from diffusers.utils import logging
16
+
17
+
18
+ try:
19
+ from diffusers.utils import PIL_INTERPOLATION
20
+ except ImportError:
21
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
22
+ PIL_INTERPOLATION = {
23
+ "linear": PIL.Image.Resampling.BILINEAR,
24
+ "bilinear": PIL.Image.Resampling.BILINEAR,
25
+ "bicubic": PIL.Image.Resampling.BICUBIC,
26
+ "lanczos": PIL.Image.Resampling.LANCZOS,
27
+ "nearest": PIL.Image.Resampling.NEAREST,
28
+ }
29
+ else:
30
+ PIL_INTERPOLATION = {
31
+ "linear": PIL.Image.LINEAR,
32
+ "bilinear": PIL.Image.BILINEAR,
33
+ "bicubic": PIL.Image.BICUBIC,
34
+ "lanczos": PIL.Image.LANCZOS,
35
+ "nearest": PIL.Image.NEAREST,
36
+ }
37
+ # ------------------------------------------------------------------------------
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+ re_attention = re.compile(
42
+ r"""
43
+ \\\(|
44
+ \\\)|
45
+ \\\[|
46
+ \\]|
47
+ \\\\|
48
+ \\|
49
+ \(|
50
+ \[|
51
+ :([+-]?[.\d]+)\)|
52
+ \)|
53
+ ]|
54
+ [^\\()\[\]:]+|
55
+ :
56
+ """,
57
+ re.X,
58
+ )
59
+
60
+
61
+ def parse_prompt_attention(text):
62
+ """
63
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
64
+ Accepted tokens are:
65
+ (abc) - increases attention to abc by a multiplier of 1.1
66
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
67
+ [abc] - decreases attention to abc by a multiplier of 1.1
68
+ \( - literal character '('
69
+ \[ - literal character '['
70
+ \) - literal character ')'
71
+ \] - literal character ']'
72
+ \\ - literal character '\'
73
+ anything else - just text
74
+ >>> parse_prompt_attention('normal text')
75
+ [['normal text', 1.0]]
76
+ >>> parse_prompt_attention('an (important) word')
77
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
78
+ >>> parse_prompt_attention('(unbalanced')
79
+ [['unbalanced', 1.1]]
80
+ >>> parse_prompt_attention('\(literal\]')
81
+ [['(literal]', 1.0]]
82
+ >>> parse_prompt_attention('(unnecessary)(parens)')
83
+ [['unnecessaryparens', 1.1]]
84
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
85
+ [['a ', 1.0],
86
+ ['house', 1.5730000000000004],
87
+ [' ', 1.1],
88
+ ['on', 1.0],
89
+ [' a ', 1.1],
90
+ ['hill', 0.55],
91
+ [', sun, ', 1.1],
92
+ ['sky', 1.4641000000000006],
93
+ ['.', 1.1]]
94
+ """
95
+
96
+ res = []
97
+ round_brackets = []
98
+ square_brackets = []
99
+
100
+ round_bracket_multiplier = 1.1
101
+ square_bracket_multiplier = 1 / 1.1
102
+
103
+ def multiply_range(start_position, multiplier):
104
+ for p in range(start_position, len(res)):
105
+ res[p][1] *= multiplier
106
+
107
+ for m in re_attention.finditer(text):
108
+ text = m.group(0)
109
+ weight = m.group(1)
110
+
111
+ if text.startswith("\\"):
112
+ res.append([text[1:], 1.0])
113
+ elif text == "(":
114
+ round_brackets.append(len(res))
115
+ elif text == "[":
116
+ square_brackets.append(len(res))
117
+ elif weight is not None and len(round_brackets) > 0:
118
+ multiply_range(round_brackets.pop(), float(weight))
119
+ elif text == ")" and len(round_brackets) > 0:
120
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
121
+ elif text == "]" and len(square_brackets) > 0:
122
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
123
+ else:
124
+ res.append([text, 1.0])
125
+
126
+ for pos in round_brackets:
127
+ multiply_range(pos, round_bracket_multiplier)
128
+
129
+ for pos in square_brackets:
130
+ multiply_range(pos, square_bracket_multiplier)
131
+
132
+ if len(res) == 0:
133
+ res = [["", 1.0]]
134
+
135
+ # merge runs of identical weights
136
+ i = 0
137
+ while i + 1 < len(res):
138
+ if res[i][1] == res[i + 1][1]:
139
+ res[i][0] += res[i + 1][0]
140
+ res.pop(i + 1)
141
+ else:
142
+ i += 1
143
+
144
+ return res
145
+
146
+
147
+ def get_prompts_with_weights(pipe: StableDiffusionPipeline, prompt: List[str], max_length: int):
148
+ r"""
149
+ Tokenize a list of prompts and return its tokens with weights of each token.
150
+
151
+ No padding, starting or ending token is included.
152
+ """
153
+ tokens = []
154
+ weights = []
155
+ truncated = False
156
+ for text in prompt:
157
+ texts_and_weights = parse_prompt_attention(text)
158
+ text_token = []
159
+ text_weight = []
160
+ for word, weight in texts_and_weights:
161
+ # tokenize and discard the starting and the ending token
162
+ token = pipe.tokenizer(word).input_ids[1:-1]
163
+ text_token += token
164
+ # copy the weight by length of token
165
+ text_weight += [weight] * len(token)
166
+ # stop if the text is too long (longer than truncation limit)
167
+ if len(text_token) > max_length:
168
+ truncated = True
169
+ break
170
+ # truncate
171
+ if len(text_token) > max_length:
172
+ truncated = True
173
+ text_token = text_token[:max_length]
174
+ text_weight = text_weight[:max_length]
175
+ tokens.append(text_token)
176
+ weights.append(text_weight)
177
+ if truncated:
178
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
179
+ return tokens, weights
180
+
181
+
182
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, no_boseos_middle=True, chunk_length=77):
183
+ r"""
184
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
185
+ """
186
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
187
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
188
+ for i in range(len(tokens)):
189
+ tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i]))
190
+ if no_boseos_middle:
191
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
192
+ else:
193
+ w = []
194
+ if len(weights[i]) == 0:
195
+ w = [1.0] * weights_length
196
+ else:
197
+ for j in range(max_embeddings_multiples):
198
+ w.append(1.0) # weight for starting token in this chunk
199
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
200
+ w.append(1.0) # weight for ending token in this chunk
201
+ w += [1.0] * (weights_length - len(w))
202
+ weights[i] = w[:]
203
+
204
+ return tokens, weights
205
+
206
+
207
+ def get_unweighted_text_embeddings(
208
+ pipe: StableDiffusionPipeline,
209
+ text_input: torch.Tensor,
210
+ chunk_length: int,
211
+ no_boseos_middle: Optional[bool] = True,
212
+ ):
213
+ """
214
+ When the length of tokens is a multiple of the capacity of the text encoder,
215
+ it should be split into chunks and sent to the text encoder individually.
216
+ """
217
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
218
+ if max_embeddings_multiples > 1:
219
+ text_embeddings = []
220
+ for i in range(max_embeddings_multiples):
221
+ # extract the i-th chunk
222
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].clone()
223
+
224
+ # cover the head and the tail by the starting and the ending tokens
225
+ text_input_chunk[:, 0] = text_input[0, 0]
226
+ text_input_chunk[:, -1] = text_input[0, -1]
227
+ text_embedding = pipe.text_encoder(text_input_chunk)[0]
228
+
229
+ if no_boseos_middle:
230
+ if i == 0:
231
+ # discard the ending token
232
+ text_embedding = text_embedding[:, :-1]
233
+ elif i == max_embeddings_multiples - 1:
234
+ # discard the starting token
235
+ text_embedding = text_embedding[:, 1:]
236
+ else:
237
+ # discard both starting and ending tokens
238
+ text_embedding = text_embedding[:, 1:-1]
239
+
240
+ text_embeddings.append(text_embedding)
241
+ text_embeddings = torch.concat(text_embeddings, axis=1)
242
+ else:
243
+ text_embeddings = pipe.text_encoder(text_input)[0]
244
+ return text_embeddings
245
+
246
+
247
+ def get_weighted_text_embeddings(
248
+ pipe: StableDiffusionPipeline,
249
+ prompt: Union[str, List[str]],
250
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
251
+ max_embeddings_multiples: Optional[int] = 3,
252
+ no_boseos_middle: Optional[bool] = False,
253
+ skip_parsing: Optional[bool] = False,
254
+ skip_weighting: Optional[bool] = False,
255
+ ):
256
+ r"""
257
+ Prompts can be assigned with local weights using brackets. For example,
258
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
259
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
260
+
261
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
262
+
263
+ Args:
264
+ pipe (`StableDiffusionPipeline`):
265
+ Pipe to provide access to the tokenizer and the text encoder.
266
+ prompt (`str` or `List[str]`):
267
+ The prompt or prompts to guide the image generation.
268
+ uncond_prompt (`str` or `List[str]`):
269
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
270
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
271
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
272
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
273
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
274
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
275
+ ending token in each of the chunk in the middle.
276
+ skip_parsing (`bool`, *optional*, defaults to `False`):
277
+ Skip the parsing of brackets.
278
+ skip_weighting (`bool`, *optional*, defaults to `False`):
279
+ Skip the weighting. When the parsing is skipped, it is forced True.
280
+ """
281
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
282
+ if isinstance(prompt, str):
283
+ prompt = [prompt]
284
+
285
+ if not skip_parsing:
286
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
287
+ if uncond_prompt is not None:
288
+ if isinstance(uncond_prompt, str):
289
+ uncond_prompt = [uncond_prompt]
290
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
291
+ else:
292
+ prompt_tokens = [
293
+ token[1:-1] for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True).input_ids
294
+ ]
295
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
296
+ if uncond_prompt is not None:
297
+ if isinstance(uncond_prompt, str):
298
+ uncond_prompt = [uncond_prompt]
299
+ uncond_tokens = [
300
+ token[1:-1]
301
+ for token in pipe.tokenizer(uncond_prompt, max_length=max_length, truncation=True).input_ids
302
+ ]
303
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
304
+
305
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
306
+ max_length = max([len(token) for token in prompt_tokens])
307
+ if uncond_prompt is not None:
308
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
309
+
310
+ max_embeddings_multiples = min(
311
+ max_embeddings_multiples,
312
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
313
+ )
314
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
315
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
316
+
317
+ # pad the length of tokens and weights
318
+ bos = pipe.tokenizer.bos_token_id
319
+ eos = pipe.tokenizer.eos_token_id
320
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
321
+ prompt_tokens,
322
+ prompt_weights,
323
+ max_length,
324
+ bos,
325
+ eos,
326
+ no_boseos_middle=no_boseos_middle,
327
+ chunk_length=pipe.tokenizer.model_max_length,
328
+ )
329
+ prompt_tokens = torch.tensor(prompt_tokens, dtype=torch.long, device=pipe.device)
330
+ if uncond_prompt is not None:
331
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
332
+ uncond_tokens,
333
+ uncond_weights,
334
+ max_length,
335
+ bos,
336
+ eos,
337
+ no_boseos_middle=no_boseos_middle,
338
+ chunk_length=pipe.tokenizer.model_max_length,
339
+ )
340
+ uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=pipe.device)
341
+
342
+ # get the embeddings
343
+ text_embeddings = get_unweighted_text_embeddings(
344
+ pipe,
345
+ prompt_tokens,
346
+ pipe.tokenizer.model_max_length,
347
+ no_boseos_middle=no_boseos_middle,
348
+ )
349
+ prompt_weights = torch.tensor(prompt_weights, dtype=text_embeddings.dtype, device=pipe.device)
350
+ if uncond_prompt is not None:
351
+ uncond_embeddings = get_unweighted_text_embeddings(
352
+ pipe,
353
+ uncond_tokens,
354
+ pipe.tokenizer.model_max_length,
355
+ no_boseos_middle=no_boseos_middle,
356
+ )
357
+ uncond_weights = torch.tensor(uncond_weights, dtype=uncond_embeddings.dtype, device=pipe.device)
358
+
359
+ # assign weights to the prompts and normalize in the sense of mean
360
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
361
+ if (not skip_parsing) and (not skip_weighting):
362
+ previous_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
363
+ text_embeddings *= prompt_weights.unsqueeze(-1)
364
+ current_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
365
+ text_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
366
+ if uncond_prompt is not None:
367
+ previous_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
368
+ uncond_embeddings *= uncond_weights.unsqueeze(-1)
369
+ current_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
370
+ uncond_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
371
+
372
+ if uncond_prompt is not None:
373
+ return text_embeddings, uncond_embeddings
374
+ return text_embeddings, None
375
+
376
+
377
+ def preprocess_image(image):
378
+ w, h = image.size
379
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
380
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
381
+ image = np.array(image).astype(np.float32) / 255.0
382
+ image = image[None].transpose(0, 3, 1, 2)
383
+ image = torch.from_numpy(image)
384
+ return 2.0 * image - 1.0
385
+
386
+
387
+ def preprocess_mask(mask, scale_factor=8):
388
+ mask = mask.convert("L")
389
+ w, h = mask.size
390
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
391
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
392
+ mask = np.array(mask).astype(np.float32) / 255.0
393
+ mask = np.tile(mask, (4, 1, 1))
394
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
395
+ mask = 1 - mask # repaint white, keep black
396
+ mask = torch.from_numpy(mask)
397
+ return mask
398
+
399
+
400
+ class StableDiffusionLongPromptWeightingPipeline(StableDiffusionPipeline):
401
+ r"""
402
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
403
+ weighting in prompt.
404
+
405
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
406
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
407
+
408
+ Args:
409
+ vae ([`AutoencoderKL`]):
410
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
411
+ text_encoder ([`CLIPTextModel`]):
412
+ Frozen text-encoder. Stable Diffusion uses the text portion of
413
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
414
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
415
+ tokenizer (`CLIPTokenizer`):
416
+ Tokenizer of class
417
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
418
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
419
+ scheduler ([`SchedulerMixin`]):
420
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
421
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
422
+ safety_checker ([`StableDiffusionSafetyChecker`]):
423
+ Classification module that estimates whether generated images could be considered offensive or harmful.
424
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
425
+ feature_extractor ([`CLIPFeatureExtractor`]):
426
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
427
+ """
428
+
429
+ if version.parse(version.parse(diffusers.__version__).base_version) >= version.parse("0.9.0"):
430
+
431
+ def __init__(
432
+ self,
433
+ vae: AutoencoderKL,
434
+ text_encoder: CLIPTextModel,
435
+ tokenizer: CLIPTokenizer,
436
+ unet: UNet2DConditionModel,
437
+ scheduler: SchedulerMixin,
438
+ safety_checker: StableDiffusionSafetyChecker,
439
+ feature_extractor: CLIPFeatureExtractor,
440
+ requires_safety_checker: bool = True,
441
+ ):
442
+ super().__init__(
443
+ vae=vae,
444
+ text_encoder=text_encoder,
445
+ tokenizer=tokenizer,
446
+ unet=unet,
447
+ scheduler=scheduler,
448
+ safety_checker=safety_checker,
449
+ feature_extractor=feature_extractor,
450
+ requires_safety_checker=requires_safety_checker,
451
+ )
452
+ self.__init__additional__()
453
+
454
+ else:
455
+
456
+ def __init__(
457
+ self,
458
+ vae: AutoencoderKL,
459
+ text_encoder: CLIPTextModel,
460
+ tokenizer: CLIPTokenizer,
461
+ unet: UNet2DConditionModel,
462
+ scheduler: SchedulerMixin,
463
+ safety_checker: StableDiffusionSafetyChecker,
464
+ feature_extractor: CLIPFeatureExtractor,
465
+ ):
466
+ super().__init__(
467
+ vae=vae,
468
+ text_encoder=text_encoder,
469
+ tokenizer=tokenizer,
470
+ unet=unet,
471
+ scheduler=scheduler,
472
+ safety_checker=safety_checker,
473
+ feature_extractor=feature_extractor,
474
+ )
475
+ self.__init__additional__()
476
+
477
+ def __init__additional__(self):
478
+ if not hasattr(self, "vae_scale_factor"):
479
+ setattr(self, "vae_scale_factor", 2 ** (len(self.vae.config.block_out_channels) - 1))
480
+
481
+ @property
482
+ def _execution_device(self):
483
+ r"""
484
+ Returns the device on which the pipeline's models will be executed. After calling
485
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
486
+ hooks.
487
+ """
488
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
489
+ return self.device
490
+ for module in self.unet.modules():
491
+ if (
492
+ hasattr(module, "_hf_hook")
493
+ and hasattr(module._hf_hook, "execution_device")
494
+ and module._hf_hook.execution_device is not None
495
+ ):
496
+ return torch.device(module._hf_hook.execution_device)
497
+ return self.device
498
+
499
+ def _encode_prompt(
500
+ self,
501
+ prompt,
502
+ device,
503
+ num_images_per_prompt,
504
+ do_classifier_free_guidance,
505
+ negative_prompt,
506
+ max_embeddings_multiples,
507
+ ):
508
+ r"""
509
+ Encodes the prompt into text encoder hidden states.
510
+
511
+ Args:
512
+ prompt (`str` or `list(int)`):
513
+ prompt to be encoded
514
+ device: (`torch.device`):
515
+ torch device
516
+ num_images_per_prompt (`int`):
517
+ number of images that should be generated per prompt
518
+ do_classifier_free_guidance (`bool`):
519
+ whether to use classifier free guidance or not
520
+ negative_prompt (`str` or `List[str]`):
521
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
522
+ if `guidance_scale` is less than `1`).
523
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
524
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
525
+ """
526
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
527
+
528
+ if negative_prompt is None:
529
+ negative_prompt = [""] * batch_size
530
+ elif isinstance(negative_prompt, str):
531
+ negative_prompt = [negative_prompt] * batch_size
532
+ if batch_size != len(negative_prompt):
533
+ raise ValueError(
534
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
535
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
536
+ " the batch size of `prompt`."
537
+ )
538
+
539
+ text_embeddings, uncond_embeddings = get_weighted_text_embeddings(
540
+ pipe=self,
541
+ prompt=prompt,
542
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
543
+ max_embeddings_multiples=max_embeddings_multiples,
544
+ )
545
+ bs_embed, seq_len, _ = text_embeddings.shape
546
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
547
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
548
+
549
+ if do_classifier_free_guidance:
550
+ bs_embed, seq_len, _ = uncond_embeddings.shape
551
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
552
+ uncond_embeddings = uncond_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
553
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
554
+
555
+ return text_embeddings
556
+
557
+ def check_inputs(self, prompt, height, width, strength, callback_steps):
558
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
559
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
560
+
561
+ if strength < 0 or strength > 1:
562
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
563
+
564
+ if height % 8 != 0 or width % 8 != 0:
565
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
566
+
567
+ if (callback_steps is None) or (
568
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
569
+ ):
570
+ raise ValueError(
571
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
572
+ f" {type(callback_steps)}."
573
+ )
574
+
575
+ def get_timesteps(self, num_inference_steps, strength, device, is_text2img):
576
+ if is_text2img:
577
+ return self.scheduler.timesteps.to(device), num_inference_steps
578
+ else:
579
+ # get the original timestep using init_timestep
580
+ offset = self.scheduler.config.get("steps_offset", 0)
581
+ init_timestep = int(num_inference_steps * strength) + offset
582
+ init_timestep = min(init_timestep, num_inference_steps)
583
+
584
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
585
+ timesteps = self.scheduler.timesteps[t_start:].to(device)
586
+ return timesteps, num_inference_steps - t_start
587
+
588
+ def run_safety_checker(self, image, device, dtype):
589
+ if self.safety_checker is not None:
590
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
591
+ image, has_nsfw_concept = self.safety_checker(
592
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
593
+ )
594
+ else:
595
+ has_nsfw_concept = None
596
+ return image, has_nsfw_concept
597
+
598
+ def decode_latents(self, latents):
599
+ latents = 1 / 0.18215 * latents
600
+ image = self.vae.decode(latents).sample
601
+ image = (image / 2 + 0.5).clamp(0, 1)
602
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
603
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
604
+ return image
605
+
606
+ def prepare_extra_step_kwargs(self, generator, eta):
607
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
608
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
609
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
610
+ # and should be between [0, 1]
611
+
612
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
613
+ extra_step_kwargs = {}
614
+ if accepts_eta:
615
+ extra_step_kwargs["eta"] = eta
616
+
617
+ # check if the scheduler accepts generator
618
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
619
+ if accepts_generator:
620
+ extra_step_kwargs["generator"] = generator
621
+ return extra_step_kwargs
622
+
623
+ def prepare_latents(self, image, timestep, batch_size, height, width, dtype, device, generator, latents=None):
624
+ if image is None:
625
+ shape = (
626
+ batch_size,
627
+ self.unet.in_channels,
628
+ height // self.vae_scale_factor,
629
+ width // self.vae_scale_factor,
630
+ )
631
+
632
+ if latents is None:
633
+ if device.type == "mps":
634
+ # randn does not work reproducibly on mps
635
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
636
+ else:
637
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
638
+ else:
639
+ if latents.shape != shape:
640
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
641
+ latents = latents.to(device)
642
+
643
+ # scale the initial noise by the standard deviation required by the scheduler
644
+ latents = latents * self.scheduler.init_noise_sigma
645
+ return latents, None, None
646
+ else:
647
+ init_latent_dist = self.vae.encode(image).latent_dist
648
+ init_latents = init_latent_dist.sample(generator=generator)
649
+ init_latents = 0.18215 * init_latents
650
+ init_latents = torch.cat([init_latents] * batch_size, dim=0)
651
+ init_latents_orig = init_latents
652
+ shape = init_latents.shape
653
+
654
+ # add noise to latents using the timesteps
655
+ if device.type == "mps":
656
+ noise = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
657
+ else:
658
+ noise = torch.randn(shape, generator=generator, device=device, dtype=dtype)
659
+ latents = self.scheduler.add_noise(init_latents, noise, timestep)
660
+ return latents, init_latents_orig, noise
661
+
662
+ @torch.no_grad()
663
+ def __call__(
664
+ self,
665
+ prompt: Union[str, List[str]],
666
+ negative_prompt: Optional[Union[str, List[str]]] = None,
667
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
668
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
669
+ height: int = 512,
670
+ width: int = 512,
671
+ num_inference_steps: int = 50,
672
+ guidance_scale: float = 7.5,
673
+ strength: float = 0.8,
674
+ num_images_per_prompt: Optional[int] = 1,
675
+ eta: float = 0.0,
676
+ generator: Optional[torch.Generator] = None,
677
+ latents: Optional[torch.FloatTensor] = None,
678
+ max_embeddings_multiples: Optional[int] = 3,
679
+ output_type: Optional[str] = "pil",
680
+ return_dict: bool = True,
681
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
682
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
683
+ callback_steps: int = 1,
684
+ ):
685
+ r"""
686
+ Function invoked when calling the pipeline for generation.
687
+
688
+ Args:
689
+ prompt (`str` or `List[str]`):
690
+ The prompt or prompts to guide the image generation.
691
+ negative_prompt (`str` or `List[str]`, *optional*):
692
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
693
+ if `guidance_scale` is less than `1`).
694
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
695
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
696
+ process.
697
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
698
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
699
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
700
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
701
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
702
+ height (`int`, *optional*, defaults to 512):
703
+ The height in pixels of the generated image.
704
+ width (`int`, *optional*, defaults to 512):
705
+ The width in pixels of the generated image.
706
+ num_inference_steps (`int`, *optional*, defaults to 50):
707
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
708
+ expense of slower inference.
709
+ guidance_scale (`float`, *optional*, defaults to 7.5):
710
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
711
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
712
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
713
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
714
+ usually at the expense of lower image quality.
715
+ strength (`float`, *optional*, defaults to 0.8):
716
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
717
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
718
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
719
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
720
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
721
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
722
+ The number of images to generate per prompt.
723
+ eta (`float`, *optional*, defaults to 0.0):
724
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
725
+ [`schedulers.DDIMScheduler`], will be ignored for others.
726
+ generator (`torch.Generator`, *optional*):
727
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
728
+ deterministic.
729
+ latents (`torch.FloatTensor`, *optional*):
730
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
731
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
732
+ tensor will ge generated by sampling using the supplied random `generator`.
733
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
734
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
735
+ output_type (`str`, *optional*, defaults to `"pil"`):
736
+ The output format of the generate image. Choose between
737
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
738
+ return_dict (`bool`, *optional*, defaults to `True`):
739
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
740
+ plain tuple.
741
+ callback (`Callable`, *optional*):
742
+ A function that will be called every `callback_steps` steps during inference. The function will be
743
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
744
+ is_cancelled_callback (`Callable`, *optional*):
745
+ A function that will be called every `callback_steps` steps during inference. If the function returns
746
+ `True`, the inference will be cancelled.
747
+ callback_steps (`int`, *optional*, defaults to 1):
748
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
749
+ called at every step.
750
+
751
+ Returns:
752
+ `None` if cancelled by `is_cancelled_callback`,
753
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
754
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
755
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
756
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
757
+ (nsfw) content, according to the `safety_checker`.
758
+ """
759
+ # 0. Default height and width to unet
760
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
761
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
762
+
763
+ # 1. Check inputs. Raise error if not correct
764
+ self.check_inputs(prompt, height, width, strength, callback_steps)
765
+
766
+ # 2. Define call parameters
767
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
768
+ device = self._execution_device
769
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
770
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
771
+ # corresponds to doing no classifier free guidance.
772
+ do_classifier_free_guidance = guidance_scale > 1.0
773
+
774
+ # 3. Encode input prompt
775
+ text_embeddings = self._encode_prompt(
776
+ prompt,
777
+ device,
778
+ num_images_per_prompt,
779
+ do_classifier_free_guidance,
780
+ negative_prompt,
781
+ max_embeddings_multiples,
782
+ )
783
+ dtype = text_embeddings.dtype
784
+
785
+ # 4. Preprocess image and mask
786
+ if isinstance(image, PIL.Image.Image):
787
+ image = preprocess_image(image)
788
+ if image is not None:
789
+ image = image.to(device=self.device, dtype=dtype)
790
+ if isinstance(mask_image, PIL.Image.Image):
791
+ mask_image = preprocess_mask(mask_image, self.vae_scale_factor)
792
+ if mask_image is not None:
793
+ mask = mask_image.to(device=self.device, dtype=dtype)
794
+ mask = torch.cat([mask] * batch_size * num_images_per_prompt)
795
+ else:
796
+ mask = None
797
+
798
+ # 5. set timesteps
799
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
800
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device, image is None)
801
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
802
+
803
+ # 6. Prepare latent variables
804
+ latents, init_latents_orig, noise = self.prepare_latents(
805
+ image,
806
+ latent_timestep,
807
+ batch_size * num_images_per_prompt,
808
+ height,
809
+ width,
810
+ dtype,
811
+ device,
812
+ generator,
813
+ latents,
814
+ )
815
+
816
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
817
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
818
+
819
+ # 8. Denoising loop
820
+ for i, t in enumerate(self.progress_bar(timesteps)):
821
+ # expand the latents if we are doing classifier free guidance
822
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
823
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
824
+
825
+ # predict the noise residual
826
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
827
+
828
+ # perform guidance
829
+ if do_classifier_free_guidance:
830
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
831
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
832
+
833
+ # compute the previous noisy sample x_t -> x_t-1
834
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
835
+
836
+ if mask is not None:
837
+ # masking
838
+ init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, torch.tensor([t]))
839
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
840
+
841
+ # call the callback, if provided
842
+ if i % callback_steps == 0:
843
+ if callback is not None:
844
+ callback(i, t, latents)
845
+ if is_cancelled_callback is not None and is_cancelled_callback():
846
+ return None
847
+
848
+ # 9. Post-processing
849
+ image = self.decode_latents(latents)
850
+
851
+ # 10. Run safety checker
852
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
853
+
854
+ # 11. Convert to PIL
855
+ if output_type == "pil":
856
+ image = self.numpy_to_pil(image)
857
+
858
+ if not return_dict:
859
+ return image, has_nsfw_concept
860
+
861
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
862
+
863
+ def text2img(
864
+ self,
865
+ prompt: Union[str, List[str]],
866
+ negative_prompt: Optional[Union[str, List[str]]] = None,
867
+ height: int = 512,
868
+ width: int = 512,
869
+ num_inference_steps: int = 50,
870
+ guidance_scale: float = 7.5,
871
+ num_images_per_prompt: Optional[int] = 1,
872
+ eta: float = 0.0,
873
+ generator: Optional[torch.Generator] = None,
874
+ latents: Optional[torch.FloatTensor] = None,
875
+ max_embeddings_multiples: Optional[int] = 3,
876
+ output_type: Optional[str] = "pil",
877
+ return_dict: bool = True,
878
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
879
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
880
+ callback_steps: int = 1,
881
+ ):
882
+ r"""
883
+ Function for text-to-image generation.
884
+ Args:
885
+ prompt (`str` or `List[str]`):
886
+ The prompt or prompts to guide the image generation.
887
+ negative_prompt (`str` or `List[str]`, *optional*):
888
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
889
+ if `guidance_scale` is less than `1`).
890
+ height (`int`, *optional*, defaults to 512):
891
+ The height in pixels of the generated image.
892
+ width (`int`, *optional*, defaults to 512):
893
+ The width in pixels of the generated image.
894
+ num_inference_steps (`int`, *optional*, defaults to 50):
895
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
896
+ expense of slower inference.
897
+ guidance_scale (`float`, *optional*, defaults to 7.5):
898
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
899
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
900
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
901
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
902
+ usually at the expense of lower image quality.
903
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
904
+ The number of images to generate per prompt.
905
+ eta (`float`, *optional*, defaults to 0.0):
906
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
907
+ [`schedulers.DDIMScheduler`], will be ignored for others.
908
+ generator (`torch.Generator`, *optional*):
909
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
910
+ deterministic.
911
+ latents (`torch.FloatTensor`, *optional*):
912
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
913
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
914
+ tensor will ge generated by sampling using the supplied random `generator`.
915
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
916
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
917
+ output_type (`str`, *optional*, defaults to `"pil"`):
918
+ The output format of the generate image. Choose between
919
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
920
+ return_dict (`bool`, *optional*, defaults to `True`):
921
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
922
+ plain tuple.
923
+ callback (`Callable`, *optional*):
924
+ A function that will be called every `callback_steps` steps during inference. The function will be
925
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
926
+ is_cancelled_callback (`Callable`, *optional*):
927
+ A function that will be called every `callback_steps` steps during inference. If the function returns
928
+ `True`, the inference will be cancelled.
929
+ callback_steps (`int`, *optional*, defaults to 1):
930
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
931
+ called at every step.
932
+ Returns:
933
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
934
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
935
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
936
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
937
+ (nsfw) content, according to the `safety_checker`.
938
+ """
939
+ return self.__call__(
940
+ prompt=prompt,
941
+ negative_prompt=negative_prompt,
942
+ height=height,
943
+ width=width,
944
+ num_inference_steps=num_inference_steps,
945
+ guidance_scale=guidance_scale,
946
+ num_images_per_prompt=num_images_per_prompt,
947
+ eta=eta,
948
+ generator=generator,
949
+ latents=latents,
950
+ max_embeddings_multiples=max_embeddings_multiples,
951
+ output_type=output_type,
952
+ return_dict=return_dict,
953
+ callback=callback,
954
+ is_cancelled_callback=is_cancelled_callback,
955
+ callback_steps=callback_steps,
956
+ )
957
+
958
+ def img2img(
959
+ self,
960
+ image: Union[torch.FloatTensor, PIL.Image.Image],
961
+ prompt: Union[str, List[str]],
962
+ negative_prompt: Optional[Union[str, List[str]]] = None,
963
+ strength: float = 0.8,
964
+ num_inference_steps: Optional[int] = 50,
965
+ guidance_scale: Optional[float] = 7.5,
966
+ num_images_per_prompt: Optional[int] = 1,
967
+ eta: Optional[float] = 0.0,
968
+ generator: Optional[torch.Generator] = None,
969
+ max_embeddings_multiples: Optional[int] = 3,
970
+ output_type: Optional[str] = "pil",
971
+ return_dict: bool = True,
972
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
973
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
974
+ callback_steps: int = 1,
975
+ ):
976
+ r"""
977
+ Function for image-to-image generation.
978
+ Args:
979
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
980
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
981
+ process.
982
+ prompt (`str` or `List[str]`):
983
+ The prompt or prompts to guide the image generation.
984
+ negative_prompt (`str` or `List[str]`, *optional*):
985
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
986
+ if `guidance_scale` is less than `1`).
987
+ strength (`float`, *optional*, defaults to 0.8):
988
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
989
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
990
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
991
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
992
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
993
+ num_inference_steps (`int`, *optional*, defaults to 50):
994
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
995
+ expense of slower inference. This parameter will be modulated by `strength`.
996
+ guidance_scale (`float`, *optional*, defaults to 7.5):
997
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
998
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
999
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1000
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1001
+ usually at the expense of lower image quality.
1002
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1003
+ The number of images to generate per prompt.
1004
+ eta (`float`, *optional*, defaults to 0.0):
1005
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1006
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1007
+ generator (`torch.Generator`, *optional*):
1008
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1009
+ deterministic.
1010
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1011
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1012
+ output_type (`str`, *optional*, defaults to `"pil"`):
1013
+ The output format of the generate image. Choose between
1014
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1015
+ return_dict (`bool`, *optional*, defaults to `True`):
1016
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1017
+ plain tuple.
1018
+ callback (`Callable`, *optional*):
1019
+ A function that will be called every `callback_steps` steps during inference. The function will be
1020
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1021
+ is_cancelled_callback (`Callable`, *optional*):
1022
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1023
+ `True`, the inference will be cancelled.
1024
+ callback_steps (`int`, *optional*, defaults to 1):
1025
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1026
+ called at every step.
1027
+ Returns:
1028
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1029
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1030
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1031
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1032
+ (nsfw) content, according to the `safety_checker`.
1033
+ """
1034
+ return self.__call__(
1035
+ prompt=prompt,
1036
+ negative_prompt=negative_prompt,
1037
+ image=image,
1038
+ num_inference_steps=num_inference_steps,
1039
+ guidance_scale=guidance_scale,
1040
+ strength=strength,
1041
+ num_images_per_prompt=num_images_per_prompt,
1042
+ eta=eta,
1043
+ generator=generator,
1044
+ max_embeddings_multiples=max_embeddings_multiples,
1045
+ output_type=output_type,
1046
+ return_dict=return_dict,
1047
+ callback=callback,
1048
+ is_cancelled_callback=is_cancelled_callback,
1049
+ callback_steps=callback_steps,
1050
+ )
1051
+
1052
+ def inpaint(
1053
+ self,
1054
+ image: Union[torch.FloatTensor, PIL.Image.Image],
1055
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
1056
+ prompt: Union[str, List[str]],
1057
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1058
+ strength: float = 0.8,
1059
+ num_inference_steps: Optional[int] = 50,
1060
+ guidance_scale: Optional[float] = 7.5,
1061
+ num_images_per_prompt: Optional[int] = 1,
1062
+ eta: Optional[float] = 0.0,
1063
+ generator: Optional[torch.Generator] = None,
1064
+ max_embeddings_multiples: Optional[int] = 3,
1065
+ output_type: Optional[str] = "pil",
1066
+ return_dict: bool = True,
1067
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1068
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1069
+ callback_steps: int = 1,
1070
+ ):
1071
+ r"""
1072
+ Function for inpaint.
1073
+ Args:
1074
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
1075
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1076
+ process. This is the image whose masked region will be inpainted.
1077
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
1078
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1079
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1080
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1081
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1082
+ prompt (`str` or `List[str]`):
1083
+ The prompt or prompts to guide the image generation.
1084
+ negative_prompt (`str` or `List[str]`, *optional*):
1085
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1086
+ if `guidance_scale` is less than `1`).
1087
+ strength (`float`, *optional*, defaults to 0.8):
1088
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1089
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1090
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1091
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1092
+ num_inference_steps (`int`, *optional*, defaults to 50):
1093
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1094
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1095
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1096
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1097
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1098
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1099
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1100
+ usually at the expense of lower image quality.
1101
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1102
+ The number of images to generate per prompt.
1103
+ eta (`float`, *optional*, defaults to 0.0):
1104
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1105
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1106
+ generator (`torch.Generator`, *optional*):
1107
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1108
+ deterministic.
1109
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1110
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1111
+ output_type (`str`, *optional*, defaults to `"pil"`):
1112
+ The output format of the generate image. Choose between
1113
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1114
+ return_dict (`bool`, *optional*, defaults to `True`):
1115
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1116
+ plain tuple.
1117
+ callback (`Callable`, *optional*):
1118
+ A function that will be called every `callback_steps` steps during inference. The function will be
1119
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1120
+ is_cancelled_callback (`Callable`, *optional*):
1121
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1122
+ `True`, the inference will be cancelled.
1123
+ callback_steps (`int`, *optional*, defaults to 1):
1124
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1125
+ called at every step.
1126
+ Returns:
1127
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1128
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1129
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1130
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1131
+ (nsfw) content, according to the `safety_checker`.
1132
+ """
1133
+ return self.__call__(
1134
+ prompt=prompt,
1135
+ negative_prompt=negative_prompt,
1136
+ image=image,
1137
+ mask_image=mask_image,
1138
+ num_inference_steps=num_inference_steps,
1139
+ guidance_scale=guidance_scale,
1140
+ strength=strength,
1141
+ num_images_per_prompt=num_images_per_prompt,
1142
+ eta=eta,
1143
+ generator=generator,
1144
+ max_embeddings_multiples=max_embeddings_multiples,
1145
+ output_type=output_type,
1146
+ return_dict=return_dict,
1147
+ callback=callback,
1148
+ is_cancelled_callback=is_cancelled_callback,
1149
+ callback_steps=callback_steps,
1150
+ )
v0.14.0/lpw_stable_diffusion_onnx.py ADDED
@@ -0,0 +1,1143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL
7
+ import torch
8
+ from packaging import version
9
+ from transformers import CLIPFeatureExtractor, CLIPTokenizer
10
+
11
+ import diffusers
12
+ from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, SchedulerMixin
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.utils import logging
15
+
16
+
17
+ try:
18
+ from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE
19
+ except ImportError:
20
+ ORT_TO_NP_TYPE = {
21
+ "tensor(bool)": np.bool_,
22
+ "tensor(int8)": np.int8,
23
+ "tensor(uint8)": np.uint8,
24
+ "tensor(int16)": np.int16,
25
+ "tensor(uint16)": np.uint16,
26
+ "tensor(int32)": np.int32,
27
+ "tensor(uint32)": np.uint32,
28
+ "tensor(int64)": np.int64,
29
+ "tensor(uint64)": np.uint64,
30
+ "tensor(float16)": np.float16,
31
+ "tensor(float)": np.float32,
32
+ "tensor(double)": np.float64,
33
+ }
34
+
35
+ try:
36
+ from diffusers.utils import PIL_INTERPOLATION
37
+ except ImportError:
38
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
39
+ PIL_INTERPOLATION = {
40
+ "linear": PIL.Image.Resampling.BILINEAR,
41
+ "bilinear": PIL.Image.Resampling.BILINEAR,
42
+ "bicubic": PIL.Image.Resampling.BICUBIC,
43
+ "lanczos": PIL.Image.Resampling.LANCZOS,
44
+ "nearest": PIL.Image.Resampling.NEAREST,
45
+ }
46
+ else:
47
+ PIL_INTERPOLATION = {
48
+ "linear": PIL.Image.LINEAR,
49
+ "bilinear": PIL.Image.BILINEAR,
50
+ "bicubic": PIL.Image.BICUBIC,
51
+ "lanczos": PIL.Image.LANCZOS,
52
+ "nearest": PIL.Image.NEAREST,
53
+ }
54
+ # ------------------------------------------------------------------------------
55
+
56
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
57
+
58
+ re_attention = re.compile(
59
+ r"""
60
+ \\\(|
61
+ \\\)|
62
+ \\\[|
63
+ \\]|
64
+ \\\\|
65
+ \\|
66
+ \(|
67
+ \[|
68
+ :([+-]?[.\d]+)\)|
69
+ \)|
70
+ ]|
71
+ [^\\()\[\]:]+|
72
+ :
73
+ """,
74
+ re.X,
75
+ )
76
+
77
+
78
+ def parse_prompt_attention(text):
79
+ """
80
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
81
+ Accepted tokens are:
82
+ (abc) - increases attention to abc by a multiplier of 1.1
83
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
84
+ [abc] - decreases attention to abc by a multiplier of 1.1
85
+ \( - literal character '('
86
+ \[ - literal character '['
87
+ \) - literal character ')'
88
+ \] - literal character ']'
89
+ \\ - literal character '\'
90
+ anything else - just text
91
+ >>> parse_prompt_attention('normal text')
92
+ [['normal text', 1.0]]
93
+ >>> parse_prompt_attention('an (important) word')
94
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
95
+ >>> parse_prompt_attention('(unbalanced')
96
+ [['unbalanced', 1.1]]
97
+ >>> parse_prompt_attention('\(literal\]')
98
+ [['(literal]', 1.0]]
99
+ >>> parse_prompt_attention('(unnecessary)(parens)')
100
+ [['unnecessaryparens', 1.1]]
101
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
102
+ [['a ', 1.0],
103
+ ['house', 1.5730000000000004],
104
+ [' ', 1.1],
105
+ ['on', 1.0],
106
+ [' a ', 1.1],
107
+ ['hill', 0.55],
108
+ [', sun, ', 1.1],
109
+ ['sky', 1.4641000000000006],
110
+ ['.', 1.1]]
111
+ """
112
+
113
+ res = []
114
+ round_brackets = []
115
+ square_brackets = []
116
+
117
+ round_bracket_multiplier = 1.1
118
+ square_bracket_multiplier = 1 / 1.1
119
+
120
+ def multiply_range(start_position, multiplier):
121
+ for p in range(start_position, len(res)):
122
+ res[p][1] *= multiplier
123
+
124
+ for m in re_attention.finditer(text):
125
+ text = m.group(0)
126
+ weight = m.group(1)
127
+
128
+ if text.startswith("\\"):
129
+ res.append([text[1:], 1.0])
130
+ elif text == "(":
131
+ round_brackets.append(len(res))
132
+ elif text == "[":
133
+ square_brackets.append(len(res))
134
+ elif weight is not None and len(round_brackets) > 0:
135
+ multiply_range(round_brackets.pop(), float(weight))
136
+ elif text == ")" and len(round_brackets) > 0:
137
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
138
+ elif text == "]" and len(square_brackets) > 0:
139
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
140
+ else:
141
+ res.append([text, 1.0])
142
+
143
+ for pos in round_brackets:
144
+ multiply_range(pos, round_bracket_multiplier)
145
+
146
+ for pos in square_brackets:
147
+ multiply_range(pos, square_bracket_multiplier)
148
+
149
+ if len(res) == 0:
150
+ res = [["", 1.0]]
151
+
152
+ # merge runs of identical weights
153
+ i = 0
154
+ while i + 1 < len(res):
155
+ if res[i][1] == res[i + 1][1]:
156
+ res[i][0] += res[i + 1][0]
157
+ res.pop(i + 1)
158
+ else:
159
+ i += 1
160
+
161
+ return res
162
+
163
+
164
+ def get_prompts_with_weights(pipe, prompt: List[str], max_length: int):
165
+ r"""
166
+ Tokenize a list of prompts and return its tokens with weights of each token.
167
+
168
+ No padding, starting or ending token is included.
169
+ """
170
+ tokens = []
171
+ weights = []
172
+ truncated = False
173
+ for text in prompt:
174
+ texts_and_weights = parse_prompt_attention(text)
175
+ text_token = []
176
+ text_weight = []
177
+ for word, weight in texts_and_weights:
178
+ # tokenize and discard the starting and the ending token
179
+ token = pipe.tokenizer(word, return_tensors="np").input_ids[0, 1:-1]
180
+ text_token += list(token)
181
+ # copy the weight by length of token
182
+ text_weight += [weight] * len(token)
183
+ # stop if the text is too long (longer than truncation limit)
184
+ if len(text_token) > max_length:
185
+ truncated = True
186
+ break
187
+ # truncate
188
+ if len(text_token) > max_length:
189
+ truncated = True
190
+ text_token = text_token[:max_length]
191
+ text_weight = text_weight[:max_length]
192
+ tokens.append(text_token)
193
+ weights.append(text_weight)
194
+ if truncated:
195
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
196
+ return tokens, weights
197
+
198
+
199
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, no_boseos_middle=True, chunk_length=77):
200
+ r"""
201
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
202
+ """
203
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
204
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
205
+ for i in range(len(tokens)):
206
+ tokens[i] = [bos] + tokens[i] + [eos] * (max_length - 1 - len(tokens[i]))
207
+ if no_boseos_middle:
208
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
209
+ else:
210
+ w = []
211
+ if len(weights[i]) == 0:
212
+ w = [1.0] * weights_length
213
+ else:
214
+ for j in range(max_embeddings_multiples):
215
+ w.append(1.0) # weight for starting token in this chunk
216
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
217
+ w.append(1.0) # weight for ending token in this chunk
218
+ w += [1.0] * (weights_length - len(w))
219
+ weights[i] = w[:]
220
+
221
+ return tokens, weights
222
+
223
+
224
+ def get_unweighted_text_embeddings(
225
+ pipe,
226
+ text_input: np.array,
227
+ chunk_length: int,
228
+ no_boseos_middle: Optional[bool] = True,
229
+ ):
230
+ """
231
+ When the length of tokens is a multiple of the capacity of the text encoder,
232
+ it should be split into chunks and sent to the text encoder individually.
233
+ """
234
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
235
+ if max_embeddings_multiples > 1:
236
+ text_embeddings = []
237
+ for i in range(max_embeddings_multiples):
238
+ # extract the i-th chunk
239
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].copy()
240
+
241
+ # cover the head and the tail by the starting and the ending tokens
242
+ text_input_chunk[:, 0] = text_input[0, 0]
243
+ text_input_chunk[:, -1] = text_input[0, -1]
244
+
245
+ text_embedding = pipe.text_encoder(input_ids=text_input_chunk)[0]
246
+
247
+ if no_boseos_middle:
248
+ if i == 0:
249
+ # discard the ending token
250
+ text_embedding = text_embedding[:, :-1]
251
+ elif i == max_embeddings_multiples - 1:
252
+ # discard the starting token
253
+ text_embedding = text_embedding[:, 1:]
254
+ else:
255
+ # discard both starting and ending tokens
256
+ text_embedding = text_embedding[:, 1:-1]
257
+
258
+ text_embeddings.append(text_embedding)
259
+ text_embeddings = np.concatenate(text_embeddings, axis=1)
260
+ else:
261
+ text_embeddings = pipe.text_encoder(input_ids=text_input)[0]
262
+ return text_embeddings
263
+
264
+
265
+ def get_weighted_text_embeddings(
266
+ pipe,
267
+ prompt: Union[str, List[str]],
268
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
269
+ max_embeddings_multiples: Optional[int] = 4,
270
+ no_boseos_middle: Optional[bool] = False,
271
+ skip_parsing: Optional[bool] = False,
272
+ skip_weighting: Optional[bool] = False,
273
+ **kwargs,
274
+ ):
275
+ r"""
276
+ Prompts can be assigned with local weights using brackets. For example,
277
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
278
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
279
+
280
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
281
+
282
+ Args:
283
+ pipe (`OnnxStableDiffusionPipeline`):
284
+ Pipe to provide access to the tokenizer and the text encoder.
285
+ prompt (`str` or `List[str]`):
286
+ The prompt or prompts to guide the image generation.
287
+ uncond_prompt (`str` or `List[str]`):
288
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
289
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
290
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
291
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
292
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
293
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
294
+ ending token in each of the chunk in the middle.
295
+ skip_parsing (`bool`, *optional*, defaults to `False`):
296
+ Skip the parsing of brackets.
297
+ skip_weighting (`bool`, *optional*, defaults to `False`):
298
+ Skip the weighting. When the parsing is skipped, it is forced True.
299
+ """
300
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
301
+ if isinstance(prompt, str):
302
+ prompt = [prompt]
303
+
304
+ if not skip_parsing:
305
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
306
+ if uncond_prompt is not None:
307
+ if isinstance(uncond_prompt, str):
308
+ uncond_prompt = [uncond_prompt]
309
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
310
+ else:
311
+ prompt_tokens = [
312
+ token[1:-1]
313
+ for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True, return_tensors="np").input_ids
314
+ ]
315
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
316
+ if uncond_prompt is not None:
317
+ if isinstance(uncond_prompt, str):
318
+ uncond_prompt = [uncond_prompt]
319
+ uncond_tokens = [
320
+ token[1:-1]
321
+ for token in pipe.tokenizer(
322
+ uncond_prompt,
323
+ max_length=max_length,
324
+ truncation=True,
325
+ return_tensors="np",
326
+ ).input_ids
327
+ ]
328
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
329
+
330
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
331
+ max_length = max([len(token) for token in prompt_tokens])
332
+ if uncond_prompt is not None:
333
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
334
+
335
+ max_embeddings_multiples = min(
336
+ max_embeddings_multiples,
337
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
338
+ )
339
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
340
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
341
+
342
+ # pad the length of tokens and weights
343
+ bos = pipe.tokenizer.bos_token_id
344
+ eos = pipe.tokenizer.eos_token_id
345
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
346
+ prompt_tokens,
347
+ prompt_weights,
348
+ max_length,
349
+ bos,
350
+ eos,
351
+ no_boseos_middle=no_boseos_middle,
352
+ chunk_length=pipe.tokenizer.model_max_length,
353
+ )
354
+ prompt_tokens = np.array(prompt_tokens, dtype=np.int32)
355
+ if uncond_prompt is not None:
356
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
357
+ uncond_tokens,
358
+ uncond_weights,
359
+ max_length,
360
+ bos,
361
+ eos,
362
+ no_boseos_middle=no_boseos_middle,
363
+ chunk_length=pipe.tokenizer.model_max_length,
364
+ )
365
+ uncond_tokens = np.array(uncond_tokens, dtype=np.int32)
366
+
367
+ # get the embeddings
368
+ text_embeddings = get_unweighted_text_embeddings(
369
+ pipe,
370
+ prompt_tokens,
371
+ pipe.tokenizer.model_max_length,
372
+ no_boseos_middle=no_boseos_middle,
373
+ )
374
+ prompt_weights = np.array(prompt_weights, dtype=text_embeddings.dtype)
375
+ if uncond_prompt is not None:
376
+ uncond_embeddings = get_unweighted_text_embeddings(
377
+ pipe,
378
+ uncond_tokens,
379
+ pipe.tokenizer.model_max_length,
380
+ no_boseos_middle=no_boseos_middle,
381
+ )
382
+ uncond_weights = np.array(uncond_weights, dtype=uncond_embeddings.dtype)
383
+
384
+ # assign weights to the prompts and normalize in the sense of mean
385
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
386
+ if (not skip_parsing) and (not skip_weighting):
387
+ previous_mean = text_embeddings.mean(axis=(-2, -1))
388
+ text_embeddings *= prompt_weights[:, :, None]
389
+ text_embeddings *= (previous_mean / text_embeddings.mean(axis=(-2, -1)))[:, None, None]
390
+ if uncond_prompt is not None:
391
+ previous_mean = uncond_embeddings.mean(axis=(-2, -1))
392
+ uncond_embeddings *= uncond_weights[:, :, None]
393
+ uncond_embeddings *= (previous_mean / uncond_embeddings.mean(axis=(-2, -1)))[:, None, None]
394
+
395
+ # For classifier free guidance, we need to do two forward passes.
396
+ # Here we concatenate the unconditional and text embeddings into a single batch
397
+ # to avoid doing two forward passes
398
+ if uncond_prompt is not None:
399
+ return text_embeddings, uncond_embeddings
400
+
401
+ return text_embeddings
402
+
403
+
404
+ def preprocess_image(image):
405
+ w, h = image.size
406
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
407
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
408
+ image = np.array(image).astype(np.float32) / 255.0
409
+ image = image[None].transpose(0, 3, 1, 2)
410
+ return 2.0 * image - 1.0
411
+
412
+
413
+ def preprocess_mask(mask, scale_factor=8):
414
+ mask = mask.convert("L")
415
+ w, h = mask.size
416
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
417
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
418
+ mask = np.array(mask).astype(np.float32) / 255.0
419
+ mask = np.tile(mask, (4, 1, 1))
420
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
421
+ mask = 1 - mask # repaint white, keep black
422
+ return mask
423
+
424
+
425
+ class OnnxStableDiffusionLongPromptWeightingPipeline(OnnxStableDiffusionPipeline):
426
+ r"""
427
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
428
+ weighting in prompt.
429
+
430
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
431
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
432
+ """
433
+ if version.parse(version.parse(diffusers.__version__).base_version) >= version.parse("0.9.0"):
434
+
435
+ def __init__(
436
+ self,
437
+ vae_encoder: OnnxRuntimeModel,
438
+ vae_decoder: OnnxRuntimeModel,
439
+ text_encoder: OnnxRuntimeModel,
440
+ tokenizer: CLIPTokenizer,
441
+ unet: OnnxRuntimeModel,
442
+ scheduler: SchedulerMixin,
443
+ safety_checker: OnnxRuntimeModel,
444
+ feature_extractor: CLIPFeatureExtractor,
445
+ requires_safety_checker: bool = True,
446
+ ):
447
+ super().__init__(
448
+ vae_encoder=vae_encoder,
449
+ vae_decoder=vae_decoder,
450
+ text_encoder=text_encoder,
451
+ tokenizer=tokenizer,
452
+ unet=unet,
453
+ scheduler=scheduler,
454
+ safety_checker=safety_checker,
455
+ feature_extractor=feature_extractor,
456
+ requires_safety_checker=requires_safety_checker,
457
+ )
458
+ self.__init__additional__()
459
+
460
+ else:
461
+
462
+ def __init__(
463
+ self,
464
+ vae_encoder: OnnxRuntimeModel,
465
+ vae_decoder: OnnxRuntimeModel,
466
+ text_encoder: OnnxRuntimeModel,
467
+ tokenizer: CLIPTokenizer,
468
+ unet: OnnxRuntimeModel,
469
+ scheduler: SchedulerMixin,
470
+ safety_checker: OnnxRuntimeModel,
471
+ feature_extractor: CLIPFeatureExtractor,
472
+ ):
473
+ super().__init__(
474
+ vae_encoder=vae_encoder,
475
+ vae_decoder=vae_decoder,
476
+ text_encoder=text_encoder,
477
+ tokenizer=tokenizer,
478
+ unet=unet,
479
+ scheduler=scheduler,
480
+ safety_checker=safety_checker,
481
+ feature_extractor=feature_extractor,
482
+ )
483
+ self.__init__additional__()
484
+
485
+ def __init__additional__(self):
486
+ self.unet_in_channels = 4
487
+ self.vae_scale_factor = 8
488
+
489
+ def _encode_prompt(
490
+ self,
491
+ prompt,
492
+ num_images_per_prompt,
493
+ do_classifier_free_guidance,
494
+ negative_prompt,
495
+ max_embeddings_multiples,
496
+ ):
497
+ r"""
498
+ Encodes the prompt into text encoder hidden states.
499
+
500
+ Args:
501
+ prompt (`str` or `list(int)`):
502
+ prompt to be encoded
503
+ num_images_per_prompt (`int`):
504
+ number of images that should be generated per prompt
505
+ do_classifier_free_guidance (`bool`):
506
+ whether to use classifier free guidance or not
507
+ negative_prompt (`str` or `List[str]`):
508
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
509
+ if `guidance_scale` is less than `1`).
510
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
511
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
512
+ """
513
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
514
+
515
+ if negative_prompt is None:
516
+ negative_prompt = [""] * batch_size
517
+ elif isinstance(negative_prompt, str):
518
+ negative_prompt = [negative_prompt] * batch_size
519
+ if batch_size != len(negative_prompt):
520
+ raise ValueError(
521
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
522
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
523
+ " the batch size of `prompt`."
524
+ )
525
+
526
+ text_embeddings, uncond_embeddings = get_weighted_text_embeddings(
527
+ pipe=self,
528
+ prompt=prompt,
529
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
530
+ max_embeddings_multiples=max_embeddings_multiples,
531
+ )
532
+
533
+ text_embeddings = text_embeddings.repeat(num_images_per_prompt, 0)
534
+ if do_classifier_free_guidance:
535
+ uncond_embeddings = uncond_embeddings.repeat(num_images_per_prompt, 0)
536
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
537
+
538
+ return text_embeddings
539
+
540
+ def check_inputs(self, prompt, height, width, strength, callback_steps):
541
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
542
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
543
+
544
+ if strength < 0 or strength > 1:
545
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
546
+
547
+ if height % 8 != 0 or width % 8 != 0:
548
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
549
+
550
+ if (callback_steps is None) or (
551
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
552
+ ):
553
+ raise ValueError(
554
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
555
+ f" {type(callback_steps)}."
556
+ )
557
+
558
+ def get_timesteps(self, num_inference_steps, strength, is_text2img):
559
+ if is_text2img:
560
+ return self.scheduler.timesteps, num_inference_steps
561
+ else:
562
+ # get the original timestep using init_timestep
563
+ offset = self.scheduler.config.get("steps_offset", 0)
564
+ init_timestep = int(num_inference_steps * strength) + offset
565
+ init_timestep = min(init_timestep, num_inference_steps)
566
+
567
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
568
+ timesteps = self.scheduler.timesteps[t_start:]
569
+ return timesteps, num_inference_steps - t_start
570
+
571
+ def run_safety_checker(self, image):
572
+ if self.safety_checker is not None:
573
+ safety_checker_input = self.feature_extractor(
574
+ self.numpy_to_pil(image), return_tensors="np"
575
+ ).pixel_values.astype(image.dtype)
576
+ # There will throw an error if use safety_checker directly and batchsize>1
577
+ images, has_nsfw_concept = [], []
578
+ for i in range(image.shape[0]):
579
+ image_i, has_nsfw_concept_i = self.safety_checker(
580
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
581
+ )
582
+ images.append(image_i)
583
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
584
+ image = np.concatenate(images)
585
+ else:
586
+ has_nsfw_concept = None
587
+ return image, has_nsfw_concept
588
+
589
+ def decode_latents(self, latents):
590
+ latents = 1 / 0.18215 * latents
591
+ # image = self.vae_decoder(latent_sample=latents)[0]
592
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
593
+ image = np.concatenate(
594
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
595
+ )
596
+ image = np.clip(image / 2 + 0.5, 0, 1)
597
+ image = image.transpose((0, 2, 3, 1))
598
+ return image
599
+
600
+ def prepare_extra_step_kwargs(self, generator, eta):
601
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
602
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
603
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
604
+ # and should be between [0, 1]
605
+
606
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
607
+ extra_step_kwargs = {}
608
+ if accepts_eta:
609
+ extra_step_kwargs["eta"] = eta
610
+
611
+ # check if the scheduler accepts generator
612
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
613
+ if accepts_generator:
614
+ extra_step_kwargs["generator"] = generator
615
+ return extra_step_kwargs
616
+
617
+ def prepare_latents(self, image, timestep, batch_size, height, width, dtype, generator, latents=None):
618
+ if image is None:
619
+ shape = (
620
+ batch_size,
621
+ self.unet_in_channels,
622
+ height // self.vae_scale_factor,
623
+ width // self.vae_scale_factor,
624
+ )
625
+
626
+ if latents is None:
627
+ latents = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
628
+ else:
629
+ if latents.shape != shape:
630
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
631
+
632
+ # scale the initial noise by the standard deviation required by the scheduler
633
+ latents = (torch.from_numpy(latents) * self.scheduler.init_noise_sigma).numpy()
634
+ return latents, None, None
635
+ else:
636
+ init_latents = self.vae_encoder(sample=image)[0]
637
+ init_latents = 0.18215 * init_latents
638
+ init_latents = np.concatenate([init_latents] * batch_size, axis=0)
639
+ init_latents_orig = init_latents
640
+ shape = init_latents.shape
641
+
642
+ # add noise to latents using the timesteps
643
+ noise = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
644
+ latents = self.scheduler.add_noise(
645
+ torch.from_numpy(init_latents), torch.from_numpy(noise), timestep
646
+ ).numpy()
647
+ return latents, init_latents_orig, noise
648
+
649
+ @torch.no_grad()
650
+ def __call__(
651
+ self,
652
+ prompt: Union[str, List[str]],
653
+ negative_prompt: Optional[Union[str, List[str]]] = None,
654
+ image: Union[np.ndarray, PIL.Image.Image] = None,
655
+ mask_image: Union[np.ndarray, PIL.Image.Image] = None,
656
+ height: int = 512,
657
+ width: int = 512,
658
+ num_inference_steps: int = 50,
659
+ guidance_scale: float = 7.5,
660
+ strength: float = 0.8,
661
+ num_images_per_prompt: Optional[int] = 1,
662
+ eta: float = 0.0,
663
+ generator: Optional[torch.Generator] = None,
664
+ latents: Optional[np.ndarray] = None,
665
+ max_embeddings_multiples: Optional[int] = 3,
666
+ output_type: Optional[str] = "pil",
667
+ return_dict: bool = True,
668
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
669
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
670
+ callback_steps: int = 1,
671
+ **kwargs,
672
+ ):
673
+ r"""
674
+ Function invoked when calling the pipeline for generation.
675
+
676
+ Args:
677
+ prompt (`str` or `List[str]`):
678
+ The prompt or prompts to guide the image generation.
679
+ negative_prompt (`str` or `List[str]`, *optional*):
680
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
681
+ if `guidance_scale` is less than `1`).
682
+ image (`np.ndarray` or `PIL.Image.Image`):
683
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
684
+ process.
685
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
686
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
687
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
688
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
689
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
690
+ height (`int`, *optional*, defaults to 512):
691
+ The height in pixels of the generated image.
692
+ width (`int`, *optional*, defaults to 512):
693
+ The width in pixels of the generated image.
694
+ num_inference_steps (`int`, *optional*, defaults to 50):
695
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
696
+ expense of slower inference.
697
+ guidance_scale (`float`, *optional*, defaults to 7.5):
698
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
699
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
700
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
701
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
702
+ usually at the expense of lower image quality.
703
+ strength (`float`, *optional*, defaults to 0.8):
704
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
705
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
706
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
707
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
708
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
709
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
710
+ The number of images to generate per prompt.
711
+ eta (`float`, *optional*, defaults to 0.0):
712
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
713
+ [`schedulers.DDIMScheduler`], will be ignored for others.
714
+ generator (`torch.Generator`, *optional*):
715
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
716
+ deterministic.
717
+ latents (`np.ndarray`, *optional*):
718
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
719
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
720
+ tensor will ge generated by sampling using the supplied random `generator`.
721
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
722
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
723
+ output_type (`str`, *optional*, defaults to `"pil"`):
724
+ The output format of the generate image. Choose between
725
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
726
+ return_dict (`bool`, *optional*, defaults to `True`):
727
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
728
+ plain tuple.
729
+ callback (`Callable`, *optional*):
730
+ A function that will be called every `callback_steps` steps during inference. The function will be
731
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
732
+ is_cancelled_callback (`Callable`, *optional*):
733
+ A function that will be called every `callback_steps` steps during inference. If the function returns
734
+ `True`, the inference will be cancelled.
735
+ callback_steps (`int`, *optional*, defaults to 1):
736
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
737
+ called at every step.
738
+
739
+ Returns:
740
+ `None` if cancelled by `is_cancelled_callback`,
741
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
742
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
743
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
744
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
745
+ (nsfw) content, according to the `safety_checker`.
746
+ """
747
+ # 0. Default height and width to unet
748
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
749
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
750
+
751
+ # 1. Check inputs. Raise error if not correct
752
+ self.check_inputs(prompt, height, width, strength, callback_steps)
753
+
754
+ # 2. Define call parameters
755
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
756
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
757
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
758
+ # corresponds to doing no classifier free guidance.
759
+ do_classifier_free_guidance = guidance_scale > 1.0
760
+
761
+ # 3. Encode input prompt
762
+ text_embeddings = self._encode_prompt(
763
+ prompt,
764
+ num_images_per_prompt,
765
+ do_classifier_free_guidance,
766
+ negative_prompt,
767
+ max_embeddings_multiples,
768
+ )
769
+ dtype = text_embeddings.dtype
770
+
771
+ # 4. Preprocess image and mask
772
+ if isinstance(image, PIL.Image.Image):
773
+ image = preprocess_image(image)
774
+ if image is not None:
775
+ image = image.astype(dtype)
776
+ if isinstance(mask_image, PIL.Image.Image):
777
+ mask_image = preprocess_mask(mask_image, self.vae_scale_factor)
778
+ if mask_image is not None:
779
+ mask = mask_image.astype(dtype)
780
+ mask = np.concatenate([mask] * batch_size * num_images_per_prompt)
781
+ else:
782
+ mask = None
783
+
784
+ # 5. set timesteps
785
+ self.scheduler.set_timesteps(num_inference_steps)
786
+ timestep_dtype = next(
787
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
788
+ )
789
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
790
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, image is None)
791
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
792
+
793
+ # 6. Prepare latent variables
794
+ latents, init_latents_orig, noise = self.prepare_latents(
795
+ image,
796
+ latent_timestep,
797
+ batch_size * num_images_per_prompt,
798
+ height,
799
+ width,
800
+ dtype,
801
+ generator,
802
+ latents,
803
+ )
804
+
805
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
806
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
807
+
808
+ # 8. Denoising loop
809
+ for i, t in enumerate(self.progress_bar(timesteps)):
810
+ # expand the latents if we are doing classifier free guidance
811
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
812
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
813
+ latent_model_input = latent_model_input.numpy()
814
+
815
+ # predict the noise residual
816
+ noise_pred = self.unet(
817
+ sample=latent_model_input,
818
+ timestep=np.array([t], dtype=timestep_dtype),
819
+ encoder_hidden_states=text_embeddings,
820
+ )
821
+ noise_pred = noise_pred[0]
822
+
823
+ # perform guidance
824
+ if do_classifier_free_guidance:
825
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
826
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
827
+
828
+ # compute the previous noisy sample x_t -> x_t-1
829
+ scheduler_output = self.scheduler.step(
830
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
831
+ )
832
+ latents = scheduler_output.prev_sample.numpy()
833
+
834
+ if mask is not None:
835
+ # masking
836
+ init_latents_proper = self.scheduler.add_noise(
837
+ torch.from_numpy(init_latents_orig),
838
+ torch.from_numpy(noise),
839
+ t,
840
+ ).numpy()
841
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
842
+
843
+ # call the callback, if provided
844
+ if i % callback_steps == 0:
845
+ if callback is not None:
846
+ callback(i, t, latents)
847
+ if is_cancelled_callback is not None and is_cancelled_callback():
848
+ return None
849
+
850
+ # 9. Post-processing
851
+ image = self.decode_latents(latents)
852
+
853
+ # 10. Run safety checker
854
+ image, has_nsfw_concept = self.run_safety_checker(image)
855
+
856
+ # 11. Convert to PIL
857
+ if output_type == "pil":
858
+ image = self.numpy_to_pil(image)
859
+
860
+ if not return_dict:
861
+ return image, has_nsfw_concept
862
+
863
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
864
+
865
+ def text2img(
866
+ self,
867
+ prompt: Union[str, List[str]],
868
+ negative_prompt: Optional[Union[str, List[str]]] = None,
869
+ height: int = 512,
870
+ width: int = 512,
871
+ num_inference_steps: int = 50,
872
+ guidance_scale: float = 7.5,
873
+ num_images_per_prompt: Optional[int] = 1,
874
+ eta: float = 0.0,
875
+ generator: Optional[torch.Generator] = None,
876
+ latents: Optional[np.ndarray] = None,
877
+ max_embeddings_multiples: Optional[int] = 3,
878
+ output_type: Optional[str] = "pil",
879
+ return_dict: bool = True,
880
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
881
+ callback_steps: int = 1,
882
+ **kwargs,
883
+ ):
884
+ r"""
885
+ Function for text-to-image generation.
886
+ Args:
887
+ prompt (`str` or `List[str]`):
888
+ The prompt or prompts to guide the image generation.
889
+ negative_prompt (`str` or `List[str]`, *optional*):
890
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
891
+ if `guidance_scale` is less than `1`).
892
+ height (`int`, *optional*, defaults to 512):
893
+ The height in pixels of the generated image.
894
+ width (`int`, *optional*, defaults to 512):
895
+ The width in pixels of the generated image.
896
+ num_inference_steps (`int`, *optional*, defaults to 50):
897
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
898
+ expense of slower inference.
899
+ guidance_scale (`float`, *optional*, defaults to 7.5):
900
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
901
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
902
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
903
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
904
+ usually at the expense of lower image quality.
905
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
906
+ The number of images to generate per prompt.
907
+ eta (`float`, *optional*, defaults to 0.0):
908
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
909
+ [`schedulers.DDIMScheduler`], will be ignored for others.
910
+ generator (`torch.Generator`, *optional*):
911
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
912
+ deterministic.
913
+ latents (`np.ndarray`, *optional*):
914
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
915
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
916
+ tensor will ge generated by sampling using the supplied random `generator`.
917
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
918
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
919
+ output_type (`str`, *optional*, defaults to `"pil"`):
920
+ The output format of the generate image. Choose between
921
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
922
+ return_dict (`bool`, *optional*, defaults to `True`):
923
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
924
+ plain tuple.
925
+ callback (`Callable`, *optional*):
926
+ A function that will be called every `callback_steps` steps during inference. The function will be
927
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
928
+ callback_steps (`int`, *optional*, defaults to 1):
929
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
930
+ called at every step.
931
+ Returns:
932
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
933
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
934
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
935
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
936
+ (nsfw) content, according to the `safety_checker`.
937
+ """
938
+ return self.__call__(
939
+ prompt=prompt,
940
+ negative_prompt=negative_prompt,
941
+ height=height,
942
+ width=width,
943
+ num_inference_steps=num_inference_steps,
944
+ guidance_scale=guidance_scale,
945
+ num_images_per_prompt=num_images_per_prompt,
946
+ eta=eta,
947
+ generator=generator,
948
+ latents=latents,
949
+ max_embeddings_multiples=max_embeddings_multiples,
950
+ output_type=output_type,
951
+ return_dict=return_dict,
952
+ callback=callback,
953
+ callback_steps=callback_steps,
954
+ **kwargs,
955
+ )
956
+
957
+ def img2img(
958
+ self,
959
+ image: Union[np.ndarray, PIL.Image.Image],
960
+ prompt: Union[str, List[str]],
961
+ negative_prompt: Optional[Union[str, List[str]]] = None,
962
+ strength: float = 0.8,
963
+ num_inference_steps: Optional[int] = 50,
964
+ guidance_scale: Optional[float] = 7.5,
965
+ num_images_per_prompt: Optional[int] = 1,
966
+ eta: Optional[float] = 0.0,
967
+ generator: Optional[torch.Generator] = None,
968
+ max_embeddings_multiples: Optional[int] = 3,
969
+ output_type: Optional[str] = "pil",
970
+ return_dict: bool = True,
971
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
972
+ callback_steps: int = 1,
973
+ **kwargs,
974
+ ):
975
+ r"""
976
+ Function for image-to-image generation.
977
+ Args:
978
+ image (`np.ndarray` or `PIL.Image.Image`):
979
+ `Image`, or ndarray representing an image batch, that will be used as the starting point for the
980
+ process.
981
+ prompt (`str` or `List[str]`):
982
+ The prompt or prompts to guide the image generation.
983
+ negative_prompt (`str` or `List[str]`, *optional*):
984
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
985
+ if `guidance_scale` is less than `1`).
986
+ strength (`float`, *optional*, defaults to 0.8):
987
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
988
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
989
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
990
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
991
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
992
+ num_inference_steps (`int`, *optional*, defaults to 50):
993
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
994
+ expense of slower inference. This parameter will be modulated by `strength`.
995
+ guidance_scale (`float`, *optional*, defaults to 7.5):
996
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
997
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
998
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
999
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1000
+ usually at the expense of lower image quality.
1001
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1002
+ The number of images to generate per prompt.
1003
+ eta (`float`, *optional*, defaults to 0.0):
1004
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1005
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1006
+ generator (`torch.Generator`, *optional*):
1007
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1008
+ deterministic.
1009
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1010
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1011
+ output_type (`str`, *optional*, defaults to `"pil"`):
1012
+ The output format of the generate image. Choose between
1013
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1014
+ return_dict (`bool`, *optional*, defaults to `True`):
1015
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1016
+ plain tuple.
1017
+ callback (`Callable`, *optional*):
1018
+ A function that will be called every `callback_steps` steps during inference. The function will be
1019
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1020
+ callback_steps (`int`, *optional*, defaults to 1):
1021
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1022
+ called at every step.
1023
+ Returns:
1024
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1025
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1026
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1027
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1028
+ (nsfw) content, according to the `safety_checker`.
1029
+ """
1030
+ return self.__call__(
1031
+ prompt=prompt,
1032
+ negative_prompt=negative_prompt,
1033
+ image=image,
1034
+ num_inference_steps=num_inference_steps,
1035
+ guidance_scale=guidance_scale,
1036
+ strength=strength,
1037
+ num_images_per_prompt=num_images_per_prompt,
1038
+ eta=eta,
1039
+ generator=generator,
1040
+ max_embeddings_multiples=max_embeddings_multiples,
1041
+ output_type=output_type,
1042
+ return_dict=return_dict,
1043
+ callback=callback,
1044
+ callback_steps=callback_steps,
1045
+ **kwargs,
1046
+ )
1047
+
1048
+ def inpaint(
1049
+ self,
1050
+ image: Union[np.ndarray, PIL.Image.Image],
1051
+ mask_image: Union[np.ndarray, PIL.Image.Image],
1052
+ prompt: Union[str, List[str]],
1053
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1054
+ strength: float = 0.8,
1055
+ num_inference_steps: Optional[int] = 50,
1056
+ guidance_scale: Optional[float] = 7.5,
1057
+ num_images_per_prompt: Optional[int] = 1,
1058
+ eta: Optional[float] = 0.0,
1059
+ generator: Optional[torch.Generator] = None,
1060
+ max_embeddings_multiples: Optional[int] = 3,
1061
+ output_type: Optional[str] = "pil",
1062
+ return_dict: bool = True,
1063
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
1064
+ callback_steps: int = 1,
1065
+ **kwargs,
1066
+ ):
1067
+ r"""
1068
+ Function for inpaint.
1069
+ Args:
1070
+ image (`np.ndarray` or `PIL.Image.Image`):
1071
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1072
+ process. This is the image whose masked region will be inpainted.
1073
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
1074
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1075
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1076
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1077
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1078
+ prompt (`str` or `List[str]`):
1079
+ The prompt or prompts to guide the image generation.
1080
+ negative_prompt (`str` or `List[str]`, *optional*):
1081
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1082
+ if `guidance_scale` is less than `1`).
1083
+ strength (`float`, *optional*, defaults to 0.8):
1084
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1085
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1086
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1087
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1088
+ num_inference_steps (`int`, *optional*, defaults to 50):
1089
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1090
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1091
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1092
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1093
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1094
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1095
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1096
+ usually at the expense of lower image quality.
1097
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1098
+ The number of images to generate per prompt.
1099
+ eta (`float`, *optional*, defaults to 0.0):
1100
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1101
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1102
+ generator (`torch.Generator`, *optional*):
1103
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1104
+ deterministic.
1105
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1106
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1107
+ output_type (`str`, *optional*, defaults to `"pil"`):
1108
+ The output format of the generate image. Choose between
1109
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1110
+ return_dict (`bool`, *optional*, defaults to `True`):
1111
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1112
+ plain tuple.
1113
+ callback (`Callable`, *optional*):
1114
+ A function that will be called every `callback_steps` steps during inference. The function will be
1115
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1116
+ callback_steps (`int`, *optional*, defaults to 1):
1117
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1118
+ called at every step.
1119
+ Returns:
1120
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1121
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1122
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1123
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1124
+ (nsfw) content, according to the `safety_checker`.
1125
+ """
1126
+ return self.__call__(
1127
+ prompt=prompt,
1128
+ negative_prompt=negative_prompt,
1129
+ image=image,
1130
+ mask_image=mask_image,
1131
+ num_inference_steps=num_inference_steps,
1132
+ guidance_scale=guidance_scale,
1133
+ strength=strength,
1134
+ num_images_per_prompt=num_images_per_prompt,
1135
+ eta=eta,
1136
+ generator=generator,
1137
+ max_embeddings_multiples=max_embeddings_multiples,
1138
+ output_type=output_type,
1139
+ return_dict=return_dict,
1140
+ callback=callback,
1141
+ callback_steps=callback_steps,
1142
+ **kwargs,
1143
+ )
v0.14.0/magic_mix.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ import torch
4
+ from PIL import Image
5
+ from torchvision import transforms as tfms
6
+ from tqdm.auto import tqdm
7
+ from transformers import CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers import (
10
+ AutoencoderKL,
11
+ DDIMScheduler,
12
+ DiffusionPipeline,
13
+ LMSDiscreteScheduler,
14
+ PNDMScheduler,
15
+ UNet2DConditionModel,
16
+ )
17
+
18
+
19
+ class MagicMixPipeline(DiffusionPipeline):
20
+ def __init__(
21
+ self,
22
+ vae: AutoencoderKL,
23
+ text_encoder: CLIPTextModel,
24
+ tokenizer: CLIPTokenizer,
25
+ unet: UNet2DConditionModel,
26
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler],
27
+ ):
28
+ super().__init__()
29
+
30
+ self.register_modules(vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, scheduler=scheduler)
31
+
32
+ # convert PIL image to latents
33
+ def encode(self, img):
34
+ with torch.no_grad():
35
+ latent = self.vae.encode(tfms.ToTensor()(img).unsqueeze(0).to(self.device) * 2 - 1)
36
+ latent = 0.18215 * latent.latent_dist.sample()
37
+ return latent
38
+
39
+ # convert latents to PIL image
40
+ def decode(self, latent):
41
+ latent = (1 / 0.18215) * latent
42
+ with torch.no_grad():
43
+ img = self.vae.decode(latent).sample
44
+ img = (img / 2 + 0.5).clamp(0, 1)
45
+ img = img.detach().cpu().permute(0, 2, 3, 1).numpy()
46
+ img = (img * 255).round().astype("uint8")
47
+ return Image.fromarray(img[0])
48
+
49
+ # convert prompt into text embeddings, also unconditional embeddings
50
+ def prep_text(self, prompt):
51
+ text_input = self.tokenizer(
52
+ prompt,
53
+ padding="max_length",
54
+ max_length=self.tokenizer.model_max_length,
55
+ truncation=True,
56
+ return_tensors="pt",
57
+ )
58
+
59
+ text_embedding = self.text_encoder(text_input.input_ids.to(self.device))[0]
60
+
61
+ uncond_input = self.tokenizer(
62
+ "",
63
+ padding="max_length",
64
+ max_length=self.tokenizer.model_max_length,
65
+ truncation=True,
66
+ return_tensors="pt",
67
+ )
68
+
69
+ uncond_embedding = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
70
+
71
+ return torch.cat([uncond_embedding, text_embedding])
72
+
73
+ def __call__(
74
+ self,
75
+ img: Image.Image,
76
+ prompt: str,
77
+ kmin: float = 0.3,
78
+ kmax: float = 0.6,
79
+ mix_factor: float = 0.5,
80
+ seed: int = 42,
81
+ steps: int = 50,
82
+ guidance_scale: float = 7.5,
83
+ ) -> Image.Image:
84
+ tmin = steps - int(kmin * steps)
85
+ tmax = steps - int(kmax * steps)
86
+
87
+ text_embeddings = self.prep_text(prompt)
88
+
89
+ self.scheduler.set_timesteps(steps)
90
+
91
+ width, height = img.size
92
+ encoded = self.encode(img)
93
+
94
+ torch.manual_seed(seed)
95
+ noise = torch.randn(
96
+ (1, self.unet.in_channels, height // 8, width // 8),
97
+ ).to(self.device)
98
+
99
+ latents = self.scheduler.add_noise(
100
+ encoded,
101
+ noise,
102
+ timesteps=self.scheduler.timesteps[tmax],
103
+ )
104
+
105
+ input = torch.cat([latents] * 2)
106
+
107
+ input = self.scheduler.scale_model_input(input, self.scheduler.timesteps[tmax])
108
+
109
+ with torch.no_grad():
110
+ pred = self.unet(
111
+ input,
112
+ self.scheduler.timesteps[tmax],
113
+ encoder_hidden_states=text_embeddings,
114
+ ).sample
115
+
116
+ pred_uncond, pred_text = pred.chunk(2)
117
+ pred = pred_uncond + guidance_scale * (pred_text - pred_uncond)
118
+
119
+ latents = self.scheduler.step(pred, self.scheduler.timesteps[tmax], latents).prev_sample
120
+
121
+ for i, t in enumerate(tqdm(self.scheduler.timesteps)):
122
+ if i > tmax:
123
+ if i < tmin: # layout generation phase
124
+ orig_latents = self.scheduler.add_noise(
125
+ encoded,
126
+ noise,
127
+ timesteps=t,
128
+ )
129
+
130
+ input = (mix_factor * latents) + (
131
+ 1 - mix_factor
132
+ ) * orig_latents # interpolating between layout noise and conditionally generated noise to preserve layout sematics
133
+ input = torch.cat([input] * 2)
134
+
135
+ else: # content generation phase
136
+ input = torch.cat([latents] * 2)
137
+
138
+ input = self.scheduler.scale_model_input(input, t)
139
+
140
+ with torch.no_grad():
141
+ pred = self.unet(
142
+ input,
143
+ t,
144
+ encoder_hidden_states=text_embeddings,
145
+ ).sample
146
+
147
+ pred_uncond, pred_text = pred.chunk(2)
148
+ pred = pred_uncond + guidance_scale * (pred_text - pred_uncond)
149
+
150
+ latents = self.scheduler.step(pred, t, latents).prev_sample
151
+
152
+ return self.decode(latents)
v0.14.0/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
+ from transformers import (
6
+ CLIPFeatureExtractor,
7
+ CLIPTextModel,
8
+ CLIPTokenizer,
9
+ MBart50TokenizerFast,
10
+ MBartForConditionalGeneration,
11
+ pipeline,
12
+ )
13
+
14
+ from diffusers import DiffusionPipeline
15
+ from diffusers.configuration_utils import FrozenDict
16
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
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
+
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: 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 bfloat16
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.14.0/one_step_unet.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ result = scheduler_output - scheduler_output + torch.ones_like(scheduler_output)
23
+
24
+ return result
v0.14.0/sd_text2img_k_diffusion.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ from k_diffusion.external import CompVisDenoiser, CompVisVDenoiser
21
+
22
+ from diffusers import DiffusionPipeline, LMSDiscreteScheduler
23
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
24
+ from diffusers.utils import is_accelerate_available, logging
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ class ModelWrapper:
31
+ def __init__(self, model, alphas_cumprod):
32
+ self.model = model
33
+ self.alphas_cumprod = alphas_cumprod
34
+
35
+ def apply_model(self, *args, **kwargs):
36
+ if len(args) == 3:
37
+ encoder_hidden_states = args[-1]
38
+ args = args[:2]
39
+ if kwargs.get("cond", None) is not None:
40
+ encoder_hidden_states = kwargs.pop("cond")
41
+ return self.model(*args, encoder_hidden_states=encoder_hidden_states, **kwargs).sample
42
+
43
+
44
+ class StableDiffusionPipeline(DiffusionPipeline):
45
+ r"""
46
+ Pipeline for text-to-image generation using Stable Diffusion.
47
+
48
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
49
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
50
+
51
+ Args:
52
+ vae ([`AutoencoderKL`]):
53
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
54
+ text_encoder ([`CLIPTextModel`]):
55
+ Frozen text-encoder. Stable Diffusion uses the text portion of
56
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
57
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
58
+ tokenizer (`CLIPTokenizer`):
59
+ Tokenizer of class
60
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
61
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
62
+ scheduler ([`SchedulerMixin`]):
63
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
64
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
65
+ safety_checker ([`StableDiffusionSafetyChecker`]):
66
+ Classification module that estimates whether generated images could be considered offensive or harmful.
67
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
68
+ feature_extractor ([`CLIPFeatureExtractor`]):
69
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
70
+ """
71
+ _optional_components = ["safety_checker", "feature_extractor"]
72
+
73
+ def __init__(
74
+ self,
75
+ vae,
76
+ text_encoder,
77
+ tokenizer,
78
+ unet,
79
+ scheduler,
80
+ safety_checker,
81
+ feature_extractor,
82
+ ):
83
+ super().__init__()
84
+
85
+ if safety_checker is None:
86
+ logger.warning(
87
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
88
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
89
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
90
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
91
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
92
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
93
+ )
94
+
95
+ # get correct sigmas from LMS
96
+ scheduler = LMSDiscreteScheduler.from_config(scheduler.config)
97
+ self.register_modules(
98
+ vae=vae,
99
+ text_encoder=text_encoder,
100
+ tokenizer=tokenizer,
101
+ unet=unet,
102
+ scheduler=scheduler,
103
+ safety_checker=safety_checker,
104
+ feature_extractor=feature_extractor,
105
+ )
106
+
107
+ model = ModelWrapper(unet, scheduler.alphas_cumprod)
108
+ if scheduler.prediction_type == "v_prediction":
109
+ self.k_diffusion_model = CompVisVDenoiser(model)
110
+ else:
111
+ self.k_diffusion_model = CompVisDenoiser(model)
112
+
113
+ def set_sampler(self, scheduler_type: str):
114
+ warnings.warn("The `set_sampler` method is deprecated, please use `set_scheduler` instead.")
115
+ return self.set_scheduler(scheduler_type)
116
+
117
+ def set_scheduler(self, scheduler_type: str):
118
+ library = importlib.import_module("k_diffusion")
119
+ sampling = getattr(library, "sampling")
120
+ self.sampler = getattr(sampling, scheduler_type)
121
+
122
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
123
+ r"""
124
+ Enable sliced attention computation.
125
+
126
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
127
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
128
+
129
+ Args:
130
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
131
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
132
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
133
+ `attention_head_dim` must be a multiple of `slice_size`.
134
+ """
135
+ if slice_size == "auto":
136
+ # half the attention head size is usually a good trade-off between
137
+ # speed and memory
138
+ slice_size = self.unet.config.attention_head_dim // 2
139
+ self.unet.set_attention_slice(slice_size)
140
+
141
+ def disable_attention_slicing(self):
142
+ r"""
143
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
144
+ back to computing attention in one step.
145
+ """
146
+ # set slice_size = `None` to disable `attention slicing`
147
+ self.enable_attention_slicing(None)
148
+
149
+ def enable_sequential_cpu_offload(self, gpu_id=0):
150
+ r"""
151
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
152
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
153
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
154
+ """
155
+ if is_accelerate_available():
156
+ from accelerate import cpu_offload
157
+ else:
158
+ raise ImportError("Please install accelerate via `pip install accelerate`")
159
+
160
+ device = torch.device(f"cuda:{gpu_id}")
161
+
162
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
163
+ if cpu_offloaded_model is not None:
164
+ cpu_offload(cpu_offloaded_model, device)
165
+
166
+ @property
167
+ def _execution_device(self):
168
+ r"""
169
+ Returns the device on which the pipeline's models will be executed. After calling
170
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
171
+ hooks.
172
+ """
173
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
174
+ return self.device
175
+ for module in self.unet.modules():
176
+ if (
177
+ hasattr(module, "_hf_hook")
178
+ and hasattr(module._hf_hook, "execution_device")
179
+ and module._hf_hook.execution_device is not None
180
+ ):
181
+ return torch.device(module._hf_hook.execution_device)
182
+ return self.device
183
+
184
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
185
+ r"""
186
+ Encodes the prompt into text encoder hidden states.
187
+
188
+ Args:
189
+ prompt (`str` or `list(int)`):
190
+ prompt to be encoded
191
+ device: (`torch.device`):
192
+ torch device
193
+ num_images_per_prompt (`int`):
194
+ number of images that should be generated per prompt
195
+ do_classifier_free_guidance (`bool`):
196
+ whether to use classifier free guidance or not
197
+ negative_prompt (`str` or `List[str]`):
198
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
199
+ if `guidance_scale` is less than `1`).
200
+ """
201
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
202
+
203
+ text_inputs = self.tokenizer(
204
+ prompt,
205
+ padding="max_length",
206
+ max_length=self.tokenizer.model_max_length,
207
+ truncation=True,
208
+ return_tensors="pt",
209
+ )
210
+ text_input_ids = text_inputs.input_ids
211
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="pt").input_ids
212
+
213
+ if not torch.equal(text_input_ids, untruncated_ids):
214
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
215
+ logger.warning(
216
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
217
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
218
+ )
219
+
220
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
221
+ attention_mask = text_inputs.attention_mask.to(device)
222
+ else:
223
+ attention_mask = None
224
+
225
+ text_embeddings = self.text_encoder(
226
+ text_input_ids.to(device),
227
+ attention_mask=attention_mask,
228
+ )
229
+ text_embeddings = text_embeddings[0]
230
+
231
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
232
+ bs_embed, seq_len, _ = text_embeddings.shape
233
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
234
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
235
+
236
+ # get unconditional embeddings for classifier free guidance
237
+ if do_classifier_free_guidance:
238
+ uncond_tokens: List[str]
239
+ if negative_prompt is None:
240
+ uncond_tokens = [""] * batch_size
241
+ elif type(prompt) is not type(negative_prompt):
242
+ raise TypeError(
243
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
244
+ f" {type(prompt)}."
245
+ )
246
+ elif isinstance(negative_prompt, str):
247
+ uncond_tokens = [negative_prompt]
248
+ elif batch_size != len(negative_prompt):
249
+ raise ValueError(
250
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
251
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
252
+ " the batch size of `prompt`."
253
+ )
254
+ else:
255
+ uncond_tokens = negative_prompt
256
+
257
+ max_length = text_input_ids.shape[-1]
258
+ uncond_input = self.tokenizer(
259
+ uncond_tokens,
260
+ padding="max_length",
261
+ max_length=max_length,
262
+ truncation=True,
263
+ return_tensors="pt",
264
+ )
265
+
266
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
267
+ attention_mask = uncond_input.attention_mask.to(device)
268
+ else:
269
+ attention_mask = None
270
+
271
+ uncond_embeddings = self.text_encoder(
272
+ uncond_input.input_ids.to(device),
273
+ attention_mask=attention_mask,
274
+ )
275
+ uncond_embeddings = uncond_embeddings[0]
276
+
277
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
278
+ seq_len = uncond_embeddings.shape[1]
279
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
280
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
281
+
282
+ # For classifier free guidance, we need to do two forward passes.
283
+ # Here we concatenate the unconditional and text embeddings into a single batch
284
+ # to avoid doing two forward passes
285
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
286
+
287
+ return text_embeddings
288
+
289
+ def run_safety_checker(self, image, device, dtype):
290
+ if self.safety_checker is not None:
291
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
292
+ image, has_nsfw_concept = self.safety_checker(
293
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
294
+ )
295
+ else:
296
+ has_nsfw_concept = None
297
+ return image, has_nsfw_concept
298
+
299
+ def decode_latents(self, latents):
300
+ latents = 1 / 0.18215 * latents
301
+ image = self.vae.decode(latents).sample
302
+ image = (image / 2 + 0.5).clamp(0, 1)
303
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
304
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
305
+ return image
306
+
307
+ def check_inputs(self, prompt, height, width, callback_steps):
308
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
309
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
310
+
311
+ if height % 8 != 0 or width % 8 != 0:
312
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
313
+
314
+ if (callback_steps is None) or (
315
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
316
+ ):
317
+ raise ValueError(
318
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
319
+ f" {type(callback_steps)}."
320
+ )
321
+
322
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
323
+ shape = (batch_size, num_channels_latents, height // 8, width // 8)
324
+ if latents is None:
325
+ if device.type == "mps":
326
+ # randn does not work reproducibly on mps
327
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
328
+ else:
329
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
330
+ else:
331
+ if latents.shape != shape:
332
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
333
+ latents = latents.to(device)
334
+
335
+ # scale the initial noise by the standard deviation required by the scheduler
336
+ return latents
337
+
338
+ @torch.no_grad()
339
+ def __call__(
340
+ self,
341
+ prompt: Union[str, List[str]],
342
+ height: int = 512,
343
+ width: int = 512,
344
+ num_inference_steps: int = 50,
345
+ guidance_scale: float = 7.5,
346
+ negative_prompt: Optional[Union[str, List[str]]] = None,
347
+ num_images_per_prompt: Optional[int] = 1,
348
+ eta: float = 0.0,
349
+ generator: Optional[torch.Generator] = None,
350
+ latents: Optional[torch.FloatTensor] = None,
351
+ output_type: Optional[str] = "pil",
352
+ return_dict: bool = True,
353
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
354
+ callback_steps: int = 1,
355
+ **kwargs,
356
+ ):
357
+ r"""
358
+ Function invoked when calling the pipeline for generation.
359
+
360
+ Args:
361
+ prompt (`str` or `List[str]`):
362
+ The prompt or prompts to guide the image generation.
363
+ height (`int`, *optional*, defaults to 512):
364
+ The height in pixels of the generated image.
365
+ width (`int`, *optional*, defaults to 512):
366
+ The width in pixels of the generated image.
367
+ num_inference_steps (`int`, *optional*, defaults to 50):
368
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
369
+ expense of slower inference.
370
+ guidance_scale (`float`, *optional*, defaults to 7.5):
371
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
372
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
373
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
374
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
375
+ usually at the expense of lower image quality.
376
+ negative_prompt (`str` or `List[str]`, *optional*):
377
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
378
+ if `guidance_scale` is less than `1`).
379
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
380
+ The number of images to generate per prompt.
381
+ eta (`float`, *optional*, defaults to 0.0):
382
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
383
+ [`schedulers.DDIMScheduler`], will be ignored for others.
384
+ generator (`torch.Generator`, *optional*):
385
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
386
+ deterministic.
387
+ latents (`torch.FloatTensor`, *optional*):
388
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
389
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
390
+ tensor will ge generated by sampling using the supplied random `generator`.
391
+ output_type (`str`, *optional*, defaults to `"pil"`):
392
+ The output format of the generate image. Choose between
393
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
394
+ return_dict (`bool`, *optional*, defaults to `True`):
395
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
396
+ plain tuple.
397
+ callback (`Callable`, *optional*):
398
+ A function that will be called every `callback_steps` steps during inference. The function will be
399
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
400
+ callback_steps (`int`, *optional*, defaults to 1):
401
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
402
+ called at every step.
403
+
404
+ Returns:
405
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
406
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
407
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
408
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
409
+ (nsfw) content, according to the `safety_checker`.
410
+ """
411
+
412
+ # 1. Check inputs. Raise error if not correct
413
+ self.check_inputs(prompt, height, width, callback_steps)
414
+
415
+ # 2. Define call parameters
416
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
417
+ device = self._execution_device
418
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
419
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
420
+ # corresponds to doing no classifier free guidance.
421
+ do_classifier_free_guidance = True
422
+ if guidance_scale <= 1.0:
423
+ raise ValueError("has to use guidance_scale")
424
+
425
+ # 3. Encode input prompt
426
+ text_embeddings = self._encode_prompt(
427
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
428
+ )
429
+
430
+ # 4. Prepare timesteps
431
+ self.scheduler.set_timesteps(num_inference_steps, device=text_embeddings.device)
432
+ sigmas = self.scheduler.sigmas
433
+ sigmas = sigmas.to(text_embeddings.dtype)
434
+
435
+ # 5. Prepare latent variables
436
+ num_channels_latents = self.unet.in_channels
437
+ latents = self.prepare_latents(
438
+ batch_size * num_images_per_prompt,
439
+ num_channels_latents,
440
+ height,
441
+ width,
442
+ text_embeddings.dtype,
443
+ device,
444
+ generator,
445
+ latents,
446
+ )
447
+ latents = latents * sigmas[0]
448
+ self.k_diffusion_model.sigmas = self.k_diffusion_model.sigmas.to(latents.device)
449
+ self.k_diffusion_model.log_sigmas = self.k_diffusion_model.log_sigmas.to(latents.device)
450
+
451
+ def model_fn(x, t):
452
+ latent_model_input = torch.cat([x] * 2)
453
+
454
+ noise_pred = self.k_diffusion_model(latent_model_input, t, cond=text_embeddings)
455
+
456
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
457
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
458
+ return noise_pred
459
+
460
+ latents = self.sampler(model_fn, latents, sigmas)
461
+
462
+ # 8. Post-processing
463
+ image = self.decode_latents(latents)
464
+
465
+ # 9. Run safety checker
466
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
467
+
468
+ # 10. Convert to PIL
469
+ if output_type == "pil":
470
+ image = self.numpy_to_pil(image)
471
+
472
+ if not return_dict:
473
+ return (image, has_nsfw_concept)
474
+
475
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.14.0/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
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import DiffusionPipeline
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
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 logging
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: 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 bfloat16
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.14.0/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
+ from transformers import (
6
+ CLIPFeatureExtractor,
7
+ CLIPTextModel,
8
+ CLIPTokenizer,
9
+ WhisperForConditionalGeneration,
10
+ WhisperProcessor,
11
+ )
12
+
13
+ from diffusers import (
14
+ AutoencoderKL,
15
+ DDIMScheduler,
16
+ DiffusionPipeline,
17
+ LMSDiscreteScheduler,
18
+ PNDMScheduler,
19
+ UNet2DConditionModel,
20
+ )
21
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
23
+ from diffusers.utils import logging
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: 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 bfloat16
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.14.0/stable_diffusion_comparison.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import torch
4
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
5
+
6
+ from diffusers import (
7
+ AutoencoderKL,
8
+ DDIMScheduler,
9
+ DiffusionPipeline,
10
+ LMSDiscreteScheduler,
11
+ PNDMScheduler,
12
+ StableDiffusionPipeline,
13
+ UNet2DConditionModel,
14
+ )
15
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
16
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
17
+
18
+
19
+ pipe1_model_id = "CompVis/stable-diffusion-v1-1"
20
+ pipe2_model_id = "CompVis/stable-diffusion-v1-2"
21
+ pipe3_model_id = "CompVis/stable-diffusion-v1-3"
22
+ pipe4_model_id = "CompVis/stable-diffusion-v1-4"
23
+
24
+
25
+ class StableDiffusionComparisonPipeline(DiffusionPipeline):
26
+ r"""
27
+ Pipeline for parallel comparison of Stable Diffusion v1-v4
28
+ This pipeline inherits from DiffusionPipeline and depends on the use of an Auth Token for
29
+ downloading pre-trained checkpoints from Hugging Face Hub.
30
+ If using Hugging Face Hub, pass the Model ID for Stable Diffusion v1.4 as the previous 3 checkpoints will be loaded
31
+ automatically.
32
+ Args:
33
+ vae ([`AutoencoderKL`]):
34
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
35
+ text_encoder ([`CLIPTextModel`]):
36
+ Frozen text-encoder. Stable Diffusion uses the text portion of
37
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
38
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
39
+ tokenizer (`CLIPTokenizer`):
40
+ Tokenizer of class
41
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
42
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
43
+ scheduler ([`SchedulerMixin`]):
44
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
45
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
46
+ safety_checker ([`StableDiffusionMegaSafetyChecker`]):
47
+ Classification module that estimates whether generated images could be considered offensive or harmful.
48
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
49
+ feature_extractor ([`CLIPFeatureExtractor`]):
50
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ vae: AutoencoderKL,
56
+ text_encoder: CLIPTextModel,
57
+ tokenizer: CLIPTokenizer,
58
+ unet: UNet2DConditionModel,
59
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
60
+ safety_checker: StableDiffusionSafetyChecker,
61
+ feature_extractor: CLIPFeatureExtractor,
62
+ requires_safety_checker: bool = True,
63
+ ):
64
+ super()._init_()
65
+
66
+ self.pipe1 = StableDiffusionPipeline.from_pretrained(pipe1_model_id)
67
+ self.pipe2 = StableDiffusionPipeline.from_pretrained(pipe2_model_id)
68
+ self.pipe3 = StableDiffusionPipeline.from_pretrained(pipe3_model_id)
69
+ self.pipe4 = StableDiffusionPipeline(
70
+ vae=vae,
71
+ text_encoder=text_encoder,
72
+ tokenizer=tokenizer,
73
+ unet=unet,
74
+ scheduler=scheduler,
75
+ safety_checker=safety_checker,
76
+ feature_extractor=feature_extractor,
77
+ requires_safety_checker=requires_safety_checker,
78
+ )
79
+
80
+ self.register_modules(pipeline1=self.pipe1, pipeline2=self.pipe2, pipeline3=self.pipe3, pipeline4=self.pipe4)
81
+
82
+ @property
83
+ def layers(self) -> Dict[str, Any]:
84
+ return {k: getattr(self, k) for k in self.config.keys() if not k.startswith("_")}
85
+
86
+ def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
87
+ r"""
88
+ Enable sliced attention computation.
89
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
90
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
91
+ Args:
92
+ slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
93
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
94
+ a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
95
+ `attention_head_dim` must be a multiple of `slice_size`.
96
+ """
97
+ if slice_size == "auto":
98
+ # half the attention head size is usually a good trade-off between
99
+ # speed and memory
100
+ slice_size = self.unet.config.attention_head_dim // 2
101
+ self.unet.set_attention_slice(slice_size)
102
+
103
+ def disable_attention_slicing(self):
104
+ r"""
105
+ Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
106
+ back to computing attention in one step.
107
+ """
108
+ # set slice_size = `None` to disable `attention slicing`
109
+ self.enable_attention_slicing(None)
110
+
111
+ @torch.no_grad()
112
+ def text2img_sd1_1(
113
+ self,
114
+ prompt: Union[str, List[str]],
115
+ height: int = 512,
116
+ width: int = 512,
117
+ num_inference_steps: int = 50,
118
+ guidance_scale: float = 7.5,
119
+ negative_prompt: Optional[Union[str, List[str]]] = None,
120
+ num_images_per_prompt: Optional[int] = 1,
121
+ eta: float = 0.0,
122
+ generator: Optional[torch.Generator] = None,
123
+ latents: Optional[torch.FloatTensor] = None,
124
+ output_type: Optional[str] = "pil",
125
+ return_dict: bool = True,
126
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
127
+ callback_steps: int = 1,
128
+ **kwargs,
129
+ ):
130
+ return self.pipe1(
131
+ prompt=prompt,
132
+ height=height,
133
+ width=width,
134
+ num_inference_steps=num_inference_steps,
135
+ guidance_scale=guidance_scale,
136
+ negative_prompt=negative_prompt,
137
+ num_images_per_prompt=num_images_per_prompt,
138
+ eta=eta,
139
+ generator=generator,
140
+ latents=latents,
141
+ output_type=output_type,
142
+ return_dict=return_dict,
143
+ callback=callback,
144
+ callback_steps=callback_steps,
145
+ **kwargs,
146
+ )
147
+
148
+ @torch.no_grad()
149
+ def text2img_sd1_2(
150
+ self,
151
+ prompt: Union[str, List[str]],
152
+ height: int = 512,
153
+ width: int = 512,
154
+ num_inference_steps: int = 50,
155
+ guidance_scale: float = 7.5,
156
+ negative_prompt: Optional[Union[str, List[str]]] = None,
157
+ num_images_per_prompt: Optional[int] = 1,
158
+ eta: float = 0.0,
159
+ generator: Optional[torch.Generator] = None,
160
+ latents: Optional[torch.FloatTensor] = None,
161
+ output_type: Optional[str] = "pil",
162
+ return_dict: bool = True,
163
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
164
+ callback_steps: int = 1,
165
+ **kwargs,
166
+ ):
167
+ return self.pipe2(
168
+ prompt=prompt,
169
+ height=height,
170
+ width=width,
171
+ num_inference_steps=num_inference_steps,
172
+ guidance_scale=guidance_scale,
173
+ negative_prompt=negative_prompt,
174
+ num_images_per_prompt=num_images_per_prompt,
175
+ eta=eta,
176
+ generator=generator,
177
+ latents=latents,
178
+ output_type=output_type,
179
+ return_dict=return_dict,
180
+ callback=callback,
181
+ callback_steps=callback_steps,
182
+ **kwargs,
183
+ )
184
+
185
+ @torch.no_grad()
186
+ def text2img_sd1_3(
187
+ self,
188
+ prompt: Union[str, List[str]],
189
+ height: int = 512,
190
+ width: int = 512,
191
+ num_inference_steps: int = 50,
192
+ guidance_scale: float = 7.5,
193
+ negative_prompt: Optional[Union[str, List[str]]] = None,
194
+ num_images_per_prompt: Optional[int] = 1,
195
+ eta: float = 0.0,
196
+ generator: Optional[torch.Generator] = None,
197
+ latents: Optional[torch.FloatTensor] = None,
198
+ output_type: Optional[str] = "pil",
199
+ return_dict: bool = True,
200
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
201
+ callback_steps: int = 1,
202
+ **kwargs,
203
+ ):
204
+ return self.pipe3(
205
+ prompt=prompt,
206
+ height=height,
207
+ width=width,
208
+ num_inference_steps=num_inference_steps,
209
+ guidance_scale=guidance_scale,
210
+ negative_prompt=negative_prompt,
211
+ num_images_per_prompt=num_images_per_prompt,
212
+ eta=eta,
213
+ generator=generator,
214
+ latents=latents,
215
+ output_type=output_type,
216
+ return_dict=return_dict,
217
+ callback=callback,
218
+ callback_steps=callback_steps,
219
+ **kwargs,
220
+ )
221
+
222
+ @torch.no_grad()
223
+ def text2img_sd1_4(
224
+ self,
225
+ prompt: Union[str, List[str]],
226
+ height: int = 512,
227
+ width: int = 512,
228
+ num_inference_steps: int = 50,
229
+ guidance_scale: float = 7.5,
230
+ negative_prompt: Optional[Union[str, List[str]]] = None,
231
+ num_images_per_prompt: Optional[int] = 1,
232
+ eta: float = 0.0,
233
+ generator: Optional[torch.Generator] = None,
234
+ latents: Optional[torch.FloatTensor] = None,
235
+ output_type: Optional[str] = "pil",
236
+ return_dict: bool = True,
237
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
238
+ callback_steps: int = 1,
239
+ **kwargs,
240
+ ):
241
+ return self.pipe4(
242
+ prompt=prompt,
243
+ height=height,
244
+ width=width,
245
+ num_inference_steps=num_inference_steps,
246
+ guidance_scale=guidance_scale,
247
+ negative_prompt=negative_prompt,
248
+ num_images_per_prompt=num_images_per_prompt,
249
+ eta=eta,
250
+ generator=generator,
251
+ latents=latents,
252
+ output_type=output_type,
253
+ return_dict=return_dict,
254
+ callback=callback,
255
+ callback_steps=callback_steps,
256
+ **kwargs,
257
+ )
258
+
259
+ @torch.no_grad()
260
+ def _call_(
261
+ self,
262
+ prompt: Union[str, List[str]],
263
+ height: int = 512,
264
+ width: int = 512,
265
+ num_inference_steps: int = 50,
266
+ guidance_scale: float = 7.5,
267
+ negative_prompt: Optional[Union[str, List[str]]] = None,
268
+ num_images_per_prompt: Optional[int] = 1,
269
+ eta: float = 0.0,
270
+ generator: Optional[torch.Generator] = None,
271
+ latents: Optional[torch.FloatTensor] = None,
272
+ output_type: Optional[str] = "pil",
273
+ return_dict: bool = True,
274
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
275
+ callback_steps: int = 1,
276
+ **kwargs,
277
+ ):
278
+ r"""
279
+ Function invoked when calling the pipeline for generation. This function will generate 4 results as part
280
+ of running all the 4 pipelines for SD1.1-1.4 together in a serial-processing, parallel-invocation fashion.
281
+ Args:
282
+ prompt (`str` or `List[str]`):
283
+ The prompt or prompts to guide the image generation.
284
+ height (`int`, optional, defaults to 512):
285
+ The height in pixels of the generated image.
286
+ width (`int`, optional, defaults to 512):
287
+ The width in pixels of the generated image.
288
+ num_inference_steps (`int`, optional, defaults to 50):
289
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
290
+ expense of slower inference.
291
+ guidance_scale (`float`, optional, defaults to 7.5):
292
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
293
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
294
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
295
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
296
+ usually at the expense of lower image quality.
297
+ eta (`float`, optional, defaults to 0.0):
298
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
299
+ [`schedulers.DDIMScheduler`], will be ignored for others.
300
+ generator (`torch.Generator`, optional):
301
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
302
+ deterministic.
303
+ latents (`torch.FloatTensor`, optional):
304
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
305
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
306
+ tensor will ge generated by sampling using the supplied random `generator`.
307
+ output_type (`str`, optional, defaults to `"pil"`):
308
+ The output format of the generate image. Choose between
309
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
310
+ return_dict (`bool`, optional, defaults to `True`):
311
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
312
+ plain tuple.
313
+ Returns:
314
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
315
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
316
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
317
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
318
+ (nsfw) content, according to the `safety_checker`.
319
+ """
320
+
321
+ device = "cuda" if torch.cuda.is_available() else "cpu"
322
+ self.to(device)
323
+
324
+ # Checks if the height and width are divisible by 8 or not
325
+ if height % 8 != 0 or width % 8 != 0:
326
+ raise ValueError(f"`height` and `width` must be divisible by 8 but are {height} and {width}.")
327
+
328
+ # Get first result from Stable Diffusion Checkpoint v1.1
329
+ res1 = self.text2img_sd1_1(
330
+ prompt=prompt,
331
+ height=height,
332
+ width=width,
333
+ num_inference_steps=num_inference_steps,
334
+ guidance_scale=guidance_scale,
335
+ negative_prompt=negative_prompt,
336
+ num_images_per_prompt=num_images_per_prompt,
337
+ eta=eta,
338
+ generator=generator,
339
+ latents=latents,
340
+ output_type=output_type,
341
+ return_dict=return_dict,
342
+ callback=callback,
343
+ callback_steps=callback_steps,
344
+ **kwargs,
345
+ )
346
+
347
+ # Get first result from Stable Diffusion Checkpoint v1.2
348
+ res2 = self.text2img_sd1_2(
349
+ prompt=prompt,
350
+ height=height,
351
+ width=width,
352
+ num_inference_steps=num_inference_steps,
353
+ guidance_scale=guidance_scale,
354
+ negative_prompt=negative_prompt,
355
+ num_images_per_prompt=num_images_per_prompt,
356
+ eta=eta,
357
+ generator=generator,
358
+ latents=latents,
359
+ output_type=output_type,
360
+ return_dict=return_dict,
361
+ callback=callback,
362
+ callback_steps=callback_steps,
363
+ **kwargs,
364
+ )
365
+
366
+ # Get first result from Stable Diffusion Checkpoint v1.3
367
+ res3 = self.text2img_sd1_3(
368
+ prompt=prompt,
369
+ height=height,
370
+ width=width,
371
+ num_inference_steps=num_inference_steps,
372
+ guidance_scale=guidance_scale,
373
+ negative_prompt=negative_prompt,
374
+ num_images_per_prompt=num_images_per_prompt,
375
+ eta=eta,
376
+ generator=generator,
377
+ latents=latents,
378
+ output_type=output_type,
379
+ return_dict=return_dict,
380
+ callback=callback,
381
+ callback_steps=callback_steps,
382
+ **kwargs,
383
+ )
384
+
385
+ # Get first result from Stable Diffusion Checkpoint v1.4
386
+ res4 = self.text2img_sd1_4(
387
+ prompt=prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=num_inference_steps,
391
+ guidance_scale=guidance_scale,
392
+ negative_prompt=negative_prompt,
393
+ num_images_per_prompt=num_images_per_prompt,
394
+ eta=eta,
395
+ generator=generator,
396
+ latents=latents,
397
+ output_type=output_type,
398
+ return_dict=return_dict,
399
+ callback=callback,
400
+ callback_steps=callback_steps,
401
+ **kwargs,
402
+ )
403
+
404
+ # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
405
+ return StableDiffusionPipelineOutput([res1[0], res2[0], res3[0], res4[0]])
v0.14.0/stable_diffusion_mega.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import PIL.Image
4
+ import torch
5
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
6
+
7
+ from diffusers import (
8
+ AutoencoderKL,
9
+ DDIMScheduler,
10
+ DiffusionPipeline,
11
+ LMSDiscreteScheduler,
12
+ PNDMScheduler,
13
+ StableDiffusionImg2ImgPipeline,
14
+ StableDiffusionInpaintPipelineLegacy,
15
+ StableDiffusionPipeline,
16
+ UNet2DConditionModel,
17
+ )
18
+ from diffusers.configuration_utils import FrozenDict
19
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
20
+ from diffusers.utils import deprecate, logging
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: 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: 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: 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.14.0/stable_unclip.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
6
+ from transformers.models.clip.modeling_clip import CLIPTextModelOutput
7
+
8
+ from diffusers.models import PriorTransformer
9
+ from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
10
+ from diffusers.schedulers import UnCLIPScheduler
11
+ from diffusers.utils import logging, randn_tensor
12
+
13
+
14
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
15
+
16
+
17
+ def _encode_image(self, image, device, num_images_per_prompt, do_classifier_free_guidance):
18
+ image = image.to(device=device)
19
+ image_embeddings = image # take image as image_embeddings
20
+ image_embeddings = image_embeddings.unsqueeze(1)
21
+
22
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
23
+ bs_embed, seq_len, _ = image_embeddings.shape
24
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
25
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
26
+
27
+ if do_classifier_free_guidance:
28
+ uncond_embeddings = torch.zeros_like(image_embeddings)
29
+
30
+ # For classifier free guidance, we need to do two forward passes.
31
+ # Here we concatenate the unconditional and text embeddings into a single batch
32
+ # to avoid doing two forward passes
33
+ image_embeddings = torch.cat([uncond_embeddings, image_embeddings])
34
+
35
+ return image_embeddings
36
+
37
+
38
+ class StableUnCLIPPipeline(DiffusionPipeline):
39
+ def __init__(
40
+ self,
41
+ prior: PriorTransformer,
42
+ tokenizer: CLIPTokenizer,
43
+ text_encoder: CLIPTextModelWithProjection,
44
+ prior_scheduler: UnCLIPScheduler,
45
+ decoder_pipe_kwargs: Optional[dict] = None,
46
+ ):
47
+ super().__init__()
48
+
49
+ decoder_pipe_kwargs = dict(image_encoder=None) if decoder_pipe_kwargs is None else decoder_pipe_kwargs
50
+
51
+ decoder_pipe_kwargs["torch_dtype"] = decoder_pipe_kwargs.get("torch_dtype", None) or prior.dtype
52
+
53
+ self.decoder_pipe = StableDiffusionImageVariationPipeline.from_pretrained(
54
+ "lambdalabs/sd-image-variations-diffusers", **decoder_pipe_kwargs
55
+ )
56
+
57
+ # replace `_encode_image` method
58
+ self.decoder_pipe._encode_image = types.MethodType(_encode_image, self.decoder_pipe)
59
+
60
+ self.register_modules(
61
+ prior=prior,
62
+ tokenizer=tokenizer,
63
+ text_encoder=text_encoder,
64
+ prior_scheduler=prior_scheduler,
65
+ )
66
+
67
+ def _encode_prompt(
68
+ self,
69
+ prompt,
70
+ device,
71
+ num_images_per_prompt,
72
+ do_classifier_free_guidance,
73
+ text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
74
+ text_attention_mask: Optional[torch.Tensor] = None,
75
+ ):
76
+ if text_model_output is None:
77
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
78
+ # get prompt text embeddings
79
+ text_inputs = self.tokenizer(
80
+ prompt,
81
+ padding="max_length",
82
+ max_length=self.tokenizer.model_max_length,
83
+ return_tensors="pt",
84
+ )
85
+ text_input_ids = text_inputs.input_ids
86
+ text_mask = text_inputs.attention_mask.bool().to(device)
87
+
88
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
89
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
90
+ logger.warning(
91
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
92
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
93
+ )
94
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
95
+
96
+ text_encoder_output = self.text_encoder(text_input_ids.to(device))
97
+
98
+ text_embeddings = text_encoder_output.text_embeds
99
+ text_encoder_hidden_states = text_encoder_output.last_hidden_state
100
+
101
+ else:
102
+ batch_size = text_model_output[0].shape[0]
103
+ text_embeddings, text_encoder_hidden_states = text_model_output[0], text_model_output[1]
104
+ text_mask = text_attention_mask
105
+
106
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
107
+ text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
108
+ text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
109
+
110
+ if do_classifier_free_guidance:
111
+ uncond_tokens = [""] * batch_size
112
+
113
+ uncond_input = self.tokenizer(
114
+ uncond_tokens,
115
+ padding="max_length",
116
+ max_length=self.tokenizer.model_max_length,
117
+ truncation=True,
118
+ return_tensors="pt",
119
+ )
120
+ uncond_text_mask = uncond_input.attention_mask.bool().to(device)
121
+ uncond_embeddings_text_encoder_output = self.text_encoder(uncond_input.input_ids.to(device))
122
+
123
+ uncond_embeddings = uncond_embeddings_text_encoder_output.text_embeds
124
+ uncond_text_encoder_hidden_states = uncond_embeddings_text_encoder_output.last_hidden_state
125
+
126
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
127
+
128
+ seq_len = uncond_embeddings.shape[1]
129
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt)
130
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len)
131
+
132
+ seq_len = uncond_text_encoder_hidden_states.shape[1]
133
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
134
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
135
+ batch_size * num_images_per_prompt, seq_len, -1
136
+ )
137
+ uncond_text_mask = uncond_text_mask.repeat_interleave(num_images_per_prompt, dim=0)
138
+
139
+ # done duplicates
140
+
141
+ # For classifier free guidance, we need to do two forward passes.
142
+ # Here we concatenate the unconditional and text embeddings into a single batch
143
+ # to avoid doing two forward passes
144
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
145
+ text_encoder_hidden_states = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])
146
+
147
+ text_mask = torch.cat([uncond_text_mask, text_mask])
148
+
149
+ return text_embeddings, text_encoder_hidden_states, text_mask
150
+
151
+ @property
152
+ def _execution_device(self):
153
+ r"""
154
+ Returns the device on which the pipeline's models will be executed. After calling
155
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
156
+ hooks.
157
+ """
158
+ if self.device != torch.device("meta") or not hasattr(self.prior, "_hf_hook"):
159
+ return self.device
160
+ for module in self.prior.modules():
161
+ if (
162
+ hasattr(module, "_hf_hook")
163
+ and hasattr(module._hf_hook, "execution_device")
164
+ and module._hf_hook.execution_device is not None
165
+ ):
166
+ return torch.device(module._hf_hook.execution_device)
167
+ return self.device
168
+
169
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
170
+ if latents is None:
171
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
172
+ else:
173
+ if latents.shape != shape:
174
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
175
+ latents = latents.to(device)
176
+
177
+ latents = latents * scheduler.init_noise_sigma
178
+ return latents
179
+
180
+ def to(self, torch_device: Optional[Union[str, torch.device]] = None):
181
+ self.decoder_pipe.to(torch_device)
182
+ super().to(torch_device)
183
+
184
+ @torch.no_grad()
185
+ def __call__(
186
+ self,
187
+ prompt: Optional[Union[str, List[str]]] = None,
188
+ height: Optional[int] = None,
189
+ width: Optional[int] = None,
190
+ num_images_per_prompt: int = 1,
191
+ prior_num_inference_steps: int = 25,
192
+ generator: Optional[torch.Generator] = None,
193
+ prior_latents: Optional[torch.FloatTensor] = None,
194
+ text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
195
+ text_attention_mask: Optional[torch.Tensor] = None,
196
+ prior_guidance_scale: float = 4.0,
197
+ decoder_guidance_scale: float = 8.0,
198
+ decoder_num_inference_steps: int = 50,
199
+ decoder_num_images_per_prompt: Optional[int] = 1,
200
+ decoder_eta: float = 0.0,
201
+ output_type: Optional[str] = "pil",
202
+ return_dict: bool = True,
203
+ ):
204
+ if prompt is not None:
205
+ if isinstance(prompt, str):
206
+ batch_size = 1
207
+ elif isinstance(prompt, list):
208
+ batch_size = len(prompt)
209
+ else:
210
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
211
+ else:
212
+ batch_size = text_model_output[0].shape[0]
213
+
214
+ device = self._execution_device
215
+
216
+ batch_size = batch_size * num_images_per_prompt
217
+
218
+ do_classifier_free_guidance = prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0
219
+
220
+ text_embeddings, text_encoder_hidden_states, text_mask = self._encode_prompt(
221
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, text_model_output, text_attention_mask
222
+ )
223
+
224
+ # prior
225
+
226
+ self.prior_scheduler.set_timesteps(prior_num_inference_steps, device=device)
227
+ prior_timesteps_tensor = self.prior_scheduler.timesteps
228
+
229
+ embedding_dim = self.prior.config.embedding_dim
230
+
231
+ prior_latents = self.prepare_latents(
232
+ (batch_size, embedding_dim),
233
+ text_embeddings.dtype,
234
+ device,
235
+ generator,
236
+ prior_latents,
237
+ self.prior_scheduler,
238
+ )
239
+
240
+ for i, t in enumerate(self.progress_bar(prior_timesteps_tensor)):
241
+ # expand the latents if we are doing classifier free guidance
242
+ latent_model_input = torch.cat([prior_latents] * 2) if do_classifier_free_guidance else prior_latents
243
+
244
+ predicted_image_embedding = self.prior(
245
+ latent_model_input,
246
+ timestep=t,
247
+ proj_embedding=text_embeddings,
248
+ encoder_hidden_states=text_encoder_hidden_states,
249
+ attention_mask=text_mask,
250
+ ).predicted_image_embedding
251
+
252
+ if do_classifier_free_guidance:
253
+ predicted_image_embedding_uncond, predicted_image_embedding_text = predicted_image_embedding.chunk(2)
254
+ predicted_image_embedding = predicted_image_embedding_uncond + prior_guidance_scale * (
255
+ predicted_image_embedding_text - predicted_image_embedding_uncond
256
+ )
257
+
258
+ if i + 1 == prior_timesteps_tensor.shape[0]:
259
+ prev_timestep = None
260
+ else:
261
+ prev_timestep = prior_timesteps_tensor[i + 1]
262
+
263
+ prior_latents = self.prior_scheduler.step(
264
+ predicted_image_embedding,
265
+ timestep=t,
266
+ sample=prior_latents,
267
+ generator=generator,
268
+ prev_timestep=prev_timestep,
269
+ ).prev_sample
270
+
271
+ prior_latents = self.prior.post_process_latents(prior_latents)
272
+
273
+ image_embeddings = prior_latents
274
+
275
+ output = self.decoder_pipe(
276
+ image=image_embeddings,
277
+ height=height,
278
+ width=width,
279
+ num_inference_steps=decoder_num_inference_steps,
280
+ guidance_scale=decoder_guidance_scale,
281
+ generator=generator,
282
+ output_type=output_type,
283
+ return_dict=return_dict,
284
+ num_images_per_prompt=decoder_num_images_per_prompt,
285
+ eta=decoder_eta,
286
+ )
287
+ return output
v0.14.0/text_inpainting.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Union
2
+
3
+ import PIL
4
+ import torch
5
+ from transformers import (
6
+ CLIPFeatureExtractor,
7
+ CLIPSegForImageSegmentation,
8
+ CLIPSegProcessor,
9
+ CLIPTextModel,
10
+ CLIPTokenizer,
11
+ )
12
+
13
+ from diffusers import DiffusionPipeline
14
+ from diffusers.configuration_utils import FrozenDict
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
17
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
18
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
19
+ from diffusers.utils import deprecate, is_accelerate_available, logging
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: 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.14.0/tiled_upscaling.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Peter Willemsen <peter@codebuffet.co>. 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 math
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL
20
+ import torch
21
+ from PIL import Image
22
+ from transformers import CLIPTextModel, CLIPTokenizer
23
+
24
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
25
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
26
+ from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler
27
+
28
+
29
+ def make_transparency_mask(size, overlap_pixels, remove_borders=[]):
30
+ size_x = size[0] - overlap_pixels * 2
31
+ size_y = size[1] - overlap_pixels * 2
32
+ for letter in ["l", "r"]:
33
+ if letter in remove_borders:
34
+ size_x += overlap_pixels
35
+ for letter in ["t", "b"]:
36
+ if letter in remove_borders:
37
+ size_y += overlap_pixels
38
+ mask = np.ones((size_y, size_x), dtype=np.uint8) * 255
39
+ mask = np.pad(mask, mode="linear_ramp", pad_width=overlap_pixels, end_values=0)
40
+
41
+ if "l" in remove_borders:
42
+ mask = mask[:, overlap_pixels : mask.shape[1]]
43
+ if "r" in remove_borders:
44
+ mask = mask[:, 0 : mask.shape[1] - overlap_pixels]
45
+ if "t" in remove_borders:
46
+ mask = mask[overlap_pixels : mask.shape[0], :]
47
+ if "b" in remove_borders:
48
+ mask = mask[0 : mask.shape[0] - overlap_pixels, :]
49
+ return mask
50
+
51
+
52
+ def clamp(n, smallest, largest):
53
+ return max(smallest, min(n, largest))
54
+
55
+
56
+ def clamp_rect(rect: [int], min: [int], max: [int]):
57
+ return (
58
+ clamp(rect[0], min[0], max[0]),
59
+ clamp(rect[1], min[1], max[1]),
60
+ clamp(rect[2], min[0], max[0]),
61
+ clamp(rect[3], min[1], max[1]),
62
+ )
63
+
64
+
65
+ def add_overlap_rect(rect: [int], overlap: int, image_size: [int]):
66
+ rect = list(rect)
67
+ rect[0] -= overlap
68
+ rect[1] -= overlap
69
+ rect[2] += overlap
70
+ rect[3] += overlap
71
+ rect = clamp_rect(rect, [0, 0], [image_size[0], image_size[1]])
72
+ return rect
73
+
74
+
75
+ def squeeze_tile(tile, original_image, original_slice, slice_x):
76
+ result = Image.new("RGB", (tile.size[0] + original_slice, tile.size[1]))
77
+ result.paste(
78
+ original_image.resize((tile.size[0], tile.size[1]), Image.BICUBIC).crop(
79
+ (slice_x, 0, slice_x + original_slice, tile.size[1])
80
+ ),
81
+ (0, 0),
82
+ )
83
+ result.paste(tile, (original_slice, 0))
84
+ return result
85
+
86
+
87
+ def unsqueeze_tile(tile, original_image_slice):
88
+ crop_rect = (original_image_slice * 4, 0, tile.size[0], tile.size[1])
89
+ tile = tile.crop(crop_rect)
90
+ return tile
91
+
92
+
93
+ def next_divisible(n, d):
94
+ divisor = n % d
95
+ return n - divisor
96
+
97
+
98
+ class StableDiffusionTiledUpscalePipeline(StableDiffusionUpscalePipeline):
99
+ r"""
100
+ Pipeline for tile-based text-guided image super-resolution using Stable Diffusion 2, trading memory for compute
101
+ to create gigantic images.
102
+
103
+ This model inherits from [`StableDiffusionUpscalePipeline`]. Check the superclass documentation for the generic methods the
104
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
105
+
106
+ Args:
107
+ vae ([`AutoencoderKL`]):
108
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
109
+ text_encoder ([`CLIPTextModel`]):
110
+ Frozen text-encoder. Stable Diffusion uses the text portion of
111
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
112
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
113
+ tokenizer (`CLIPTokenizer`):
114
+ Tokenizer of class
115
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
116
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
117
+ low_res_scheduler ([`SchedulerMixin`]):
118
+ A scheduler used to add initial noise to the low res conditioning image. It must be an instance of
119
+ [`DDPMScheduler`].
120
+ scheduler ([`SchedulerMixin`]):
121
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
122
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ vae: AutoencoderKL,
128
+ text_encoder: CLIPTextModel,
129
+ tokenizer: CLIPTokenizer,
130
+ unet: UNet2DConditionModel,
131
+ low_res_scheduler: DDPMScheduler,
132
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
133
+ max_noise_level: int = 350,
134
+ ):
135
+ super().__init__(
136
+ vae=vae,
137
+ text_encoder=text_encoder,
138
+ tokenizer=tokenizer,
139
+ unet=unet,
140
+ low_res_scheduler=low_res_scheduler,
141
+ scheduler=scheduler,
142
+ max_noise_level=max_noise_level,
143
+ )
144
+
145
+ def _process_tile(self, original_image_slice, x, y, tile_size, tile_border, image, final_image, **kwargs):
146
+ torch.manual_seed(0)
147
+ crop_rect = (
148
+ min(image.size[0] - (tile_size + original_image_slice), x * tile_size),
149
+ min(image.size[1] - (tile_size + original_image_slice), y * tile_size),
150
+ min(image.size[0], (x + 1) * tile_size),
151
+ min(image.size[1], (y + 1) * tile_size),
152
+ )
153
+ crop_rect_with_overlap = add_overlap_rect(crop_rect, tile_border, image.size)
154
+ tile = image.crop(crop_rect_with_overlap)
155
+ translated_slice_x = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
156
+ translated_slice_x = translated_slice_x - (original_image_slice / 2)
157
+ translated_slice_x = max(0, translated_slice_x)
158
+ to_input = squeeze_tile(tile, image, original_image_slice, translated_slice_x)
159
+ orig_input_size = to_input.size
160
+ to_input = to_input.resize((tile_size, tile_size), Image.BICUBIC)
161
+ upscaled_tile = super(StableDiffusionTiledUpscalePipeline, self).__call__(image=to_input, **kwargs).images[0]
162
+ upscaled_tile = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4), Image.BICUBIC)
163
+ upscaled_tile = unsqueeze_tile(upscaled_tile, original_image_slice)
164
+ upscaled_tile = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4), Image.BICUBIC)
165
+ remove_borders = []
166
+ if x == 0:
167
+ remove_borders.append("l")
168
+ elif crop_rect[2] == image.size[0]:
169
+ remove_borders.append("r")
170
+ if y == 0:
171
+ remove_borders.append("t")
172
+ elif crop_rect[3] == image.size[1]:
173
+ remove_borders.append("b")
174
+ transparency_mask = Image.fromarray(
175
+ make_transparency_mask(
176
+ (upscaled_tile.size[0], upscaled_tile.size[1]), tile_border * 4, remove_borders=remove_borders
177
+ ),
178
+ mode="L",
179
+ )
180
+ final_image.paste(
181
+ upscaled_tile, (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4), transparency_mask
182
+ )
183
+
184
+ @torch.no_grad()
185
+ def __call__(
186
+ self,
187
+ prompt: Union[str, List[str]],
188
+ image: Union[PIL.Image.Image, List[PIL.Image.Image]],
189
+ num_inference_steps: int = 75,
190
+ guidance_scale: float = 9.0,
191
+ noise_level: int = 50,
192
+ negative_prompt: Optional[Union[str, List[str]]] = None,
193
+ num_images_per_prompt: Optional[int] = 1,
194
+ eta: float = 0.0,
195
+ generator: Optional[torch.Generator] = None,
196
+ latents: Optional[torch.FloatTensor] = None,
197
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
198
+ callback_steps: int = 1,
199
+ tile_size: int = 128,
200
+ tile_border: int = 32,
201
+ original_image_slice: int = 32,
202
+ ):
203
+ r"""
204
+ Function invoked when calling the pipeline for generation.
205
+
206
+ Args:
207
+ prompt (`str` or `List[str]`):
208
+ The prompt or prompts to guide the image generation.
209
+ image (`PIL.Image.Image` or List[`PIL.Image.Image`] or `torch.FloatTensor`):
210
+ `Image`, or tensor representing an image batch which will be upscaled. *
211
+ num_inference_steps (`int`, *optional*, defaults to 50):
212
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
213
+ expense of slower inference.
214
+ guidance_scale (`float`, *optional*, defaults to 7.5):
215
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
216
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
217
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
218
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
219
+ usually at the expense of lower image quality.
220
+ negative_prompt (`str` or `List[str]`, *optional*):
221
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
222
+ if `guidance_scale` is less than `1`).
223
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
224
+ The number of images to generate per prompt.
225
+ eta (`float`, *optional*, defaults to 0.0):
226
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
227
+ [`schedulers.DDIMScheduler`], will be ignored for others.
228
+ generator (`torch.Generator`, *optional*):
229
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
230
+ deterministic.
231
+ latents (`torch.FloatTensor`, *optional*):
232
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
233
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
234
+ tensor will ge generated by sampling using the supplied random `generator`.
235
+ tile_size (`int`, *optional*):
236
+ The size of the tiles. Too big can result in an OOM-error.
237
+ tile_border (`int`, *optional*):
238
+ The number of pixels around a tile to consider (bigger means less seams, too big can lead to an OOM-error).
239
+ original_image_slice (`int`, *optional*):
240
+ The amount of pixels of the original image to calculate with the current tile (bigger means more depth
241
+ is preserved, less blur occurs in the final image, too big can lead to an OOM-error or loss in detail).
242
+ callback (`Callable`, *optional*):
243
+ A function that take a callback function with a single argument, a dict,
244
+ that contains the (partially) processed image under "image",
245
+ as well as the progress (0 to 1, where 1 is completed) under "progress".
246
+
247
+ Returns: A PIL.Image that is 4 times larger than the original input image.
248
+
249
+ """
250
+
251
+ final_image = Image.new("RGB", (image.size[0] * 4, image.size[1] * 4))
252
+ tcx = math.ceil(image.size[0] / tile_size)
253
+ tcy = math.ceil(image.size[1] / tile_size)
254
+ total_tile_count = tcx * tcy
255
+ current_count = 0
256
+ for y in range(tcy):
257
+ for x in range(tcx):
258
+ self._process_tile(
259
+ original_image_slice,
260
+ x,
261
+ y,
262
+ tile_size,
263
+ tile_border,
264
+ image,
265
+ final_image,
266
+ prompt=prompt,
267
+ num_inference_steps=num_inference_steps,
268
+ guidance_scale=guidance_scale,
269
+ noise_level=noise_level,
270
+ negative_prompt=negative_prompt,
271
+ num_images_per_prompt=num_images_per_prompt,
272
+ eta=eta,
273
+ generator=generator,
274
+ latents=latents,
275
+ )
276
+ current_count += 1
277
+ if callback is not None:
278
+ callback({"progress": current_count / total_tile_count, "image": final_image})
279
+ return final_image
280
+
281
+
282
+ def main():
283
+ # Run a demo
284
+ model_id = "stabilityai/stable-diffusion-x4-upscaler"
285
+ pipe = StableDiffusionTiledUpscalePipeline.from_pretrained(model_id, revision="fp16", torch_dtype=torch.float16)
286
+ pipe = pipe.to("cuda")
287
+ image = Image.open("../../docs/source/imgs/diffusers_library.jpg")
288
+
289
+ def callback(obj):
290
+ print(f"progress: {obj['progress']:.4f}")
291
+ obj["image"].save("diffusers_library_progress.jpg")
292
+
293
+ final_image = pipe(image=image, prompt="Black font, white background, vector", noise_level=40, callback=callback)
294
+ final_image.save("diffusers_library.jpg")
295
+
296
+
297
+ if __name__ == "__main__":
298
+ main()
v0.14.0/unclip_text_interpolation.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch.nn import functional as F
6
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
7
+ from transformers.models.clip.modeling_clip import CLIPTextModelOutput
8
+
9
+ from diffusers import (
10
+ DiffusionPipeline,
11
+ ImagePipelineOutput,
12
+ PriorTransformer,
13
+ UnCLIPScheduler,
14
+ UNet2DConditionModel,
15
+ UNet2DModel,
16
+ )
17
+ from diffusers.pipelines.unclip import UnCLIPTextProjModel
18
+ from diffusers.utils import is_accelerate_available, logging, randn_tensor
19
+
20
+
21
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
22
+
23
+
24
+ def slerp(val, low, high):
25
+ """
26
+ Find the interpolation point between the 'low' and 'high' values for the given 'val'. See https://en.wikipedia.org/wiki/Slerp for more details on the topic.
27
+ """
28
+ low_norm = low / torch.norm(low)
29
+ high_norm = high / torch.norm(high)
30
+ omega = torch.acos((low_norm * high_norm))
31
+ so = torch.sin(omega)
32
+ res = (torch.sin((1.0 - val) * omega) / so) * low + (torch.sin(val * omega) / so) * high
33
+ return res
34
+
35
+
36
+ class UnCLIPTextInterpolationPipeline(DiffusionPipeline):
37
+
38
+ """
39
+ Pipeline for prompt-to-prompt interpolation on CLIP text embeddings and using the UnCLIP / Dall-E to decode them to images.
40
+
41
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
42
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
43
+
44
+ Args:
45
+ text_encoder ([`CLIPTextModelWithProjection`]):
46
+ Frozen text-encoder.
47
+ tokenizer (`CLIPTokenizer`):
48
+ Tokenizer of class
49
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
50
+ prior ([`PriorTransformer`]):
51
+ The canonincal unCLIP prior to approximate the image embedding from the text embedding.
52
+ text_proj ([`UnCLIPTextProjModel`]):
53
+ Utility class to prepare and combine the embeddings before they are passed to the decoder.
54
+ decoder ([`UNet2DConditionModel`]):
55
+ The decoder to invert the image embedding into an image.
56
+ super_res_first ([`UNet2DModel`]):
57
+ Super resolution unet. Used in all but the last step of the super resolution diffusion process.
58
+ super_res_last ([`UNet2DModel`]):
59
+ Super resolution unet. Used in the last step of the super resolution diffusion process.
60
+ prior_scheduler ([`UnCLIPScheduler`]):
61
+ Scheduler used in the prior denoising process. Just a modified DDPMScheduler.
62
+ decoder_scheduler ([`UnCLIPScheduler`]):
63
+ Scheduler used in the decoder denoising process. Just a modified DDPMScheduler.
64
+ super_res_scheduler ([`UnCLIPScheduler`]):
65
+ Scheduler used in the super resolution denoising process. Just a modified DDPMScheduler.
66
+
67
+ """
68
+
69
+ prior: PriorTransformer
70
+ decoder: UNet2DConditionModel
71
+ text_proj: UnCLIPTextProjModel
72
+ text_encoder: CLIPTextModelWithProjection
73
+ tokenizer: CLIPTokenizer
74
+ super_res_first: UNet2DModel
75
+ super_res_last: UNet2DModel
76
+
77
+ prior_scheduler: UnCLIPScheduler
78
+ decoder_scheduler: UnCLIPScheduler
79
+ super_res_scheduler: UnCLIPScheduler
80
+
81
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.__init__
82
+ def __init__(
83
+ self,
84
+ prior: PriorTransformer,
85
+ decoder: UNet2DConditionModel,
86
+ text_encoder: CLIPTextModelWithProjection,
87
+ tokenizer: CLIPTokenizer,
88
+ text_proj: UnCLIPTextProjModel,
89
+ super_res_first: UNet2DModel,
90
+ super_res_last: UNet2DModel,
91
+ prior_scheduler: UnCLIPScheduler,
92
+ decoder_scheduler: UnCLIPScheduler,
93
+ super_res_scheduler: UnCLIPScheduler,
94
+ ):
95
+ super().__init__()
96
+
97
+ self.register_modules(
98
+ prior=prior,
99
+ decoder=decoder,
100
+ text_encoder=text_encoder,
101
+ tokenizer=tokenizer,
102
+ text_proj=text_proj,
103
+ super_res_first=super_res_first,
104
+ super_res_last=super_res_last,
105
+ prior_scheduler=prior_scheduler,
106
+ decoder_scheduler=decoder_scheduler,
107
+ super_res_scheduler=super_res_scheduler,
108
+ )
109
+
110
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.prepare_latents
111
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
112
+ if latents is None:
113
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
114
+ else:
115
+ if latents.shape != shape:
116
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
117
+ latents = latents.to(device)
118
+
119
+ latents = latents * scheduler.init_noise_sigma
120
+ return latents
121
+
122
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline._encode_prompt
123
+ def _encode_prompt(
124
+ self,
125
+ prompt,
126
+ device,
127
+ num_images_per_prompt,
128
+ do_classifier_free_guidance,
129
+ text_model_output: Optional[Union[CLIPTextModelOutput, Tuple]] = None,
130
+ text_attention_mask: Optional[torch.Tensor] = None,
131
+ ):
132
+ if text_model_output is None:
133
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
134
+ # get prompt text embeddings
135
+ text_inputs = self.tokenizer(
136
+ prompt,
137
+ padding="max_length",
138
+ max_length=self.tokenizer.model_max_length,
139
+ truncation=True,
140
+ return_tensors="pt",
141
+ )
142
+ text_input_ids = text_inputs.input_ids
143
+ text_mask = text_inputs.attention_mask.bool().to(device)
144
+
145
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
146
+
147
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
148
+ text_input_ids, untruncated_ids
149
+ ):
150
+ removed_text = self.tokenizer.batch_decode(
151
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
152
+ )
153
+ logger.warning(
154
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
155
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
156
+ )
157
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
158
+
159
+ text_encoder_output = self.text_encoder(text_input_ids.to(device))
160
+
161
+ prompt_embeds = text_encoder_output.text_embeds
162
+ text_encoder_hidden_states = text_encoder_output.last_hidden_state
163
+
164
+ else:
165
+ batch_size = text_model_output[0].shape[0]
166
+ prompt_embeds, text_encoder_hidden_states = text_model_output[0], text_model_output[1]
167
+ text_mask = text_attention_mask
168
+
169
+ prompt_embeds = prompt_embeds.repeat_interleave(num_images_per_prompt, dim=0)
170
+ text_encoder_hidden_states = text_encoder_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
171
+ text_mask = text_mask.repeat_interleave(num_images_per_prompt, dim=0)
172
+
173
+ if do_classifier_free_guidance:
174
+ uncond_tokens = [""] * batch_size
175
+
176
+ uncond_input = self.tokenizer(
177
+ uncond_tokens,
178
+ padding="max_length",
179
+ max_length=self.tokenizer.model_max_length,
180
+ truncation=True,
181
+ return_tensors="pt",
182
+ )
183
+ uncond_text_mask = uncond_input.attention_mask.bool().to(device)
184
+ negative_prompt_embeds_text_encoder_output = self.text_encoder(uncond_input.input_ids.to(device))
185
+
186
+ negative_prompt_embeds = negative_prompt_embeds_text_encoder_output.text_embeds
187
+ uncond_text_encoder_hidden_states = negative_prompt_embeds_text_encoder_output.last_hidden_state
188
+
189
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
190
+
191
+ seq_len = negative_prompt_embeds.shape[1]
192
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt)
193
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len)
194
+
195
+ seq_len = uncond_text_encoder_hidden_states.shape[1]
196
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.repeat(1, num_images_per_prompt, 1)
197
+ uncond_text_encoder_hidden_states = uncond_text_encoder_hidden_states.view(
198
+ batch_size * num_images_per_prompt, seq_len, -1
199
+ )
200
+ uncond_text_mask = uncond_text_mask.repeat_interleave(num_images_per_prompt, dim=0)
201
+
202
+ # done duplicates
203
+
204
+ # For classifier free guidance, we need to do two forward passes.
205
+ # Here we concatenate the unconditional and text embeddings into a single batch
206
+ # to avoid doing two forward passes
207
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
208
+ text_encoder_hidden_states = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states])
209
+
210
+ text_mask = torch.cat([uncond_text_mask, text_mask])
211
+
212
+ return prompt_embeds, text_encoder_hidden_states, text_mask
213
+
214
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline.enable_sequential_cpu_offload
215
+ def enable_sequential_cpu_offload(self, gpu_id=0):
216
+ r"""
217
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
218
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
219
+ when their specific submodule has its `forward` method called.
220
+ """
221
+ if is_accelerate_available():
222
+ from accelerate import cpu_offload
223
+ else:
224
+ raise ImportError("Please install accelerate via `pip install accelerate`")
225
+
226
+ device = torch.device(f"cuda:{gpu_id}")
227
+
228
+ # TODO: self.prior.post_process_latents is not covered by the offload hooks, so it fails if added to the list
229
+ models = [
230
+ self.decoder,
231
+ self.text_proj,
232
+ self.text_encoder,
233
+ self.super_res_first,
234
+ self.super_res_last,
235
+ ]
236
+ for cpu_offloaded_model in models:
237
+ if cpu_offloaded_model is not None:
238
+ cpu_offload(cpu_offloaded_model, device)
239
+
240
+ @property
241
+ # Copied from diffusers.pipelines.unclip.pipeline_unclip.UnCLIPPipeline._execution_device
242
+ def _execution_device(self):
243
+ r"""
244
+ Returns the device on which the pipeline's models will be executed. After calling
245
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
246
+ hooks.
247
+ """
248
+ if self.device != torch.device("meta") or not hasattr(self.decoder, "_hf_hook"):
249
+ return self.device
250
+ for module in self.decoder.modules():
251
+ if (
252
+ hasattr(module, "_hf_hook")
253
+ and hasattr(module._hf_hook, "execution_device")
254
+ and module._hf_hook.execution_device is not None
255
+ ):
256
+ return torch.device(module._hf_hook.execution_device)
257
+ return self.device
258
+
259
+ @torch.no_grad()
260
+ def __call__(
261
+ self,
262
+ start_prompt: str,
263
+ end_prompt: str,
264
+ steps: int = 5,
265
+ prior_num_inference_steps: int = 25,
266
+ decoder_num_inference_steps: int = 25,
267
+ super_res_num_inference_steps: int = 7,
268
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
269
+ prior_guidance_scale: float = 4.0,
270
+ decoder_guidance_scale: float = 8.0,
271
+ enable_sequential_cpu_offload=True,
272
+ gpu_id=0,
273
+ output_type: Optional[str] = "pil",
274
+ return_dict: bool = True,
275
+ ):
276
+ """
277
+ Function invoked when calling the pipeline for generation.
278
+
279
+ Args:
280
+ start_prompt (`str`):
281
+ The prompt to start the image generation interpolation from.
282
+ end_prompt (`str`):
283
+ The prompt to end the image generation interpolation at.
284
+ steps (`int`, *optional*, defaults to 5):
285
+ The number of steps over which to interpolate from start_prompt to end_prompt. The pipeline returns
286
+ the same number of images as this value.
287
+ prior_num_inference_steps (`int`, *optional*, defaults to 25):
288
+ The number of denoising steps for the prior. More denoising steps usually lead to a higher quality
289
+ image at the expense of slower inference.
290
+ decoder_num_inference_steps (`int`, *optional*, defaults to 25):
291
+ The number of denoising steps for the decoder. More denoising steps usually lead to a higher quality
292
+ image at the expense of slower inference.
293
+ super_res_num_inference_steps (`int`, *optional*, defaults to 7):
294
+ The number of denoising steps for super resolution. More denoising steps usually lead to a higher
295
+ quality image at the expense of slower inference.
296
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
297
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
298
+ to make generation deterministic.
299
+ prior_guidance_scale (`float`, *optional*, defaults to 4.0):
300
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
301
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
302
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
303
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
304
+ usually at the expense of lower image quality.
305
+ decoder_guidance_scale (`float`, *optional*, defaults to 4.0):
306
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
307
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
308
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
309
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
310
+ usually at the expense of lower image quality.
311
+ output_type (`str`, *optional*, defaults to `"pil"`):
312
+ The output format of the generated image. Choose between
313
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
314
+ enable_sequential_cpu_offload (`bool`, *optional*, defaults to `True`):
315
+ If True, offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
316
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
317
+ when their specific submodule has its `forward` method called.
318
+ gpu_id (`int`, *optional*, defaults to `0`):
319
+ The gpu_id to be passed to enable_sequential_cpu_offload. Only works when enable_sequential_cpu_offload is set to True.
320
+ return_dict (`bool`, *optional*, defaults to `True`):
321
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
322
+ """
323
+
324
+ if not isinstance(start_prompt, str) or not isinstance(end_prompt, str):
325
+ raise ValueError(
326
+ f"`start_prompt` and `end_prompt` should be of type `str` but got {type(start_prompt)} and"
327
+ f" {type(end_prompt)} instead"
328
+ )
329
+
330
+ if enable_sequential_cpu_offload:
331
+ self.enable_sequential_cpu_offload(gpu_id=gpu_id)
332
+
333
+ device = self._execution_device
334
+
335
+ # Turn the prompts into embeddings.
336
+ inputs = self.tokenizer(
337
+ [start_prompt, end_prompt],
338
+ padding="max_length",
339
+ truncation=True,
340
+ max_length=self.tokenizer.model_max_length,
341
+ return_tensors="pt",
342
+ )
343
+ inputs.to(device)
344
+ text_model_output = self.text_encoder(**inputs)
345
+
346
+ text_attention_mask = torch.max(inputs.attention_mask[0], inputs.attention_mask[1])
347
+ text_attention_mask = torch.cat([text_attention_mask.unsqueeze(0)] * steps).to(device)
348
+
349
+ # Interpolate from the start to end prompt using slerp and add the generated images to an image output pipeline
350
+ batch_text_embeds = []
351
+ batch_last_hidden_state = []
352
+
353
+ for interp_val in torch.linspace(0, 1, steps):
354
+ text_embeds = slerp(interp_val, text_model_output.text_embeds[0], text_model_output.text_embeds[1])
355
+ last_hidden_state = slerp(
356
+ interp_val, text_model_output.last_hidden_state[0], text_model_output.last_hidden_state[1]
357
+ )
358
+ batch_text_embeds.append(text_embeds.unsqueeze(0))
359
+ batch_last_hidden_state.append(last_hidden_state.unsqueeze(0))
360
+
361
+ batch_text_embeds = torch.cat(batch_text_embeds)
362
+ batch_last_hidden_state = torch.cat(batch_last_hidden_state)
363
+
364
+ text_model_output = CLIPTextModelOutput(
365
+ text_embeds=batch_text_embeds, last_hidden_state=batch_last_hidden_state
366
+ )
367
+
368
+ batch_size = text_model_output[0].shape[0]
369
+
370
+ do_classifier_free_guidance = prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0
371
+
372
+ prompt_embeds, text_encoder_hidden_states, text_mask = self._encode_prompt(
373
+ prompt=None,
374
+ device=device,
375
+ num_images_per_prompt=1,
376
+ do_classifier_free_guidance=do_classifier_free_guidance,
377
+ text_model_output=text_model_output,
378
+ text_attention_mask=text_attention_mask,
379
+ )
380
+
381
+ # prior
382
+
383
+ self.prior_scheduler.set_timesteps(prior_num_inference_steps, device=device)
384
+ prior_timesteps_tensor = self.prior_scheduler.timesteps
385
+
386
+ embedding_dim = self.prior.config.embedding_dim
387
+
388
+ prior_latents = self.prepare_latents(
389
+ (batch_size, embedding_dim),
390
+ prompt_embeds.dtype,
391
+ device,
392
+ generator,
393
+ None,
394
+ self.prior_scheduler,
395
+ )
396
+
397
+ for i, t in enumerate(self.progress_bar(prior_timesteps_tensor)):
398
+ # expand the latents if we are doing classifier free guidance
399
+ latent_model_input = torch.cat([prior_latents] * 2) if do_classifier_free_guidance else prior_latents
400
+
401
+ predicted_image_embedding = self.prior(
402
+ latent_model_input,
403
+ timestep=t,
404
+ proj_embedding=prompt_embeds,
405
+ encoder_hidden_states=text_encoder_hidden_states,
406
+ attention_mask=text_mask,
407
+ ).predicted_image_embedding
408
+
409
+ if do_classifier_free_guidance:
410
+ predicted_image_embedding_uncond, predicted_image_embedding_text = predicted_image_embedding.chunk(2)
411
+ predicted_image_embedding = predicted_image_embedding_uncond + prior_guidance_scale * (
412
+ predicted_image_embedding_text - predicted_image_embedding_uncond
413
+ )
414
+
415
+ if i + 1 == prior_timesteps_tensor.shape[0]:
416
+ prev_timestep = None
417
+ else:
418
+ prev_timestep = prior_timesteps_tensor[i + 1]
419
+
420
+ prior_latents = self.prior_scheduler.step(
421
+ predicted_image_embedding,
422
+ timestep=t,
423
+ sample=prior_latents,
424
+ generator=generator,
425
+ prev_timestep=prev_timestep,
426
+ ).prev_sample
427
+
428
+ prior_latents = self.prior.post_process_latents(prior_latents)
429
+
430
+ image_embeddings = prior_latents
431
+
432
+ # done prior
433
+
434
+ # decoder
435
+
436
+ text_encoder_hidden_states, additive_clip_time_embeddings = self.text_proj(
437
+ image_embeddings=image_embeddings,
438
+ prompt_embeds=prompt_embeds,
439
+ text_encoder_hidden_states=text_encoder_hidden_states,
440
+ do_classifier_free_guidance=do_classifier_free_guidance,
441
+ )
442
+
443
+ if device.type == "mps":
444
+ # HACK: MPS: There is a panic when padding bool tensors,
445
+ # so cast to int tensor for the pad and back to bool afterwards
446
+ text_mask = text_mask.type(torch.int)
447
+ decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), value=1)
448
+ decoder_text_mask = decoder_text_mask.type(torch.bool)
449
+ else:
450
+ decoder_text_mask = F.pad(text_mask, (self.text_proj.clip_extra_context_tokens, 0), value=True)
451
+
452
+ self.decoder_scheduler.set_timesteps(decoder_num_inference_steps, device=device)
453
+ decoder_timesteps_tensor = self.decoder_scheduler.timesteps
454
+
455
+ num_channels_latents = self.decoder.in_channels
456
+ height = self.decoder.sample_size
457
+ width = self.decoder.sample_size
458
+
459
+ decoder_latents = self.prepare_latents(
460
+ (batch_size, num_channels_latents, height, width),
461
+ text_encoder_hidden_states.dtype,
462
+ device,
463
+ generator,
464
+ None,
465
+ self.decoder_scheduler,
466
+ )
467
+
468
+ for i, t in enumerate(self.progress_bar(decoder_timesteps_tensor)):
469
+ # expand the latents if we are doing classifier free guidance
470
+ latent_model_input = torch.cat([decoder_latents] * 2) if do_classifier_free_guidance else decoder_latents
471
+
472
+ noise_pred = self.decoder(
473
+ sample=latent_model_input,
474
+ timestep=t,
475
+ encoder_hidden_states=text_encoder_hidden_states,
476
+ class_labels=additive_clip_time_embeddings,
477
+ attention_mask=decoder_text_mask,
478
+ ).sample
479
+
480
+ if do_classifier_free_guidance:
481
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
482
+ noise_pred_uncond, _ = noise_pred_uncond.split(latent_model_input.shape[1], dim=1)
483
+ noise_pred_text, predicted_variance = noise_pred_text.split(latent_model_input.shape[1], dim=1)
484
+ noise_pred = noise_pred_uncond + decoder_guidance_scale * (noise_pred_text - noise_pred_uncond)
485
+ noise_pred = torch.cat([noise_pred, predicted_variance], dim=1)
486
+
487
+ if i + 1 == decoder_timesteps_tensor.shape[0]:
488
+ prev_timestep = None
489
+ else:
490
+ prev_timestep = decoder_timesteps_tensor[i + 1]
491
+
492
+ # compute the previous noisy sample x_t -> x_t-1
493
+ decoder_latents = self.decoder_scheduler.step(
494
+ noise_pred, t, decoder_latents, prev_timestep=prev_timestep, generator=generator
495
+ ).prev_sample
496
+
497
+ decoder_latents = decoder_latents.clamp(-1, 1)
498
+
499
+ image_small = decoder_latents
500
+
501
+ # done decoder
502
+
503
+ # super res
504
+
505
+ self.super_res_scheduler.set_timesteps(super_res_num_inference_steps, device=device)
506
+ super_res_timesteps_tensor = self.super_res_scheduler.timesteps
507
+
508
+ channels = self.super_res_first.in_channels // 2
509
+ height = self.super_res_first.sample_size
510
+ width = self.super_res_first.sample_size
511
+
512
+ super_res_latents = self.prepare_latents(
513
+ (batch_size, channels, height, width),
514
+ image_small.dtype,
515
+ device,
516
+ generator,
517
+ None,
518
+ self.super_res_scheduler,
519
+ )
520
+
521
+ if device.type == "mps":
522
+ # MPS does not support many interpolations
523
+ image_upscaled = F.interpolate(image_small, size=[height, width])
524
+ else:
525
+ interpolate_antialias = {}
526
+ if "antialias" in inspect.signature(F.interpolate).parameters:
527
+ interpolate_antialias["antialias"] = True
528
+
529
+ image_upscaled = F.interpolate(
530
+ image_small, size=[height, width], mode="bicubic", align_corners=False, **interpolate_antialias
531
+ )
532
+
533
+ for i, t in enumerate(self.progress_bar(super_res_timesteps_tensor)):
534
+ # no classifier free guidance
535
+
536
+ if i == super_res_timesteps_tensor.shape[0] - 1:
537
+ unet = self.super_res_last
538
+ else:
539
+ unet = self.super_res_first
540
+
541
+ latent_model_input = torch.cat([super_res_latents, image_upscaled], dim=1)
542
+
543
+ noise_pred = unet(
544
+ sample=latent_model_input,
545
+ timestep=t,
546
+ ).sample
547
+
548
+ if i + 1 == super_res_timesteps_tensor.shape[0]:
549
+ prev_timestep = None
550
+ else:
551
+ prev_timestep = super_res_timesteps_tensor[i + 1]
552
+
553
+ # compute the previous noisy sample x_t -> x_t-1
554
+ super_res_latents = self.super_res_scheduler.step(
555
+ noise_pred, t, super_res_latents, prev_timestep=prev_timestep, generator=generator
556
+ ).prev_sample
557
+
558
+ image = super_res_latents
559
+ # done super res
560
+
561
+ # post processing
562
+
563
+ image = image * 0.5 + 0.5
564
+ image = image.clamp(0, 1)
565
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
566
+
567
+ if output_type == "pil":
568
+ image = self.numpy_to_pil(image)
569
+
570
+ if not return_dict:
571
+ return (image,)
572
+
573
+ return ImagePipelineOutput(images=image)
v0.14.0/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
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
10
+
11
+ from diffusers import DiffusionPipeline
12
+ from diffusers.configuration_utils import FrozenDict
13
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
14
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
15
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
16
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
17
+ from diffusers.utils import deprecate, logging
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
+
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: 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 bfloat16
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)