Diffusers documentation

InstructPix2Pix

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

InstructPix2Pix

LoRA

InstructPix2Pix: Learning to Follow Image Editing Instructions 由 Tim Brooks、Aleksander Holynski 和 Alexei A. Efros 撰写。

该论文的摘要如下:

我们提出了一种根据人类指令编辑图像的方法:给定一张输入图像以及一条告知模型应如何操作的书面指令,我们的模型会遵循这些指令对图像进行编辑。为了获取该问题的训练数据,我们结合了两个大型预训练模型——语言模型(GPT-3)和文本到图像模型(Stable Diffusion)——的知识,生成了一个包含大量图像编辑示例的数据集。我们的条件扩散模型 InstructPix2Pix 在生成的数据上进行训练,并在推理阶段泛化到真实图像和用户编写的指令。由于该模型在前向传播中执行编辑,且无需针对每个示例进行微调或反演,因此我们的模型可以快速编辑图像,仅需几秒钟。我们展示了针对多样化的输入图像和书面指令的令人信服的编辑结果。

您可以在论文、原始代码库中查找有关 InstructPix2Pix 的更多信息,并尝试使用演示。

请务必参阅 调度器指南,了解如何探索调度器速度与质量之间的权衡,并查看 跨流水线复用组件 部分,了解如何高效地将相同组件加载到多个流水线中。

StableDiffusionInstructPix2PixPipeline

class diffusers.StableDiffusionInstructPix2PixPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = Nonerequires_safety_checker: bool = True )

参数

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

用于根据文本指令进行像素级图像编辑的 Pipeline(基于 Stable Diffusion)。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

该 pipeline 还继承了以下加载方法:

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 100guidance_scale: float = 7.5image_guidance_scale: float = 1.5negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']cross_attention_kwargs: dict[str, typing.Any] | None = None**kwargs ) → StableDiffusionPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则需要传入 prompt_embeds。
  • image (torch.Tensor np.ndarray、PIL.Image.Image、list[torch.Tensor]、list[PIL.Image.Image] 或 list[np.ndarray]) — Image 或表示图像批次的张量,将根据 prompt 进行重绘。也可以接受图像潜变量作为 image,但如果直接传入潜变量,则不会再次进行编码。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • guidance_scale (float,可选,默认值为 7.5) — 较高的 guidance scale 值会促使模型生成与文本 prompt 紧密相关的图像,但代价是图像质量降低。当 guidance_scale > 1 时,guidance scale 生效。
  • image_guidance_scale (float,可选,默认值为 1.5) — 将生成的图像推向初始 image。通过设置 image_guidance_scale > 1 来启用图像引导比例。较高的图像引导比例会促使生成的图像与源 image 紧密关联,通常以牺牲图像质量为代价。此流水线要求该值至少为 1。
  • negative_prompt (str 或 list[str],可选) — 用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义,则需要改为传入 negative_prompt_embeds。在未使用引导(guidance_scale < 1)时将被忽略。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (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 Adapter 使用的可选图像输入。
  • ip_adapter_image_embeds (list[torch.Tensor], 可选) — IP-Adapter 的预生成图像嵌入。它应是一个列表,长度与 IP-Adapter 的数量相同。每个元素应为形状为 (batch_size, num_images, emb_dim) 的张量。如果 do_classifier_free_guidance 设置为 True,则应包含负向图像嵌入。如果未提供,嵌入将从 ip_adapter_image 输入参数计算得出。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、可选) — 在推理过程中,每个去噪步骤结束时调用的函数,或 PipelineCallback 或 MultiPipelineCallbacks 的子类,其参数如下: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 属性中列出的变量。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 self.processor 中定义的 AttentionProcessor。

返回值

StableDiffusionPipelineOutput 或 tuple

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

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

示例:

>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionInstructPix2PixPipeline


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"

>>> image = download_image(img_url).resize((512, 512))

>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
...     "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")

>>> prompt = "make the mountains snowy"
>>> image = pipe(prompt=prompt, image=image).images[0]

load_textual_inversion

< >

( pretrained_model_name_or_path: str | list[str] | dict[str, torch.Tensor] | list[dict[str, torch.Tensor]]token: str | list[str] | None = Nonetokenizer: 'PreTrainedTokenizer' | None = Nonetext_encoder: 'PreTrainedModel' | None = None**kwargs )

