Diffusers 文档

扰动注意力引导

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

扰动注意力引导

扰动注意力引导 (PAG) 是一种新的扩散采样引导方法,可以提高无条件和条件设置下的样本质量,无需进一步训练或集成外部模块即可实现这一点。

PAG 在 Self-Rectifying Diffusion Sampling with Perturbed-Attention Guidance 中被提出,作者是 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)无法充分利用的各种下游任务中的基线性能,包括带有空 prompts 的 ControlNet 和图像恢复,例如图像修复和去模糊。

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

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

由于 RegEx 被支持作为匹配层标识符的方式,因此正确使用它至关重要,否则可能会出现意外行为。推荐使用 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' )

参数

使用 AnimateDiffPerturbed Attention Guidance 的文本到视频生成管线。

此模型继承自 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 ) AnimateDiffPipelineOutputtuple

参数

  • 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_frames (int, 可选, 默认为 16) — 生成的视频帧数。 默认为 16 帧,以每秒 8 帧的速度计算,相当于 2 秒的视频。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的视频,但会牺牲更慢的推理速度。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲较低的图像质量。 当 guidance_scale > 1 时,guidance scale 启用。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示或提示列表。 如果未定义,则需要改为传递 negative_prompt_embeds。 当不使用 guidance 时(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 输入参数生成 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, 可选): 用于 IP 适配器的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可选) — IP 适配器的预生成图像嵌入。 它应该是一个列表,长度与 IP 适配器的数量相同。 每个元素都应是形状为 (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 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预倒数第二层的输出用于计算 prompt embeddings。
  • 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], 可选) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (strList[str], 可选) — 不引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 一个 LoRA 比例,如果加载了 LoRA 层,它将应用于文本编码器的所有 LoRA 层。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预倒数第二层的输出用于计算 prompt embeddings。

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

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)。 混元 DiT 使用微调的 [双语 CLIP]。
  • tokenizer (Optional[~transformers.BertTokenizer, ~transformers.CLIPTokenizer]) — 用于标记文本的 BertTokenizerCLIPTokenizer
  • transformer (HunyuanDiT2DModel) — 腾讯混元设计的 HunyuanDiT 模型。
  • text_encoder_2 (T5EncoderModel) — mT5 嵌入器。具体来说,它是 ‘t5-v1_1-xxl’。
  • tokenizer_2 (MT5Tokenizer) — mT5 嵌入器的 tokenizer。
  • 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 ) StableDiffusionPipelineOutput or tuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则需要传递 prompt_embeds
  • height (int) — 生成图像的高度,以像素为单位。
  • width (int) — 生成图像的宽度,以像素为单位。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。 此参数受 strength 调制。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 更紧密相关的图像,但会以降低图像质量为代价。 当 guidance_scale > 1 时,guidance scale 启用。
  • negative_prompt (strList[str], 可选) — 用于指导图像生成中不应包含的内容的提示或提示列表。 如果未定义,则需要传递 negative_prompt_embeds 代替。 当不使用 guidance (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 输入参数生成 negative_prompt_embeds
  • negative_prompt_embeds_2 (torch.Tensor, 可选) — 预生成的负面文本嵌入。 可用于轻松调整文本输入(提示权重)。 如果未提供,则从 negative_prompt 输入参数生成 negative_prompt_embeds
  • prompt_attention_mask (torch.Tensor, 可选) — 用于 prompt 的注意力掩码。 当直接传递 prompt_embeds 时是必需的。
  • prompt_attention_mask_2 (torch.Tensor, 可选) — 用于 prompt 的注意力掩码。 当直接传递 prompt_embeds_2 时是必需的。
  • negative_prompt_attention_mask (torch.Tensor, 可选) — 用于 negative prompt 的注意力掩码。 当直接传递 negative_prompt_embeds 时是必需的。
  • negative_prompt_attention_mask_2 (torch.Tensor, 可选) — 用于 negative prompt 的注意力掩码。 当直接传递 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], 可选) — 图像的目标尺寸。用于计算时间 ID。
  • crops_coords_top_left (Tuple[int, int], 可选, 默认为 (0, 0)) — 裁剪区域的左上角坐标。用于计算时间 ID。
  • use_resolution_binning (bool, 可选, 默认为 True) — 是否使用分辨率分箱。如果为 True,输入分辨率将被映射到最接近的标准分辨率。支持的分辨率包括 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960, 768x1024, 864x1152, 960x1280, 1280x768 和 768x1280。建议设置为 True
  • pag_scale (float, 可选, 默认为 3.0) — 受扰动注意力引导的缩放因子。如果设置为 0.0,则不会使用受扰动注意力引导。
  • pag_adaptive_scale (float, 可选, 默认为 0.0) — 受扰动注意力引导的自适应缩放因子。如果设置为 0.0,则使用 pag_scale

返回

StableDiffusionPipelineOutputtuple

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

用于使用 HunyuanDiT 生成的 pipeline 的调用函数。

