Diffusers 文档
Attend-and-Excite
并获得增强的文档体验
开始使用
Attend-and-Excite
Stable Diffusion 的 Attend-and-Excite 在 Attend-and-Excite: Attention-Based Semantic Guidance for Text-to-Image Diffusion Models 中提出,并提供对图像生成的文本注意力控制。
论文摘要如下:
最近的文本到图像生成模型已经展示了无与伦比的能力,可以生成由目标文本提示引导的多样化和富有创意的图像。虽然具有革命性,但当前最先进的扩散模型仍然可能无法生成完全传达给定文本提示中语义的图像。我们分析了公开可用的 Stable Diffusion 模型,并评估了灾难性忽略的存在性,即模型未能从输入提示中生成一个或多个主题。此外,我们发现,在某些情况下,模型也未能正确地将属性(例如,颜色)绑定到其对应的主题。为了帮助减轻这些失败案例,我们引入了生成语义护理(GSN)的概念,我们寻求在推理时动态地干预生成过程,以提高生成图像的忠实度。使用基于注意力的 GSN 公式,称为 Attend-and-Excite,我们引导模型改进交叉注意力单元,以关注文本提示中的所有主题标记,并加强 - 或激发 - 它们的激活,从而鼓励模型生成文本提示中描述的所有主题。我们将我们的方法与替代方法进行比较,并证明它在一系列文本提示中更忠实地传达了所需的概念。
您可以在 项目页面、原始代码库 上找到关于 Attend-and-Excite 的更多信息,或者在 演示 中尝试一下。
请务必查看调度器 指南,了解如何探索调度器速度和质量之间的权衡,并查看 跨 pipelines 重用组件 部分,了解如何有效地将相同的组件加载到多个 pipelines 中。
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) — 用于标记文本的
CLIPTokenizer
。 - unet (UNet2DConditionModel) — 用于对编码后的图像潜在空间进行去噪的
UNet2DConditionModel
。 - scheduler (SchedulerMixin) — 调度器,与
unet
结合使用,以对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、 LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker
) — 分类模块,用于评估生成的图像是否可能被认为具有攻击性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡。 - feature_extractor (CLIPImageProcessor) —
CLIPImageProcessor
,用于从生成的图像中提取特征;用作safety_checker
的输入。
使用 Stable Diffusion 和 Attend-and-Excite 进行文本到图像生成的 Pipeline。
此模型继承自 DiffusionPipeline。查看超类文档,了解为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法
- 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 或 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) — 更高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但代价是图像质量降低。 当guidance_scale > 1
时,将启用 Guidance scale。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不包含的内容的提示或提示列表。如果未定义,则需要改为传递negative_prompt_embeds
。 当不使用 guidance 时(guidance_scale < 1
),将忽略此参数。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个 prompt 生成的图像数量。 - eta (
float
, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。 仅适用于 DDIMScheduler,在其他调度器中将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成结果具有确定性的torch.Generator
。 - latents (
torch.Tensor
, 可选) — 预生成的噪声潜在空间,从高斯分布中采样,用作图像生成的输入。 可用于通过不同的 prompt 微调相同的生成结果。 如果未提供,则通过使用提供的随机generator
进行采样来生成潜在张量。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。 可用于轻松调整文本输入(prompt 权重)。 如果未提供,则从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负文本嵌入。 可用于轻松调整文本输入(prompt 权重)。 如果未提供,则从negative_prompt
输入参数生成negative_prompt_embeds
。 - output_type (
str
, 可选, 默认为"pil"
) — 生成图像的输出格式。 在PIL.Image
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 StableDiffusionPipelineOutput 而不是普通 tuple。 - 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
, 可选,默认从宽度和高度计算) — 语义注意力图的 2D 分辨率。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预最终层的输出计算 prompt embeddings。
返回
StableDiffusionPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple
,其中第一个元素是包含生成图像的列表,第二个元素是 bool
列表,指示相应的生成图像是否包含“不适宜工作场所观看”(nsfw)内容。
调用 pipeline 的函数以进行生成。
示例
>>> 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
< 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]
, 可选) — 要编码的 prompt - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器 guidance - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
。不使用 guidance 时忽略(即,如果guidance_scale
小于1
则忽略)。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,则将从prompt
输入参数生成文本 embeddings。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入,例如 prompt 加权。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - lora_scale (
float
, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 比例。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预最终层的输出计算 prompt embeddings。
将 prompt 编码为文本编码器隐藏状态。
用于列出您希望更改的 token 索引的实用函数
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 pipelines 的输出类。