Buckets:

mishig's picture
|
download
raw
45.8 kB
# 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](https://huggingface.co/papers/2302.08453)
使用预训练模型,我们可以提供控制图像(例如深度图)来控制 Stable Diffusion 的文本到图像生成,使其遵循深度图像的结构并填充细节。
该论文的摘要如下:
*大规模文本到图像(T2I)模型令人惊叹的生成能力,展示了其学习复杂结构和有意义语义的强大实力。然而,仅依赖文本提示词无法充分利用模型所学到的知识,尤其是在需要灵活且精确的控制(例如颜色和结构)时。本文旨在“挖掘”T2I 模型隐式学习到的能力,并显式地利用这些能力,以更细粒度的方式控制生成过程。具体而言,我们提出学习简单且轻量级的 T2I-Adapters,以将 T2I 模型内部的知识与外部控制信号对齐,同时冻结原始的大型 T2I 模型。通过这种方式,我们可以根据不同的条件训练各种适配器,从而在生成结果的颜色和结构上实现丰富的控制和编辑效果。此外,所提出的 T2I-Adapters 具有极具实用价值的特性,例如可组合性和泛化能力。大量实验表明,我们的 T2I-Adapter 具有出色的生成质量和广泛的应用范围。*
该模型由社区贡献者 [HimariO](https://github.com/HimariO) ❤️ 贡献。
## StableDiffusionAdapterPipeline[[diffusers.StableDiffusionAdapterPipeline]]
#### diffusers.StableDiffusionAdapterPipeline[[diffusers.StableDiffusionAdapterPipeline]]
```python
diffusers.StableDiffusionAdapterPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, adapter: diffusers.models.adapter.T2IAdapter | diffusers.models.adapter.MultiAdapter | list[diffusers.models.adapter.T2IAdapter], scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, requires_safety_checker: bool = True)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py#L191)
**参数:**
adapter (`T2IAdapter` 或 `MultiAdapter` 或 `list[T2IAdapter]`):在去噪过程中为 unet 提供额外的条件。如果将多个 Adapter 设置为列表,则每个 Adapter 的输出会相加,以生成一个合并的额外条件。
adapter_weights (`list[float]`, *可选*,默认为 None) : 浮点数列表,表示在将各适配器输出相加之前,分别乘以每个适配器输出的权重。
vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL)):变分自编码器(VAE)模型,用于将图像编码为潜在表示,并从潜在表示解码回图像。
text_encoder (`CLIPTextModel`):冻结的文本编码器。Stable Diffusion 使用的是 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分,具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。
tokenizer (`CLIPTokenizer`):[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。
unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel)):用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。
scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin)):用于与 `unet` 配合以去除编码后的图像潜变量噪声的调度器。可以是 [DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler) 或 [PNDMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/pndm#diffusers.PNDMScheduler) 之一。
safety_checker (`StableDiffusionSafetyChecker`):一个分类模块,用于评估生成的图像是否可能被视为冒犯性或有害内容。详情请参阅[模型卡片](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)。
feature_extractor (`CLIPImageProcessor`):用于从生成的图像中提取特征,并将其作为 `safety_checker` 输入的模型。
使用 Stable Diffusion 并结合 T2I-Adapter 进行文本到图像生成的 Pipeline https://huggingface.co/papers/2302.08453
该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档,了解该库为所有 pipeline 实现的通用方法(例如下载或保存、在特定设备上运行等)。
#### __调用__[[diffusers.StableDiffusionAdapterPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, image: typing.Union[torch.Tensor, PIL.Image.Image, list[PIL.Image.Image]] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, guidance_scale: float = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.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: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, adapter_conditioning_scale: float | list[float] = 1.0, clip_skip: int | None = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py#L689)
**参数:**
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]`,*可选*):用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中,指定去噪过程所使用的自定义时间步。如果未定义,则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。
sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义,将使用传入 `num_inference_steps` 时的默认行为。
guidance_scale (`float`,*可选*,默认值为 7.5):如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://huggingface.co/papers/2205.11487)中公式 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](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler),对其他调度器将被忽略。
generator (`torch.Generator` 或 `list[torch.Generator]`,*可选*):一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html),用于使生成过程具有确定性。
latents (`torch.Tensor`, *可选*) : 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机`generator`进行采样来生成潜变量张量。
prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入,*例如* 提示词加权。如果未提供,文本嵌入将从 `prompt` 输入参数生成。
negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入,*例如* 提示词权重。如果未提供,negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。
output_type (`str`,*可选*,默认为 `"pil"`):生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/):`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](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `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 `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the `safety_checker`.
调用生成 pipeline 时调用的函数。
示例:
```py
>>> 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[[diffusers.StableDiffusionAdapterPipeline.enable_attention_slicing]]
```python
enable_attention_slicing(slice_size: str | int = 'auto')
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2030)
**参数:**
slice_size (`str` 或 `int`,*可选*,默认为 `"auto"`):当值为 `"auto"` 时,将输入到注意力头的数据减半,因此注意力计算将分两步进行。如果值为 `"max"`,则每次只运行一个切片,以节省最大内存。如果提供了数字,则使用 `attention_head_dim // slice_size` 个切片。在这种情况下,`attention_head_dim` 必须是 `slice_size` 的倍数。
启用切片注意力计算。启用此选项后,注意力模块会将输入张量拆分为多个切片,分步计算注意力。当存在多个注意力头时,计算将按顺序针对每个头执行。此功能可用于节省部分内存,代价是速度略有下降。
> [!WARNING] > ⚠️ 如果你已经在使用 `scaled_dot_product_attention`(SDPA),请勿启用注意力切片
来自 PyTorch > 2.0 或 xFormers。这些注意力计算本身已经非常节省内存,因此您无需启用 > 此功能。如果您在 SDPA 或 xFormers 中启用注意力切片,可能会导致严重的性能下降!
示例:
```py
>>> 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]
```
#### disable_attention_slicing[[diffusers.StableDiffusionAdapterPipeline.disable_attention_slicing]]
```python
disable_attention_slicing()
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2067)
禁用切片注意力计算。如果之前调用过 `enable_attention_slicing`,则注意力将一次性计算完成。
#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionAdapterPipeline.enable_xformers_memory_efficient_attention]]
```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L1975)
**参数:**
attention_op (`Callable`,*可选*):覆盖默认的 `None` 运算符,用作 xFormers 的 [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 函数的 `op` 参数。
启用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力机制。启用此选项后,您应能观察到更低的 GPU 内存占用,并可能在推理阶段获得加速。训练阶段的加速不保证。
> [!WARNING] > ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient
attention 的优先级高于 >。
示例:
```py
>>> 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)
```
#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionAdapterPipeline.disable_xformers_memory_efficient_attention]]
```python
disable_xformers_memory_efficient_attention()
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2006)
禁用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力。
#### encode_prompt[[diffusers.StableDiffusionAdapterPipeline.encode_prompt]]
```python
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: float | None = None, clip_skip: int | None = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py#L311)
**参数:**
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[[diffusers.StableDiffusionAdapterPipeline.get_guidance_scale_embedding]]
```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py#L648)
**参数:**
w (`torch.Tensor`) : 生成具有指定 guidance scale 的嵌入向量,以用于后续丰富时间步嵌入。
embedding_dim (`int`,*可选*,默认值为 512):要生成的嵌入的维度。
dtype (`torch.dtype`,*可选*,默认为 `torch.float32`):生成嵌入的数据类型。
**返回:** `torch.Tensor`
形状为 `(len(w), embedding_dim)` 的嵌入向量。
参见 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
## StableDiffusionXLAdapterPipeline[[diffusers.StableDiffusionXLAdapterPipeline]]
#### diffusers.StableDiffusionXLAdapterPipeline[[diffusers.StableDiffusionXLAdapterPipeline]]
```python
diffusers.StableDiffusionXLAdapterPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, text_encoder_2: CLIPTextModelWithProjection, tokenizer: CLIPTokenizer, tokenizer_2: CLIPTokenizer, unet: UNet2DConditionModel, adapter: diffusers.models.adapter.T2IAdapter | diffusers.models.adapter.MultiAdapter | list[diffusers.models.adapter.T2IAdapter], scheduler: KarrasDiffusionSchedulers, force_zeros_for_empty_prompt: bool = True, feature_extractor: CLIPImageProcessorPil = None, image_encoder: CLIPVisionModelWithProjection = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py#L213)
**参数:**
adapter (`T2IAdapter` 或 `MultiAdapter` 或 `list[T2IAdapter]`):在去噪过程中为 unet 提供额外的条件。如果将多个 Adapter 设置为列表,则每个 Adapter 的输出会相加,以生成一个合并的额外条件。
adapter_weights (`list[float]`, *可选*,默认为 None) : 浮点数列表,表示在将各适配器输出相加之前,分别乘以每个适配器输出的权重。
vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL)):变分自编码器(VAE)模型,用于将图像编码为潜在表示,并从潜在表示解码回图像。
text_encoder (`CLIPTextModel`):冻结的文本编码器。Stable Diffusion 使用的是 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel) 的文本部分,具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。
tokenizer (`CLIPTokenizer`):[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。
unet ([UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel)):用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。
scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin)):用于与 `unet` 配合以去除编码后的图像潜变量噪声的调度器。可以是 [DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler) 或 [PNDMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/pndm#diffusers.PNDMScheduler) 之一。
safety_checker (`StableDiffusionSafetyChecker`):一个分类模块,用于评估生成的图像是否可能被视为冒犯性或有害内容。详情请参阅[模型卡片](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)。
feature_extractor (`CLIPImageProcessor`):用于从生成的图像中提取特征,并将其作为 `safety_checker` 输入的模型。
使用 Stable Diffusion 并结合 T2I-Adapter 进行文本到图像生成的 Pipeline https://huggingface.co/papers/2302.08453
该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档,了解该库为所有 pipeline 实现的通用方法(例如下载或保存、在特定设备上运行等)。
该 pipeline 还继承了以下加载方法:
- 用于加载文本反转嵌入的 [load_textual_inversion()](/docs/diffusers/v0.43.0/zh/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- 用于加载 `.ckpt` 文件的 [from_single_file()](/docs/diffusers/v0.43.0/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- 用于加载 LoRA 权重的 [load_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights)
- 用于保存 LoRA 权重的 [save_lora_weights()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights)
- 用于加载 IP Adapter 的 [load_ip_adapter()](/docs/diffusers/v0.43.0/zh/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)
#### __调用__[[diffusers.StableDiffusionXLAdapterPipeline.__call__]]
```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, timesteps: list[int] = None, sigmas: list[float] = None, denoising_end: float | None = None, guidance_scale: float = 5.0, negative_prompt: str | list[str] | None = None, negative_prompt_2: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1, cross_attention_kwargs: dict[str, typing.Any] | None = None, guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), target_size: tuple[int, int] | None = None, negative_original_size: tuple[int, int] | None = None, negative_crops_coords_top_left: tuple[int, int] = (0, 0), negative_target_size: tuple[int, int] | None = None, adapter_conditioning_scale: float | list[float] = 1.0, adapter_conditioning_factor: float = 1.0, clip_skip: int | None = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py#L858)
**参数:**
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](https://huggingface.co/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](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 以及未在低分辨率上专门微调的检查点,低于 512 像素的宽度效果不佳。
num_inference_steps (`int`, *可选*,默认为 50):去噪步数。更多的去噪步数通常能带来更高质量的图像,但代价是推理速度变慢。
timesteps (`list[int]`,*可选*):用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中,指定去噪过程所使用的自定义时间步。如果未定义,则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。
sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义,将使用传入 `num_inference_steps` 时的默认行为。
denoising_end (`float`, *可选*) : 指定时,确定在有意提前终止之前,总去噪过程需要完成的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留相当多的噪声,具体程度由调度器选择的离散时间步决定。当此管道作为“去噪器混合”多管道设置的一部分时,应理想地使用 denoising_end 参数,如 [**优化图像输出**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output) 中所述。
guidance_scale (`float`,*可选*,默认值为 5.0):如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为[Imagen Paper](https://huggingface.co/papers/2205.11487)中公式 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](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler),对其他调度器将被忽略。
generator (`torch.Generator` 或 `list[torch.Generator]`,*可选*):一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html),用于使生成过程具有确定性。
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` 输入参数生成 pooled 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](https://pillow.readthedocs.io/en/stable/):`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](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。
guidance_rescale (`float`, *optional*, defaults to 0.0) : Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). 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](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](https://huggingface.co/papers/2307.01952) 中的第 2.2 节。
target_size (`tuple[int]`,*可选*,默认为 (1024, 1024)):在大多数情况下,应将 `target_size` 设置为生成图像所需的宽度和高度。如果未指定,则默认为 `(height, width)`。这是 [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节中所述 SDXL 微条件的一部分。[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952) 第 2.2 节。
negative_original_size (`tuple[int]`,*可选*,默认为 (1024, 1024)):用于基于特定的图像分辨率对生成过程进行负向条件控制。这是 SDXL 微条件化的一部分,如 [https://huggingface.co/papers/2307.01952](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](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](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`
`~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput`,如果 `return_dict` 为 True,否则为 `tuple`。当返回元组时,第一个元素是一个包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
```py
>>> 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[[diffusers.StableDiffusionXLAdapterPipeline.enable_attention_slicing]]
```python
enable_attention_slicing(slice_size: str | int = 'auto')
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2030)
**参数:**
slice_size (`str` 或 `int`,*可选*,默认为 `"auto"`):当值为 `"auto"` 时,将输入到注意力头的数据减半,因此注意力计算将分两步进行。如果值为 `"max"`,则每次只运行一个切片,以节省最大内存。如果提供了数字,则使用 `attention_head_dim // slice_size` 个切片。在这种情况下,`attention_head_dim` 必须是 `slice_size` 的倍数。
启用切片注意力计算。启用此选项后,注意力模块会将输入张量拆分为多个切片,分步计算注意力。当存在多个注意力头时,计算将按顺序针对每个头执行。此功能可用于节省部分内存,代价是速度略有下降。
> [!WARNING] > ⚠️ 如果你已经在使用 `scaled_dot_product_attention`(SDPA),请勿启用注意力切片
来自 PyTorch > 2.0 或 xFormers。这些注意力计算本身已经非常节省内存,因此您无需启用 > 此功能。如果您在 SDPA 或 xFormers 中启用注意力切片,可能会导致严重的性能下降!
示例:
```py
>>> 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]
```
#### disable_attention_slicing[[diffusers.StableDiffusionXLAdapterPipeline.disable_attention_slicing]]
```python
disable_attention_slicing()
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2067)
禁用切片注意力计算。如果之前调用过 `enable_attention_slicing`,则注意力将一次性计算完成。
#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionXLAdapterPipeline.enable_xformers_memory_efficient_attention]]
```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L1975)
**参数:**
attention_op (`Callable`,*可选*):覆盖默认的 `None` 运算符,用作 xFormers 的 [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 函数的 `op` 参数。
启用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力机制。启用此选项后,您应能观察到更低的 GPU 内存占用,并可能在推理阶段获得加速。训练阶段的加速不保证。
> [!WARNING] > ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时,memory efficient
attention 的优先级高于 >。
示例:
```py
>>> 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)
```
#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionXLAdapterPipeline.disable_xformers_memory_efficient_attention]]
```python
disable_xformers_memory_efficient_attention()
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/pipeline_utils.py#L2006)
禁用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力。
#### encode_prompt[[diffusers.StableDiffusionXLAdapterPipeline.encode_prompt]]
```python
encode_prompt(prompt: str, prompt_2: str | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, negative_prompt_2: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py#L311)
**参数:**
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` 输入参数生成 pooled negative_prompt_embeds。
lora_scale (`float`, *可选*) : 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。
clip_skip (`int`, *可选*) : 在计算提示嵌入时,从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出来计算提示嵌入。
将提示词编码为文本编码器的隐藏状态。
#### get_guidance_scale_embedding[[diffusers.StableDiffusionXLAdapterPipeline.get_guidance_scale_embedding]]
```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```
[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py#L817)
**参数:**
w (`torch.Tensor`) : 生成具有指定 guidance scale 的嵌入向量,以用于后续丰富时间步嵌入。
embedding_dim (`int`,*可选*,默认值为 512):要生成的嵌入的维度。
dtype (`torch.dtype`,*可选*,默认为 `torch.float32`):生成嵌入的数据类型。
**返回:** `torch.Tensor`
形状为 `(len(w), embedding_dim)` 的嵌入向量。
参见 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

Xet Storage Details

Size:
45.8 kB
·
Xet hash:
0e29c23f6952a8c9dc088e276810e9c3429fc10c0ad912573858311f16e6631e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.