Diffusers documentation

DeepFloyd IF

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

and get access to the augmented documentation experience

to get started

DeepFloyd IF

LoRA MPS

概述

DeepFloyd IF 是一款新颖的、最先进的开源文本生成图像模型,具有高度的照片真实感和语言理解能力。 该模型采用模块化设计,由一个冻结的文本编码器和三个级联的像素扩散模块组成:

  • 阶段 1:一个根据文本提示生成 64x64 像素图像的基础模型,
  • 阶段 2:一个 64x64 px => 256x256 px 的超分辨率模型,以及
  • 阶段 3:一个 256x256 px => 1024x1024 px 的超分辨率模型 阶段 1 和阶段 2 使用基于 T5 变换器的冻结文本编码器来提取文本嵌入,然后将其输入到增强了交叉注意力和注意力池化的 UNet 架构中。 阶段 3 是 Stability AI 的 x4 放大模型。 其结果是一个高效模型,性能优于当前最先进的模型,在 COCO 数据集上实现了 6.66 的零样本 FID 分数。 我们的工作强调了更大的 UNet 架构在级联扩散模型第一阶段中的潜力,并描绘了文本到图像合成的美好前景。

用法

在使用 IF 之前,您需要接受其使用条款。操作方法如下:

  1. 请确保您拥有一个 Hugging Face 账户 并已登录。
  2. 在 DeepFloyd/IF-I-XL-v1.0 的模型卡片上接受许可协议。接受第一阶段模型卡片的许可协议后,将自动接受其他 IF 模型的许可协议。
  3. 请确保已在本地登录。安装 huggingface_hub:
pip install huggingface_hub --upgrade

在 Python shell 中运行登录函数:

from huggingface_hub import login

login()

并输入您的 Hugging Face Hub 访问令牌。

接下来,我们安装 diffusers 及其依赖项:

pip install -q diffusers accelerate transformers

以下各节提供了更详细的示例,说明如何使用 IF。具体而言:

可用的检查点

Google Colab Open In Colab

文本到图像生成

默认情况下,diffusers 使用 模型 CPU 卸载 来运行整个 IF 流水线,仅需 14 GB 的显存即可。

from diffusers import DiffusionPipeline
from diffusers.utils import pt_to_pil, make_image_grid
import torch

# stage 1
stage_1 = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()

