Diffusers 文件
Attend-and-Excite
並獲得增強的文件體驗
開始使用
Attend-and-Excite
Attend-and-Excite for Stable Diffusion 是在 Attend-and-Excite: Attention-Based Semantic Guidance for Text-to-Image Diffusion Models 中提出的,它提供了對影像生成的文字注意力控制。
論文摘要如下:
最近的文字到影像生成模型展示了根據目標文字提示生成多樣化和創意影像的無與倫比的能力。儘管具有革命性,但目前最先進的擴散模型在生成完全傳達給定文字提示語義的影像方面可能仍會失敗。我們分析了公開可用的Stable Diffusion模型,並評估了災難性忽略的存在,即模型未能生成輸入提示中的一個或多個主體。此外,我們發現,在某些情況下,模型也未能將其屬性(例如,顏色)正確繫結到其對應的主體。為了幫助緩解這些失敗情況,我們引入了生成語義護理(GSN)的概念,我們試圖在推理時即時干預生成過程,以提高生成影像的忠實度。透過GSN的基於注意力的公式,稱為Attend-and-Excite,我們引導模型細化交叉注意力單元,以關注文字提示中的所有主體token,並增強——或激發——它們的啟用,鼓勵模型生成文字提示中描述的所有主體。我們將我們的方法與替代方法進行比較,並證明它在各種文字提示中更忠實地傳達了所需的 концепции。
您可以在專案頁面、原始程式碼庫上找到有關Attend-and-Excite的更多資訊,或者在演示中試用。
StableDiffusionAttendAndExcitePipeline
class diffusers.StableDiffusionAttendAndExcitePipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor requires_safety_checker: bool = True )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器(VAE)模型。
- text_encoder (CLIPTextModel) — 凍結文字編碼器(clip-vit-large-patch14)。
- tokenizer (CLIPTokenizer) — 用於對文字進行token化的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用於對編碼影像潛伏進行去噪的
UNet2DConditionModel
。 - scheduler (SchedulerMixin) — 用於與
unet
結合對編碼影像潛伏進行去噪的排程器。可以是DDIMScheduler、LMSDiscreteScheduler或PNDMScheduler之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分類模組,用於評估生成的影像是否可能被認為是冒犯性或有害的。有關模型潛在危害的更多詳細資訊,請參閱模型卡。 - feature_extractor (CLIPImageProcessor) — 用於從生成的影像中提取特徵的
CLIPImageProcessor
;用作safety_checker
的輸入。
用於使用Stable Diffusion和Attend-and-Excite進行文字到影像生成的管道。
此模型繼承自DiffusionPipeline。請檢視超類文件以瞭解為所有管道實現通用方法(下載、儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
__call__
< source >( prompt: typing.Union[str, typing.List[str]] token_indices: typing.Union[typing.List[int], typing.List[typing.List[int]]] height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: 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 max_iter_to_alter: int = 25 thresholds: dict = {0: 0.05, 10: 0.5, 20: 0.8} scale_factor: int = 20 attn_res: typing.Optional[typing.Tuple[int]] = (16, 16) clip_skip: typing.Optional[int] = None ) → StableDiffusionPipelineOutput or tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,則需要傳入prompt_embeds
。 - token_indices (
List[int]
) — 用於透過attend-and-excite進行修改的token索引。 - 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
時,啟用引導比例。 - 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`。 - max_iter_to_alter (
int
, 可選, 預設為25
) — 應用 Attend-and-Excite 的去噪步數。`max_iter_to_alter` 去噪步是應用 Attend-and-Excite 的時候。例如,如果 `max_iter_to_alter` 為 `25`,總共有 `30` 個去噪步,則前 `25` 個去噪步應用 Attend-and-Excite,後 `5` 個去噪步不應用。 - thresholds (
dict
, 可選, 預設為{0 -- 0.05, 10: 0.5, 20: 0.8}
):定義迭代和所需的閾值以應用迭代潛在細化的字典。 - scale_factor (
int
, 可選, 預設為 20) — 控制每次 Attend-and-Excite 更新步長的縮放因子。 - attn_res (
tuple
, 可選, 預設為根據寬度和高度計算) — 語義注意力圖的二維解析度。 - clip_skip (
int
, 可選) — 在計算提示嵌入時從 CLIP 中跳過的層數。值為 1 表示使用倒數第二層的輸出來計算提示嵌入。
返回
StableDiffusionPipelineOutput 或 tuple
如果 `return_dict` 為 `True`,則返回 StableDiffusionPipelineOutput,否則返回一個 `tuple`,其中第一個元素是生成的影像列表,第二個元素是指示相應生成的影像是否包含“不安全內容”(nsfw)的 `bool` 列表。
用於生成的管道的呼叫函式。
示例
>>> import torch
>>> from diffusers import StableDiffusionAttendAndExcitePipeline
>>> pipe = StableDiffusionAttendAndExcitePipeline.from_pretrained(
... "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
... ).to("cuda")
>>> prompt = "a cat and a frog"
>>> # use get_indices function to find out indices of the tokens you want to alter
>>> pipe.get_indices(prompt)
{0: '<|startoftext|>', 1: 'a</w>', 2: 'cat</w>', 3: 'and</w>', 4: 'a</w>', 5: 'frog</w>', 6: '<|endoftext|>'}
>>> token_indices = [2, 5]
>>> seed = 6141
>>> generator = torch.Generator("cuda").manual_seed(seed)
>>> images = pipe(
... prompt=prompt,
... token_indices=token_indices,
... guidance_scale=7.5,
... generator=generator,
... num_inference_steps=50,
... max_iter_to_alter=25,
... ).images
>>> image = images[0]
>>> image.save(f"../images/{prompt}_{seed}.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 表示使用倒數第二層的輸出來計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
實用函式,用於列出您希望更改的令牌的索引
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 管道的輸出類。