[来源关键摘录] 2022 年 8 月 22 日官方发布文章,展示使用开源 Diffusers 管线运行与定制 Stable Diffusion 扩散模型。
[正文前段节选] Hugging Face
Search models, datasets, users... ⌘K
Back to Articles
Stable Diffusion with 🧨 Diffusers
August 22, 2022
Update on GitHub
Pedro Cuenca
Nathan Lambert
Patrick von Platen
patrickvonplaten
Stable Diffusion 🎨
...using 🧨 Diffusers
Stable Diffusion is a text-to-image latent diffusion model created by the researchers and engineers from CompVis, Stability AI and LAION.
It is trained on 512x512 images from a subset of the LAION-5B database.
LAION-5B is the largest, freely accessible multi-modal dataset that currently exists.
In this post, we want to show how to use Stable Diffusion with the 🧨 Diffusers library, explain how the model works and finally dive a bit deeper into how diffusers allows
one to customize the image generation pipeline.
Note: It is highly recommended to have a basic understanding of how diffusion models work. If diffusion
models are completely new to you, we recommend reading one of the following blog posts:
The Annotated Diffusion Model
Getting started with 🧨 Diffusers
Now, let's get started by generating some images 🎨.
Running Stable Diffusion
Before using the model, you need to accept the model license in order to download and use the weights. Note: the license does not need to be explicitly accepted through the UI anymore.
The license is designed to mitigate the potential harmful effects of such a powerful machine learning system.
We request users to read the license entirely and carefully. Here we offer a summary:
You can't use the model to deliberately produce nor share illegal or harmful outputs or content,
We claim no rights on the outputs you generate, you are free to use them and are accountable for their use which should not go against the provisions set in the license, and
You may re-distribute the weights and use the model commercially and/or as a service. If you do, please be aware you have to include the same use restrictions as the ones in the license and share a copy of the CreativeML OpenRAIL-M to all your users.
First, you should install diffusers==0.10.2 to run the following code snippets:
pip install diffusers==0.10.2 transformers scipy ftfy accelerate
In this post we'll use model version v1-4, but you can also use other versions of the model such as 1.5, 2, and 2.1 with minimal code changes.
The Stable Diffusion model can be run in inference with just a couple of lines using the StableDiffusionPipeline pipeline. The pipeline sets up everything you need to generate images from text with
a simple from_pretrained function call.
from diffusers import StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
If a GPU is available, let's move it to one!
pipe.to("cuda")
Note: If you are limited by GPU memory and have less than 10GB of GPU RAM available, please
make sure to load the StableDiffusionPipeline in float16 precision instead of the default
float32 precision as done above.
You can do so by loading the weights from the fp16 branch and by telling diffusers to expect the
weights to be in float16 precision:
import torch
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", revision="fp16", torch_dtype=torch.float16)
To run the pipeline, simply define the prompt and call pipe.
prompt = "a photograph of an astronaut riding a horse"
image = pipe(prompt).images[0]
# you can save the image with
# image.save(f"astronaut_rides_horse.png")
The result would look as follows
The previous code will give you a different image every time you run it.
If at some point you get a black image, it may be because the content filter built inside the model might have detected an NSFW result.
If you believe this shouldn't be the case, try tweaking your prompt or using a different seed. In fact, the model predictions include information about whether NSFW was detected for a particular result. Let's see what they look like:
result = pipe(prompt)
print(result)
'images': [<PIL.Image.Image image mode=RGB size=512x512>],
'nsfw_content_detected': [False]
If you want deterministic output you can seed a random seed and pass a generator to the pipeline.
Every time you use a generator with the same seed you'll get the same image output.
generator = torch.Generator("cuda").manual_seed(1024)
image = pipe(prompt, guidance_scale=7.5, generator=generator).images[0]
You can change the number of inference steps using the num_inference_steps argument.
In general, results are better the more steps you use, however the more steps, the longer the generation takes.
Stable Diffusion works quite well with a relatively small number of steps, so we recommend using the default number of inference steps of 50.
If you want faster results you can use a smaller number. If you want potentially higher quality results,
you can use larger numbers.
Let's try out running the pipeline with less denoising steps.
image = pipe(prompt, guidance_scale=7.5, num_inference_steps=15, generator=generator).images[0]
Note how the structure is the same, but there are problems in the astronauts suit and the general form of the horse.
This shows that using only 15 denoising steps has significantly degraded the quality of the generation result. As stated earlier 50 denoising steps is usually sufficient to generate high-quality images.
Besides num_inference_steps, we've been using another function argument, called guidance_scale in all
previous examples. guidance_scale is a way to increase the adherence to the conditional signal that guides the generation (text, in this case) as well as overall sample quality.
It is also known as classifier-free guidance, which in simple terms forces the generation to better match the prompt potentially at the cost of image quality or diversity.
Values between 7 and 8.5 are usually good choices for Stable Diffusion. By default the pipeline
uses a guidance_scale of 7.5.
If you use a very large value the images might look good, but will be less diverse.
You can learn about the technical details of this parameter in this section of the post.
Next, let's see how you can generate several images of the same prompt at once.
First, we'll create an image_grid function to help us visualize them nicely in a grid.
from PIL import Image
def image_grid(imgs, rows, cols):
assert len(imgs) == rows*cols
w, h = imgs[0].size
grid = Image.new('RGB', size=(cols*w, rows*h))
grid_w, grid_h = grid.size
for i, img in enumerate(imgs):
grid.paste(img, box=(i%cols*w, i//cols*h))
We can generate multiple images for the same prompt by simply using a list with the same prompt repeated several times. We'll send the list to the pipeline instead of the string we used before.
num_images = 3
prompt = ["a photograph of an astronaut riding a horse"] * num_images
images = pipe(prompt).images
grid = image_grid(images, rows=1, cols=3)
# you can save the grid with
# grid.save(f"astronaut_rides_horse.png")
By default, stable diffusion produces images of 512 × 512 pixels. It's very easy to override the default using the height and width arguments to create rectangular images in portrait or landscape ratios.
When choosing image sizes, we advise the following:
Make sure height and width are both multiples of 8.
Going below 512 might result in lower quality images.
Going over 512 in both directions will repeat image areas (global coherence is lost).
The best way to create non-square images is to use 512 in one dimension, and a value larger than that in the other one.
Let's run an example:
image = pipe(prompt, height=512, width=768).images[0]
How does Stable Diffusion work?
Having seen the high-quality images that stable diffusion can produce, let's try to understand
a bit better how the model functions.
Stable Diffusion is based on a particular type of diffusion model called Latent Diffusion, proposed in High-Resolution Image Synthesis with Latent Diffusion Models.
[...内容已截断,完整版请查看原文或 Wayback 快照]