# stage 2
stage_2 = DiffusionPipeline.from_pretrained(
    "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()

# stage 3
safety_modules = {
    "feature_extractor": stage_1.feature_extractor,
    "safety_checker": stage_1.safety_checker,
    "watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()

prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
generator = torch.manual_seed(1)

# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)

# stage 1
stage_1_output = stage_1(
    prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, generator=generator, output_type="pt"
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")

# stage 2
stage_2_output = stage_2(
    image=stage_1_output,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    generator=generator,
    output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")

# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, noise_level=100, generator=generator).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=3)

文本引导的图像到图像生成

相同的 IF 模型权重可用于文本引导的图像到图像转换或图像变体生成。 在这种情况下,只需确保使用 IFImg2ImgPipeline 和 IFImg2ImgSuperResolutionPipeline 流水线来加载权重即可。

注意:你也可以利用 components 参数,如此处所述,直接将文本到图像流水线的权重移动到图像到图像流水线中,而无需加载两次。

from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch

# download image
url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
original_image = load_image(url)
original_image = original_image.resize((768, 512))

# stage 1
stage_1 = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()

# stage 2
stage_2 = IFImg2ImgSuperResolutionPipeline.from_pretrained(
    "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()

# stage 3
safety_modules = {
    "feature_extractor": stage_1.feature_extractor,
    "safety_checker": stage_1.safety_checker,
    "watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()

prompt = "A fantasy landscape in style minecraft"
generator = torch.manual_seed(1)

# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)

# stage 1
stage_1_output = stage_1(
    image=original_image,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    generator=generator,
    output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")

# stage 2
stage_2_output = stage_2(
    image=stage_1_output,
    original_image=original_image,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    generator=generator,
    output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")

# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=4)

文本引导的图像修复生成

相同的 IF 模型权重可用于文本引导的图像到图像转换或图像变化。 在这种情况下,只需确保使用 IFInpaintingPipeline 和 IFInpaintingSuperResolutionPipeline 流水线来加载权重即可。

注意:你也可以利用 ~DiffusionPipeline.components() 函数,如此处所述,直接将文本生成图像流水线的权重移动到图像生成图像流水线中,而无需加载两次。

from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch

# download image
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
original_image = load_image(url)

# download mask
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
mask_image = load_image(url)

# stage 1
stage_1 = IFInpaintingPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
stage_1.enable_model_cpu_offload()

# stage 2
stage_2 = IFInpaintingSuperResolutionPipeline.from_pretrained(
    "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16
)
stage_2.enable_model_cpu_offload()

# stage 3
safety_modules = {
    "feature_extractor": stage_1.feature_extractor,
    "safety_checker": stage_1.safety_checker,
    "watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, dtype=torch.float16
)
stage_3.enable_model_cpu_offload()

prompt = "blue sunglasses"
generator = torch.manual_seed(1)

# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)

# stage 1
stage_1_output = stage_1(
    image=original_image,
    mask_image=mask_image,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    generator=generator,
    output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")

# stage 2
stage_2_output = stage_2(
    image=stage_1_output,
    original_image=original_image,
    mask_image=mask_image,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    generator=generator,
    output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_II.png")

# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, mask_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=5)

在不同流水线之间进行转换

除了通过 from_pretrained 加载之外,Pipelines 还可以直接从彼此加载。

from diffusers import IFPipeline, IFSuperResolutionPipeline

pipe_1 = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0")
pipe_2 = IFSuperResolutionPipeline.from_pretrained("DeepFloyd/IF-II-L-v1.0")


from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline

pipe_1 = IFImg2ImgPipeline(**pipe_1.components)
pipe_2 = IFImg2ImgSuperResolutionPipeline(**pipe_2.components)


from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline

pipe_1 = IFInpaintingPipeline(**pipe_1.components)
pipe_2 = IFInpaintingSuperResolutionPipeline(**pipe_2.components)

优化速度

让 IF 运行得最快的最简单优化方法是将所有模型组件移至 GPU。

pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

你还可以减少时间步数来运行扩散过程。

这可以通过 num_inference_steps 参数来实现:

pipe("<prompt>", num_inference_steps=30)

或者使用 timesteps 参数:

from diffusers.pipelines.deepfloyd_if import fast27_timesteps

pipe("<prompt>", timesteps=fast27_timesteps)

在进行图像变化或图像修复时,你也可以通过 strength 参数来减少时间步的数量。strength 参数表示要添加到输入图像中的噪声量,同时也决定了去噪过程中要执行的步数。数值越小,图像的变化越小,但运行速度越快。

pipe = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

image = pipe(image=image, prompt="<prompt>", strength=0.3).images

您也可以使用 torch.compile。请注意,我们尚未对 torch.compile 与 IF 的组合进行详尽测试,其结果可能不符合预期。

from diffusers import DiffusionPipeline
import torch

pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

pipe.text_encoder = torch.compile(pipe.text_encoder, mode="reduce-overhead", fullgraph=True)
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)

优化内存

在优化 GPU 内存时,我们可以使用标准的 diffusers CPU offloading API。

基于模型的 CPU 卸载,

pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_model_cpu_offload()

或更激进的基于层的 CPU 卸载。

pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_sequential_cpu_offload()

此外,T5 可以以 8 位精度加载

from transformers import T5EncoderModel

text_encoder = T5EncoderModel.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)

from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0",
    text_encoder=text_encoder,  # pass the previously instantiated 8bit text encoder
    unet=None,
    device_map="auto",
)

prompt_embeds, negative_embeds = pipe.encode_prompt("<prompt>")

对于 CPU 内存受限的机器(例如 Google Colab 免费层),我们无法一次性将所有模型组件加载到 CPU 中。在这种情况下,我们可以在需要相应的模型组件时,手动仅加载包含文本编码器或 UNet 的 pipeline。

from diffusers import IFPipeline, IFSuperResolutionPipeline
import torch
import gc
from transformers import T5EncoderModel
from diffusers.utils import pt_to_pil, make_image_grid

text_encoder = T5EncoderModel.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)

# text to image
pipe = DiffusionPipeline.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0",
    text_encoder=text_encoder,  # pass the previously instantiated 8bit text encoder
    unet=None,
    device_map="auto",
)

prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

# Remove the pipeline so we can re-load the pipeline with the unet
del text_encoder
del pipe
gc.collect()
torch.cuda.empty_cache()

pipe = IFPipeline.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16, device_map="auto"
)

generator = torch.Generator().manual_seed(0)
stage_1_output = pipe(
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    output_type="pt",
    generator=generator,
).images

#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")

# Remove the pipeline so we can load the super-resolution pipeline
del pipe
gc.collect()
torch.cuda.empty_cache()

# First super resolution

pipe = IFSuperResolutionPipeline.from_pretrained(
    "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", dtype=torch.float16, device_map="auto"
)

generator = torch.Generator().manual_seed(0)
stage_2_output = pipe(
    image=stage_1_output,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds,
    output_type="pt",
    generator=generator,
).images

#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0]], rows=1, rows=2)

可用的流水线:

Pipeline任务Colab
pipeline_if.py文本到图像生成-
pipeline_if_superresolution.py文本到图像生成-
pipeline_if_img2img.py图像到图像生成-
pipeline_if_img2img_superresolution.py图像到图像生成-
pipeline_if_inpainting.py图像到图像生成-
pipeline_if_inpainting_superresolution.py图像到图像生成-

IFPipeline

类 diffusers.IFPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )

__call__

< >

( prompt: str | list[str] = Nonenum_inference_steps: int = 100timesteps: list = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1height: int | None = Nonewidth: int | None = Noneeta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用等间距的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • height (int,可选,默认为 self.unet.config.sample_size) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认为 self.unet.config.sample_size) — 生成图像的宽度(以像素为单位)。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η):https://huggingface.co/papers/2010.02502。仅适用于 schedulers.DDIMScheduler,对其他调度器将被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个函数,将在推理过程中每 callback_steps 步被调用一次。该函数将以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — callback 函数的调用频率。如果未指定,则回调将在每一步被调用。
  • clean_caption (bool,可选,默认为 True) — 是否在创建嵌入之前清理字幕。需要安装 beautifulsoup4 和 ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。

返回值

~pipelines.stable_diffusion.IFPipelineOutput 或 tuple

~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.

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

示例:

>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch

>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()

>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
...     "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()

>>> image = super_res_1_pipe(
...     image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt"
... ).images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> safety_modules = {
...     "feature_extractor": pipe.feature_extractor,
...     "safety_checker": pipe.safety_checker,
...     "watermarker": pipe.watermarker,
... }
>>> super_res_2_pipe = DiffusionPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
... )
>>> super_res_2_pipe.enable_model_cpu_offload()

>>> image = super_res_2_pipe(
...     prompt=prompt,
...     image=image,
... ).images
>>> image[0].save("./if_stage_II.png")

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • do_classifier_free_guidance (bool,可选,默认为 True) — 是否使用 classifier free guidance
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词应生成的图像数量
  • device — (torch.device,可选): 用于放置生成的嵌入向量的 torch 设备
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入 negative_prompt_embeds。如果未定义,则必须改为传入 negative_prompt_embeds。 在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • clean_caption(bool,默认为 False)— 如果为 True,该函数将在编码之前对提供的 caption 进行预处理和清理。

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

IFSuperResolutionPipeline

class diffusers.IFSuperResolutionPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )

__call__

< >

( prompt: str | list[str] = Noneheight: int = Nonewidth: int = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = Nonenum_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 250clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • height (int,可选,默认为 None) — 生成图像的高度(以像素为单位)。
  • width (int,可选,默认为 None) — 生成图像的宽度(以像素为单位)。
  • image (PIL.Image.Image, np.ndarray, torch.Tensor) — 要放大的图像。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int],可选,默认为 None) — 用于去噪过程的自定义时间步。如果未定义,则使用等间距的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • 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 生成器,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • 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。
  • noise_level (int,可选,默认为 250) — 添加到放大图像中的噪声量。必须位于 [0, 1000) 范围内
  • clean_caption (bool,可选,默认为 True) — 是否在创建嵌入之前清理字幕。需要安装 beautifulsoup4 和 ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。

返回值

~pipelines.stable_diffusion.IFPipelineOutput 或 tuple

~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.

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

示例:

>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch

>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()

>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
...     "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()

>>> image = super_res_1_pipe(
...     image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds
... ).images
>>> image[0].save("./if_stage_II.png")

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • do_classifier_free_guidance (bool,可选,默认为 True) — 是否使用 classifier free guidance
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词应生成的图像数量
  • device — (torch.device,可选): 用于放置生成的嵌入向量的 torch 设备
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入 negative_prompt_embeds。如果未定义,则必须改为传入 negative_prompt_embeds。 在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • clean_caption(bool,默认为 False)— 如果为 True,该函数将在编码之前对提供的 caption 进行预处理和清理。

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

IFImg2ImgPipeline

