Diffusers 文档

扰动注意力引导

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

扰动注意力引导

LoRA

扰动注意力引导 (PAG) 是一种新的扩散采样引导方法,它在无条件和条件设置下都能提高样本质量,无需额外训练或集成外部模块。

PAG 在 Donghoon Ahn, Hyoungwon Cho, Jaewon Min, Wooseok Jang, Jungwoo Kim, SeonHwa Kim, Hyun Hee Park, Kyong Hwan Jin 和 Seungryong Kim 的论文 《基于扰动注意力引导的自校正扩散采样》 中引入。

论文摘要如下:

最近的研究表明,扩散模型能够生成高质量样本,但其质量严重依赖于采样引导技术,例如分类器引导 (CG) 和无分类器引导 (CFG)。这些技术通常不适用于无条件生成或各种下游任务,如图像修复。在本文中,我们提出了一种新的采样引导方法,称为扰动注意力引导 (PAG),它在无条件和条件设置下都能提高扩散样本质量,无需额外训练或集成外部模块。PAG 旨在在整个去噪过程中逐步增强样本结构。它通过将扩散 U-Net 中选定的自注意力图替换为单位矩阵,考虑到自注意力机制捕捉结构信息的能力,并引导去噪过程远离这些降级样本,从而生成具有降级结构的中间样本。在 ADM 和 Stable Diffusion 中,PAG 令人惊讶地提高了条件甚至无条件场景下的样本质量。此外,PAG 显著提高了现有引导(如 CG 或 CFG)无法充分利用的各种下游任务的基线性能,包括带有空提示的 ControlNet 以及图像修复(如图像修补和去模糊)。

可以通过在实例化 PAG 管道时将 `pag_applied_layers` 指定为参数来使用 PAG。它可以是单个字符串或字符串列表。每个字符串可以是唯一的层标识符或用于标识一个或多个层的正则表达式。

  • 作为普通字符串的完整标识符:`down_blocks.2.attentions.0.transformer_blocks.0.attn1.processor`
  • 作为正则表达式的完整标识符:`down_blocks.2.(attentions|motion_modules).0.transformer_blocks.0.attn1.processor`
  • 作为正则表达式的部分标识符:`down_blocks.2` 或 `attn1`
  • 标识符列表(可以是字符串和正则表达式的组合):`["blocks.1", "blocks.(14|20)", r"down_blocks\.(2,3)"]`

由于支持正则表达式作为匹配层标识符的方式,因此正确使用它至关重要,否则可能会出现意外行为。推荐的使用 PAG 方式是将层指定为 `blocks.{layer_index}` 和 `blocks.({layer_index_1|layer_index_2|...})`。以任何其他方式使用它虽然可行,但可能会绕过我们的基本验证检查并给出意外结果。

AnimateDiffPAGPipeline

class diffusers.AnimateDiffPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter scheduler: KarrasDiffusionSchedulers feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid_block.*attn1' )

参数

使用 AnimateDiff扰动注意力引导 进行文本到视频生成的管道。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None num_frames: typing.Optional[int] = 16 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_videos_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 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] decode_chunk_size: int = 16 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) AnimateDiffPipelineOutput or tuple

参数

  • prompt (str or 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_frames (int, 可选, 默认为 16) — 生成的视频帧数。默认为 16 帧,按每秒 8 帧计算,相当于 2 秒视频。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的视频,但会牺牲推理速度。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时启用引导比例。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不包含内容的提示或提示列表。如果未定义,则需要传递 negative_prompt_embeds。当不使用引导时 (guidance_scale < 1) 将忽略。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布采样的预生成噪声潜在表示,用作视频生成的输入。可用于使用不同提示调整相同生成。如果未提供,则使用提供的随机 generator 进行采样以生成潜在张量。潜在表示的形状应为 (batch_size, num_channel, num_frames, height, width)
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示加权)。如果未提供,则文本嵌入从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入(提示加权)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选): 与 IP 适配器配合使用的可选图像输入。
  • 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") — 生成视频的输出格式。在 torch.TensorPIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 TextToVideoSDPipelineOutput 而不是普通的元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor
  • clip_skip (int, 可选) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, 可选) — 在推理过程中每个去噪步骤结束时调用的函数。该函数将使用以下参数调用: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

AnimateDiffPipelineOutputtuple

如果 return_dictTrue,则返回 AnimateDiffPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的帧列表。

用于生成的管道的调用函数。

示例

>>> import torch
>>> from diffusers import AnimateDiffPAGPipeline, MotionAdapter, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
>>> motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-2"
>>> motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id)
>>> scheduler = DDIMScheduler.from_pretrained(
...     model_id, subfolder="scheduler", beta_schedule="linear", steps_offset=1, clip_sample=False
... )
>>> pipe = AnimateDiffPAGPipeline.from_pretrained(
...     model_id,
...     motion_adapter=motion_adapter,
...     scheduler=scheduler,
...     pag_applied_layers=["mid"],
...     torch_dtype=torch.float16,
... ).to("cuda")

>>> video = pipe(
...     prompt="car, futuristic cityscape with neon lights, street, no human",
...     negative_prompt="low quality, bad quality",
...     num_inference_steps=25,
...     guidance_scale=6.0,
...     pag_scale=3.0,
...     generator=torch.Generator().manual_seed(42),
... ).frames[0]

>>> export_to_gif(video, "animatediff_pag.gif")

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 (strList[str], 可选) — 待编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[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 表示使用倒数第二层的输出计算提示嵌入。

将提示编码为文本编码器隐藏状态。

HunyuanDiTPAGPipeline

class diffusers.HunyuanDiTPAGPipeline

< >

( vae: AutoencoderKL text_encoder: BertModel tokenizer: BertTokenizer transformer: HunyuanDiT2DModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.stable_diffusion.safety_checker.StableDiffusionSafetyChecker] = None feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None requires_safety_checker: bool = True text_encoder_2: typing.Optional[transformers.models.t5.modeling_t5.T5EncoderModel] = None tokenizer_2: typing.Optional[transformers.models.mt5.tokenization_mt5.MT5Tokenizer] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。我们使用 sdxl-vae-fp16-fix
  • text_encoder (Optional[~transformers.BertModel, ~transformers.CLIPTextModel]) — 冻结文本编码器 (clip-vit-large-patch14)。HunyuanDiT 使用一个经过微调的 [bilingual CLIP]。
  • tokenizer (Optional[~transformers.BertTokenizer, ~transformers.CLIPTokenizer]) — 用于文本分词的 BertTokenizerCLIPTokenizer
  • transformer (HunyuanDiT2DModel) — 腾讯混元设计的 HunyuanDiT 模型。
  • text_encoder_2 (T5EncoderModel) — mT5 嵌入器。具体来说,它是 't5-v1_1-xxl'。
  • tokenizer_2 (MT5Tokenizer) — mT5 嵌入器的分词器。
  • scheduler (DDPMScheduler) — 与 HunyuanDiT 结合使用,用于对编码图像潜在表示去噪的调度器。

使用 HunyuanDiT 和扰动注意力引导进行中英文图像生成。

此模型继承自 DiffusionPipeline。有关库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)的详细信息,请查阅超类文档。

