Diffusers 文件
深度圖到影像
並獲得增強的文件體驗
開始使用
深度圖到影像
Stable Diffusion 模型還可以使用 MiDaS 基於影像推斷深度。這允許您傳遞文字提示和初始影像來調節新影像的生成,並使用 depth_map
來保留影像結構。
務必檢視 Stable Diffusion 的 提示 部分,瞭解如何探索排程器速度和質量之間的權衡,以及如何高效地重用管道元件!
如果您有興趣使用官方檢查點之一完成任務,請探索 CompVis、Runway 和 Stability AI Hub 組織!
StableDiffusionDepth2ImgPipeline
類 diffusers.StableDiffusionDepth2ImgPipeline
< 源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers depth_estimator: DPTForDepthEstimation feature_extractor: DPTImageProcessor )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於分詞的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛在表示去噪的
UNet2DConditionModel
。 - scheduler (SchedulerMixin) — 用於與
unet
結合去噪編碼影像潛在表示的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
用於文字引導的基於深度圖到影像的 Stable Diffusion 生成管道。
該模型繼承自 DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
__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 depth_map: typing.Optional[torch.Tensor] = None strength: float = 0.8 num_inference_steps: typing.Optional[int] = 50 guidance_scale: typing.Optional[float] = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → 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]
) — 用作起點的影像或表示影像批次的張量。僅當depth_map
非None
時,才能接受影像潛在表示作為image
。 - depth_map (
torch.Tensor
, 可選) — 用於影像生成過程的額外條件深度預測。如果未定義,它會自動使用self.depth_estimator
預測深度。 - strength (
float
, 可選, 預設為 0.8) — 指示轉換參考image
的程度。必須介於 0 和 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步數取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的所有迭代次數。值為 1 基本上會忽略image
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但會以較慢的推理速度為代價。此引數受strength
調節。 - 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
。 - 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 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將傳遞給self.processor
中定義的AttentionProcessor
。 - clip_skip (
int
, 可選) — 計算提示詞嵌入時要從 CLIP 中跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。 - callback_on_step_end (
Callable
, 可選) — 在推理過程中每個去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
中指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 StableDiffusionPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成影像的列表。
用於生成的管道的呼叫函式。
示例
>>> import torch
>>> import requests
>>> from PIL import Image
>>> from diffusers import StableDiffusionDepth2ImgPipeline
>>> pipe = StableDiffusionDepth2ImgPipeline.from_pretrained(
... "stabilityai/stable-diffusion-2-depth",
... torch_dtype=torch.float16,
... )
>>> pipe.to("cuda")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> init_image = Image.open(requests.get(url, stream=True).raw)
>>> prompt = "two tigers"
>>> n_prompt = "bad, deformed, ugly, bad anotomy"
>>> image = pipe(prompt=prompt, image=init_image, negative_prompt=n_prompt, strength=0.7).images[0]
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
, 可選) — 覆蓋預設的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 的記憶體高效注意力。
load_textual_inversion
< source >( pretrained_model_name_or_path: typing.Union[str, typing.List[str], typing.Dict[str, torch.Tensor], typing.List[typing.Dict[str, torch.Tensor]]] token: typing.Union[str, typing.List[str], NoneType] = None tokenizer: typing.Optional[ForwardRef('PreTrainedTokenizer')] = None text_encoder: typing.Optional[ForwardRef('PreTrainedModel')] = None **kwargs )
引數
- pretrained_model_name_or_path (
str
或os.PathLike
或List[str 或 os.PathLike]
或Dict
或List[Dict]
) — 可以是以下其中一種或其列表:- Hub 上託管的預訓練模型的模型 ID 字串(例如
sd-concepts-library/low-poly-hd-logos-icons
)。 - 包含文字反轉權重的目錄路徑(例如
./my_text_inversion_directory/
)。 - 包含文字反轉權重的檔案路徑(例如
./my_text_inversions.pt
)。 - 一個 torch 狀態字典。
- Hub 上託管的預訓練模型的模型 ID 字串(例如
- token (
str
或List[str]
, 可選) — 覆蓋用於文字反轉權重的令牌。如果pretrained_model_name_or_path
是列表,則token
也必須是等長的列表。 - text_encoder (CLIPTextModel, 可選) — 凍結的文字編碼器(clip-vit-large-patch14)。如果未指定,函式將使用 self.tokenizer。
- tokenizer (CLIPTokenizer, 可選) — 用於標記文字的
CLIPTokenizer
。如果未指定,函式將使用 self.tokenizer。 - weight_name (
str
, 可選) — 自定義權重檔案的名稱。應在以下情況使用:- 儲存的文字反轉檔案為 🤗 Diffusers 格式,但以特定權重名稱(例如
text_inv.bin
)儲存。 - 儲存的文字反轉檔案為 Automatic1111 格式。
- 儲存的文字反轉檔案為 🤗 Diffusers 格式,但以特定權重名稱(例如
- cache_dir (
Union[str, os.PathLike]
, 可選) — 如果不使用標準快取,則下載的預訓練模型配置的快取目錄路徑。 - force_download (
bool
, 可選, 預設為False
) — 是否強制(重新)下載模型權重和配置檔案,如果已存在快取版本則覆蓋。 - proxies (
Dict[str, str]
, 可選) — 按協議或端點使用的代理伺服器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理用於每個請求。 - local_files_only (
bool
, 可選, 預設為False
) — 是否只加載本地模型權重和配置檔案。如果設定為True
,模型將不會從 Hub 下載。 - hf_token (
str
或 bool, 可選) — 用作遠端檔案 HTTP bearer 授權的令牌。如果為True
,則使用從diffusers-cli login
生成的令牌(儲存在~/.huggingface
中)。 - revision (
str
, 可選, 預設為"main"
) — 要使用的特定模型版本。它可以是分支名稱、標籤名稱、提交 ID 或 Git 允許的任何識別符號。 - subfolder (
str
, 可選, 預設為""
) — 模型檔案在 Hub 或本地較大模型倉庫中的子資料夾位置。 - mirror (
str
, 可選) — 如果您在中國下載模型,則映象源可以解決可訪問性問題。我們不保證源的及時性或安全性,您應該參考映象站點以獲取更多資訊。
將文字反轉嵌入載入到 StableDiffusionPipeline 的文字編碼器中(支援 🤗 Diffusers 和 Automatic1111 兩種格式)。
示例
載入 🤗 Diffusers 格式的文字反轉嵌入向量
from diffusers import StableDiffusionPipeline
import torch
model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
prompt = "A <cat-toy> backpack"
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
要載入 Automatic1111 格式的文字反轉嵌入向量,請務必先下載該向量(例如從 civitAI),然後載入該向量
本地
from diffusers import StableDiffusionPipeline
import torch
model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
load_lora_weights
< source >( pretrained_model_name_or_path_or_dict: typing.Union[str, typing.Dict[str, torch.Tensor]] adapter_name: typing.Optional[str] = None hotswap: bool = False **kwargs )
引數
- pretrained_model_name_or_path_or_dict (
str
或os.PathLike
或dict
) — 請參閱 lora_state_dict()。 - adapter_name (
str
, 可選) — 用於引用已載入介面卡模型的介面卡名稱。如果未指定,將使用default_{i}
,其中 i 是正在載入的介面卡總數。 - low_cpu_mem_usage (
bool
, 可選) — 透過僅載入預訓練的 LoRA 權重而不初始化隨機權重來加快模型載入速度。 - hotswap (
bool
, 可選) — 預設為False
。是否用新載入的介面卡就地替換現有(LoRA)介面卡。這意味著,不是載入額外的介面卡,而是將現有介面卡權重替換為新介面卡的權重。這可以更快且更節省記憶體。然而,熱插拔的主要優點是,當模型使用 torch.compile 編譯時,載入新介面卡不需要重新編譯模型。使用熱插拔時,傳入的adapter_name
應該是已載入介面卡的名稱。如果新介面卡和舊介面卡具有不同的秩和/或 LoRA alpha(即縮放),則在載入介面卡之前需要呼叫一個額外的方法:
將 pretrained_model_name_or_path_or_dict
中指定的 LoRA 權重載入到 self.unet
和 self.text_encoder
中。
所有 kwargs 都轉發到 self.lora_state_dict
。
有關如何載入 state dict 的更多詳細資訊,請參閱 lora_state_dict()。
有關如何將 state dict 載入到 self.unet
中的更多詳細資訊,請參閱 load_lora_into_unet()。
有關如何將 state dict 載入到 self.text_encoder
中的更多詳細資訊,請參閱 load_lora_into_text_encoder()。
save_lora_weights
< source >( save_directory: typing.Union[str, os.PathLike] unet_lora_layers: typing.Dict[str, typing.Union[torch.nn.modules.module.Module, torch.Tensor]] = None text_encoder_lora_layers: typing.Dict[str, torch.nn.modules.module.Module] = None is_main_process: bool = True weight_name: str = None save_function: typing.Callable = None safe_serialization: bool = True unet_lora_adapter_metadata = None text_encoder_lora_adapter_metadata = None )
引數
- save_directory (
str
或os.PathLike
) — 儲存 LoRA 引數的目錄。如果不存在,則將建立。 - unet_lora_layers (
Dict[str, torch.nn.Module]
或Dict[str, torch.Tensor]
) — 對應於unet
的 LoRA 層狀態字典。 - text_encoder_lora_layers (
Dict[str, torch.nn.Module]
或Dict[str, torch.Tensor]
) — 對應於text_encoder
的 LoRA 層狀態字典。必須明確傳遞文字編碼器 LoRA 狀態字典,因為它來自 🤗 Transformers。 - is_main_process (
bool
, 可選, 預設為True
) — 呼叫此函式的程序是否為主程序。在分散式訓練期間很有用,您需要在所有程序上呼叫此函式。在這種情況下,僅在主程序上設定is_main_process=True
以避免競爭條件。 - save_function (
Callable
) — 用於儲存狀態字典的函式。在分散式訓練期間需要將torch.save
替換為其他方法時很有用。可以透過環境變數DIFFUSERS_SAVE_MODE
配置。 - safe_serialization (
bool
, 可選, 預設為True
) — 是否使用safetensors
或傳統 PyTorch 方式(帶pickle
)儲存模型。 - unet_lora_adapter_metadata — 與 unet 關聯的 LoRA 介面卡元資料,將隨狀態字典一起序列化。
- text_encoder_lora_adapter_metadata — 與文字編碼器關聯的 LoRA 介面卡元資料,將隨狀態字典一起序列化。
儲存對應於 UNet 和文字編碼器的 LoRA 引數。
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_embeds
將從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 管道的輸出類。