Diffusers documentation

Stable Diffusion 2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Stable Diffusion 2

Stable Diffusion 2 — это модель латентной диффузии для генерации изображений по текстовому описанию, созданная на основе оригинальной Stable Diffusion. Над ней работали Robin Rombach и Katherine Crowson из Stability AI и LAION.

Релиз Stable Diffusion 2.0 включает в себя надежные модели text-to-image, обученные с использованием нового текстового энкодера (OpenCLIP), разработанного LAION при поддержке Stability AI, что значительно повышает качество генерируемых изображений по сравнению с предыдущими релизами V1. Модели text-to-image в этом релизе могут генерировать изображения с разрешением по умолчанию как 512x512 пикселей, так и 768x768 пикселей. Эти модели обучены на эстетическом подмножестве датасета LAION-5B, созданном командой DeepFloyd из Stability AI, которое затем дополнительно фильтруется для удаления контента для взрослых с помощью фильтра NSFW от LAION.

Для получения подробной информации о том, как работает Stable Diffusion 2 и чем он отличается от оригинальной Stable Diffusion, обратитесь к официальному анонсу.

Архитектура Stable Diffusion 2 в целом идентична исходной модели Stable Diffusion, поэтому обратитесь к документации её API, чтобы узнать, как использовать Stable Diffusion 2. Мы рекомендуем использовать DPMSolverMultistepScheduler, так как он обеспечивает разумный баланс между скоростью и качеством и может работать всего с 20 шагами.

Stable Diffusion 2 доступен для таких задач, как генерация изображений по тексту, inpainting, супер-разрешение и генерация изображений по глубине:

ЗадачаРепозиторий
text-to-image (512x512)sd2-community/stable-diffusion-2-base
текст в изображение (768x768)sd2-community/stable-diffusion-2
inpaintingsd2-community/stable-diffusion-2-inpainting
сверхразрешениеstable-diffusion-x4-upscaler
depth-to-imagesd2-community/stable-diffusion-2-depth

Вот несколько примеров использования Stable Diffusion 2 для каждой задачи:

Обязательно ознакомьтесь с разделом Советы по Stable Diffusion, чтобы узнать, как исследовать баланс между скоростью и качеством планировщика, а также как эффективно переиспользовать компоненты конвейера!

Если вы хотите использовать одну из официальных контрольных точек для задачи, изучите организации CompVis и Stability AI на Hub!

Текст в изображение

from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
import torch

repo_id = "stabilityai/stable-diffusion-2-base"
pipe = DiffusionPipeline.from_pretrained(repo_id, dtype=torch.float16, variant="fp16")

pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "High quality photo of an astronaut riding a horse in space"
image = pipe(prompt, num_inference_steps=25).images[0]
image

Инпейнтинг

import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
from diffusers.utils import load_image, make_image_grid

img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

init_image = load_image(img_url).resize((512, 512))
mask_image = load_image(mask_url).resize((512, 512))

repo_id = "stabilityai/stable-diffusion-2-inpainting"
pipe = DiffusionPipeline.from_pretrained(repo_id, dtype=torch.float16, variant="fp16")

pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
image = pipe(prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=25).images[0]
make_image_grid([init_image, mask_image, image], rows=1, cols=3)

Сверхразрешение

from diffusers import StableDiffusionUpscalePipeline
from diffusers.utils import load_image, make_image_grid
import torch

# load model and scheduler
model_id = "stabilityai/stable-diffusion-x4-upscaler"
pipeline = StableDiffusionUpscalePipeline.from_pretrained(model_id, dtype=torch.float16)
pipeline = pipeline.to("cuda")  # or "mps", "xpu", "cpu"

# let's download an  image
url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
low_res_img = load_image(url)
low_res_img = low_res_img.resize((128, 128))
prompt = "a white cat"
upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
make_image_grid([low_res_img.resize((512, 512)), upscaled_image.resize((512, 512))], rows=1, cols=2)

Глубина в изображение

import torch
from diffusers import StableDiffusionDepth2ImgPipeline
from diffusers.utils import load_image, make_image_grid

pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-2-depth",
    dtype=torch.float16,
).to("cuda")  # or "mps", "xpu", "cpu"


url = "http://images.cocodataset.org/val2017/000000039769.jpg"
init_image = load_image(url)
prompt = "two tigers"
negative_prompt = "bad, deformed, ugly, bad anotomy"
image = pipe(prompt=prompt, image=init_image, negative_prompt=negative_prompt, strength=0.7).images[0]
make_image_grid([init_image, image], rows=1, cols=2)
Update on GitHub