类 diffusers.IFImg2ImgPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.7num_inference_steps: int = 80timesteps: list = Noneguidance_scale: float = 10.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • image (torch.Tensor or PIL.Image.Image) — Image, or tensor representing an image batch, that will be used as the starting point for the process.
  • strength (float,可选,默认值为 0.7) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时,实际上会忽略 image。
  • num_inference_steps (int,可选,默认值为 80) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用等间距的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认值为 10.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • 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 生成器,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个函数,将在推理过程中每 callback_steps 步被调用一次。该函数将以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — callback 函数的调用频率。如果未指定,则回调将在每一步被调用。
  • clean_caption (bool,可选,默认为 True) — 是否在创建嵌入之前清理字幕。需要安装 beautifulsoup4 和 ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。

返回值

~pipelines.stable_diffusion.IFPipelineOutput 或 tuple

~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.

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

示例:

>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))

>>> pipe = IFImg2ImgPipeline.from_pretrained(
...     "DeepFloyd/IF-I-XL-v1.0",
...     variant="fp16",
...     torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()

>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

>>> image = pipe(
...     image=original_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
...     output_type="pt",
... ).images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
...     "DeepFloyd/IF-II-L-v1.0",
...     text_encoder=None,
...     variant="fp16",
...     torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()

>>> image = super_res_1_pipe(
...     image=image,
...     original_image=original_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • do_classifier_free_guidance (bool,可选,默认为 True) — 是否使用 classifier free guidance
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词应生成的图像数量
  • device — (torch.device,可选): 用于放置生成的嵌入向量的 torch 设备
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入 negative_prompt_embeds。如果未定义,则必须改为传入 negative_prompt_embeds。 在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • clean_caption(bool,默认为 False)— 如果为 True,该函数将在编码之前对提供的 caption 进行预处理和清理。

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

IFImg2ImgSuperResolutionPipeline

class diffusers.IFImg2ImgSuperResolutionPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor]original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.8prompt: str | list[str] = Nonenum_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 250clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • image (torch.Tensor or PIL.Image.Image) — Image, or tensor representing an image batch, that will be used as the starting point for the process.
  • original_image (torch.Tensor 或 PIL.Image.Image) — image 所基于的原始图像。
  • strength (float,可选,默认值为 0.8) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声将达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时基本上会忽略 image。
  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用等间距的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • 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 生成器,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • 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。
  • noise_level (int,可选,默认为 250) — 添加到放大图像中的噪声量。必须位于 [0, 1000) 范围内
  • clean_caption (bool,可选,默认为 True) — 是否在创建嵌入之前清理字幕。需要安装 beautifulsoup4 和 ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。

返回值

~pipelines.stable_diffusion.IFPipelineOutput 或 tuple

~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.

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

示例:

>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))

>>> pipe = IFImg2ImgPipeline.from_pretrained(
...     "DeepFloyd/IF-I-XL-v1.0",
...     variant="fp16",
...     torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()

>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

>>> image = pipe(
...     image=original_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
...     output_type="pt",
... ).images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
...     "DeepFloyd/IF-II-L-v1.0",
...     text_encoder=None,
...     variant="fp16",
...     torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()

>>> image = super_res_1_pipe(
...     image=image,
...     original_image=original_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • do_classifier_free_guidance (bool,可选,默认为 True) — 是否使用 classifier free guidance
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词应生成的图像数量
  • device — (torch.device,可选): 用于放置生成的嵌入向量的 torch 设备
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入 negative_prompt_embeds。如果未定义,则必须改为传入 negative_prompt_embeds。 在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • clean_caption(bool,默认为 False)— 如果为 True,该函数将在编码之前对提供的 caption 进行预处理和清理。

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

IFInpaintingPipeline

class diffusers.IFInpaintingPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )

__call__

< >

( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonemask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 1.0num_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • image (torch.Tensor or PIL.Image.Image) — Image, or tensor representing an image batch, that will be used as the starting point for the process.
  • mask_image (PIL.Image.Image) — Image,或表示图像批次的张量,用于对 image 进行遮罩。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,在使用前会先转换为单通道(亮度)。如果它是张量,则应包含一个颜色通道(L)而不是三个,因此预期的形状应为 (B, H, W, 1)。
  • strength (float,可选,默认为 1.0) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时,实际上会忽略 image。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用等间距的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • 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 生成器,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 一个函数,将在推理过程中每 callback_steps 步被调用一次。该函数将以以下参数被调用:callback(step: int, timestep: int, latents: torch.Tensor)。
  • callback_steps (int,可选,默认为 1) — callback 函数的调用频率。如果未指定,则回调将在每一步被调用。
  • clean_caption (bool,可选,默认为 True) — 是否在创建嵌入之前清理字幕。需要安装 beautifulsoup4 和 ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 diffusers.models.attention_processor 中 self.processor 下定义的 AttentionProcessor。

返回值

~pipelines.stable_diffusion.IFPipelineOutput 或 tuple

~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.

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

示例:

>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO

>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image

>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image

>>> pipe = IFInpaintingPipeline.from_pretrained(
...     "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()

>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

>>> image = pipe(
...     image=original_image,
...     mask_image=mask_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
...     output_type="pt",
... ).images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
...     "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()

>>> image = super_res_1_pipe(
...     image=image,
...     mask_image=mask_image,
...     original_image=original_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • do_classifier_free_guidance (bool,可选,默认为 True) — 是否使用 classifier free guidance
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词应生成的图像数量
  • device — (torch.device,可选): 用于放置生成的嵌入向量的 torch 设备
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入 negative_prompt_embeds。如果未定义,则必须改为传入 negative_prompt_embeds。 在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • clean_caption(bool,默认为 False)— 如果为 True,该函数将在编码之前对提供的 caption 进行预处理和清理。

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

IFInpaintingSuperResolutionPipeline

class diffusers.IFInpaintingSuperResolutionPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor]original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonemask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.8prompt: str | list[str] = Nonenum_inference_steps: int = 100timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 0clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • image (torch.Tensor or PIL.Image.Image) — Image, or tensor representing an image batch, that will be used as the starting point for the process.
  • original_image (torch.Tensor 或 PIL.Image.Image) — image 所基于的原始图像。
  • mask_image (PIL.Image.Image) — Image,或表示图像批次的张量,用于对 image 进行遮罩。遮罩中的白色像素将被重绘,而黑色像素将保留。如果 mask_image 是 PIL 图像,在使用前会先转换为单通道(亮度)。如果它是张量,则应包含一个颜色通道(L)而不是三个,因此预期的形状应为 (B, H, W, 1)。
  • strength (float,可选,默认值为 0.8) — 从概念上讲,表示对参考 image 进行多大程度的变换。取值必须在 0 到 1 之间。image 将作为起始点,strength 越大,添加的噪声越多。去噪步数取决于初始添加的噪声量。当 strength 为 1 时,添加的噪声将达到最大值,去噪过程将运行 num_inference_steps 中指定的完整迭代次数。因此,值为 1 时基本上会忽略 image。
  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • num_inference_steps (int,可选,默认为 100) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于去噪过程的自定义时间步。如果未定义,则使用等间距的 num_inference_steps 个时间步。必须按降序排列。
  • guidance_scale (float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 guidance_scale 小于 1 时忽略)。
  • 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 生成器,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通元组。
  • 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。
  • noise_level (int,可选,默认为 0) — 要添加到放大图像中的噪声量。必须位于 [0, 1000) 范围内
  • clean_caption (bool,可选,默认为 True) — 是否在创建嵌入之前清理字幕。需要安装 beautifulsoup4 和 ftfy。如果未安装这些依赖项,嵌入将直接从原始提示创建。

返回值

~pipelines.stable_diffusion.IFPipelineOutput 或 tuple

~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.

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

示例:

>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO

>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image

>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image

>>> pipe = IFInpaintingPipeline.from_pretrained(
...     "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()

>>> prompt = "blue sunglasses"

>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
...     image=original_image,
...     mask_image=mask_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
...     output_type="pt",
... ).images

>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")

>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
...     "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()

>>> image = super_res_1_pipe(
...     image=image,
...     mask_image=mask_image,
...     original_image=original_image,
...     prompt_embeds=prompt_embeds,
...     negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")

encode_prompt

< >

( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • do_classifier_free_guidance (bool,可选,默认为 True) — 是否使用 classifier free guidance
  • num_images_per_prompt (int,可选,默认为 1) — 每个提示词应生成的图像数量
  • device — (torch.device,可选): 用于放置生成的嵌入向量的 torch 设备
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须改为传入 negative_prompt_embeds。如果未定义,则必须改为传入 negative_prompt_embeds。 在未使用引导时会被忽略(即当 guidance_scale 小于 1 时会被忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • clean_caption(bool,默认为 False)— 如果为 True,该函数将在编码之前对提供的 caption 进行预处理和清理。

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

Update on GitHub