Diffusers 文件
ControlNet
並獲得增強的文件體驗
開始使用
ControlNet
ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《為文字到影像擴散模型新增條件控制》 中提出。
透過 ControlNet 模型,你可以提供額外的控制影像來條件化和控制 Stable Diffusion 的生成。例如,如果你提供一個深度圖,ControlNet 模型將生成一個保留深度圖空間資訊的影像。這是一種更靈活、更準確的影像生成控制方式。
論文摘要如下:
我們提出了 ControlNet,一種用於為大型預訓練文字到影像擴散模型新增空間條件控制的神經網路架構。ControlNet 鎖定即用型大型擴散模型,並重用它們在數十億影像上預訓練的深度且穩健的編碼層作為強大的主幹,以學習多樣化的條件控制。該神經網路架構透過“零卷積”(零初始化卷積層)連線,這些層逐步從零開始增長引數,並確保沒有有害噪聲會影響微調。我們使用 Stable Diffusion 測試了各種條件控制,例如邊緣、深度、分割、人體姿態等,可以使用單個或多個條件,帶或不帶提示。我們表明 ControlNets 的訓練在小型(<50k)和大型(>1m)資料集上都很穩健。大量結果表明,ControlNet 可以促進更廣泛的應用,以控制影像擴散模型。
此模型由 takuma104 貢獻。❤️
原始程式碼庫可在 lllyasviel/ControlNet 找到,你可以在 lllyasviel 的 Hub 配置檔案中找到官方 ControlNet 檢查點。
StableDiffusionControlNetPipeline
class diffusers.StableDiffusionControlNetPipeline
< 來源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
引數
- vae (AutoencoderKL) — 用於編碼和解碼影像到潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於標記文字的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛在表示進行去噪的
UNet2DConditionModel
。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪過程中為unet
提供額外的條件。如果將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將被新增在一起,以建立合併的額外條件。 - scheduler (SchedulerMixin) — 與
unet
結合使用以對編碼影像潛在表示進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 用於評估生成影像是否可能具有冒犯性或有害的分類模組。有關模型潛在危害的更多詳細資訊,請參閱 模型卡。 - feature_extractor (CLIPImageProcessor) — 用於從生成影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
用於使用 ControlNet 指導進行文字到影像生成的管道。
此模型繼承自 DiffusionPipeline。請查閱超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
__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 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 7.5 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, 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]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): ControlNet 輸入條件,用於為unet
提供生成指導。如果型別指定為torch.Tensor
,則直接傳遞給 ControlNet。PIL.Image.Image
也可以作為影像接受。輸出影像的尺寸預設為image
的尺寸。如果傳入了高度和/或寬度,image
將相應地調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表中的每個元素都可以正確地批次輸入到單個 ControlNet。當prompt
是一個列表時,如果為單個 ControlNet 傳入影像列表,則每個影像都將與prompt
列表中的每個提示配對。這也適用於多個 ControlNet,其中可以傳入影像列表的列表,以便為每個提示和每個 ControlNet 進行批次處理。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的高度(畫素)。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的寬度(畫素)。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影像,但推理速度會變慢。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步,適用於支援timesteps
引數的排程器,在其set_timesteps
方法中。如果未定義,將使用傳入num_inference_steps
時的預設行為。必須按降序排列。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於支援sigmas
引數的排程器,在其set_timesteps
方法中。如果未定義,將使用傳入num_inference_steps
時的預設行為。 - 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
輸入引數生成negative_prompt_embeds
。 - ip_adapter_image — (
PipelineImageInput
, 可選): 與 IP Adapters 配合使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 適用於 IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - 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
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始unet
的殘差之前乘以controlnet_conditioning_scale
。如果在init
中指定了多個 ControlNet,則可以將其相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — ControlNet 編碼器會嘗試識別輸入影像的內容,即使您刪除了所有提示。建議guidance_scale
值在 3.0 到 5.0 之間。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — ControlNet 開始應用的總體步數百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 停止應用的總體步數百分比。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可選) — 一個函式或PipelineCallback
或MultiPipelineCallbacks
的子類,在推理過程中每個去噪步驟結束時呼叫,帶有以下引數: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
,其中第一個元素是生成的影像列表,第二個元素是布林值列表,指示相應的生成影像是否包含“不適合工作”(nsfw)內容。
用於生成的管道的呼叫函式。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> import cv2
>>> from PIL import Image
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> image = np.array(image)
>>> # get canny image
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)
>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> # remove following line if xformers is not installed
>>> pipe.enable_xformers_memory_efficient_attention()
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
... "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
... ).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
,則注意力將一步計算完成。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
enable_xformers_memory_efficient_attention
< 源 >( 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)
load_textual_inversion
< 源 >( 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]
, 可選) — 覆蓋用於文字反轉權重的 token。如果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 授權的 token。如果為True
,則使用diffusers-cli login
生成的 token(儲存在~/.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")
encode_prompt
< 源 >( 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 表示使用倒數第二層的輸出計算提示詞嵌入。
將提示編碼為文字編碼器隱藏狀態。
get_guidance_scale_embedding
< source >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionControlNetImg2ImgPipeline
class diffusers.StableDiffusionControlNetImg2ImgPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (CLIPTextModel) — 凍結的文字編碼器 (clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於文字分詞的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛在表示去噪的
UNet2DConditionModel
。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪過程中向unet
提供額外的條件。如果將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將被新增在一起以建立組合的附加條件。 - scheduler (SchedulerMixin) — 與
unet
結合使用以對編碼影像潛在表示去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 用於評估生成影像是否可能具有攻擊性或有害的分類模組。請參閱模型卡以瞭解有關模型潛在危害的更多詳細資訊。 - feature_extractor (CLIPImageProcessor) — 用於從生成影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
使用 Stable Diffusion 和 ControlNet 引導的影像到影像生成管道。
此模型繼承自 DiffusionPipeline。請查閱超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( 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 control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.8 num_inference_steps: int = 50 guidance_scale: float = 7.5 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.8 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, 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]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): 用作影像生成過程起點的初始影像。也可以接受影像潛在表示作為image
,如果直接傳遞潛在表示,則不會再次編碼。 - control_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
,List[PIL.Image.Image]
,List[np.ndarray]
, —List[List[torch.Tensor]]
,List[List[np.ndarray]]
或List[List[PIL.Image.Image]]
): ControlNet 輸入條件,用於為unet
提供生成引導。如果型別指定為torch.Tensor
,則按原樣傳遞給 ControlNet。PIL.Image.Image
也可以作為影像接受。輸出影像的尺寸預設為image
的尺寸。如果傳遞了 height 和/或 width,則image
會相應調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表的每個元素可以正確批處理以輸入到單個 ControlNet。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的高度(畫素)。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的寬度(畫素)。 - strength (
float
, 可選, 預設為 0.8) — 指示轉換參考image
的程度。必須介於 0 和 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的全部迭代次數。值為 1 基本上會忽略image
。 - 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
輸入引數生成negative_prompt_embeds
。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP 介面卡數量相同。每個元素應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,則應包含負影像嵌入。如果未提供,則從ip_adapter_image
輸入引數計算嵌入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇PIL.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將傳遞給self.processor
中定義的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 的輸出乘以controlnet_conditioning_scale
,然後新增到原始unet
中的殘差中。如果init
中指定了多個 ControlNet,則可以將相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — 即使您刪除所有提示詞,ControlNet 編碼器也會嘗試識別輸入影像的內容。建議guidance_scale
值介於 3.0 和 5.0 之間。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — ControlNet 開始應用的步驟總數的百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 停止應用的步驟總數的百分比。 - clip_skip (
int
, 可選) — 在計算提示詞嵌入時要跳過的 CLIP 層數。值為 1 表示將使用倒數第二層的輸出計算提示詞嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可選) — 在推理過程中每個去噪步驟結束時呼叫的函式或PipelineCallback
或MultiPipelineCallbacks
的子類,具有以下引數: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
,其中第一個元素是生成的影像列表,第二個元素是布林值列表,指示相應的生成影像是否包含“不適合工作”(nsfw)內容。
用於生成的管道的呼叫函式。
示例
>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import StableDiffusionControlNetImg2ImgPipeline, ControlNetModel, UniPCMultistepScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> import cv2
>>> from PIL import Image
>>> # download an image
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
... )
>>> np_image = np.array(image)
>>> # get canny image
>>> np_image = cv2.Canny(np_image, 100, 200)
>>> np_image = np_image[:, :, None]
>>> np_image = np.concatenate([np_image, np_image, np_image], axis=2)
>>> canny_image = Image.fromarray(np_image)
>>> # load control net and stable diffusion v1-5
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
>>> pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> # speed up diffusion process with faster scheduler and memory optimization
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> generator = torch.manual_seed(0)
>>> image = pipe(
... "futuristic-looking woman",
... num_inference_steps=20,
... generator=generator,
... image=image,
... control_image=canny_image,
... ).images[0]
enable_attention_slicing
< source >( 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
,則注意力將一步計算完成。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
停用切片 VAE 解碼。如果之前啟用了 enable_vae_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 承載授權的令牌。如果為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")
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 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
StableDiffusionControlNetInpaintPipeline
class diffusers.StableDiffusionControlNetInpaintPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (CLIPTextModel) — 凍結文字編碼器(clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於標記文字的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於去噪編碼影像潛在的
UNet2DConditionModel
。 - controlnet (ControlNetModel 或
List[ControlNetModel]
) — 在去噪過程中為unet
提供額外的條件。如果您將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將相加,以建立組合的附加條件。 - scheduler (SchedulerMixin) — 用於與
unet
結合以對編碼影像潛在進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分類模組,用於估計生成的影像是否可能被視為冒犯性或有害。有關模型潛在危害的更多詳細資訊,請參閱模型卡。 - feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
使用 Stable Diffusion 和 ControlNet 指導的影像修復管道。
此模型繼承自 DiffusionPipeline。請查閱超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- from_single_file() 用於載入
.ckpt
檔案 - load_ip_adapter() 用於載入 IP 介面卡
此管道可與專門為影像修復微調過的檢查點(stable-diffusion-v1-5/stable-diffusion-inpainting)以及預設的文字到影像 Stable Diffusion 檢查點(stable-diffusion-v1-5/stable-diffusion-v1-5)一起使用。預設的文字到影像 Stable Diffusion 檢查點可能更適合那些在其上進行微調的 ControlNet,例如 lllyasviel/control_v11p_sd15_inpaint。
__call__
< source >( 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 mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 1.0 num_inference_steps: int = 50 guidance_scale: float = 7.5 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 ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.5 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, 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]
): 用作起點的影像批處理(PIL 影像、NumPy 陣列或張量)。對於 NumPy 陣列和 PyTorch 張量,預期值範圍在[0, 1]
之間。如果它是張量或張量列表,則預期形狀應為(B, C, H, W)
或(C, H, W)
。如果它是 NumPy 陣列或陣列列表,則預期形狀應為(B, H, W, C)
或(H, W, C)
。它也可以接受影像潛在表示作為image
,但如果直接傳遞潛在表示,則不會再次編碼。 - mask_image (
torch.Tensor
,PIL.Image.Image
,np.ndarray
,List[torch.Tensor]
, —List[PIL.Image.Image]
, 或List[np.ndarray]
): PIL 影像、NumPy 陣列或張量,表示用於遮罩image
的影像批處理。遮罩中白色畫素的部分將被重新繪製,而黑色畫素則被保留。如果mask_image
是 PIL 影像,則在使用前會將其轉換為單通道(亮度)。如果它是 NumPy 陣列或 PyTorch 張量,它應該包含一個顏色通道(L)而不是 3 個,因此 PyTorch 張量的預期形狀應為(B, 1, H, W)
、(B, H, W)
、(1, H, W)
、(H, W)
。對於 NumPy 陣列,則應為(B, H, W, 1)
、(B, H, W)
、(H, W, 1)
或(H, W)
。 - control_image (
torch.Tensor
,PIL.Image.Image
,List[torch.Tensor]
,List[PIL.Image.Image]
, —List[List[torch.Tensor]]
, 或List[List[PIL.Image.Image]]
): ControlNet 輸入條件,為unet
提供生成指導。如果型別指定為torch.Tensor
,則按原樣傳遞給 ControlNet。PIL.Image.Image
也可以作為影像接受。輸出影像的尺寸預設為image
的尺寸。如果傳遞了 height 和/或 width,則image
會相應地調整大小。如果在init
中指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表中的每個元素都可以正確批次輸入到單個 ControlNet。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的畫素高度。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影像的畫素寬度。 - padding_mask_crop (
int
, 可選, 預設為None
) — 對影像和遮罩進行裁剪時的邊距大小。如果為None
,則不裁剪影像和mask_image
。如果padding_mask_crop
不為None
,它將首先找到一個與影像長寬比相同且包含所有遮罩區域的矩形區域,然後根據padding_mask_crop
擴充套件該區域。然後,影像和mask_image
將根據擴充套件區域進行裁剪,再調整大小以用於影像修復。當遮罩區域很小而影像很大且包含與影像修復無關的資訊(例如背景)時,這很有用。 - strength (
float
, 可選, 預設為 1.0) — 表示參考image
的轉換程度。必須在 0 到 1 之間。image
用作起點,strength
越高,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲最大,去噪過程將執行num_inference_steps
中指定的全部迭代次數。值為 1 基本上會忽略image
。 - 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
輸入引數生成negative_prompt_embeds
。 - ip_adapter_image — (
PipelineImageInput
, 可選): 與 IP 介面卡配合使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP 介面卡數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,則應包含負影像嵌入。如果未提供,則根據ip_adapter_image
輸入引數計算嵌入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元組。 - cross_attention_kwargs (
dict
, 可選) — 如果指定,則將 kwargs 字典傳遞給self.processor
中定義的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 0.5) — ControlNet 的輸出乘以controlnet_conditioning_scale
,然後新增到原始unet
中的殘差。如果在init
中指定了多個 ControlNet,則可以將其相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — ControlNet 編碼器會嘗試識別輸入影像的內容,即使您刪除了所有提示。建議guidance_scale
值在 3.0 到 5.0 之間。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — ControlNet 開始應用的步驟總數百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 停止應用的步驟總數百分比。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
,PipelineCallback
,MultiPipelineCallbacks
, 可選) — 在推理過程中每個去噪步驟結束時呼叫的函式或PipelineCallback
或MultiPipelineCallbacks
的子類,具有以下引數: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
,其中第一個元素是生成的影像列表,第二個元素是布林值列表,指示相應的生成影像是否包含“不適合工作”(nsfw)內容。
用於生成的管道的呼叫函式。
示例
>>> # !pip install transformers accelerate
>>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch
>>> init_image = load_image(
... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))
>>> generator = torch.Generator(device="cpu").manual_seed(1)
>>> mask_image = load_image(
... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))
>>> def make_canny_condition(image):
... image = np.array(image)
... image = cv2.Canny(image, 100, 200)
... image = image[:, :, None]
... image = np.concatenate([image, image, image], axis=2)
... image = Image.fromarray(image)
... return image
>>> control_image = make_canny_condition(init_image)
>>> controlnet = ControlNetModel.from_pretrained(
... "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
... )
>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()
>>> # generate image
>>> image = pipe(
... "a handsome man with ray-ban sunglasses",
... num_inference_steps=20,
... generator=generator,
... eta=1.0,
... image=init_image,
... mask_image=mask_image,
... control_image=control_image,
... ).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
,則注意力將一步計算完成。
啟用切片 VAE 解碼。啟用此選項後,VAE 會將輸入張量分片,分步計算解碼。這有助於節省一些記憶體並允許更大的批次大小。
停用切片 VAE 解碼。如果之前啟用了 enable_vae_slicing
,此方法將返回一步計算解碼。
enable_xformers_memory_efficient_attention
< 源 >( 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)
load_textual_inversion
< 源 >( 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]
, 可選) — 覆蓋用於文字反轉權重的 token。如果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 承載授權的令牌。如果為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")
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 管道的輸出類。
FlaxStableDiffusionControlNetPipeline
class diffusers.FlaxStableDiffusionControlNetPipeline
< source >( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel controlnet: FlaxControlNetModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_flax.FlaxDDIMScheduler, diffusers.schedulers.scheduling_pndm_flax.FlaxPNDMScheduler, diffusers.schedulers.scheduling_lms_discrete_flax.FlaxLMSDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep_flax.FlaxDPMSolverMultistepScheduler] safety_checker: FlaxStableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor dtype: dtype = <class 'jax.numpy.float32'> )
引數
- vae (FlaxAutoencoderKL) — 變分自動編碼器(VAE)模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (FlaxCLIPTextModel) — 凍結的文字編碼器(clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於標記文字的
CLIPTokenizer
。 - unet (FlaxUNet2DConditionModel) — 一個
FlaxUNet2DConditionModel
,用於對編碼影像的潛在表示進行去噪。 - controlnet (FlaxControlNetModel — 在去噪過程中為
unet
提供額外的條件。 - scheduler (SchedulerMixin) — 與
unet
結合使用的排程器,用於對編碼影像的潛在表示進行去噪。可以是FlaxDDIMScheduler
、FlaxLMSDiscreteScheduler
、FlaxPNDMScheduler
或FlaxDPMSolverMultistepScheduler
之一。 - safety_checker (
FlaxStableDiffusionSafetyChecker
) — 分類模組,用於評估生成的影像是否可能被視為冒犯性或有害。請參閱模型卡,瞭解有關模型潛在危害的更多詳細資訊。 - feature_extractor (CLIPImageProcessor) — 一個
CLIPImageProcessor
,用於從生成的影像中提取特徵;用作safety_checker
的輸入。
基於 Flax 的管道,用於使用帶有 ControlNet Guidance 的 Stable Diffusion 進行文字到影像生成。
該模型繼承自FlaxDiffusionPipeline。請檢視超類文件,瞭解所有管道實現的通用方法(下載、儲存、在特定裝置上執行等)。
__call__
< source >( prompt_ids: Array image: Array params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array num_inference_steps: int = 50 guidance_scale: typing.Union[float, jax.Array] = 7.5 latents: Array = None neg_prompt_ids: Array = None controlnet_conditioning_scale: typing.Union[float, jax.Array] = 1.0 return_dict: bool = True jit: bool = False ) → FlaxStableDiffusionPipelineOutput 或 tuple
引數
- prompt_ids (
jnp.ndarray
) — 用於引導影像生成的提示詞。 - image (
jnp.ndarray
) — 表示 ControlNet 輸入條件的陣列,用於為unet
提供生成指導。 - params (
Dict
或FrozenDict
) — 包含模型引數/權重的字典。 - prng_seed (
jax.Array
) — 包含隨機數生成器金鑰的陣列。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多去噪步數通常會帶來更高質量的影像,但會以更慢的推理速度為代價。 - guidance_scale (
float
, 可選, 預設為 7.5) — 較高的指導比例值會促使模型生成與文字prompt
緊密相關的影像,但會以較低的影像質量為代價。當guidance_scale > 1
時,啟用指導比例。 - latents (
jnp.ndarray
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在變數,用作影像生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,則使用提供的隨機generator
取樣生成潛在變數陣列。 - controlnet_conditioning_scale (
float
或jnp.ndarray
, 可選, 預設為 1.0) — ControlNet 的輸出乘以controlnet_conditioning_scale
後,再新增到原始unet
中的殘差。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通的元組。 - jit (
bool
, 預設為False
) — 是否執行生成和安全評分函式的pmap
版本。存在此引數是因為
__call__
尚未實現端到端的 pmap。它將在未來版本中移除。
返回
如果 return_dict
為 True
,則返回 FlaxStableDiffusionPipelineOutput;否則,返回一個 tuple
,其中第一個元素是生成的影像列表,第二個元素是一個 bool
列表,指示相應生成的影像是否包含“不適合工作”(nsfw)內容。
用於生成的管道的呼叫函式。
示例
>>> import jax
>>> import numpy as np
>>> import jax.numpy as jnp
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> from diffusers.utils import load_image, make_image_grid
>>> from PIL import Image
>>> from diffusers import FlaxStableDiffusionControlNetPipeline, FlaxControlNetModel
>>> def create_key(seed=0):
... return jax.random.PRNGKey(seed)
>>> rng = create_key(0)
>>> # get canny image
>>> canny_image = load_image(
... "https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/blog_post_cell_10_output_0.jpeg"
... )
>>> prompts = "best quality, extremely detailed"
>>> negative_prompts = "monochrome, lowres, bad anatomy, worst quality, low quality"
>>> # load control net and stable diffusion v1-5
>>> controlnet, controlnet_params = FlaxControlNetModel.from_pretrained(
... "lllyasviel/sd-controlnet-canny", from_pt=True, dtype=jnp.float32
... )
>>> pipe, params = FlaxStableDiffusionControlNetPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5",
... controlnet=controlnet,
... revision="flax",
... dtype=jnp.float32,
... )
>>> params["controlnet"] = controlnet_params
>>> num_samples = jax.device_count()
>>> rng = jax.random.split(rng, jax.device_count())
>>> prompt_ids = pipe.prepare_text_inputs([prompts] * num_samples)
>>> negative_prompt_ids = pipe.prepare_text_inputs([negative_prompts] * num_samples)
>>> processed_image = pipe.prepare_image_inputs([canny_image] * num_samples)
>>> p_params = replicate(params)
>>> prompt_ids = shard(prompt_ids)
>>> negative_prompt_ids = shard(negative_prompt_ids)
>>> processed_image = shard(processed_image)
>>> output = pipe(
... prompt_ids=prompt_ids,
... image=processed_image,
... params=p_params,
... prng_seed=rng,
... num_inference_steps=50,
... neg_prompt_ids=negative_prompt_ids,
... jit=True,
... ).images
>>> output_images = pipe.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.shape[-3:])))
>>> output_images = make_image_grid(output_images, num_samples // 4, 4)
>>> output_images.save("generated_image.png")
FlaxStableDiffusionControlNetPipelineOutput
class diffusers.pipelines.stable_diffusion.FlaxStableDiffusionPipelineOutput
< source >( images: ndarray nsfw_content_detected: typing.List[bool] )
Flax-based Stable Diffusion 管道的輸出類。
返回一個新物件,用新值替換指定的欄位。