示例

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

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

KolorsPAGPipeline

class 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 结合使用,以对编码后的图像潜在表示进行去噪。可以是 DDIMScheduler, LMSDiscreteScheduler, 或 PNDMScheduler 之一。
  • force_zeros_for_empty_prompt (bool, 可选, 默认为 "False") — 负面 prompt embeddings 是否应强制始终设置为 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 进行文本到图像生成的 Pipeline。

此模型继承自 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], *可选*) — 自定义 sigma 值,用于支持在其 set_timesteps 方法中使用 sigmas 参数的调度器进行去噪过程。如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • denoising_end (float, *可选*) — 当指定时,确定在有意提前终止之前要完成的总去噪过程的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量噪声,这由调度器选择的离散时间步长决定。当此 pipeline 构成“去噪器混合”多 pipeline 设置的一部分时,应理想地使用 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://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他调度器将被忽略。
  • generator (torch.GeneratorList[torch.Generator], *可选*) — 用于使生成具有确定性的一个或多个 torch generator(s)
  • latents (torch.Tensor, *可选*) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成。如果未提供,将通过使用提供的随机 generator 进行采样来生成潜变量张量。
  • prompt_embeds (torch.Tensor, *可选*) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.Tensor, *可选*) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_prompt_embeds (torch.Tensor, *可选*) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • negative_pooled_prompt_embeds (torch.Tensor, *可选*) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput, optional): 与 IP 适配器一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], optional) — IP-Adapter 的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,它应该包含负图像嵌入。如果未提供,则从 ip_adapter_image 输入参数计算嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.kolors.KolorsPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则传递给在 diffusers.models.attention_processor 中的 self.processor 下定义的 AttentionProcessor
  • original_size (Tuple[int], optional, defaults to (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], optional, defaults to (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], optional, defaults to (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的 height 和 width。如果未指定,则默认为 (height, width)。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。
  • negative_original_size (Tuple[int], optional, defaults to (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], optional, defaults to (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], optional, defaults to (1024, 1024)) — 基于目标图像分辨率对生成过程进行负面调节。在大多数情况下,它应与 target_size 相同。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。有关更多信息,请参阅此 issue 线程:https://github.com/huggingface/diffusers/issues/4208
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, optional) — 在推理期间的每个去噪步骤结束时调用的函数或 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, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您将只能包含管道类的 ._callback_tensor_inputs 属性中列出的变量。
  • pag_scale (float, optional, defaults to 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不会使用扰动注意力引导。
  • pag_adaptive_scale (float, optional, defaults to 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale
  • max_sequence_length (int defaults to 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], optional) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • negative_prompt (str or List[str], optional) — The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).
  • prompt_embeds (torch.FloatTensor, optional) — Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.
  • pooled_prompt_embeds (torch.Tensor, optional) — Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, pooled text embeddings will be generated from prompt input argument.
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面文本嵌入 (negative text embeddings)。 可用于轻松调整文本输入,例如 prompt weighting(提示词权重)。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入 (negative pooled text embeddings)。 可用于轻松调整文本输入,例如 prompt weighting(提示词权重)。 如果未提供,则将从 negative_prompt 输入参数生成 pooled negative_prompt_embeds。
  • max_sequence_length (int,默认为 256) — 与 prompt 一起使用的最大序列长度。

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

get_guidance_scale_embedding

< >

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

参数

  • w (torch.Tensor) — 生成具有指定引导缩放比例 (guidance scale) 的嵌入向量,以随后丰富时间步嵌入 (timestep embeddings)。
  • 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) 模型,用于将图像编码和解码为潜在 (latent) 表示形式,以及从潜在表示形式解码为图像。
  • 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 进行文本到图像生成的 Pipeline。

此模型继承自 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 ) StableDiffusionPipelineOutput or tuple

参数

  • 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) — guidance scale 值越高,模型生成的图像就越紧密地与文本 prompt 相关联,但图像质量会降低。当 guidance_scale > 1 时,guidance scale 启用。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示或提示列表。如果未定义,则需要传递 negative_prompt_embeds。当不使用 guidance 时(guidance_scale < 1)将被忽略。
  • num_images_per_prompt (int, 可选,默认为 1) — 每个 prompt 生成的图像数量。
  • eta (float, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成结果具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜变量,用作图像生成的输入。可用于通过不同的 prompt 微调相同的生成结果。如果未提供,则会通过使用提供的随机 generator 进行采样来生成潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, 可选): 与 IP 适配器一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可选) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 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
  • guidance_rescale (float, 可选,默认为 0.0) — 来自 Common Diffusion Noise Schedules and Sample Steps are Flawed 的 Guidance rescale 因子。当使用零终端 SNR 时,Guidance rescale 因子应修复过度曝光。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预最终层的输出将用于计算 prompt 嵌入。
  • 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,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适宜在工作场所观看”(nsfw)的内容。

调用函数以进行管道生成。

示例