HunyuanDiT 使用两个文本编码器:mT5 和 [双语 CLIP](我们自己微调的)

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = 50 guidance_scale: typing.Optional[float] = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[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 prompt_embeds_2: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None prompt_attention_mask_2: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True 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'] guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = (1024, 1024) target_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) use_resolution_binning: bool = True pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 引导图像生成的提示。如果未定义,则需要传递 prompt_embeds
  • height (int) — 生成图像的高度(像素)。
  • width (int) — 生成图像的宽度(像素)。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会导致更高质量的图像,但推理速度会变慢。此参数受 strength 调制。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但图像质量会降低。当 guidance_scale > 1 时,引导比例启用。
  • negative_prompt (strList[str], 可选) — 引导图像生成时不包含的提示。如果未定义,则需要传递 negative_prompt_embeds。当不使用引导时(guidance_scale < 1),此参数将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个 torch.Generator,用于使生成具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可以轻松调整文本输入(提示权重)。如果未提供,则文本嵌入将从 prompt 输入参数生成。
  • prompt_embeds_2 (torch.Tensor, 可选) — 预生成的文本嵌入。可以轻松调整文本输入(提示权重)。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可以轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_prompt_embeds_2 (torch.Tensor, 可选) — 预生成的负文本嵌入。可以轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • prompt_attention_mask (torch.Tensor, 可选) — 提示的注意力掩码。当直接传递 prompt_embeds 时,此参数为必需。
  • prompt_attention_mask_2 (torch.Tensor, 可选) — 提示的注意力掩码。当直接传递 prompt_embeds_2 时,此参数为必需。
  • negative_prompt_attention_mask (torch.Tensor, 可选) — 负提示的注意力掩码。当直接传递 negative_prompt_embeds 时,此参数为必需。
  • negative_prompt_attention_mask_2 (torch.Tensor, 可选) — 负提示的注意力掩码。当直接传递 negative_prompt_embeds_2 时,此参数为必需。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback_on_step_end (Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks, 可选) — 在每个去噪步骤结束时调用的回调函数或回调函数列表。
  • callback_on_step_end_tensor_inputs (List[str], 可选) — 应该传递给回调函数的张量输入列表。如果未定义,则所有张量输入都将被传递。
  • guidance_rescale (float, 可选, 默认为 0.0) — 根据 guidance_rescale 重新缩放 noise_cfg。基于 Common Diffusion Noise Schedules and Sample Steps are Flawed 的发现。参见第 3.4 节
  • original_size (Tuple[int, int], 可选, 默认为 (1024, 1024)) — 图像的原始大小。用于计算时间 ID。
  • target_size (Tuple[int, int], optional) — 图像的目标大小。用于计算时间 ID。
  • crops_coords_top_left (Tuple[int, int], optional, defaults to (0, 0)) — 裁剪的左上角坐标。用于计算时间 ID。
  • use_resolution_binning (bool, optional, defaults to True) — 是否使用分辨率分箱。如果为 True,输入分辨率将映射到最接近的标准分辨率。支持的分辨率为 1024x1024、1280x1280、1024x768、1152x864、1280x960、768x1024、864x1152、960x1280、1280x768 和 768x1280。建议设置为 True
  • pag_scale (float, optional, defaults to 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, optional, defaults to 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

使用 HunyuanDiT 生成的管线调用函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Tencent-Hunyuan/HunyuanDiT-v1.2-Diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=[14],
... ).to("cuda")

>>> # prompt = "an astronaut riding a horse"
>>> prompt = "一个宇航员在骑马"
>>> image = pipe(prompt, guidance_scale=4, pag_scale=3).images[0]

encode_prompt

< >

( prompt: str device: device = None dtype: dtype = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None max_sequence_length: typing.Optional[int] = None text_encoder_index: int = 0 )

参数

  • prompt (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • dtype (torch.dtype) — torch 数据类型
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1 则忽略),此参数将被忽略。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • prompt_attention_mask (torch.Tensor, 可选) — 提示词的注意力掩码。当直接传入 prompt_embeds 时必需。
  • negative_prompt_attention_mask (torch.Tensor, 可选) — 负面提示词的注意力掩码。当直接传入 negative_prompt_embeds 时必需。
  • max_sequence_length (int, 可选) — 用于提示词的最大序列长度。
  • text_encoder_index (int, 可选) — 要使用的文本编码器索引。0 表示 clip,1 表示 T5。

将提示编码为文本编码器隐藏状态。

KolorsPAGPipeline

diffusers.KolorsPAGPipeline

< >

( vae: AutoencoderKL text_encoder: ChatGLMModel tokenizer: ChatGLMTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = False pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。
  • text_encoder (ChatGLMModel) — 冻结文本编码器。Kolors 使用 ChatGLM3-6B
  • tokenizer (ChatGLMTokenizer) — 类 ChatGLMTokenizer 的分词器。
  • unet (UNet2DConditionModel) — 用于对编码图像潜在表示进行去噪的条件 U-Net 架构。
  • scheduler (SchedulerMixin) — 一个与 unet 结合使用的调度器,用于对编码图像潜在表示进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "False") — 是否强制将负面提示嵌入始终设置为 0。另请参阅 Kwai-Kolors/Kolors-diffusers 的配置。
  • pag_applied_layers (strList[str]``, *可选*, 默认为 “mid”`) — 设置应用扰动注意力引导的 transformer 注意力层。可以是字符串或字符串列表,包括“down”、“mid”、“up”、整个 transformer 块或特定的 transformer 块注意力层,例如:[“mid”][“down”, “mid”] [“down”, “mid”, “up.block_1”][“down”, “mid”, “up.block_1.attentions_0”, “up.block_1.attentions_1”]

使用 Kolors 进行文本到图像生成的管线。

此模型继承自 DiffusionPipeline。有关库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)的详细信息,请查阅超类文档。

该管道还继承了以下加载方法

__call__

< >

( 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 denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 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 pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_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, 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 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 max_sequence_length: int = 256 ) ~pipelines.kolors.KolorsPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 引导图像生成的提示词。如果未定义,则必须传入 prompt_embeds
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。为获得最佳结果,默认设置为 1024。对于 Kwai-Kolors/Kolors-diffusers 和未专门针对低分辨率进行微调的检查点,任何低于 512 像素的值都无法正常工作。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。为获得最佳结果,默认设置为 1024。对于 Kwai-Kolors/Kolors-diffusers 和未专门针对低分辨率进行微调的检查点,任何低于 512 像素的值都无法正常工作。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会生成更高质量的图像,但推理速度会变慢。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义时间步长,适用于支持 set_timesteps 方法中 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 (strList[str], 可选) — 不引导图像生成的提示词。如果未定义,则必须传入 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.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示词调整相同的生成。如果未提供,将通过使用提供的随机 generator 采样生成一个潜在变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化负面提示嵌入将从 negative_prompt 输入参数生成。
  • 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: PIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.kolors.KolorsPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为 self.processor 中定义的 AttentionProcessor 的参数传递到 diffusers.models.attention_processor
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 original_sizetarget_size 不同,图像将显示为缩小或放大。如果未指定,original_size 默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/papers/2307.01952 中 2.2 节所述。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的所需高度和宽度。如果未指定,它将默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 中 2.2 节所述。
  • negative_original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于根据特定图像分辨率对生成过程进行负向条件。作为 SDXL 微观条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节。欲了解更多信息,请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可选, 默认为 (0, 0)) — 用于根据特定裁剪坐标对生成过程进行负向条件。作为 SDXL 微观条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节。欲了解更多信息,请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于根据目标图像分辨率对生成过程进行负向条件。在大多数情况下,它应该与 target_size 相同。作为 SDXL 微观条件的一部分,详见 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节。欲了解更多信息,请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类。参数如下: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale
  • max_sequence_length (int 默认为 256) — 与 prompt 一起使用的最大序列长度。

返回

~pipelines.kolors.KolorsPipelineOutputtuple

如果 return_dict 为 True,则为 ~pipelines.kolors.KolorsPipelineOutput,否则为 tuple。当返回元组时,第一个元素是生成的图像列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "Kwai-Kolors/Kolors-diffusers",
...     variant="fp16",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["down.block_2.attentions_1", "up.block_0.attentions_1"],
... )
>>> pipe = pipe.to("cuda")

>>> prompt = (
...     "A photo of a ladybug, macro, zoom, high quality, film, holding a wooden sign with the text 'KOLORS'"
... )
>>> image = pipe(prompt, guidance_scale=5.5, pag_scale=1.5).images[0]

encode_prompt

< >

( prompt device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 256 )

参数

  • prompt (strList[str], 可选) — 待编码的提示
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即 guidance_scale 小于 1 时),此参数将被忽略。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化 negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • max_sequence_length (int 默认为 256) — 与 prompt 一起使用的最大序列长度。

将提示编码为文本编码器隐藏状态。

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

参数

  • w (torch.Tensor) — 生成具有指定引导尺度的嵌入向量,以随后丰富时间步嵌入。
  • 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

StableDiffusionPAGInpaintPipeline

class diffusers.StableDiffusionPAGInpaintPipeline

< >

( 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 pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 冻结文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于文本分词的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于去噪编码图像潜在的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 用于与 unet 结合去噪编码图像潜在的调度器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 中的一个。
  • safety_checker (StableDiffusionSafetyChecker) — 评估生成图像是否可能具有冒犯性或有害的分类模块。有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

用于使用 Stable Diffusion 进行文本到图像生成的管道。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.9999 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.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[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 (strList[str], 可选) — 引导图像生成时不应包含的提示。如果未定义,则需要传递 negative_prompt_embeds。当不使用引导时(guidance_scale < 1),此参数将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜在变量,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,将使用提供的随机 generator 采样生成潜在张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选): 用于 IP 适配器的可选图像输入。
  • 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.Imagenp.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 的引导重缩放因子。当使用零终端 SNR 时,引导重缩放因子应修复过曝。
  • clip_skip (int, 可选) — 计算提示嵌入时从 CLIP 中跳过的层数。值为 1 表示将使用预最终层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类,带有以下参数: 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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,将不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

用于生成的管道的调用函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForInpainting

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")
>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     strength=0.8,
...     num_inference_steps=50,
...     guidance_scale=guidance_scale,
...     generator=generator,
...     pag_scale=pag_scale,
... ).images[0]

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 (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图片数量
  • do_classifier_free_guidance (bool) — 是否使用分类器无关引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1),则忽略。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • 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

参数

  • w (torch.Tensor) — 生成具有指定引导尺度的嵌入向量,以随后丰富时间步嵌入。
  • 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

StableDiffusionPAGPipeline

diffusers.StableDiffusionPAGPipeline

< >

( 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 pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 冻结文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于对文本进行分词的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码图像潜在表示进行去噪的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 与 unet 结合使用的调度器,用于对编码图像潜在表示进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于评估生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

用于使用 Stable Diffusion 进行文本到图像生成的管道。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

__call__

< >

( 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.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[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], 可选) — 用于去噪过程的自定义 sigma,适用于在其 set_timesteps 方法中支持 sigmas 参数的调度器。如果未定义,将使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导尺度值鼓励模型生成与文本 prompt 密切相关的图像,但会以较低的图像质量为代价。当 guidance_scale > 1 时,启用引导尺度。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含内容的提示词。如果未定义,您需要传递 negative_prompt_embeds。当不使用引导时(guidance_scale < 1),则忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.GeneratorList[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-Adapter 数量相同。每个元素应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,它应该包含负图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 self.processor 中定义的 AttentionProcessor
  • guidance_rescale (float, 可选, 默认为 0.0) — 来自《常见扩散噪声调度和采样步骤的缺陷》的引导重缩放因子。引导重缩放因子应该在零终端 SNR 时修复过度曝光。
  • clip_skip (int, 可选) — 计算提示嵌入时从 CLIP 跳过的层数。值为 1 意味着将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类,具有以下参数: 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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

用于生成的管道的调用函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, enable_pag=True
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]

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 (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[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 表示将使用倒数第二层的输出计算提示词嵌入。

将提示编码为文本编码器隐藏状态。

get_guidance_scale_embedding

< 来源 >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

参数

  • w (torch.Tensor) — 生成带有指定引导比例的嵌入向量,以随后丰富时间步嵌入。
  • 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

StableDiffusionPAGImg2ImgPipeline

class diffusers.StableDiffusionPAGImg2ImgPipeline

< 来源 >

( 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 pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于去噪编码图像潜在的 UNet2DConditionModel
  • scheduler (SchedulerMixin) — 用于与 unet 结合以去噪编码图像潜在的调度器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于估计生成的图像是否可能具有攻击性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

用于使用 Stable Diffusion 进行文本引导的图像到图像生成管道。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

__call__

< 来源 >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.8 num_inference_steps: typing.Optional[int] = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: typing.Optional[float] = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = 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 clip_skip: 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutput or tuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则需要传递 prompt_embeds
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], 或 List[np.ndarray]) — Image、numpy 数组或表示要用作起点的图像批次的张量。对于 numpy 数组和 pytorch 张量,预期值范围在 [0, 1] 之间。如果是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果是 numpy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜在表示作为 image,但如果直接传递潜在表示,则不会再次对其进行编码。
  • strength (float, 可选, 默认为 0.8) — 指示转换参考 image 的程度。必须介于 0 和 1 之间。image 用作起点,strength 越高,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声最大,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。值为 1 基本上忽略了 image
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会导致更高质量的图像,但推理速度会变慢。此参数受 strength 调制。
  • 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 (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则需要传递 negative_prompt_embeds。在使用非引导模式时(guidance_scale < 1),此参数将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成确定性的 torch.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.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通的元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor
  • clip_skip (int, 可选) — 在计算提示词嵌入时,从 CLIP 跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类,具有以下参数: 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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

用于生成的管道的调用函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]

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 (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[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

参数

  • w (torch.Tensor) — 生成带有指定引导尺度的嵌入向量,以便后续丰富时间步嵌入。
  • 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

StableDiffusionControlNetPAGPipeline

diffusers.StableDiffusionControlNetPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码图像潜变量去噪的 UNet2DConditionModel
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪过程中为 unet 提供额外条件。如果您将多个 ControlNet 设置为列表,则每个 ControlNet 的输出会相加,以创建一个组合的额外条件。
  • scheduler (SchedulerMixin) — 与 unet 结合使用以对编码图像潜变量去噪的调度器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 中的一种。
  • safety_checker (StableDiffusionSafetyChecker) — 用于评估生成的图像是否可能具有冒犯性或有害性的分类模块。有关模型潜在危害的更多详细信息,请参阅 模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

使用 Stable Diffusion 和 ControlNet 引导的文本到图像生成管道。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

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 (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[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

参数

  • w (torch.Tensor) — 生成带有指定引导尺度的嵌入向量,以便后续丰富时间步嵌入。
  • 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

StableDiffusionControlNetPAGInpaintPipeline

diffusers.StableDiffusionControlNetPAGInpaintPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor image_encoder: CLIPVisionModelWithProjection = None requires_safety_checker: bool = True pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于标记文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码图像潜变量去噪的 UNet2DConditionModel
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪过程中为 unet 提供额外条件。如果您将多个 ControlNet 设置为列表,则每个 ControlNet 的输出会相加,以创建一个组合的额外条件。
  • scheduler (SchedulerMixin) — 与 unet 结合使用以对编码图像潜变量去噪的调度器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 中的一种。
  • safety_checker (StableDiffusionSafetyChecker) — 用于评估生成的图像是否可能具有冒犯性或有害性的分类模块。有关模型潜在危害的更多详细信息,请参阅 模型卡
  • feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的 CLIPImageProcessor;用作 safety_checker 的输入。

使用 Stable Diffusion 和 ControlNet 引导的图像修复管道。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

此管道可用于专门为修复微调过的检查点 (runwayml/stable-diffusion-inpainting) 以及默认的文本到图像 Stable Diffusion 检查点 (runwayml/stable-diffusion-v1-5)。默认的文本到图像 Stable Diffusion 检查点可能更适合那些基于它们进行微调的 ControlNet,例如 lllyasviel/control_v11p_sd15_inpaint

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 1.0 num_inference_steps: int = 50 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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.5 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,您需要传递 prompt_embeds
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], — List[PIL.Image.Image]List[np.ndarray]): Image、NumPy 数组或表示要用作起始点的图像批处理的张量。对于 NumPy 数组和 PyTorch 张量,预期值范围在 [0, 1] 之间。如果是张量或张量列表,则预期形状应为 (B, C, H, W)(C, H, W)。如果是 NumPy 数组或数组列表,则预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜变量作为 image,但如果直接传递潜变量,则不会再次编码。
  • mask_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], — List[PIL.Image.Image]List[np.ndarray]): Image、NumPy 数组或表示要遮罩 image 的图像批处理的张量。遮罩中白色像素会重绘,而黑色像素会保留。如果 mask_image 是 PIL 图像,它在使用前会转换为单通道(亮度)。如果是 NumPy 数组或 PyTorch 张量,它应该包含一个颜色通道 (L) 而不是 3 个,因此 PyTorch 张量的预期形状为 (B, 1, H, W)(B, H, W)(1, H, W)(H, W)。对于 NumPy 数组,则为 (B, H, W, 1)(B, H, W)(H, W, 1)(H, W)
  • control_image (torch.Tensor, PIL.Image.Image, List[torch.Tensor], List[PIL.Image.Image], — List[List[torch.Tensor]]List[List[PIL.Image.Image]]): ControlNet 输入条件,为 unet 提供生成指导。如果类型指定为 torch.Tensor,则直接传递给 ControlNet。PIL.Image.Image 也可以作为图像接受。输出图像的尺寸默认为 image 的尺寸。如果传递了 height 和/或 width,image 将相应地调整大小。如果在 init 中指定了多个 ControlNet,则图像必须作为列表传递,以便列表的每个元素都可以正确批处理以输入到单个 ControlNet。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(像素)。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(像素)。
  • padding_mask_crop (int, 可选, 默认为 None) — 应用于图像和遮罩的裁剪边距大小。如果为 None,则不应用裁剪。如果 padding_mask_crop 不为 None,它将首先找到一个与图像长宽比相同并包含所有遮罩区域的矩形区域,然后根据 padding_mask_crop 扩展该区域。然后,图像和遮罩图像将根据扩展区域进行裁剪,再调整大小到原始图像尺寸进行修复。当遮罩区域很小而图像很大且包含与修复无关的信息(例如背景)时,这很有用。
  • strength (float, 可选, 默认为 1.0) — 表示转换参考 image 的程度。必须介于 0 和 1 之间。image 用作起点,strength 越高,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声最大,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。值为 1 基本忽略 image
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会生成更高质量的图像,但会以较慢的推理速度为代价。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的指导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但会以较低的图像质量为代价。当 guidance_scale > 1 时,启用指导比例。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不包含内容的提示。如果未定义,则需要传入 negative_prompt_embeds。当不使用引导时(guidance_scale < 1),此参数将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布采样的预生成噪声潜在变量,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,则使用提供的随机 generator 进行采样生成潜在张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选):与 IP 适配器配合使用的可选图像输入。
  • 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.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 self.processor 中定义的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可选, 默认为 0.5) — ControlNet 的输出在添加到原始 unet 中的残差之前,乘以 controlnet_conditioning_scale。如果 init 中指定了多个 ControlNet,您可以将相应的比例设置为列表。
  • control_guidance_start (floatList[float], 可选, 默认为 0.0) — ControlNet 开始应用的步骤总数的百分比。
  • control_guidance_end (floatList[float], 可选, 默认为 1.0) — ControlNet 停止应用的步骤总数的百分比。
  • clip_skip (int, 可选) — 在计算提示嵌入时,要从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类,具有以下参数: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw)内容的 bool 列表。

用于生成的管道的调用函数。

示例

>>> # !pip install transformers accelerate
>>> import cv2
>>> from diffusers import AutoPipelineForInpainting, ControlNetModel, DDIMScheduler
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> from PIL import Image
>>> import torch

>>> init_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
... )
>>> init_image = init_image.resize((512, 512))

>>> generator = torch.Generator(device="cpu").manual_seed(1)

>>> mask_image = load_image(
...     "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
... )
>>> mask_image = mask_image.resize((512, 512))


>>> def make_canny_condition(image):
...     image = np.array(image)
...     image = cv2.Canny(image, 100, 200)
...     image = image[:, :, None]
...     image = np.concatenate([image, image, image], axis=2)
...     image = Image.fromarray(image)
...     return image


>>> control_image = make_canny_condition(init_image)

>>> controlnet = ControlNetModel.from_pretrained(
...     "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
... )
>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, enable_pag=True
... )

>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()

>>> # generate image
>>> image = pipe(
...     "a handsome man with ray-ban sunglasses",
...     num_inference_steps=20,
...     generator=generator,
...     eta=1.0,
...     image=init_image,
...     mask_image=mask_image,
...     control_image=control_image,
...     pag_scale=0.3,
... ).images[0]

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 (strList[str], 可选) — 待编码的提示
  • device — (torch.device):PyTorch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导。
  • negative_prompt (strList[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 表示将使用倒数第二层的输出计算提示嵌入。

将提示编码为文本编码器隐藏状态。

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

参数

  • w (torch.Tensor) — 生成具有指定引导比例的嵌入向量,以随后丰富时间步嵌入。
  • 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

StableDiffusionXLPAGPipeline

class diffusers.StableDiffusionXLPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 变分自动编码器(VAE)模型,用于将图像编码和解码为潜在表示。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器。Stable Diffusion XL 使用 CLIP 的文本部分,特别是 clip-vit-large-patch14 变体。
  • text_encoder_2 (CLIPTextModelWithProjection) — 第二个冻结的文本编码器。Stable Diffusion XL 使用 CLIP 的文本和池化部分,特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • tokenizer (CLIPTokenizer) — 类别 CLIPTokenizer 的分词器。
  • tokenizer_2 (CLIPTokenizer) — 第二个类别 CLIPTokenizer 的分词器。
  • unet (UNet2DConditionModel) — 用于对编码图像潜在变量进行去噪的条件 U-Net 架构。
  • scheduler (SchedulerMixin) — 用于与 unet 结合使用的调度器,以对编码图像潜在变量进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "True") — 负面提示嵌入是否应始终强制设置为 0。另请参阅 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库 为输出图像添加水印。如果未定义,如果安装了该软件包,则默认为 True,否则不使用水印。

用于使用 Stable Diffusion XL 进行文本到图像生成的管道。

此模型继承自 DiffusionPipeline。有关库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)的详细信息,请查阅超类文档。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = 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 denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 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, 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 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传递 prompt_embeds
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则 prompt 将用于这两个文本编码器。
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(像素)。为获得最佳效果,默认设置为 1024。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未专门针对低分辨率进行微调的模型检查点,低于 512 像素的任何值都无法很好地工作。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(像素)。为获得最佳效果,默认设置为 1024。对于 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], 可选) — 自定义 sigma,用于去噪过程,适用于其 set_timesteps 方法支持 sigmas 参数的调度器。如果未定义,将使用传递 num_inference_steps 时的默认行为。
  • denoising_end (float, 可选) — 指定后,确定在故意提前终止之前要完成的总去噪过程的分数(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留由调度器选择的离散时间步长确定的噪声量。当此管道作为“去噪器混合”多管道设置的一部分使用时,理想情况下应使用 denoising_end 参数,如图像输出优化中所述。
  • guidance_scale (float, 可选, 默认为 5.0) — 无分类器扩散引导中定义的引导比例。guidance_scaleImagen 论文的公式 2 中定义为 w。通过设置 guidance_scale > 1 启用引导比例。较高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲较低图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1),则忽略。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成并发送到 tokenizer_2text_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.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成确定。
  • latents (torch.Tensor, 可选) — 预生成的带噪声隐变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,将使用提供的随机 generator 采样生成隐变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,负文本嵌入将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化负文本嵌入将从 negative_prompt 输入参数生成。
  • 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") — 生成图像的输出格式。选择 PILPIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则作为 AttentionProcessor 传递给 diffusers.models.attention_processor 中的 self.processor
  • guidance_rescale (float, 可选, 默认为 0.0) — 常见扩散噪声调度和采样步长存在缺陷中提出的引导重定标因子。guidance_scale常见扩散噪声调度和采样步长存在缺陷的公式 16 中定义为 φ。引导重定标因子应在零末端信噪比(SNR)下修复过度曝光问题。
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 original_sizetarget_size 不同,图像将显示为缩小或放大。如果未指定,original_size 默认为 (height, width)。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/papers/2307.01952 的 2.2 节所述。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的期望高度和宽度。如果未指定,则默认为 (height, width)。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。
  • negative_original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于基于特定图像分辨率对生成过程进行负条件。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。更多信息请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可选, 默认为 (0, 0)) — 用于基于特定裁剪坐标对生成过程进行负条件。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。更多信息请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于基于目标图像分辨率对生成过程进行负条件。在大多数情况下应与 target_size 相同。作为 SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。更多信息请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • callback_on_step_end (Callable, 可选) — 在推理过程中每个去噪步骤结束时调用的函数。该函数通过以下参数调用: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput,否则返回 tuple。返回元组时,第一个元素是生成的图像列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, pag_scale=0.3).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则 prompt 将用于这两个文本编码器。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1),则忽略。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成并发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则 negative_prompt 将用于这两个文本编码器。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,负文本嵌入将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从`negative_prompt`输入参数生成池化负向提示词嵌入。
  • lora_scale (float, optional) — 如果加载了LoRA层,则应用于文本编码器所有LoRA层的LoRA比例。
  • clip_skip (int, optional) — 从CLIP中跳过的层数,用于计算提示词嵌入。值为1表示使用倒数第二层的输出计算提示词嵌入。

将提示编码为文本编码器隐藏状态。

get_guidance_scale_embedding

< >

( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) torch.Tensor

参数

  • w (torch.Tensor) — 生成具有指定引导尺度的嵌入向量,以随后丰富时间步嵌入。
  • embedding_dim (int, optional, 默认为512) — 要生成的嵌入的维度。
  • dtype (torch.dtype, optional, 默认为torch.float32) — 生成嵌入的数据类型。

返回

torch.Tensor

形状为 (len(w), embedding_dim) 的嵌入向量。

请参阅 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

StableDiffusionXLPAGImg2ImgPipeline

class diffusers.StableDiffusionXLPAGImg2ImgPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器(VAE)模型。
  • text_encoder (CLIPTextModel) — 冻结文本编码器。Stable Diffusion XL使用CLIP的文本部分,特别是clip-vit-large-patch14变体。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二个冻结文本编码器。Stable Diffusion XL使用CLIP的文本和池化部分,特别是laion/CLIP-ViT-bigG-14-laion2B-39B-b160k变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 类的第二个分词器。
  • unet (UNet2DConditionModel) — 用于对编码图像潜变量进行去噪的条件U-Net架构。
  • scheduler (SchedulerMixin) — 一个与unet结合使用以去噪编码图像潜变量的调度器。可以是DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler之一。
  • requires_aesthetics_score (bool, optional, 默认为"False") — unet在推理期间是否需要传递aesthetic_score条件。另请参阅stabilityai/stable-diffusion-xl-refiner-1-0的配置。
  • force_zeros_for_empty_prompt (bool, optional, 默认为"True") — 负向提示词嵌入是否应始终强制设置为0。另请参阅stabilityai/stable-diffusion-xl-base-1-0的配置。
  • add_watermarker (bool, optional) — 是否使用invisible_watermark 库为输出图像添加水印。如果未定义,则在安装了该软件包的情况下默认为True,否则不使用水印器。

用于使用 Stable Diffusion XL 进行文本到图像生成的管道。

此模型继承自 DiffusionPipeline。有关库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)的详细信息,请查阅超类文档。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.3 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 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, 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 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须传递 prompt_embeds
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示词或提示词列表。如果未定义,则 prompt 将用于两个文本编码器。
  • image (torch.TensorPIL.Image.Imagenp.ndarrayList[torch.Tensor]List[PIL.Image.Image]List[np.ndarray]) — 要通过管道修改的图像。
  • strength (float, 可选, 默认为0.3) — 概念上表示对参考 image 的转换程度。必须在0到1之间。image 将作为起点,strength 越大,添加的噪声越多。去噪步数取决于最初添加的噪声量。当 strength 为1时,添加的噪声将达到最大值,去噪过程将运行 num_inference_steps 中指定的所有迭代次数。因此,值为1基本上会忽略 image。请注意,如果 denoising_start 被声明为整数,则 strength 的值将被忽略。
  • num_inference_steps (int, 可选, 默认为50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义时间步,适用于其 set_timesteps 方法支持 timesteps 参数的调度器。如果未定义,将使用传递 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], 可选) — 用于去噪过程的自定义sigmas,适用于其 set_timesteps 方法支持 sigmas 参数的调度器。如果未定义,将使用传递 num_inference_steps 时的默认行为。
  • denoising_start (float, 可选) — 当指定时,表示在去噪过程开始前,要跳过的去噪过程总量的百分比(0.0到1.0之间)。因此,去噪过程的初始部分被跳过,并假定传入的 image 是部分去噪的图像。请注意,当指定此参数时,强度将被忽略。denoising_start 参数在此管道集成到“去噪器混合”多管道设置中时特别有用,详见优化图像质量
  • denoising_end (float, 可选) — 当指定时,确定在去噪过程有意提前终止之前要完成的去噪过程总量的百分比(0.0到1.0之间)。因此,返回的样本仍将保留大量噪声(大约还需要最后20%的时间步),应由设置了 denoising_start 为 0.8 的后续管道去噪,以便它只去噪调度器的最后20%。当此管道构成“去噪器混合”多管道设置的一部分时,应理想地利用 denoising_end 参数,如优化图像质量中所述。
  • guidance_scale (float, 可选, 默认为7.5) — 无分类器扩散引导中定义的引导比例。guidance_scale 定义为Imagen Paper中公式2的 w。通过设置 guidance_scale > 1 启用引导比例。更高的引导比例会促使生成与文本 prompt 紧密相关的图像,通常以牺牲图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词或提示词列表。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时(即,如果 guidance_scale 小于 1 时)将被忽略。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成,要发送到 tokenizer_2text_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.GeneratorList[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 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选): 用于IP适配器的可选图像输入。
  • 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.Imagenp.array
  • return_dict (bool, 可选, 默认为True) — 是否返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 self.processorAttentionProcessor
  • guidance_rescale (float, 可选, 默认为 0.0) — 由 Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的指导重缩放因子,guidance_scaleCommon Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定义为 φ。当使用零终端信噪比时,指导重缩放因子应能解决过度曝光问题。
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 original_sizetarget_size 不同,图像将显示为缩小或放大。如果未指定,original_size 默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/papers/2307.01952 的 2.2 节所述。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的所需高度和宽度。如果未指定,它将默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。
  • negative_original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 根据特定图像分辨率对生成过程进行负面条件化。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。更多信息请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可选, 默认为 (0, 0)) — 根据特定裁剪坐标对生成过程进行负面条件化。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。更多信息请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 根据目标图像分辨率对生成过程进行负面条件化。在大多数情况下,它应该与 target_size 相同。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。更多信息请参阅此问题讨论串:https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, 可选, 默认为 6.0) — 通过影响正文本条件来模拟生成图像的美学分数。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。
  • negative_aesthetic_score (float, 可选, 默认为 2.5) — SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节所述。可用于通过影响负文本条件来模拟生成图像的美学分数。
  • clip_skip (int, 可选) — 在计算提示嵌入时,从 CLIP 跳过的层数。值为 1 意味着将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 一个函数或 PipelineCallbackMultiPipelineCallbacks 的子类,在推理期间每个去噪步骤结束时调用,参数如下: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的缩放因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应缩放因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

如果 return_dict 为 True,则为 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput;否则为 tuple。当返回元组时,第一个元素是生成的图像列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForImage2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-refiner-1.0",
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示。如果未定义,则 prompt 将在两个文本编码器中使用。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1,则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_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 输入参数生成。
  • 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

参数

  • w (torch.Tensor) — 生成具有指定引导尺度的嵌入向量,以随后丰富时间步嵌入。
  • 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

StableDiffusionXLPAGInpaintPipeline

class diffusers.StableDiffusionXLPAGInpaintPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器(VAE)模型。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器。Stable Diffusion XL 使用 CLIP 的文本部分,特别是 clip-vit-large-patch14 变体。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二个冻结的文本编码器。Stable Diffusion XL 使用 CLIP 的文本和池化部分,特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 类的第二个分词器。
  • unet (UNet2DConditionModel) — 用于对编码图像潜在进行去噪的条件 U-Net 架构。
  • scheduler (SchedulerMixin) — 与 unet 结合使用以对编码图像潜在进行去噪的调度器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • requires_aesthetics_score (bool, 可选, 默认为 "False") — unet 在推理期间是否需要传递美学分数条件。另请参见 stabilityai/stable-diffusion-xl-refiner-1-0 的配置。
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "True") — 是否强制将负提示嵌入始终设置为 0。另请参见 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库 为输出图像添加水印。如果未定义,则在安装该软件包时默认为 True,否则不使用水印。

用于使用 Stable Diffusion XL 进行文本到图像生成的管道。

此模型继承自 DiffusionPipeline。有关库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)的详细信息,请查阅超类文档。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.9999 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 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, 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 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示。如果未定义,则必须传递 prompt_embeds
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示。如果未定义,则 prompt 将在两个文本编码器中使用。
  • 图像 (PIL.Image.Image) — 图像,或表示图像批次的张量,将进行修复,即图像的某些部分将用 mask_image 遮罩并根据 prompt 重新绘制。
  • mask_image (PIL.Image.Image) — 图像,或表示图像批次的张量,用于遮罩 image。遮罩中的白色像素将被重新绘制,而黑色像素将保留。如果 mask_image 是 PIL 图像,则在使用前将转换为单通道(亮度)。如果是张量,则应包含一个颜色通道(L)而不是 3 个,因此预期形状为 (B, H, W, 1)
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素高度。为获得最佳效果,默认设置为 1024。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未专门针对低分辨率进行微调的检查点,低于 512 像素的任何值都不会很好地工作。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的像素宽度。为获得最佳效果,默认设置为 1024。对于 stabilityai/stable-diffusion-xl-base-1.0 以及未专门针对低分辨率进行微调的检查点,低于 512 像素的任何值都不会很好地工作。
  • padding_mask_crop (int, 可选, 默认为 None) — 对图像和遮罩应用的裁剪边距大小。如果为 None,则不对图像和 mask_image 应用裁剪。如果 padding_mask_crop 不为 None,它将首先找到一个与图像纵横比相同且包含所有遮罩区域的矩形区域,然后根据 padding_mask_crop 扩展该区域。然后将图像和 mask_image 根据扩展区域进行裁剪,然后调整大小以适应原始图像大小进行修复。当遮罩区域较小而图像较大且包含与修复无关的信息(例如背景)时,这很有用。
  • strength (float, 可选, 默认为 0.9999) — 概念上,表示参考 image 的遮罩部分转换程度。必须介于 0 和 1 之间。image 将用作起点,strength 越大,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声将最大,去噪过程将运行 num_inference_steps 中指定的全部迭代次数。因此,值为 1 基本上会忽略参考 image 的遮罩部分。请注意,如果 denoising_start 声明为整数,则将忽略 strength 的值。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但推理速度较慢。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义时间步,适用于支持 set_timesteps 方法中 timesteps 参数的调度器。如果未定义,将使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], 可选) — 用于去噪过程的自定义 sigmas,适用于支持 set_timesteps 方法中 sigmas 参数的调度器。如果未定义,将使用传入 num_inference_steps 时的默认行为。
  • denoising_start (float, 可选) — 指定后,表示在去噪过程开始前跳过的总去噪过程的比例(0.0 到 1.0 之间)。因此,去噪过程的初始部分被跳过,并假定传入的 image 是部分去噪的图像。请注意,当指定此参数时,将忽略 strength。denoising_start 参数在将此管道集成到“混合去噪器”多管道设置中时特别有用,如 优化图像输出 中所详述。
  • denoising_end (float, 可选) — 指定后,决定在去噪过程有意提前终止前完成的总去噪过程的比例(0.0 到 1.0 之间)。因此,返回的样本仍将保留大量噪声(大约最后 20% 的时间步仍需),并且应由一个将 denoising_start 设置为 0.8 的后续管道去噪,以便它只去噪调度器的最后 20%。denoising_end 参数理想情况下应在此管道作为“去噪器混合”多管道设置的一部分时使用,如 优化图像输出 中所详述。
  • guidance_scale (float, 可选, 默认为 7.5) — 分类器自由扩散引导中定义的引导比例。guidance_scale 定义为 Imagen Paper 方程 2 中的 w。通过设置 guidance_scale > 1 来启用引导比例。更高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示。如果未定义,则必须传入 negative_prompt_embeds。在不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成,将发送到 tokenizer_2text_encoder_2 的提示。如果未定义,则在两个文本编码器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将根据 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,则将根据 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将根据 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将根据 negative_prompt 输入参数生成池化负文本嵌入。
  • ip_adapter_image — (PipelineImageInput, 可选): 与 IP 适配器配合使用的可选图像输入。
  • 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 输入参数计算嵌入。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.Generator, 可选) — 一个或多个 torch 生成器,使生成具有确定性。
  • latents (torch.Tensor, 可选) — 预生成的带噪潜像,从高斯分布中采样,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,则将通过使用提供的随机 generator 采样生成一个潜像张量。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。当返回元组时,第一个元素是包含生成图像的列表。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为 AttentionProcessor 传递给 diffusers.models.attention_processor 中定义的 self.processor
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 original_sizetarget_size 不相同,图像将显示为下采样或上采样。如果未指定,original_size 默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/papers/2307.01952 第 2.2 节所述。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的所需高度和宽度。如果未指定,它将默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于根据特定图像分辨率对生成过程进行负面调节。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可选, 默认为 (0, 0)) — 用于根据特定裁剪坐标对生成过程进行负面调节。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于根据目标图像分辨率对生成过程进行负面调节。在大多数情况下,它应该与 target_size 相同。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, 可选, 默认为 6.0) — 通过影响正向文本条件来模拟生成图像的美学分数。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_aesthetic_score (float, 可选, 默认为 2.5) — SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。可用于通过影响负文本条件来模拟生成图像的美学分数。
  • clip_skip (int, 可选) — 计算提示嵌入时从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理期间每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类,具有以下参数: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

如果 return_dict 为 True,则为 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput,否则为 tuple。当返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForInpainting
>>> from diffusers.utils import load_image

>>> pipe = AutoPipelineForInpainting.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     torch_dtype=torch.float16,
...     variant="fp16",
...     enable_pag=True,
... )
>>> pipe.to("cuda")

>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"

>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")

>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
...     prompt=prompt,
...     image=init_image,
...     mask_image=mask_image,
...     num_inference_steps=50,
...     strength=0.80,
...     pag_scale=0.3,
... ).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 待编码的提示
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示。如果未定义,则在两个文本编码器中都使用 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[str], 可选) — 不用于指导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用指导时(即,如果 guidance_scale 小于 1 时),此参数会被忽略。
  • negative_prompt_2 (strList[str], 可选) — 不用于指导图像生成的提示词,将发送到 tokenizer_2text_encoder_2。如果未定义,则在两个文本编码器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据 negative_prompt 输入参数生成负向提示词嵌入。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将根据 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

参数

  • w (torch.Tensor) — 生成具有指定指导尺度的嵌入向量,以随后丰富时间步长嵌入。
  • 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

StableDiffusionXLControlNetPAGPipeline

class diffusers.StableDiffusionXLControlNetPAGPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • text_encoder_2 (CLIPTextModelWithProjection) — 第二个冻结的文本编码器 (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)。
  • tokenizer (CLIPTokenizer) — 用于标记化文本的 CLIPTokenizer
  • tokenizer_2 (CLIPTokenizer) — 用于标记化文本的 CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码图像潜在表示进行去噪的 UNet2DConditionModel
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪过程中为 unet 提供额外条件。如果您将多个 ControlNet 设置为列表,则每个 ControlNet 的输出将被相加,以创建组合的额外条件。
  • scheduler (SchedulerMixin) — 与 unet 结合使用的调度器,用于对编码图像潜在表示进行去噪。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "True") — 是否应始终将负向提示词嵌入设置为 0。另请参阅 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库为输出图像添加水印。如果未定义,则在安装该包时默认为 True;否则不使用水印。

使用 Stable Diffusion XL 和 ControlNet 指导的文本到图像生成流水线。

此模型继承自 DiffusionPipeline。请查阅超类文档,了解所有管道实现的通用方法(下载、保存、在特定设备上运行等)。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = 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 denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 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, 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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于指导图像生成的提示词。如果未定义,需要传入 prompt_embeds
  • prompt_2 (strList[str], 可选) — 发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则在两个文本编码器中都使用 prompt
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): ControlNet 的输入条件,用于指导 unet 进行生成。如果类型指定为 torch.Tensor,则按原样传递给 ControlNet。PIL.Image.Image 也可以作为图像接受。输出图像的尺寸默认为 image 的尺寸。如果传入了 height 和/或 width,则 image 将相应地调整大小。如果在 init 中指定了多个 ControlNet,则必须将图像作为列表传入,以便列表的每个元素都可以正确地批处理以输入到单个 ControlNet。
  • 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], 可选) — 用于去噪过程的自定义时间步长,适用于在 set_timesteps 方法中支持 timesteps 参数的调度器。如果未定义,将使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], 可选) — 用于去噪过程的自定义 sigma 值,适用于在 set_timesteps 方法中支持 sigmas 参数的调度器。如果未定义,将使用传入 num_inference_steps 时的默认行为。
  • denoising_end (float, 可选) — 指定时,决定在去噪过程有意提前终止之前完成的总去噪过程的分数(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留由调度器选择的离散时间步长确定的相当数量的噪声。当此流水线作为“去噪器混合”多流水线设置的一部分时,应理想地使用 denoising_end 参数,详见 精炼图像输出
  • guidance_scale (float, 可选, 默认为 5.0) — 较高的指导尺度值鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时,启用指导尺度。
  • negative_prompt (strList[str], 可选) — 用于指导图像生成时不包含的内容的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用指导时(guidance_scale < 1),此参数会被忽略。
  • negative_prompt_2 (strList[str], 可选) — 用于指导图像生成时不包含的内容的提示词。此参数将发送到 tokenizer_2text_encoder_2。如果未定义,则在两个文本编码器中都使用 negative_prompt
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的 eta (η) 参数。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • 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_embeds` 将从 `negative_prompt` 输入参数生成。
  • 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.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 如果指定,则作为 kwargs 字典传递给 self.processor 中定义的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可选, 默认为 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,将乘以 `controlnet_conditioning_scale`。如果在 `init` 中指定了多个 ControlNet,则可以将其对应的比例设置为列表。
  • control_guidance_start (floatList[float], 可选, 默认为 0.0) — ControlNet 开始应用的步数总百分比。
  • control_guidance_end (floatList[float], 可选, 默认为 1.0) — ControlNet 停止应用的步数总百分比。
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 `original_size` 与 `target_size` 不同,则图像将显示为下采样或上采样。如果未指定,`original_size` 默认为 `(height, width)`。SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/papers/2307.01952 第 2.2 节所述。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,`target_size` 应该设置为生成图像的所需高度和宽度。如果未指定,它将默认为 `(height, width)`。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 根据特定图像分辨率对生成过程进行负条件。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], 可选, 默认为 (0, 0)) — 根据特定的裁剪坐标对生成过程进行负条件。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 根据目标图像分辨率对生成过程进行负条件。在大多数情况下应与 `target_size` 相同。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • clip_skip (int, 可选) — 计算提示嵌入时要跳过的CLIP层数。值为 1 意味着将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 一个函数或 PipelineCallbackMultiPipelineCallbacks 的子类,在推理过程中每个去噪步骤结束时调用。参数如下:`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` 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 `pag_scale`。

