Diffusers 文件
超解析度
並獲得增強的文件體驗
開始使用
超解析度
Stable Diffusion 放大器擴散模型由 CompVis、Stability AI 和 LAION 的研究人員和工程師建立。它用於將輸入影像的解析度提高 4 倍。
務必檢視 Stable Diffusion 的 提示 部分,瞭解如何探索排程器速度和質量之間的權衡,以及如何高效地重用管道元件!
如果您有興趣將其中一個官方檢查點用於任務,請探索 CompVis、Runway 和 Stability AI Hub 組織!
StableDiffusionUpscalePipeline
類 diffusers.StableDiffusionUpscalePipeline
< 源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel low_res_scheduler: DDPMScheduler scheduler: KarrasDiffusionSchedulers safety_checker: typing.Optional[typing.Any] = None feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None watermarker: typing.Optional[typing.Any] = None max_noise_level: int = 350 )
引數
- vae (AutoencoderKL) — 變分自編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (CLIPTextModel) — 凍結文字編碼器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於文字分詞的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的
UNet2DConditionModel
。 - low_res_scheduler (SchedulerMixin) — 用於向低解析度條件影像新增初始噪聲的排程器。它必須是 DDPMScheduler 的例項。
- scheduler (SchedulerMixin) — 用於與
unet
結合以對編碼影像潛在表示進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
Stable Diffusion 2 的文字引導影像超解析度管道。
此模型繼承自 DiffusionPipeline。請查閱超類文件以瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案
__call__
< 源 >( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None num_inference_steps: int = 75 guidance_scale: float = 9.0 noise_level: int = 20 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: int = None ) → StableDiffusionPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,您需要傳遞prompt_embeds
。 - image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
, 或List[np.ndarray]
) — 要放大的影像或表示影像批次的張量。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會導致更高質量的影像,但推理速度會變慢。 - guidance_scale (
float
, 可選, 預設為 7.5) — 較高的引導比例值鼓勵模型生成與文字prompt
緊密關聯的影像,但影像質量會降低。當guidance_scale > 1
時啟用引導比例。 - negative_prompt (
str
或List[str]
, 可選) — 用於引導影像生成中不包含內容的提示詞。如果未定義,您需要傳遞negative_prompt_embeds
。當不使用引導時(guidance_scale < 1
)將被忽略。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞要生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - latents (
torch.Tensor
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在表示,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,則使用提供的隨機generator
進行取樣以生成潛在張量。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示詞加權)。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入(提示詞加權)。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇PIL.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - callback (
Callable
, 可選) — 在推理期間每callback_steps
步呼叫的函式。該函式以以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,則在每一步都呼叫回撥。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將傳遞給self.processor
中定義的AttentionProcessor
。 - clip_skip (
int
, 可選) — 計算提示詞嵌入時要跳過 CLIP 的層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的影像列表,第二個元素是一個 bool
列表,指示相應的生成影像是否包含“不適合工作”(nsfw) 內容。
用於生成的管道的呼叫函式。
示例
>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import StableDiffusionUpscalePipeline
>>> import torch
>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = StableDiffusionUpscalePipeline.from_pretrained(
... model_id, variant="fp16", torch_dtype=torch.float16
... )
>>> pipeline = pipeline.to("cuda")
>>> # let's download an image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"
>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")
enable_attention_slicing
< 源 >( slice_size: typing.Union[int, str, NoneType] = 'auto' )
啟用分片注意力計算。當啟用此選項時,注意力模組會將輸入張量分片以分多步計算注意力。對於多個注意力頭,計算按每個頭順序執行。這有助於節省一些記憶體,但會略微降低速度。
⚠️ 如果您已經在使用 PyTorch 2.0 或 xFormers 的 scaled_dot_product_attention
(SDPA),請勿啟用注意力切片。這些注意力計算已經非常節省記憶體,因此您無需啟用此功能。如果您將注意力切片與 SDPA 或 xFormers 一起啟用,可能會導致嚴重的效能下降!
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5",
... torch_dtype=torch.float16,
... use_safetensors=True,
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
停用切片注意力計算。如果之前呼叫過 enable_attention_slicing
,則注意力將一步計算完成。
enable_xformers_memory_efficient_attention
< source >( attention_op: typing.Optional[typing.Callable] = None )
引數
- attention_op (
Callable
, optional) — 覆蓋預設的None
運算子,用作 xFormers 的memory_efficient_attention()
函式的op
引數。
啟用 xFormers 的記憶體高效注意力。啟用此選項後,您應該會觀察到 GPU 記憶體使用量降低,並且推理速度可能加快。訓練期間的速度提升不保證。
⚠️ 當記憶體高效注意力和切片注意力同時啟用時,記憶體高效注意力優先。
示例
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
停用 xFormers 的記憶體高效注意力。
encode_prompt
< source >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示。 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量。 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由引導。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示。如果未定義,則必須傳遞negative_prompt_embeds
。在使用引導時(即如果guidance_scale
小於1
),則忽略此引數。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,負提示嵌入將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 如果載入了 LoRA 層,則將應用於文字編碼器所有 LoRA 層的 LoRA 縮放。 - clip_skip (
int
, 可選) — 計算提示嵌入時要跳過 CLIP 的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的輸出類。