参数

  • pretrained_model_name_or_path (str 或 os.PathLike 或 list[str or os.PathLike] 或 Dict 或 list[Dict]) — 可以是以下其中一项,也可以是它们的列表:
    • 一个字符串,即托管在 Hub 上的预训练模型的 model id(例如 sd-concepts-library/low-poly-hd-logos-icons)。
    • 指向包含文本反转权重的目录的路径(例如 ./my_text_inversion_directory/)。
    • 指向包含文本反转权重的文件的路径(例如 ./my_text_inversions.pt)。
    • 一个 torch 状态字典。
  • token (str 或 list[str],可选) — 用于覆盖文本反转权重所使用的 token。如果 pretrained_model_name_or_path 是一个列表,则 token 也必须是一个长度相等的列表。
  • text_encoder (CLIPTextModel,可选) — 冻结的文本编码器(clip-vit-large-patch14)。 如果未指定,函数将使用 self.tokenizer。
  • tokenizer (CLIPTokenizer,可选) — 用于对文本进行分词的 CLIPTokenizer。如果未指定,函数将使用 self.tokenizer。
  • weight_name (str, 可选) — 自定义权重文件的名称。在以下情况下应使用此参数:
    • 保存的文本反演文件采用 🤗 Diffusers 格式,但保存时使用了特定的权重名称,例如 text_inv.bin。
    • 保存的文本反演文件采用 Automatic1111 格式。
  • cache_dir (str | os.PathLike, 可选) — 如果未使用标准缓存,则下载的预训练模型配置将被缓存到的目录路径。
  • force_download (bool,可选,默认为 False) — 是否强制(重新)下载模型权重和配置文件,如果存在缓存版本则覆盖它们。
  • proxies (dict[str, str],可选) — 按协议或端点使用的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。每次请求都会使用这些代理。
  • local_files_only (bool,可选,默认为 False) — 是否仅加载本地的模型权重和配置文件。如果设置为 True,则不会从 Hub 下载模型。
  • hf_token (str 或 bool,可选) — 用于远程文件的 HTTP bearer 授权令牌。如果为 True,则使用由 diffusers-cli login 生成的令牌(存储在 ~/.huggingface 中)。
  • revision (str, 可选, 默认为 "main") — 要使用的特定模型版本。它可以是分支名称、标签名称、提交 id,或 Git 允许的任何标识符。
  • subfolder (str,可选,默认为 "") — 模型文件在 Hub 或本地更大的模型仓库中的子文件夹位置。
  • mirror (str, 可选) — 镜像源,用于解决在中国下载模型时可能遇到的访问问题。我们不保证该源的时效性或安全性,详情请参阅镜像站点。

将 Textual Inversion 嵌入加载到 StableDiffusionPipeline 的文本编码器中(同时支持 🤗 Diffusers 和 Automatic1111 格式)。

示例:

要在 🤗 Diffusers 格式中加载 Textual Inversion 嵌入向量:

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")

要在 Automatic1111 格式中加载 Textual Inversion 嵌入向量,请先下载该向量(例如从 civitAI 下载),然后加载该向量

本地:

from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")

load_lora_weights

< >

( pretrained_model_name_or_path_or_dict: str | dict[str, torch.Tensor]adapter_name: str | None = Nonehotswap: bool = False**kwargs )