>>> 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], 可选) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器 guidance
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds。当不使用 guidance 时将被忽略(即,如果 guidance_scale 小于 1,则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预最终层的输出将用于计算 prompt 嵌入。

将 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

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 结合使用的调度器,用于去噪编码图像潜在表示。可以是 DDIMScheduler, LMSDiscreteScheduler, 或 PNDMScheduler 之一。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于评估生成的图像是否可能被认为是冒犯性或有害的。有关模型潜在危害的更多详细信息,请参阅 model card
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征;用作 safety_checker 的输入。

使用 Stable Diffusion 进行文本到图像生成的 Pipeline。

此模型继承自 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], 可选) — 自定义 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 的 Guidance 重新缩放因子。当使用零终端 SNR 时,Guidance 重新缩放因子应修复过度曝光。
  • 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,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适宜在工作场所观看”(nsfw)的内容。

调用函数以进行管道生成。

示例

>>> 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 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,以计算提示词嵌入。值为 1 表示预最终层的输出将用于计算提示词嵌入。

将 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

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], 可选) — 自定义 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
  • 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 适配器的预生成图像嵌入。它应该是一个列表,长度与 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 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预倒数第二层的输出将用于计算 prompt 嵌入。
  • 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,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适宜在工作场所观看”(nsfw)的内容。

调用函数以进行管道生成。

示例

>>> 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], 可选) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], 可选) — 不引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds 代替。当不使用引导时被忽略 (即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。值为 1 表示预倒数第二层的输出将用于计算 prompt 嵌入。

将 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

StableDiffusionControlNetPAGPipeline

class 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 指导的文本到图像生成 Pipeline。

此模型继承自 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 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 LoRA 缩放比例。
  • clip_skip (int, 可选) — 在计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示预最终层的输出将用于计算提示嵌入。

将 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

StableDiffusionControlNetPAGInpaintPipeline

class 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 的输入。

使用带有 ControlNet 指导的 Stable Diffusion 进行图像修复的 Pipeline。

此模型继承自 DiffusionPipeline。 查看超类文档以获取为所有管线实现的通用方法(下载、保存、在特定设备上运行等)。

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

此 pipeline 可以与专门为修复微调的 checkpoint (runwayml/stable-diffusion-inpainting) 以及默认的 text-to-image Stable Diffusion checkpoint (runwayml/stable-diffusion-v1-5) 一起使用。对于在这些 checkpoint 上微调过的 ControlNet,例如 lllyasviel/control_v11p_sd15_inpaint,默认的 text-to-image Stable Diffusion checkpoint 可能是更优的选择。

__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 的尺寸。如果传递了高度和/或宽度,则会相应地调整 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,则不对图像和 mask_image 应用裁剪。如果 padding_mask_crop 不为 None,它将首先找到一个矩形区域,该区域具有与图像相同的纵横比,并包含所有遮罩区域,然后根据 padding_mask_crop 扩展该区域。然后,将基于扩展区域裁剪图像和 mask_image,然后再调整大小为原始图像大小以进行修复。当遮罩区域较小而图像较大且包含与修复无关的信息(例如背景)时,此功能非常有用。
  • 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) — 更高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会降低图像质量。当 guidance_scale > 1 时,guidance scale 生效。
  • negative_prompt (strList[str], 可选) — 用于引导图像生成中不应包含的内容的提示或提示列表。如果未定义,则需要改为传递 negative_prompt_embeds。当不使用 guidance 时(guidance_scale < 1),将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他 scheduler 中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成过程确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预生成的噪声潜在表示,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompt 微调相同的生成结果。如果未提供,则会通过使用提供的随机 generator 进行采样来生成潜在表示张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入(prompt 加权)。如果未提供,则会从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入(prompt 加权)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, 可选): 与 IP Adapter 一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可选) — IP-Adapter 的预生成图像 embeddings。它应该是一个列表,长度与 IP-Adapter 的数量相同。每个元素都应是形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负面图像 embedding。如果未提供,则会从 ip_adapter_image 输入参数计算 embeddings。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 StableDiffusionPipelineOutput 而不是一个普通的元组 (tuple),默认为 True
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • controlnet_conditioning_scale (floatList[float], optional, defaults to 0.5) — ControlNet 的输出在添加到原始 unet 中的残差之前,会乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,您可以将相应的比例设置为列表。
  • control_guidance_start (floatList[float], optional, defaults to 0.0) — ControlNet 开始应用的步数占总步数的百分比。
  • control_guidance_end (floatList[float], optional, defaults to 1.0) — ControlNet 停止应用的步数占总步数的百分比。
  • clip_skip (int, optional) — 从 CLIP 模型中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用倒数第二层的输出计算 prompt embeddings。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, optional) — 在推理过程中,每个去噪步骤结束时调用的函数或 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, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含管道类 ._callback_tensor_inputs 属性中列出的变量。
  • 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,其中第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示相应的生成图像是否包含“不适宜在工作场所观看”(nsfw)的内容。

