Diffusers 文件
文字到影像
並獲得增強的文件體驗
開始使用
文字到影像
Stable Diffusion 模型由 CompVis、Stability AI、Runway 和 LAION 的研究人員和工程師建立。StableDiffusionPipeline 能夠根據任何文字輸入生成逼真的影像。它在 LAION-5B 資料集的一個子集中的 512x512 影像上進行訓練。此模型使用凍結的 CLIP ViT-L/14 文字編碼器,透過文字提示來調節模型。憑藉其 860M UNet 和 123M 文字編碼器,該模型相對輕量,可以在消費級 GPU 上執行。潛在擴散是 Stable Diffusion 構建在其基礎上的研究。它由 Robin Rombach、Andreas Blattmann、Dominik Lorenz、Patrick Esser、Björn Ommer 在使用潛在擴散模型進行高解析度影像合成一文中提出。
論文摘要如下:
透過將影像形成過程分解為去噪自編碼器的順序應用,擴散模型(DM)在影像資料及其他領域取得了最先進的合成結果。此外,它們的公式允許一種引導機制來控制影像生成過程而無需重新訓練。然而,由於這些模型通常直接在畫素空間中操作,因此強大 DM 的最佳化通常需要數百個 GPU 日,並且由於順序評估,推理成本很高。為了在有限的計算資源上實現 DM 訓練,同時保持其質量和靈活性,我們將其應用於強大的預訓練自編碼器的潛在空間。與之前的工作不同,在這種表示上訓練擴散模型首次允許在複雜度降低和細節保留之間達到一個接近最優的點,極大地提高了視覺保真度。透過在模型架構中引入交叉注意力層,我們將擴散模型轉變為用於文字或邊界框等一般條件輸入以及以卷積方式實現高解析度合成的強大而靈活的生成器。我們的潛在擴散模型(LDM)在影像修復方面達到了新的最先進水平,並在各種任務(包括無條件影像生成、語義場景合成和超解析度)上實現了高度競爭的效能,同時與基於畫素的 DM 相比顯著降低了計算要求。程式碼可在 https://github.com/CompVis/latent-diffusion 獲得。
務必檢視 Stable Diffusion 的 提示 部分,瞭解如何探索排程器速度和質量之間的權衡,以及如何高效地重用管道元件!
如果您有興趣將其中一個官方檢查點用於某個任務,請探索 CompVis、Runway 和 Stability AI Hub 組織!
StableDiffusionPipeline
class diffusers.StableDiffusionPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel 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
。 - scheduler (SchedulerMixin) — 與
unet
結合用於對編碼影像潛在表示進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分類模組,用於評估生成的影像是否可能被視為具有攻擊性或有害。有關模型潛在危害的更多詳細資訊,請參閱模型卡。 - feature_extractor (CLIPImageProcessor) — 用於從生成影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
用於使用 Stable Diffusion 進行文字到影像生成的管道。
此模型繼承自 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 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 guidance_rescale: float = 0.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 or tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞或提示詞列表。如果未定義,則需要傳遞prompt_embeds
。 - 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]
, 可選) — 用於去噪過程的自定義時間步長,適用於在set_timesteps
方法中支援timesteps
引數的排程器。如果未定義,將使用傳入num_inference_steps
時的預設行為。必須按降序排列。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於在set_timesteps
方法中支援sigmas
引數的排程器。如果未定義,將使用傳入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 介面卡的可選影像輸入。 - 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
。 - guidance_rescale (
float
, 可選, 預設為 0.0) — 來自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的引導重縮放因子。引導重縮放因子應在使用零終端信噪比時修復過曝問題。 - 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) 內容的 bool
列表。
用於生成的管道的呼叫函式。
示例
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt).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 的記憶體高效注意力。
啟用平鋪 VAE 解碼。啟用此選項後,VAE 將把輸入張量分割成瓦片,分多步計算編碼和解碼。這對於節省大量記憶體和處理更大的影像非常有用。
停用平鋪 VAE 解碼。如果之前啟用了 enable_vae_tiling
,此方法將恢復一步計算解碼。
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]
, 可選) — 覆蓋用於文字反轉權重的 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 承載授權的 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")
from_single_file
< source >( pretrained_model_link_or_path **kwargs )
引數
- pretrained_model_link_or_path (
str
或os.PathLike
, 可選) — 可以是以下之一:- Hub 上的
.ckpt
檔案連結(例如"https://huggingface.co/
)。/blob/main/ .ckpt" - 包含所有管道權重的檔案路徑。
- Hub 上的
- torch_dtype (
str
或torch.dtype
, 可選) — 覆蓋預設的torch.dtype
並使用其他 dtype 載入模型。 - force_download (
bool
, 可選, 預設為False
) — 是否強制(重新)下載模型權重和配置檔案,覆蓋現有快取版本。 - cache_dir (
Union[str, os.PathLike]
, 可選) — 如果未使用標準快取,下載的預訓練模型配置的快取目錄路徑。 - proxies (
Dict[str, str]
, 可選) — 要按協議或端點使用的代理伺服器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理用於每個請求。 - local_files_only (
bool
, 可選, 預設為False
) — 是否只加載本地模型權重和配置檔案。如果設定為True
,則不會從 Hub 下載模型。 - token (
str
或 bool, 可選) — 用作遠端檔案 HTTP 承載授權的 token。如果為True
,則使用從diffusers-cli login
生成的 token(儲存在~/.huggingface
中)。 - revision (
str
, 可選, 預設為"main"
) — 要使用的特定模型版本。它可以是分支名稱、標籤名稱、提交 ID 或 Git 允許的任何識別符號。 - original_config_file (
str
, 可選) — 用於訓練模型的原始配置檔案路徑。如果未提供,將從檢查點檔案推斷配置檔案。 - config (
str
, 可選) — 可以是以下之一:- Hub 上預訓練管道的倉庫 ID 字串(例如
CompVis/ldm-text2im-large-256
)。 - 包含 Diffusers 格式管道元件配置的目錄路徑(例如
./my_pipeline_directory/
)。
- Hub 上預訓練管道的倉庫 ID 字串(例如
- disable_mmap (`bool`, 可選, 預設為 `False`) — 載入 Safetensors 模型時是否停用記憶體對映 (mmap)。當模型位於網路掛載或硬碟上時,此選項可能表現更好。
- kwargs (其餘關鍵字引數字典,可選) — 可用於覆蓋可載入和可儲存的變數(特定管道類的管道元件)。被覆蓋的元件直接傳遞給管道的
__init__
方法。更多資訊請參見以下示例。
從以 .ckpt
或 .safetensors
格式儲存的預訓練管道權重例項化 DiffusionPipeline。管道預設設定為評估模式(model.eval()
)。
示例
>>> from diffusers import StableDiffusionPipeline
>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = StableDiffusionPipeline.from_single_file(
... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
... )
>>> # Download pipeline from local file
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly.ckpt")
>>> # Enable float16 and move to GPU
>>> pipeline = StableDiffusionPipeline.from_single_file(
... "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
... torch_dtype=torch.float16,
... )
>>> pipeline.to("cuda")
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
< 來源 >( 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
< 來源 >( 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 表示使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
get_guidance_scale_embedding
< 來源 >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< 來源 >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )
Stable Diffusion 管道的輸出類。
FlaxStableDiffusionPipeline
class diffusers.FlaxStableDiffusionPipeline
< 來源 >( vae: FlaxAutoencoderKL text_encoder: FlaxCLIPTextModel tokenizer: CLIPTokenizer unet: FlaxUNet2DConditionModel 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
。 - scheduler (SchedulerMixin) — 與
unet
結合使用的排程器,用於對編碼影像潛在表示進行去噪。可以是FlaxDDIMScheduler
、FlaxLMSDiscreteScheduler
、FlaxPNDMScheduler
或FlaxDPMSolverMultistepScheduler
之一。 - safety_checker (
FlaxStableDiffusionSafetyChecker
) — 分類模組,用於評估生成的影像是否可能被認為是冒犯性或有害的。有關模型潛在危害的更多詳細資訊,請參閱模型卡。 - feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
基於 Flax 的 Stable Diffusion 文字到影像生成管道。
此模型繼承自 FlaxDiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
__call__
< 來源 >( prompt_ids: <function array at 0x7fc460e1d1b0> params: typing.Union[typing.Dict, flax.core.frozen_dict.FrozenDict] prng_seed: Array num_inference_steps: int = 50 height: typing.Optional[int] = None width: typing.Optional[int] = None guidance_scale: typing.Union[float, jax.Array] = 7.5 latents: Array = None neg_prompt_ids: Array = None return_dict: bool = True jit: bool = False ) → FlaxStableDiffusionPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 引導影像生成的提示。 - 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) — 去噪步數。更多去噪步數通常會帶來更高質量的影像,但推理速度會變慢。 - guidance_scale (
float
, 可選, 預設為 7.5) — 更高的引導比例值鼓勵模型生成與文字prompt
緊密相關的影像,但影像質量會降低。當guidance_scale > 1
時,啟用引導比例。 - latents (
jnp.ndarray
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在表示,用作影像生成的輸入。可用於使用不同的提示調整相同的生成。如果未提供,則使用提供的隨機generator
取樣生成潛在陣列。 - jit (
bool
, 預設為False
) — 是否執行生成和安全評分函式的pmap
版本。此引數存在是因為
__call__
尚未實現端到端 pmap。它將在未來版本中移除。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 FlaxStableDiffusionPipelineOutput 而不是普通元組。
返回
如果 return_dict
為 True
,則返回 FlaxStableDiffusionPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不適合工作”(nsfw) 內容的 bool
列表。
用於生成的管道的呼叫函式。
示例
>>> import jax
>>> import numpy as np
>>> from flax.jax_utils import replicate
>>> from flax.training.common_utils import shard
>>> from diffusers import FlaxStableDiffusionPipeline
>>> pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="bf16", dtype=jax.numpy.bfloat16
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> prng_seed = jax.random.PRNGKey(0)
>>> num_inference_steps = 50
>>> num_samples = jax.device_count()
>>> prompt = num_samples * [prompt]
>>> prompt_ids = pipeline.prepare_inputs(prompt)
# shard inputs and rng
>>> params = replicate(params)
>>> prng_seed = jax.random.split(prng_seed, jax.device_count())
>>> prompt_ids = shard(prompt_ids)
>>> images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
>>> images = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
FlaxStableDiffusionPipelineOutput
class diffusers.pipelines.stable_diffusion.FlaxStableDiffusionPipelineOutput
< 來源 >( images: ndarray nsfw_content_detected: typing.List[bool] )
Flax-based Stable Diffusion 管道的輸出類。
返回一個新物件,用新值替換指定的欄位。