参数

  • pretrained_model_name_or_path_or_dict (str 或 os.PathLike 或 dict) — 参见 lora_state_dict()。
  • adapter_name (str, 可选) — 用于引用已加载的适配器模型的适配器名称。如果未指定,将使用 default_{i},其中 i 为正在加载的适配器总数。
  • low_cpu_mem_usage (bool,可选) — 通过仅加载预训练的 LoRA 权重而不初始化随机权重,来加快模型加载速度。
  • hotswap (bool, 可选) — 默认值为 False. 是否用新加载的适配器就地替换现有的(LoRA)适配器。这意味着,不会加载额外的适配器,而是将现有适配器的权重替换为新适配器的权重。这样可能更快且更节省内存。然而,热替换的主要优势在于,当模型使用 torch.compile 编译时,加载新适配器无需重新编译模型。使用热替换时,传入的 adapter_name 应为已加载适配器的名称。如果新适配器和旧适配器的秩和/或 LoRA alpha(即缩放)不同,在加载适配器之前需要调用一个额外方法:pipeline = ... # 加载 diffusers pipeline max_rank = ... # 想要加载的所有 LoRA 中的最高秩 # 在编译和加载 LoRA 适配器*之前*调用 pipeline.enable_lora_hotswap(target_rank=max_rank) pipeline.load_lora_weights(file_name) # 现在可选地编译模型 请注意,文本编码器的适配器热替换目前尚不支持。此技术还有一些其他限制,记录在此处:https://huggingface.co/docs/peft/main/en/package_reference/hotswap

    如果新适配器和旧适配器的秩和/或 LoRA alpha(即缩放)不同,则在加载适配器之前需要调用一个额外的方法:

    pipeline = ...  # load diffusers pipeline
    max_rank = ...  # the highest rank among all LoRAs that you want to load
    # call *before* compiling and loading the LoRA adapter
    pipeline.enable_lora_hotswap(target_rank=max_rank)
    pipeline.load_lora_weights(file_name)
    # optionally compile the model now

    请注意,目前尚不支持热替换文本编码器的适配器。该技术还存在一些其他限制,相关文档如下: https://huggingface.co/docs/peft/main/en/package_reference/hotswap

  • kwargs (dict,可选) — 参见 lora_state_dict()。

将 pretrained_model_name_or_path_or_dict 中指定的 LoRA 权重加载到 self.unet 和 self.text_encoder 中。

所有 kwargs 都会转发到 self.lora_state_dict。

有关状态字典加载方式的更多详细信息,请参阅 lora_state_dict()。

有关状态字典如何加载到 self.unet 的更多详细信息,请参阅 load_lora_into_unet()。

有关状态字典如何加载到 self.text_encoder 的更多详细信息,请参阅 load_lora_into_text_encoder()。

save_lora_weights

< >

( save_directory: str | os.PathLikeunet_lora_layers: dict[str, typing.Union[torch.nn.Module, torch.Tensor]] = Nonetext_encoder_lora_layers: dict[str, torch.nn.Module] = Noneis_main_process: bool = Trueweight_name: str = Nonesave_function: typing.Callable = Nonesafe_serialization: bool = Trueunet_lora_adapter_metadata = Nonetext_encoder_lora_adapter_metadata = None )

参数

  • save_directory (str 或 os.PathLike) — 用于保存 LoRA 参数的目录。如果该目录不存在,将会自动创建。
  • unet_lora_layers (dict[str, torch.nn.Module] 或 dict[str, torch.Tensor]) — 与 unet 对应的 LoRA 层的 state dict。
  • text_encoder_lora_layers (dict[str, torch.nn.Module] 或 dict[str, torch.Tensor]) — 与 text_encoder 对应的 LoRA 层的 state dict。由于它来自 🤗 Transformers,因此必须显式传入文本编码器的 LoRA state dict。
  • is_main_process (bool,可选,默认为 True) — 调用此函数的进程是否为主进程。在分布式训练期间,当需要在所有进程上调用此函数时非常有用。在这种情况下,仅在主进程上设置 is_main_process=True,以避免竞态条件。
  • save_function (Callable) — 用于保存状态字典的函数。在分布式训练期间,当您需要用其他方法替换 torch.save 时非常有用。可以通过环境变量 DIFFUSERS_SAVE_MODE 进行配置。
  • safe_serialization(bool,可选,默认为 True)—— 是否使用 safetensors 保存模型,还是使用传统的基于 pickle 的 PyTorch 方式。
  • unet_lora_adapter_metadata — 与 unet 关联的 LoRA 适配器元数据,将随状态字典一起序列化。
  • text_encoder_lora_adapter_metadata — 与文本编码器关联的 LoRA 适配器元数据,将随状态字典一起序列化。

保存与 UNet 和文本编码器对应的 LoRA 参数。

StableDiffusionXLInstructPix2PixPipeline

类 diffusers.StableDiffusionXLInstructPix2PixPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = Noneis_cosxl_edit: bool | None = False )