返回

StableDiffusionPipelineOutputtuple

如果 `return_dict` 为 `True`,则返回 StableDiffusionPipelineOutput,否则返回包含输出图像的 tuple

用于生成的管道的调用函数。

示例

>>> # !pip install opencv-python transformers accelerate
>>> from diffusers import AutoPipelineForText2Image, ControlNetModel, AutoencoderKL
>>> from diffusers.utils import load_image
>>> import numpy as np
>>> import torch

>>> import cv2
>>> from PIL import Image

>>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
>>> negative_prompt = "low quality, bad quality, sketches"

>>> # download an image
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
... )

>>> # initialize the models and pipeline
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()

>>> # get canny image
>>> image = np.array(image)
>>> image = cv2.Canny(image, 100, 200)
>>> image = image[:, :, None]
>>> image = np.concatenate([image, image, image], axis=2)
>>> canny_image = Image.fromarray(image)

>>> # generate image
>>> image = pipe(
...     prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image, pag_scale=0.3
... ).images[0]

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示。
  • prompt_2 (strList[str], 可选) — 要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示或提示列表。如果未定义,`prompt` 将用于两个文本编码器。
  • device — (torch.device):torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量。
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导。
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示或提示列表。如果未定义,则必须传递 `negative_prompt_embeds`。不使用引导时(即,如果 `guidance_scale` 小于 `1`),则忽略。
  • negative_prompt_2 (strList[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_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

参数

  • w (torch.Tensor) — 生成具有指定引导比例的嵌入向量,以随后丰富时间步嵌入。
  • 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

StableDiffusionXLControlNetPAGImg2ImgPipeline

class diffusers.StableDiffusionXLControlNetPAGImg2ImgPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: UNet2DConditionModel controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers requires_aesthetics_score: bool = False force_zeros_for_empty_prompt: bool = True add_watermarker: typing.Optional[bool] = None feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None pag_applied_layers: typing.Union[str, typing.List[str]] = 'mid' )

参数

  • vae (AutoencoderKL) — 用于编码和解码图像到潜在表示的变分自动编码器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 冻结文本编码器。Stable Diffusion 使用 CLIP 的文本部分,特别是 clip-vit-large-patch14 变体。
  • text_encoder_2 ( CLIPTextModelWithProjection) — 第二个冻结文本编码器。Stable Diffusion XL 使用 CLIP 的文本和池化部分,特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 类的第二个分词器。
  • unet (UNet2DConditionModel) — 用于对编码图像潜在进行去噪的条件 U-Net 架构。
  • controlnet (ControlNetModelList[ControlNetModel]) — 在去噪过程中为 unet 提供额外的条件。如果将多个 ControlNet 设置为列表,则每个 ControlNet 的输出将相加,以创建一个组合的额外条件。
  • scheduler (SchedulerMixin) — 用于与 `unet` 结合对编码图像潜在进行去噪的调度器。可以是 DDIMSchedulerLMSDiscreteSchedulerPNDMScheduler 之一。
  • requires_aesthetics_score (bool, 可选, 默认为 "False") — `unet` 在推理过程中是否需要传递 `aesthetic_score` 条件。另请参阅 `stabilityai/stable-diffusion-xl-refiner-1-0` 的配置。
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "True") — 是否强制将负提示嵌入始终设置为 0。另请参阅 `stabilityai/stable-diffusion-xl-base-1-0` 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库 对输出图像添加水印。如果未定义,如果安装了该软件包,则默认为 True,否则不使用水印。
  • feature_extractor (CLIPImageProcessor) — 用于从生成图像中提取特征的 CLIPImageProcessor;用作 `safety_checker` 的输入。

使用 Stable Diffusion XL 和 ControlNet 引导的图像到图像生成管道。

此模型继承自 DiffusionPipeline。有关库为所有管道实现通用方法(例如下载或保存、在特定设备上运行等)的详细信息,请查阅超类文档。

该管道还继承了以下加载方法

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.8 num_inference_steps: int = 50 guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: 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 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, 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 controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 0.8 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 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'] pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则必须传入 prompt_embeds
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则 prompt 将用于两个文本编码器。
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): 初始图像将作为图像生成过程的起点。如果直接传入潜在变量,也可以接受图像潜在变量作为 image,它将不会再次编码。
  • control_image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], List[np.ndarray], — List[List[torch.Tensor]], List[List[np.ndarray]]List[List[PIL.Image.Image]]): ControlNet 输入条件。ControlNet 使用此输入条件来生成对 Unet 的引导。如果类型指定为 torch.Tensor,则按原样传递给 ControlNet。PIL.Image.Image 也可以作为图像接受。输出图像的尺寸默认为 image 的尺寸。如果传入 height 和/或 width,则 image 将根据它们调整大小。如果在初始化中指定了多个 ControlNet,则图像必须作为列表传入,以便列表的每个元素可以正确批处理以输入到单个 ControlNet。
  • height (int, 可选, 默认为 control_image 的大小) — 生成图像的像素高度。低于 512 像素的任何图像对于 stabilityai/stable-diffusion-xl-base-1.0 和未专门针对低分辨率进行微调的检查点效果不佳。
  • width (int, 可选, 默认为 control_image 的大小) — 生成图像的像素宽度。低于 512 像素的任何图像对于 stabilityai/stable-diffusion-xl-base-1.0 和未专门针对低分辨率进行微调的检查点效果不佳。
  • strength (float, 可选, 默认为 0.8) — 指示转换参考 image 的程度。必须介于 0 和 1 之间。image 用作起点,strength 越高,添加的噪声越多。去噪步骤的数量取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声最大,去噪过程将运行 num_inference_steps 中指定的全部迭代次数。值为 1 基本上忽略了 image
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会生成更高质量的图像,但会以较慢的推理速度为代价。
  • guidance_scale (float, 可选, 默认为 7.5) — 如 Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 启用引导尺度。较高的引导尺度鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成并发送到 tokenizer_2text_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.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预生成的带噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,将使用提供的随机 generator 采样生成潜在变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化 negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选): 与 IP 适配器配合使用的可选图像输入。
  • 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") — 生成图像的输出格式。选择 PILPIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是纯元组。
  • cross_attention_kwargs (dict, 可选) — 如果指定,此 kwargs 字典将传递给 diffusers.models.attention_processorself.processor 定义的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], 可选, 默认为 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前乘以 controlnet_conditioning_scale。如果在初始化中指定了多个 ControlNet,则可以将其相应的比例设置为列表。
  • guess_mode (bool, 可选, 默认为 False) — 在此模式下,即使您删除所有提示词,ControlNet 编码器也会尽力识别输入图像的内容。建议 guidance_scale 在 3.0 到 5.0 之间。
  • control_guidance_start (floatList[float], 可选, 默认为 0.0) — ControlNet 开始应用的总体步骤的百分比。
  • control_guidance_end (floatList[float], 可选, 默认为 1.0) — ControlNet 停止应用的总体步骤的百分比。
  • original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 如果 original_sizetarget_size 不相同,则图像将显示为下采样或上采样。如果未指定,original_size 默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/papers/2307.01952 第 2.2 节所述。
  • target_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽高。如果未指定,则默认为 (height, width)。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (Tuple[int], 可选, 默认为 (1024, 1024)) — 用于基于特定图像分辨率对生成过程进行负面条件设置。SDXL 微条件的一部分,如 https://huggingface.ac.cn/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.ac.cn/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.ac.cn/papers/2307.01952 第 2.2 节所述。更多信息请参阅此 issue 线程:https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, 可选, 默认为 6.0) — 通过影响正文本条件来模拟生成图像的美学分数。SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_aesthetic_score (float, 可选, 默认为 2.5) — SDXL 微条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。可用于通过影响负文本条件来模拟生成图像的美学分数。
  • clip_skip (int, 可选) — 计算提示词嵌入时要从 CLIP 跳过的层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数或 PipelineCallbackMultiPipelineCallbacks 的子类。参数如下: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 属性中列出的变量。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

如果 return_dict 为 True,则为 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput,否则为包含输出图像的 tuple

调用管道进行生成时调用的函数。

示例

>>> # pip install accelerate transformers safetensors diffusers

>>> import torch
>>> import numpy as np
>>> from PIL import Image

>>> from transformers import DPTFeatureExtractor, DPTForDepthEstimation
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetPAGImg2ImgPipeline, AutoencoderKL
>>> from diffusers.utils import load_image


>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
>>> feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
>>> controlnet = ControlNetModel.from_pretrained(
...     "diffusers/controlnet-depth-sdxl-1.0-small",
...     variant="fp16",
...     use_safetensors="True",
...     torch_dtype=torch.float16,
... )
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
>>> pipe = StableDiffusionXLControlNetPAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-xl-base-1.0",
...     controlnet=controlnet,
...     vae=vae,
...     variant="fp16",
...     use_safetensors=True,
...     torch_dtype=torch.float16,
...     enable_pag=True,
... )
>>> pipe.enable_model_cpu_offload()


>>> def get_depth_map(image):
...     image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
...     with torch.no_grad(), torch.autocast("cuda"):
...         depth_map = depth_estimator(image).predicted_depth

...     depth_map = torch.nn.functional.interpolate(
...         depth_map.unsqueeze(1),
...         size=(1024, 1024),
...         mode="bicubic",
...         align_corners=False,
...     )
...     depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
...     depth_map = (depth_map - depth_min) / (depth_max - depth_min)
...     image = torch.cat([depth_map] * 3, dim=1)
...     image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
...     image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
...     return image


>>> prompt = "A robot, 4k photo"
>>> image = load_image(
...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
...     "/kandinsky/cat.png"
... ).resize((1024, 1024))
>>> controlnet_conditioning_scale = 0.5  # recommended for good generalization
>>> depth_image = get_depth_map(image)

>>> images = pipe(
...     prompt,
...     image=image,
...     control_image=depth_image,
...     strength=0.99,
...     num_inference_steps=50,
...     controlnet_conditioning_scale=controlnet_conditioning_scale,
... ).images
>>> images[0].save(f"robot_cat.png")

encode_prompt

< >

( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = 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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示词
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则 prompt 将用于两个文本编码器。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导。
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的不引导图像生成的提示词。如果未定义,则在两个文本编码器中都使用 negative_prompt
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 negative_prompt 输入参数生成负面提示词嵌入。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 negative_prompt 输入参数生成池化负面提示词嵌入。
  • lora_scale (float, 可选) — 将应用于文本编码器的所有 LoRA 层的 LoRA 缩放因子(如果已加载 LoRA 层)。
  • clip_skip (int, 可选) — 计算提示词嵌入时要跳过的 CLIP 层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。

将提示编码为文本编码器隐藏状态。

StableDiffusion3PAGPipeline

class diffusers.StableDiffusion3PAGPipeline

< >

( transformer: SD3Transformer2DModel scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModelWithProjection tokenizer: CLIPTokenizer text_encoder_2: CLIPTextModelWithProjection tokenizer_2: CLIPTokenizer text_encoder_3: T5EncoderModel tokenizer_3: T5TokenizerFast pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

参数

  • transformer (SD3Transformer2DModel) — 用于对编码图像潜在空间进行去噪的条件 Transformer (MMDiT) 架构。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 与 transformer 结合使用的调度器,用于对编码图像潜在空间进行去噪。
  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
  • text_encoder (CLIPTextModelWithProjection) — CLIP,特别是 clip-vit-large-patch14 变体,增加了投影层,其初始化为以 hidden_size 为维度的对角矩阵。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP,特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • text_encoder_3 (T5EncoderModel) — 冻结文本编码器。Stable Diffusion 3 使用 T5,特别是 t5-v1_1-xxl 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 类的第二个分词器。
  • tokenizer_3 (T5TokenizerFast) — T5Tokenizer 类的分词器。

PAG pipeline 用于使用 Stable Diffusion 3 进行文本到图像生成。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 引导图像生成的提示词。如果未定义,则必须传入 prompt_embeds
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则将使用 prompt
  • prompt_3 (strList[str], 可选) — 要发送到 tokenizer_3text_encoder_3 的提示词。如果未定义,则将使用 prompt
  • height (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(像素)。为获得最佳效果,此值默认为 1024。
  • width (int, 可选, 默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(像素)。为获得最佳效果,此值默认为 1024。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • sigmas (List[float], 可选) — 用于去噪过程的自定义 sigmas,与支持 sigmas 参数的调度器结合使用,在其 set_timesteps 方法中。如果未定义,将使用传入 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale 定义为 Imagen Paper 方程式 2 中的 w。通过设置 guidance_scale > 1 启用引导比例。较高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的不引导图像生成的提示词。如果未定义,则将使用 negative_prompt
  • negative_prompt_3 (strList[str], 可选) — 要发送到 tokenizer_3text_encoder_3 的不引导图像生成的提示词。如果未定义,则将使用 negative_prompt
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或多个 torch generator(s),用于使生成具有确定性。
  • latents (torch.FloatTensor, 可选) — 预生成的带噪潜在空间,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,则将通过使用提供的随机 generator 进行采样来生成潜在空间张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,负面提示词嵌入将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,池化负面提示词嵌入将从 negative_prompt 输入参数生成。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 如果指定,则传递给 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor 的 kwargs 字典。
  • callback_on_step_end (Callable, 可选) — 在推理期间每个去噪步骤结束时调用的函数。函数调用时带以下参数: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 属性中列出的变量。
  • max_sequence_length (int 默认为 256) — 与 prompt 一起使用的最大序列长度。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的缩放因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应缩放因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

如果 return_dict 为 True,则为 ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput,否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     enable_pag=True,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt, guidance_scale=5.0, pag_scale=0.7).images[0]
>>> image.save("sd3_pag.png")

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] prompt_3: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None clip_skip: typing.Optional[int] = None max_sequence_length: int = 256 lora_scale: typing.Optional[float] = None )

参数

  • prompt (strList[str], 可选) — 待编码的提示词。
  • prompt_2 (strList[str], 可选) — 发送给 tokenizer_2text_encoder_2 的提示词。如果未定义,则在所有文本编码器中使用 prompt
  • prompt_3 (strList[str], 可选) — 发送给 tokenizer_3text_encoder_3 的提示词。如果未定义,则在所有文本编码器中使用 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量。
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时(即,如果 guidance_scale 小于 1 时)忽略。
  • negative_prompt_2 (strList[str], 可选) — 发送给 tokenizer_2text_encoder_2 的不用于引导图像生成的提示词。如果未定义,则在所有文本编码器中使用 negative_prompt
  • negative_prompt_3 (strList[str], 可选) — 发送给 tokenizer_3text_encoder_3 的不用于引导图像生成的提示词。如果未定义,则在所有文本编码器中使用 negative_prompt
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成负文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成负池化文本嵌入。
  • clip_skip (int, 可选) — 计算提示词嵌入时从 CLIP 跳过的层数。值为 1 表示使用倒数第二层的输出计算提示词嵌入。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器的所有 LoRA 层的 LoRA 缩放因子。

StableDiffusion3PAGImg2ImgPipeline

class diffusers.StableDiffusion3PAGImg2ImgPipeline

< >

( transformer: SD3Transformer2DModel scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModelWithProjection tokenizer: CLIPTokenizer text_encoder_2: CLIPTextModelWithProjection tokenizer_2: CLIPTokenizer text_encoder_3: T5EncoderModel tokenizer_3: T5TokenizerFast pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

参数

  • transformer (SD3Transformer2DModel) — 用于对编码图像潜变量进行去噪的条件变换器 (MMDiT) 架构。
  • scheduler (FlowMatchEulerDiscreteScheduler) — 与 transformer 结合使用的调度器,用于对编码图像潜变量进行去噪。
  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示。
  • text_encoder (CLIPTextModelWithProjection) — CLIP,特别是 clip-vit-large-patch14 变体,附加了一个投影层,该层使用其维度为 hidden_size 的对角矩阵初始化。
  • text_encoder_2 (CLIPTextModelWithProjection) — CLIP,特别是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 变体。
  • text_encoder_3 (T5EncoderModel) — 冻结文本编码器。Stable Diffusion 3 使用 T5,特别是 t5-v1_1-xxl 变体。
  • tokenizer (CLIPTokenizer) — CLIPTokenizer 类的分词器。
  • tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 类的第二个分词器。
  • tokenizer_3 (T5TokenizerFast) — T5Tokenizer 类的分词器。

PAG 图像到图像生成管道,使用 Stable Diffusion 3。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.6 num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则必须传递 prompt_embeds
  • prompt_2 (strList[str], 可选) — 发送给 tokenizer_2text_encoder_2 的提示词。如果未定义,则将使用 prompt
  • prompt_3 (strList[str], 可选) — 发送给 tokenizer_3text_encoder_3 的提示词。如果未定义,则将使用 prompt
  • image (torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image]List[np.ndarray]) — 用作起点的图像批处理的 Image、numpy 数组或张量。对于 numpy 数组和 pytorch 张量,预期值范围在 [0, 1] 之间。如果是张量或张量列表,预期形状应为 (B, C, H, W)(C, H, W)。如果是 numpy 数组或数组列表,预期形状应为 (B, H, W, C)(H, W, C)。它也可以接受图像潜变量作为 image,但如果直接传递潜变量,则不会再次编码。
  • strength (float, 可选, 默认为 0.8) — 指示转换参考 image 的程度。必须介于 0 和 1 之间。image 用作起点,strength 越高,添加的噪声越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声最大,去噪过程将运行 num_inference_steps 中指定的全部迭代次数。值为 1 基本上会忽略 image
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但推理速度会变慢。
  • sigmas (List[float], 可选) — 用于去噪过程的自定义 sigmas,与支持 sigmas 参数的调度器一起使用。如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale 定义为 Imagen Paper 方程 2 中的 w。通过设置 guidance_scale > 1 启用引导比例。更高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以牺牲较低图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时(即,如果 guidance_scale 小于 1 时)忽略。
  • negative_prompt_2 (strList[str], 可选) — 发送给 tokenizer_2text_encoder_2 的不用于引导图像生成的提示词。如果未定义,则将使用 negative_prompt
  • negative_prompt_3 (strList[str], 可选) — 发送给 tokenizer_3text_encoder_3 的不用于引导图像生成的提示词。如果未定义,则将使用 negative_prompt
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.FloatTensor, 可选) — 预生成的带噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,将通过使用提供的随机 generator 进行采样来生成潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成负文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成负池化文本嵌入。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。可选择 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — 如果指定,将传递给 AttentionProcessor 的 kwargs 字典,如 diffusers.models.attention_processor 中的 self.processor 所定义。
  • callback_on_step_end (Callable, 可选) — 在推理过程中,每个去噪步骤结束时调用的函数。该函数将使用以下参数调用: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 属性中列出的变量。
  • max_sequence_length (int 默认为 256) — 与 prompt 一起使用的最大序列长度。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的缩放因子。如果设置为 0.0,则不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应缩放因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutputtuple

如果 return_dict 为 True,则为 ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput,否则为 tuple。返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import StableDiffusion3PAGImg2ImgPipeline
>>> from diffusers.utils import load_image

>>> pipe = StableDiffusion3PAGImg2ImgPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-3-medium-diffusers",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.13"],
... )
>>> pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> image = pipe(prompt, image=init_image, guidance_scale=5.0, pag_scale=0.7).images[0]

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] prompt_3: typing.Union[str, typing.List[str]] device: typing.Optional[torch.device] = None num_images_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None clip_skip: typing.Optional[int] = None max_sequence_length: int = 256 lora_scale: typing.Optional[float] = None )

参数

  • prompt (strList[str], 可选) — 待编码的提示词。
  • prompt_2 (strList[str], 可选) — 要发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则在所有文本编码器中使用 prompt
  • prompt_3 (strList[str], 可选) — 要发送到 tokenizer_3text_encoder_3 的提示词。如果未定义,则在所有文本编码器中使用 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时(即如果 guidance_scale 小于 1 时)将被忽略。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成并发送到 tokenizer_2text_encoder_2 的提示词。如果未定义,则在所有文本编码器中使用 negative_prompt
  • negative_prompt_3 (strList[str], 可选) — 不用于引导图像生成并发送到 tokenizer_3text_encoder_3 的提示词。如果未定义,则在所有文本编码器中使用 negative_prompt
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 negative_prompt 输入参数生成负面提示词嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 negative_prompt 输入参数生成池化负面提示词嵌入。
  • clip_skip (int, 可选) — 在计算提示词嵌入时跳过的 CLIP 层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。
  • lora_scale (float, 可选) — 应用于文本编码器所有 LoRA 层的 LoRA 缩放因子(如果加载了 LoRA 层)。