调用函数以进行管道生成。

示例

>>> # !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], optional) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应该生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], optional) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • lora_scale (float, optional) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, optional) — 从 CLIP 模型中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用倒数第二层的输出计算 prompt embeddings。

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

get_guidance_scale_embedding

< >

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

参数

  • w (torch.Tensor) — 使用指定的引导比例生成 embedding 向量,以随后丰富 timestep embeddings。
  • embedding_dim (int, optional, defaults to 512) — 要生成的 embeddings 的维度,默认为 512。
  • dtype (torch.dtype, optional, defaults to torch.float32) — 生成的 embeddings 的数据类型,默认为 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 library 来为输出图像添加水印。 如果未定义,如果已安装该包,则默认为 True,否则不使用水印。

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

此模型继承自 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.StableDiffusionXLPipelineOutput or tuple

参数

  • 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], 可选) — 用于支持在其 set_timesteps 方法中使用 sigmas 参数的调度器的去噪过程的自定义 sigma 值。 如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • denoising_end (float, 可选) — 当指定时,确定在有意过早终止之前要完成的总去噪过程的分数(介于 0.0 和 1.0 之间)。 因此,返回的样本仍将保留大量噪声,这由调度器选择的离散时间步长决定。 当此 pipeline 构成“去噪器混合”多 pipeline 设置的一部分时,应理想地使用 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 则忽略)。
  • negative_prompt_2 (strList[str], 可选) — 不用于引导图像生成的提示词,将发送到 tokenizer_2text_encoder_2。 如果未定义,则 negative_prompt 将用于两个文本编码器
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。 仅适用于 schedulers.DDIMScheduler, 将被其他调度器忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成确定性的一个或一组 torch 生成器
  • latents (torch.Tensor, optional) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成结果。如果未提供,则将使用提供的随机 generator 采样生成潜变量张量。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,则将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput, optional): 与 IP 适配器一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], optional) — IP 适配器的预生成图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应是形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负图像嵌入。如果未提供,则将从 ip_adapter_image 输入参数计算嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给在 diffusers.models.attention_processor 中的 self.processor 下定义的 AttentionProcessor
  • guidance_rescale (float, optional, defaults to 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], optional, defaults to (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], optional, defaults to (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], optional, defaults to (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的期望高度和宽度。如果未指定,它将默认为 (height, width)。SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。
  • negative_original_size (Tuple[int], optional, defaults to (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], optional, defaults to (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面条件约束。SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的第 2.2 节中所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], optional, defaults to (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, optional) — 在推理期间的每个去噪步骤结束时调用的函数。该函数使用以下参数调用: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, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您将只能包含在您的 pipeline 类的 ._callback_tensor_inputs 属性中列出的变量。
  • pag_scale (float, optional, defaults to 3.0) — 扰动注意力引导的比例因子。如果设置为 0.0,则不会使用扰动注意力引导。
  • pag_adaptive_scale (float, optional, defaults to 0.0) — 扰动注意力引导的自适应比例因子。如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutputtuple

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 如果 return_dict 为 True,否则为 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 (str or List[str], optional) — 要编码的提示词
  • prompt_2 (str or List[str], optional) — 要发送到 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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 LoRA 比例。
  • clip_skip (int, 可选) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。

将 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

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, 可选, 默认为 "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, optional) — 是否使用 invisible_watermark library 库为输出图像添加水印。如果未定义,如果已安装该包,则默认为 True,否则将不使用水印。

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

此模型继承自 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.StableDiffusionXLPipelineOutput or tuple

参数

  • prompt (str or List[str], optional) — 用于引导图像生成的提示或提示语。如果未定义,则必须传入 prompt_embeds
  • prompt_2 (str or List[str], optional) — 要发送到 tokenizer_2text_encoder_2 的提示或提示语。如果未定义,则 prompt 将在两个文本编码器中使用。
  • image (torch.Tensor or PIL.Image.Image or np.ndarray or List[torch.Tensor] or List[PIL.Image.Image] or List[np.ndarray]) — 要使用 pipeline 修改的图像。
  • strength (float, optional, defaults to 0.3) — 从概念上讲,表示要转换参考 image 的程度。必须介于 0 和 1 之间。image 将用作起点,strength 越大,添加的噪声就越多。去噪步骤的数量取决于最初添加的噪声量。当 strength 为 1 时,添加的噪声将最大,并且去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 本质上会忽略 image。请注意,如果 denoising_start 被声明为整数,则 strength 的值将被忽略。
  • num_inference_steps (int, optional, defaults to 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会以较慢的推理速度为代价。
  • timesteps (List[int], optional) — 用于支持在其 set_timesteps 方法中使用 timesteps 参数的调度器的去噪过程的自定义时间步长。如果未定义,则将使用传递 num_inference_steps 时的默认行为。必须按降序排列。
  • sigmas (List[float], optional) — 用于支持在其 set_timesteps 方法中使用 sigmas 参数的调度器的去噪过程的自定义 sigmas。如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • denoising_start (float, optional) — 当指定时,表示在启动去噪过程之前要绕过的总去噪过程的分数(介于 0.0 和 1.0 之间)。因此,去噪过程的初始部分被跳过,并且假定传递的 image 是部分去噪的图像。请注意,当指定此参数时,将忽略 strength。当此 pipeline 集成到“混合去噪器”多 pipeline 设置中时,denoising_start 参数尤其有利,如 优化图像质量 中详述。
  • denoising_end (float, optional) — 当指定时,确定在有意过早终止之前要完成的总去噪过程的分数(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量的噪声(大约仍然需要最后 20% 的时间步长),并且应由后继 pipeline 进行去噪,该 pipeline 的 denoising_start 设置为 0.8,以便仅对调度器的最后 20% 进行去噪。当此 pipeline 构成“混合去噪器”多 pipeline 设置的一部分时,应理想地使用 denoising_end 参数,如 优化图像质量 中详细说明。
  • guidance_scale (float, optional, defaults to 7.5) — Classifier-Free Diffusion Guidance 中定义的引导缩放。guidance_scale 定义为 Imagen Paper 的等式 2 中的 w。通过设置 guidance_scale > 1 启用引导缩放。较高的引导比例鼓励生成与文本 prompt 紧密相关的图像,通常以降低图像质量为代价。
  • negative_prompt (str or List[str], optional) — 不用于引导图像生成的提示或提示语。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1,则忽略)。
  • negative_prompt_2 (str or List[str], optional) — 不用于引导图像生成的提示或提示语,将被发送到 tokenizer_2text_encoder_2。如果未定义,则 negative_prompt 将在两个文本编码器中使用。
  • num_images_per_prompt (int, optional, defaults to 1) — 每个提示要生成的图像数量。
  • eta (float, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他调度器将被忽略。
  • generator (torch.Generator or List[torch.Generator], optional) — 用于使生成具有确定性的一个或 torch 生成器 列表。
  • latents (torch.Tensor, optional) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示来调整相同的生成。如果未提供,则将通过使用提供的随机 generator 进行采样来生成潜变量张量。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入 (pooled text embeddings)。 可用于轻松调整文本输入,例如,提示词权重。 如果未提供,池化文本嵌入将从 prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负池化文本嵌入。 可用于轻松调整文本输入,例如,提示词权重。 如果未提供,负池化文本嵌入将从 negative_prompt 输入参数生成。
  • ip_adapter_image — (PipelineImageInput, 可选): 用于 IP 适配器的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], 可选) — IP 适配器的预生成图像嵌入。它应该是一个列表,其长度与 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.stable_diffusion.StableDiffusionXLPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给在 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • guidance_rescale (float, 可选, 默认为 0.0) — 由 Common Diffusion Noise Schedules and Sample Steps are Flawed 提出的 Guidance rescale 因子。 guidance_scaleCommon Diffusion Noise Schedules and Sample Steps are Flawed 的公式 16 中定义为 φ。 Guidance rescale 因子应修复使用零终端 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
  • 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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 lora 缩放比例。
  • clip_skip (int, 可选) — 计算提示嵌入时,要从 CLIP 跳过的层数。值为 1 表示预最终层的输出将用于计算提示嵌入。

将 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

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 是否需要在推理期间传递 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 library 库为输出图像添加水印。如果未定义,如果已安装该软件包,则默认为 True,否则将不使用水印。

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

此模型继承自 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.StableDiffusionXLPipelineOutput or tuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传递 prompt_embeds 来代替。
  • prompt_2 (strList[str], 可选) — 将被发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则 prompt 将在两个文本编码器中都使用
  • image (PIL.Image.Image) — Image,或表示将要进行图像修复的图像批次的张量,例如,图像的部分将被 mask_image 遮罩,并根据 prompt 重新绘制。
  • mask_image (PIL.Image.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, optional) — 预生成的文本嵌入 (text embeddings)。 可以用于轻松调整文本输入,例如 prompt 加权。 如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本嵌入。 可以用于轻松调整文本输入,例如 prompt 加权。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, optional) — 预生成的池化文本嵌入 (pooled text embeddings)。 可以用于轻松调整文本输入,例如 prompt 加权。 如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负面池化文本嵌入。 可以用于轻松调整文本输入,例如 prompt 加权。 如果未提供,则将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput, optional): 与 IP 适配器 (IP Adapters) 一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], optional) — IP 适配器 (IP-Adapter) 的预生成图像嵌入。 它应该是一个列表,长度与 IP 适配器的数量相同。 每个元素都应为形状为 (batch_size, num_images, emb_dim) 的张量。 如果 do_classifier_free_guidance 设置为 True,则应包含负面图像嵌入。 如果未提供,则嵌入将从 ip_adapter_image 输入参数计算得出。
  • num_images_per_prompt (int, optional, defaults to 1) — 每个 prompt 要生成的图像数量。
  • eta (float, optional, defaults to 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。 仅适用于 schedulers.DDIMScheduler, 将被其他调度器忽略。
  • generator (torch.Generator, optional) — 用于使生成具有确定性的一个或一组 torch generator(s)
  • latents (torch.Tensor, optional) — 预生成的噪声潜变量 (noisy latents),从高斯分布中采样,用作图像生成的输入。 可以用于使用不同的 prompt 调整相同的生成。 如果未提供,则将通过使用提供的随机 generator 进行采样来生成 latents 张量。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。 在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组 (tuple)。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • original_size (Tuple[int], optional, defaults to (1024, 1024)) — 如果 original_sizetarget_size 不同,则图像将显示为缩小或放大。 如果未指定,original_size 默认为 (height, width)。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • crops_coords_top_left (Tuple[int], optional, defaults to (0, 0)) — crops_coords_top_left 可用于生成看起来像是从位置 crops_coords_top_left 向下“裁剪”的图像。 通常,通过将 crops_coords_top_left 设置为 (0, 0) 可以获得良好且居中的图像。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • target_size (Tuple[int], optional, defaults to (1024, 1024)) — 对于大多数情况,target_size 应设置为生成图像的所需高度和宽度。 如果未指定,它将默认为 (height, width)。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_original_size (Tuple[int], optional, defaults to (1024, 1024)) — 为了基于特定的图像分辨率对生成过程进行负面调节。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208
  • negative_crops_coords_top_left (Tuple[int], optional, defaults to (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面调节。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], optional, defaults to (1024, 1024)) — 为了基于目标图像分辨率对生成过程进行负面调节。 对于大多数情况,它应与 target_size 相同。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, optional, defaults to 6.0) — 用于通过影响正面文本条件来模拟生成图像的美学评分。 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。
  • negative_aesthetic_score (float, optional, defaults to 2.5) — 作为 SDXL 的微调条件 (micro-conditioning) 的一部分,如 https://huggingface.ac.cn/papers/2307.01952 第 2.2 节所述。 可用于通过影响负面文本条件来模拟生成图像的美学评分。
  • clip_skip (int, optional) — 从 CLIP 中跳过的层数,用于计算 prompt 嵌入。 值为 1 表示预最终层的输出将用于计算 prompt 嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, optional) — 在推理期间,在每个去噪步骤结束时调用的函数或 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, optional) — callback_on_step_end 函数的张量输入列表。 列表中指定的张量将作为 callback_kwargs 参数传递。 您将只能包含管道类 ._callback_tensor_inputs 属性中列出的变量。
  • pag_scale (float, optional, defaults to 3.0) — 扰动注意力引导 (perturbed attention guidance) 的比例因子。 如果设置为 0.0,则不会使用扰动注意力引导。
  • pag_adaptive_scale (float, optional, defaults to 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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,则将应用于文本编码器所有 LoRA 层的 lora 缩放比例。
  • clip_skip (int, 可选) — 在计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示预最终层的输出将用于计算提示嵌入。

将 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

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;否则不使用水印。

使用带有 ControlNet 指导的 Stable Diffusion XL 进行文本到图像生成的 Pipeline。

此模型继承自 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 ) StableDiffusionPipelineOutput or tuple