参数

  • 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 类的 Tokenizer。
  • unet (UNet2DConditionModel) — 用于对编码后的图像潜变量进行去噪的条件 U-Net 架构。
  • scheduler (SchedulerMixin) — 用于与 unet 配合,对编码后的图像潜变量进行去噪的调度器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
  • requires_aesthetics_score (bool,可选,默认为 "False") — unet 在推理时是否需要传入 aesthetic_score 条件。另请参阅 stabilityai/stable-diffusion-xl-refiner-1-0 的配置。
  • force_zeros_for_empty_prompt (bool,可选,默认为 "True") — 是否强制将负提示嵌入始终设置为 0。另请参阅 stabilityai/stable-diffusion-xl-base-1-0 的配置。
  • add_watermarker (bool, 可选) — 是否使用 invisible_watermark 库 为输出图像添加水印。如果未定义,则当该包已安装时默认为 True,否则不使用水印。
  • is_cosxl_edit (bool,可选) — 设置后,图像潜在表示会被缩放。

用于根据文本指令进行像素级图像编辑的 Pipeline。基于 Stable Diffusion XL。

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

该 pipeline 还继承了以下加载方法:

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 100denoising_end: float | None = Noneguidance_scale: float = 5.0image_guidance_scale: float = 1.5negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple[int, int] = Nonecrops_coords_top_left: tuple[int, int] = (0, 0)target_size: tuple[int, int] = None ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器都会使用 prompt。
  • image(torch.Tensor 或 PIL.Image.Image 或 np.ndarray 或 list[torch.Tensor] 或 list[PIL.Image.Image] 或 list[np.ndarray])— 要通过流水线处理的图像。
  • 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) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • denoising_end (float, 可选) — 如果指定,将确定在有意提前终止之前需要完成的去噪过程的总比例(介于 0.0 和 1.0 之间)。因此,返回的样本仍将保留相当多的噪声,具体程度由调度器选择的离散时间步决定。理想情况下,当此流水线作为“去噪器混合”多流水线设置的一部分时,应使用 denoising_end 参数,详见 优化图像输出
  • guidance_scale (float,可选,默认值为 5.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • image_guidance_scale (float,可选,默认值为 1.5) — 图像引导尺度用于将生成的图像推向初始图像 image。通过设置 image_guidance_scale > 1 来启用图像引导尺度。较高的图像引导尺度会促使生成与源图像 image 紧密关联的图像,通常以牺牲图像质量为代价。此流水线要求该值至少为 1。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2 (str 或 list[str],可选) — 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个函数,将在推理过程中每 callback_steps 步被调用一次。该函数将以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — callback 函数的调用频率。如果未指定,则回调将在每一步被调用。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。
  • guidance_rescale (float, optional, defaults to 0.0) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawed guidance_scale is defined as φ in equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. Guidance rescale factor should fix overexposure when using zero terminal SNR.
  • original_size (tuple[int],可选,默认为 (1024, 1024)) — 如果 original_size 与 target_size 不同,图像将看起来像是被下采样或上采样了。 如果未指定,original_size 默认为 (height, width)。这是 SDXL 微条件的一部分, 如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。
  • crops_coords_top_left (tuple[int],可选,默认为 (0, 0)) — crops_coords_top_left 可用于生成一张看似从 crops_coords_top_left 位置向下裁剪的图像。通常将 crops_coords_top_left 设置为 (0, 0) 即可获得构图良好、居中效果理想的图像。这是 SDXL 微条件的一部分,详见 https://huggingface.co/papers/2307.01952 中的第 2.2 节。
  • target_size (tuple[int], 可选,默认为 (1024, 1024)) — 在大多数情况下,target_size 应设置为生成图像所需的宽度和高度。如果未指定,则默认为 (height, width)。这是 SDXL 微条件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 节所述。

返回值

~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 或 tuple

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

调用生成 pipeline 时调用的函数。

示例:

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

>>> resolution = 768
>>> image = load_image(
...     "https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
... ).resize((resolution, resolution))
>>> edit_instruction = "Turn sky into a cloudy one"

>>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
...     "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
... ).to("cuda")

>>> edited_image = pipe(
...     prompt=edit_instruction,
...     image=image,
...     height=resolution,
...     width=resolution,
...     guidance_scale=3.0,
...     image_guidance_scale=1.5,
...     num_inference_steps=30,
... ).images[0]
>>> edited_image

encode_prompt

< >

( prompt: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • prompt_2(str 或 list[str],可选)— 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则两个文本编码器都会使用 prompt。
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用 classifier free guidance
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • negative_prompt_2(str 或 list[str],可选)— 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则两个文本编码器均使用 negative_prompt。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。 如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_pooled_prompt_embeds (torch.Tensor, 可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • lora_scale (float, 可选) — 如果加载了 LoRA 层,将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

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

Update on GitHub