PixArtSigmaPAGPipeline

class diffusers.PixArtSigmaPAGPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKL transformer: PixArtTransformer2DModel scheduler: KarrasDiffusionSchedulers pag_applied_layers: typing.Union[str, typing.List[str]] = 'blocks.1' )

PAG pipeline,用于使用 PixArt-Sigma 生成文本到图像。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: str = '' num_inference_steps: int = 20 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 4.5 num_images_per_prompt: typing.Optional[int] = 1 height: typing.Optional[int] = None width: typing.Optional[int] = None 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 prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: 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 clean_caption: bool = True use_resolution_binning: bool = True max_sequence_length: int = 300 pag_scale: float = 3.0 pag_adaptive_scale: float = 0.0 ) ImagePipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 引导图像生成的提示词。如果未定义,则必须传递 prompt_embeds
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时(即如果 guidance_scale 小于 1 时)将被忽略。
  • num_inference_steps (int, 可选, 默认为 100) — 去噪步数。更多去噪步数通常会产生更高质量的图像,但推理速度会变慢。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义时间步,适用于支持在其 set_timesteps 方法中包含 timesteps 参数的调度器。如果未定义,则使用传递 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], 可选) — 用于去噪过程的自定义 sigma,适用于支持在其 set_timesteps 方法中包含 sigmas 参数的调度器。如果未定义,则使用传递 num_inference_steps 时的默认行为。
  • guidance_scale (float, 可选, 默认为 4.5) — Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过将 guidance_scale 设置为 > 1 来启用引导比例。更高的引导比例会鼓励生成与文本 prompt 更紧密相关的图像,通常以牺牲较低图像质量为代价。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词要生成的图像数量。
  • height (int, 可选, 默认为 self.unet.config.sample_size) — 生成图像的高度(像素)。
  • width (int, 可选, 默认为 self.unet.config.sample_size) — 生成图像的宽度(像素)。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。
  • latents (torch.Tensor, 可选) — 预生成的带噪声隐变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,将使用提供的随机 generator 采样生成隐变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • prompt_attention_mask (torch.Tensor, 可选) — 文本嵌入的预生成注意力掩码。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。对于 PixArt-Sigma,此负面提示词应为空字符串。如果未提供,则将从 negative_prompt 输入参数生成负面提示词嵌入。
  • negative_prompt_attention_mask (torch.Tensor, 可选) — 负面文本嵌入的预生成注意力掩码。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL: PIL.Image.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个函数,在推理过程中每 callback_steps 步都会被调用。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,回调将在每一步都被调用。
  • clean_caption (bool, 可选, 默认为 True) — 是否在创建嵌入之前清理标题。需要安装 beautifulsoup4ftfy。如果未安装这些依赖项,嵌入将从原始提示词创建。
  • use_resolution_binning (bool 默认为 True) — 如果设置为 True,请求的高度和宽度将首先使用 ASPECT_RATIO_1024_BIN 映射到最接近的分辨率。生成的隐变量解码成图像后,它们将被重新调整大小到请求的分辨率。对于生成非方形图像非常有用。
  • max_sequence_length (int 默认为 300) — 与 prompt 一起使用的最大序列长度。
  • pag_scale (float, 可选, 默认为 3.0) — 扰动注意力引导的缩放因子。如果设置为 0.0,将不使用扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 扰动注意力引导的自适应缩放因子。如果设置为 0.0,则使用 pag_scale

返回

ImagePipelineOutputtuple

如果 return_dictTrue,则返回 ImagePipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import AutoPipelineForText2Image

>>> pipe = AutoPipelineForText2Image.from_pretrained(
...     "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
...     torch_dtype=torch.float16,
...     pag_applied_layers=["blocks.14"],
...     enable_pag=True,
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "A small cactus with a happy face in the Sahara desert"
>>> image = pipe(prompt, pag_scale=4.0, guidance_scale=1.0).images[0]

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True negative_prompt: str = '' num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None clean_caption: bool = False max_sequence_length: int = 300 **kwargs )

参数

  • prompt (strList[str], 可选) — 要编码的提示词
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传递 negative_prompt_embeds。在不使用引导时(即如果 guidance_scale 小于 1 时)将被忽略。对于 PixArt-Alpha,这应该为空字符串。
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用分类器自由引导。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词应生成的图像数量。
  • device — (torch.device, 可选): 放置结果嵌入的 torch 设备。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将根据 `prompt` 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。对于 PixArt-Alpha,它应该是空字符串的嵌入。
  • clean_caption (bool, 默认为 False) — 如果为 True,函数将在编码前预处理并清理提供的标题。
  • max_sequence_length (int, 默认为 300) — 用于提示词的最大序列长度。

将提示编码为文本编码器隐藏状态。

< > 在 GitHub 上更新