参数

  • 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], 可选的) — 自定义时间步长,用于去噪过程,scheduler 需要在其 set_timesteps 方法中支持 timesteps 参数。如果未定义,则将使用传递 num_inference_steps 时的默认行为。必须以降序排列。
  • sigmas (List[float], 可选的) — 自定义 sigmas,用于去噪过程,scheduler 需要在其 set_timesteps 方法中支持 sigmas 参数。如果未定义,则将使用传递 num_inference_steps 时的默认行为。
  • denoising_end (float, 可选的) — 如果指定,则确定在有意提前终止之前要完成的总去噪过程的比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留大量的噪声,这由调度程序选择的离散时间步长决定。当此 pipeline 构成“混合去噪器”多 pipeline 设置的一部分时,应理想地使用 denoising_end 参数,如 Refining the Image Output 中详述的那样。
  • guidance_scale (float, 可选的, 默认为 5.0) — 较高的 guidance scale 值会鼓励模型生成与文本 prompt 紧密相关的图像,但会以降低图像质量为代价。当 guidance_scale > 1 时,guidance scale 启用。
  • negative_prompt (strList[str], *可选的*) — 用于引导图像生成中不包含内容的提示词。如果未定义,则需要传递 negative_prompt_embeds 代替。当不使用 guidance 时(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,在其他 scheduler 中将被忽略。
  • generator (torch.GeneratorList[torch.Generator], *可选的*) — 用于使生成确定性的 torch.Generator
  • latents (torch.Tensor, 可选的) — 从高斯分布中采样的预生成的噪声 latents,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,则会通过使用提供的随机 generator 进行采样来生成 latents tensor。
  • prompt_embeds (torch.Tensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 negative_prompt 输入参数生成 negative_prompt_embeds
  • pooled_prompt_embeds (torch.Tensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则会从 negative_prompt 输入参数生成池化的 negative_prompt_embeds
  • ip_adapter_image — (PipelineImageInput, optional): 与 IP 适配器一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], optional) — IP 适配器预生成的图像嵌入。它应该是一个列表,长度与 IP 适配器的数量相同。每个元素都应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负面图像嵌入。如果未提供,则会从 ip_adapter_image 输入参数计算嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 self.processor 中定义的 AttentionProcessor
  • controlnet_conditioning_scale (float or List[float], optional, defaults to 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,会乘以 controlnet_conditioning_scale。如果在 init 中指定了多个 ControlNet,则可以将相应的比例设置为列表。
  • control_guidance_start (float or List[float], optional, defaults to 0.0) — ControlNet 开始应用的全部步骤的百分比。
  • control_guidance_end (float or List[float], optional, defaults to 1.0) — ControlNet 停止应用的全部步骤的百分比。
  • original_size (Tuple[int], optional, defaults to (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], optional, defaults to (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], optional, defaults to (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的所需高度和宽度。如果未指定,则默认为 (height, width)。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。
  • negative_original_size (Tuple[int], optional, defaults to (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], optional, defaults to (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面调节。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], optional, defaults to (1024, 1024)) — 为了基于目标图像分辨率对生成过程进行负面调节。在大多数情况下,它应该与 target_size 相同。SDXL 微调的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。有关更多信息,请参阅此问题线程:https://github.com/huggingface/diffusers/issues/4208
  • clip_skip (int, optional) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示将使用预最终层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, optional) — 一个函数或 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, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您将只能包含 pipeline 类的 ._callback_tensor_inputs 属性中列出的变量。
  • 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

调用函数以进行管道生成。

示例

>>> # !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 (str or List[str], optional) — 要编码的提示
  • prompt_2 (str or List[str], optional) — 要发送到 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 时忽略(即,如果 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 输入参数生成池化 negative_prompt_embeds。
  • lora_scale (float, 可选) — 当加载 LoRA 层时,将应用于文本编码器所有 LoRA 层的 lora 缩放比例。
  • clip_skip (int, 可选) — 计算提示嵌入时要从 CLIP 跳过的层数。值为 1 表示预最终层的输出将用于计算提示嵌入。

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

get_guidance_scale_embedding

< >

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

参数

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

返回

torch.Tensor

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

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

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 library 库为输出图像添加水印。如果未定义,如果已安装该软件包,则默认为 True,否则将不使用任何水印添加器。
  • feature_extractor (CLIPImageProcessor) — 一个 CLIPImageProcessor,用于从生成的图像中提取特征;用作 safety_checker 的输入。

使用 ControlNet 引导的 Stable Diffusion XL 进行图像到图像生成的 Pipeline。

此模型继承自 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.StableDiffusionXLPipelineOutput or tuple

参数

  • 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 的大小。如果在 init 中指定了多个 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://arxiv.org/abs/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, optional) — 预生成的池化文本嵌入 (pooled text embeddings)。 可以用于轻松调整文本输入,例如 提示词权重调整。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, optional) — 预生成的负面池化文本嵌入。 可以用于轻松调整文本输入,例如 提示词权重调整。 如果未提供,将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • ip_adapter_image — (PipelineImageInput, optional): 与 IP 适配器 (IP Adapters) 一起使用的可选图像输入。
  • ip_adapter_image_embeds (List[torch.Tensor], optional) — IP 适配器 (IP-Adapter) 的预生成图像嵌入。 它应该是一个列表,长度与 IP 适配器的数量相同。 每个元素都应该是一个形状为 (batch_size, num_images, emb_dim) 的张量。 如果 do_classifier_free_guidance 设置为 True,则应包含负图像嵌入。 如果未提供,则从 ip_adapter_image 输入参数计算嵌入。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。 在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • cross_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给 AttentionProcessor,定义在 diffusers.models.attention_processor 中的 self.processor 下。
  • controlnet_conditioning_scale (float or List[float], optional, defaults to 1.0) — ControlNet 的输出在添加到原始 unet 中的残差之前,会乘以 controlnet_conditioning_scale。 如果在 init 中指定了多个 ControlNet,则可以将相应的比例设置为列表。
  • guess_mode (bool, optional, defaults to False) — 在此模式下,即使您移除所有提示词,ControlNet 编码器也会尽力识别输入图像的内容。 建议 guidance_scale 在 3.0 到 5.0 之间。
  • control_guidance_start (float or List[float], optional, defaults to 0.0) — ControlNet 开始应用的总步数的百分比。
  • control_guidance_end (float or List[float], optional, defaults to 1.0) — ControlNet 停止应用的总步数的百分比。
  • original_size (Tuple[int], optional, defaults to (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], optional, defaults to (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], optional, defaults to (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像的期望的高度和宽度。 如果未指定,则默认为 (height, width)。 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。
  • negative_original_size (Tuple[int], optional, defaults to (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], optional, defaults to (0, 0)) — 为了基于特定的裁剪坐标对生成过程进行负面条件约束。 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208
  • negative_target_size (Tuple[int], optional, defaults to (1024, 1024)) — 为了基于目标图像分辨率对生成过程进行负面条件约束。 在大多数情况下,它应与 target_size 相同。 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 有关更多信息,请参阅此问题线程: https://github.com/huggingface/diffusers/issues/4208
  • aesthetic_score (float, optional, defaults to 6.0) — 用于通过影响正面文本条件来模拟生成图像的美学评分。 SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。
  • negative_aesthetic_score (float, optional, defaults to 2.5) — SDXL 微调条件的一部分,如 https://huggingface.ac.cn/papers/2307.01952 的 2.2 节中所述。 可用于通过影响负面文本条件来模拟生成图像的美学评分。
  • clip_skip (int, optional) — 从 CLIP 中跳过的层数,用于计算提示词嵌入。 值 1 表示预最终层的输出将用于计算提示词嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, optional) — 在推理期间的每个去噪步骤结束时调用的函数或 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, optional) — callback_on_step_end 函数的张量输入列表。 列表中指定的张量将作为 callback_kwargs 参数传递。 您将只能包含在管道类的 ._callback_tensor_inputs 属性中列出的变量。
  • pag_scale (float, optional, defaults to 3.0) — 扰动注意力引导的比例因子。 如果设置为 0.0,则不会使用扰动注意力引导。
  • pag_adaptive_scale (float, optional, defaults to 0.0) — 扰动注意力引导的自适应比例因子。 如果设置为 0.0,则使用 pag_scale

返回

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutputtuple

~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput 如果 return_dict 为 True,否则为包含输出图像的 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.fuctional.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 (str or List[str], optional) — 要编码的提示词 (prompt)
  • prompt_2 (str or List[str], optional) — 要发送到 tokenizer_2text_encoder_2 的提示词 (prompt) 或提示词 (prompts)。 如果未定义,则 prompt 将在两个文本编码器 (text-encoders) 中使用
  • 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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • lora_scale (float, 可选) — lora 比例,如果加载了 LoRA 层,则该比例将应用于文本编码器的所有 LoRA 层。
  • clip_skip (int, 可选) — 从 CLIP 中跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。

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

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 流水线,用于使用 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.StableDiffusion3PipelineOutput or tuple

参数

  • 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 值,用于调度器,这些调度器在其 set_timesteps 方法中支持 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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, 可选) — kwargs 字典,如果指定,则会传递给 AttentionProcessor,如 diffusers.models.attention_processorself.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 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_2 (strList[str], 可选) — 不引导图像生成的提示,将发送到 tokenizer_3text_encoder_3。如果未定义,则在两个文本编码器中使用 negative_prompt
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • 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) — 条件 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 管道,用于使用 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 值,适用于调度器在其 set_timesteps 方法中支持 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 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • joint_attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给在 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • callback_on_step_end (Callable, optional) — 一个函数,在推理期间的每个去噪步骤结束时调用。该函数使用以下参数调用: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, optional) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您将只能包含在管道类的 ._callback_tensor_inputs 属性中列出的变量。
  • max_sequence_length (int, 默认值为 256) — 与 prompt 一起使用的最大序列长度。
  • pag_scale (float, optional, 默认值为 3.0) — 扰动注意力引导的缩放因子。如果设置为 0.0,则不会使用扰动注意力引导。
  • pag_adaptive_scale (float, optional, 默认值为 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], optional) — 要编码的提示
  • prompt_2 (strList[str], optional) — 要发送到 tokenizer_2text_encoder_2 的提示。如果未定义,则在所有文本编码器中使用 prompt
  • prompt_3 (strList[str], optional) — 要发送到 tokenizer_3text_encoder_3 的提示。如果未定义,则在所有文本编码器中使用 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[str], optional) — 不引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • negative_prompt_2 (strList[str], optional) — 不引导图像生成的提示,将发送到 tokenizer_2text_encoder_2。如果未定义,则在所有文本编码器中使用 negative_prompt
  • negative_prompt_2 (strList[str], optional) — 不引导图像生成的提示,将发送到 tokenizer_3text_encoder_3。如果未定义,则在两个文本编码器中使用 negative_prompt
  • prompt_embeds (torch.FloatTensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • pooled_prompt_embeds (torch.FloatTensor, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.FloatTensor, optional) — 预生成的负面池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • clip_skip (int, optional) — 从 CLIP 跳过的层数,用于计算提示嵌入。值为 1 表示预最终层的输出将用于计算提示嵌入。
  • lora_scale (float, optional) — 如果加载了 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 管道,用于使用 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], 可选) — 用于去噪过程的自定义西格玛值,适用于在其 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://arxiv.org/abs/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_embeds。
  • 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 defaults to 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) — 用于提示的最大序列长度。

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

< > 在 GitHub 上更新