Diffusers documentation
T2I-Adapter
T2I-Adapter
Chong Mou、Xintao Wang、Liangbin Xie、Jian Zhang、Zhongang Qi、Ying Shan、Xiaohu Qie 的 T2I-Adapter: Learning Adapters to Dig out More Controllable Ability for Text-to-Image Diffusion Models
使用预训练模型,我们可以提供控制图像(例如深度图)来控制 Stable Diffusion 的文本到图像生成,使其遵循深度图像的结构并填充细节。
该论文的摘要如下:
大规模文本到图像(T2I)模型令人惊叹的生成能力,展示了其学习复杂结构和有意义语义的强大实力。然而,仅依赖文本提示词无法充分利用模型所学到的知识,尤其是在需要灵活且精确的控制(例如颜色和结构)时。本文旨在“挖掘”T2I 模型隐式习得的能力,并显式地利用这些能力,以更细粒度的方式控制生成过程。具体而言,我们提出学习简单且轻量级的 T2I-Adapters,以将 T2I 模型内部的知识与外部控制信号对齐,同时冻结原始的大型 T2I 模型。通过这种方式,我们可以根据不同的条件训练各种适配器,从而在生成结果的颜色和结构上实现丰富的控制和编辑效果。此外,所提出的 T2I-Adapters 具有诸如可组合性和泛化能力等具有实际应用价值的特性。大量实验表明,我们的 T2I-Adapter 具有出色的生成质量和广泛的应用范围。
该模型由社区贡献者 HimariO ❤️ 贡献。
StableDiffusionAdapterPipeline
class diffusers.StableDiffusionAdapterPipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModeladapter: diffusers.models.adapter.T2IAdapter | diffusers.models.adapter.MultiAdapter | list[diffusers.models.adapter.T2IAdapter]scheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = True )
参数
- adapter(
T2IAdapter或MultiAdapter或list[T2IAdapter])— 在去噪过程中为 unet 提供额外的条件信息。如果以列表形式设置多个 Adapter,则会将每个 Adapter 的输出相加,以生成一个合并后的额外条件。 - adapter_weights (
list[float],可选,默认为 None) — 浮点数列表,表示在将各适配器输出相加之前,分别乘以每个适配器输出的权重。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — 冻结的文本编码器。Stable Diffusion 使用 CLIP 的文本部分,具体为 clip-vit-large-patch14 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。
- scheduler (SchedulerMixin) —
用于与
unet配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker) — 用于评估生成图像是否可能被视为冒犯性或有害的分类模块。 详情请参阅 模型卡片。 - feature_extractor (
CLIPImageProcessor) — 用于从生成的图像中提取特征,并将其作为safety_checker输入的模型。
使用 T2I-Adapter 增强的 Stable Diffusion 文本生成图像 Pipeline https://huggingface.co/papers/2302.08453
该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[torch.Tensor, PIL.Image.Image, list[PIL.Image.Image]] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list = Nonesigmas: list = Noneguidance_scale: float = 7.5negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneadapter_conditioning_scale: float | list[float] = 1.0clip_skip: int | None = None ) → ~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - image (
torch.Tensor、PIL.Image.Image、list[torch.Tensor]或list[PIL.Image.Image]或list[list[PIL.Image.Image]]) — Adapter 的输入条件。Adapter 使用该输入条件生成对 Unet 的引导。如果类型指定为torch.Tensor,则会按原样传递给 Adapter。也可以接受 PIL.Image.Image` 作为图像。控制图像会自动调整大小以适配输出图像。 - 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参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - guidance_scale (
float,可选,默认值为 7.5) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的图像,通常以牺牲图像质量为代价。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入negative_prompt_embeds。如果未定义,则必须改为传入negative_prompt_embeds。 在未使用引导时会被忽略(即当guidance_scale小于1时会被忽略)。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - eta(
float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput而不是普通元组。 - callback (
Callable, 可选) — 一个函数,将在推理过程中每callback_steps步被调用一次。该函数将以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。 - callback_steps (
int,可选,默认为 1) —callback函数的调用频率。如果未指定,则回调将在每一步被调用。 - cross_attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中self.processor下定义的AttnProcessor。 - adapter_conditioning_scale (
float或list[float],可选,默认值为 1.0) — 适配器的输出在加到原始 unet 的残差之前,会先乘以adapter_conditioning_scale。如果在初始化时指定了多个适配器,可以将对应的缩放值设置为列表。 - clip_skip (
int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
返回值
~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput 或 tuple
~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput if return_dict is True, otherwise a
tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the safety_checker`.
调用生成 pipeline 时调用的函数。
示例:
>>> from PIL import Image
>>> from diffusers.utils import load_image
>>> import torch
>>> from diffusers import StableDiffusionAdapterPipeline, T2IAdapter
>>> image = load_image(
... "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/t2i-adapter/color_ref.png"
... )
>>> color_palette = image.resize((8, 8))
>>> color_palette = color_palette.resize((512, 512), resample=Image.Resampling.NEAREST)
>>> adapter = T2IAdapter.from_pretrained("TencentARC/t2iadapter_color_sd14v1", torch_dtype=torch.float16)
>>> pipe = StableDiffusionAdapterPipeline.from_pretrained(
... "CompVis/stable-diffusion-v1-4",
... adapter=adapter,
... torch_dtype=torch.float16,
... )
>>> pipe.to("cuda")
>>> out_image = pipe(
... "At night, glowing cubes in front of the beach",
... image=color_palette,
... ).images[0]enable_attention_slicing
< source >( slice_size: str | int = '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",
... 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 内存占用,并且在推理期间可能会获得加速。训练期间的加速并不保证。
> ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient attention 具有 > 优先权。
示例:
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", 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 的内存高效注意力。
encode_prompt
< source >( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - device — (
torch.device): torch 设备 - num_images_per_prompt (
int) — 每个提示词应生成的图像数量 - do_classifier_free_guidance (
bool) — 是否使用 classifier free guidance - 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
< source >( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor
StableDiffusionXLAdapterPipeline
类 diffusers.StableDiffusionXLAdapterPipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModeladapter: diffusers.models.adapter.T2IAdapter | diffusers.models.adapter.MultiAdapter | list[diffusers.models.adapter.T2IAdapter]scheduler: KarrasDiffusionSchedulersforce_zeros_for_empty_prompt: bool = Truefeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )
参数
- adapter(
T2IAdapter或MultiAdapter或list[T2IAdapter])— 在去噪过程中为 unet 提供额外的条件信息。如果以列表形式设置多个 Adapter,则会将每个 Adapter 的输出相加,以生成一个合并后的额外条件。 - adapter_weights (
list[float],可选,默认为 None) — 浮点数列表,表示在将各适配器输出相加之前,分别乘以每个适配器输出的权重。 - vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel) — 冻结的文本编码器。Stable Diffusion 使用 CLIP 的文本部分,具体为 clip-vit-large-patch14 变体。 - tokenizer (
CLIPTokenizer) — CLIPTokenizer 类的分词器。 - unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。
- scheduler (SchedulerMixin) —
用于与
unet配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - safety_checker (
StableDiffusionSafetyChecker) — 用于评估生成图像是否可能被视为冒犯性或有害的分类模块。 详情请参阅 模型卡片。 - feature_extractor (
CLIPImageProcessor) — 用于从生成的图像中提取特征,并将其作为safety_checker输入的模型。
使用 T2I-Adapter 增强的 Stable Diffusion 文本生成图像 Pipeline https://huggingface.co/papers/2302.08453
该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。
该 pipeline 还继承了以下加载方法:
- 用于加载文本反转嵌入的 load_textual_inversion()
- 用于加载
.ckpt文件的 from_single_file() - 用于加载 LoRA 权重的 load_lora_weights()
- 用于保存 LoRA 权重的 save_lora_weights()
- 用于加载 IP Adapter 的 load_ip_adapter()
__call__
< source >( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list = Nonesigmas: list = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple = (0, 0)target_size: tuple[int, int] | None = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple = (0, 0)negative_target_size: tuple[int, int] | None = Noneadapter_conditioning_scale: float | list[float] = 1.0adapter_conditioning_factor: float = 1.0clip_skip: int | None = None ) → ~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput or tuple
参数
- prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - prompt_2(
str或list[str],可选)— 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,则两个文本编码器都会使用prompt。 - image (
torch.Tensor、PIL.Image.Image、list[torch.Tensor]或list[PIL.Image.Image]或list[list[PIL.Image.Image]]) — Adapter 的输入条件。Adapter 使用该输入条件生成对 Unet 的引导。如果类型指定为torch.Tensor,则会按原样传递给 Adapter。也可以接受 PIL.Image.Image` 作为图像。控制图像会自动调整大小以适配输出图像。 - height (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未在低分辨率上专门微调的检查点,低于 512 像素的效果不佳。 - width (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未在低分辨率上专门微调的检查点,低于 512 像素的宽度效果不佳。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - timesteps (
list[int], 可选) — 用于支持timesteps参数的调度器去噪过程的自定义时间步,该参数位于其set_timesteps方法中。如果未定义,则使用传入num_inference_steps时的默认行为。必须按降序排列。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - denoising_end (
float, 可选) — 如果指定,将确定在有意提前终止之前需要完成的去噪过程的总比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留相当多的噪声,具体程度由调度器选择的离散时间步决定。理想情况下,当此流水线作为“去噪器混合”多流水线设置的一部分时,应使用 denoising_end 参数,详见 优化图像输出 - guidance_scale (
float,可选,默认值为 5.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的图像,通常以牺牲图像质量为代价。 - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - negative_prompt_2(
str或list[str],可选)— 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则两个文本编码器均使用negative_prompt。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - eta(
float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - pooled_prompt_embeds (
torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从prompt输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - ip_adapter_image — (
PipelineImageInput,可选):用于配合 IP Adapter 使用的可选图像输入。 - 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:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.stable_diffusion_xl.StableDiffusionAdapterPipelineOutput而不是普通元组。 - callback (
Callable, 可选) — 一个函数,将在推理过程中每callback_steps步被调用一次。该函数将以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。 - callback_steps (
int,可选,默认为 1) —callback函数的调用频率。如果未指定,则回调将在每一步被调用。 - cross_attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中self.processor下定义的AttentionProcessor。 - guidance_rescale (
float, optional, defaults to 0.0) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleis defined asφin equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. Guidance rescale factor should fix overexposure when using zero terminal SNR. - original_size (
tuple[int],可选,默认为 (1024, 1024)) — 如果original_size与target_size不同,图像将看起来像是被下采样或上采样了。 如果未指定,original_size默认为(height, width)。这是 SDXL 微条件的一部分, 如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。 - crops_coords_top_left (
tuple[int],可选,默认为 (0, 0)) —crops_coords_top_left可用于生成一张看似从crops_coords_top_left位置向下裁剪的图像。通常将crops_coords_top_left设置为 (0, 0) 即可获得构图良好、居中效果理想的图像。这是 SDXL 微条件的一部分,详见 https://huggingface.co/papers/2307.01952 中的第 2.2 节。 - target_size (
tuple[int],可选,默认为 (1024, 1024)) — 在大多数情况下,target_size应设置为生成图像所需的宽度和高度。如果未指定,则默认为(height, width)。这是 https://huggingface.co/papers/2307.01952 第 2.2 节中所述 SDXL 微条件的一部分。 https://huggingface.co/papers/2307.01952 第 2.2 节。 - negative_original_size (
tuple[int],可选,默认为 (1024, 1024)) — 根据特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,详见 https://huggingface.co/papers/2307.01952 的第 2.2 节。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
tuple[int],可选,默认为 (0, 0)) — 根据特定的裁剪坐标对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,详见 https://huggingface.co/papers/2307.01952 第 2.2 节的说明。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
tuple[int],可选,默认为 (1024, 1024)) — 根据目标图像分辨率对生成过程进行负向条件控制。在大多数情况下,它应与target_size相同。这是 SDXL 微条件控制的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。更多信息,请参阅此 issue 讨论: https://github.com/huggingface/diffusers/issues/4208。 - adapter_conditioning_scale (
float或list[float],可选,默认值为 1.0) — 适配器的输出在加到原始 unet 的残差之前,会先乘以adapter_conditioning_scale。如果在初始化时指定了多个适配器,可以将对应的缩放值设置为列表。 - adapter_conditioning_factor (
float, 可选,默认值为 1.0) — 应用 adapter 的时间步比例。如果adapter_conditioning_factor为0.0,则完全不应用 adapter。如果adapter_conditioning_factor为1.0,则在所有时间步上应用 adapter。如果adapter_conditioning_factor为0.5,则在一半的时间步上应用 adapter。 - clip_skip (
int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
返回值
~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是一个包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers import T2IAdapter, StableDiffusionXLAdapterPipeline, DDPMScheduler
>>> from diffusers.utils import load_image
>>> sketch_image = load_image("https://huggingface.co/Adapter/t2iadapter/resolve/main/sketch.png").convert("L")
>>> model_id = "stabilityai/stable-diffusion-xl-base-1.0"
>>> adapter = T2IAdapter.from_pretrained(
... "Adapter/t2iadapter",
... subfolder="sketch_sdxl_1.0",
... torch_dtype=torch.float16,
... adapter_type="full_adapter_xl",
... )
>>> scheduler = DDPMScheduler.from_pretrained(model_id, subfolder="scheduler")
>>> pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
... model_id, adapter=adapter, torch_dtype=torch.float16, variant="fp16", scheduler=scheduler
... ).to("cuda")
>>> generator = torch.manual_seed(42)
>>> sketch_image_out = pipe(
... prompt="a photo of a dog in real world, high quality",
... negative_prompt="extra digit, fewer digits, cropped, worst quality, low quality",
... image=sketch_image,
... generator=generator,
... guidance_scale=7.5,
... ).images[0]enable_attention_slicing
< source >( slice_size: str | int = '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",
... 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 内存占用,并且在推理期间可能会获得加速。训练期间的加速并不保证。
> ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient attention 具有 > 优先权。
示例:
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", 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 的内存高效注意力。
encode_prompt
< source >( prompt: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
参数
- prompt (
str或list[str],可选) — 要编码的提示 - prompt_2(
str或list[str],可选)— 要发送给tokenizer_2和text_encoder_2的提示词。如果未定义,则两个文本编码器都会使用prompt。 - device — (
torch.device): torch 设备 - num_images_per_prompt (
int) — 每个提示词应生成的图像数量 - do_classifier_free_guidance (
bool) — 是否使用 classifier free guidance - negative_prompt (
str或list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds。在未使用引导时会被忽略(即当guidance_scale小于1时忽略)。 - negative_prompt_2(
str或list[str],可选)— 用于引导图像生成的负面提示词,将发送给tokenizer_2和text_encoder_2。如果未定义,则两个文本编码器均使用negative_prompt。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从negative_prompt输入参数生成。 - pooled_prompt_embeds (
torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从prompt输入参数生成池化文本嵌入。 - negative_pooled_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从negative_prompt输入参数生成池化的 negative_prompt_embeds。 - lora_scale (
float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。 - clip_skip (
int, 可选) — 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示使用倒数第二层的输出来计算提示嵌入。
将提示词编码为文本编码器的隐藏状态。
get_guidance_scale_embedding
< source >( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor