Diffusers 文档

DeepFloyd IF

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

DeepFloyd IF

概述

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

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

使用方法

在使用 IF 之前,您需要接受其使用条件。为此,请

  1. 确保您拥有 Hugging Face 帐户 并已登录。
  2. DeepFloyd/IF-I-XL-v1.0 的模型卡上接受许可。在阶段 I 模型卡上接受许可将自动接受其他 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 卸载,以尽可能少的 14 GB VRAM 运行整个 IF pipeline。

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", torch_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", torch_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, torch_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 模型权重可以用于文本引导的图像到图像转换或图像变体。在这种情况下,只需确保使用 IFImg2ImgPipelineIFImg2ImgSuperResolutionPipeline pipelines 加载权重。

注意:您也可以直接将文本到图像 (text-to-image) 流程的权重移动到图像到图像 (image-to-image) 流程,而无需重复加载。只需使用 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", torch_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", torch_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, torch_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 模型权重可以用于文本引导的图像到图像转换或图像变体。在这种情况下,只需确保使用 IFInpaintingPipelineIFInpaintingSuperResolutionPipeline 流程加载权重即可。

注意:您也可以直接将文本到图像 (text-to-image) 流程的权重移动到图像到图像 (image-to-image) 流程,而无需重复加载。只需使用 ~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", torch_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", torch_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, torch_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 加载之外,流程还可以直接从彼此加载。

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", torch_dtype=torch.float16)
pipe.to("cuda")

您还可以使用较少的 timestep 运行扩散过程。

这可以通过 num_inference_steps 参数来完成

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

或者使用 timesteps 参数

from diffusers.pipelines.deepfloyd_if import fast27_timesteps

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

在进行图像变体或图像修复时,您还可以使用 strength 参数来减少 timestep 的数量。strength 参数是添加到输入图像的噪声量,它也决定了去噪过程中运行的步数。数值越小,图像变化越小,但运行速度越快。

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

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", torch_dtype=torch.float16)
pipe.to("cuda")

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 卸载 API。

可以使用基于模型的 CPU 卸载,

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

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

pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_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 RAM 受限的机器,例如 Google Colab 免费套餐,我们无法一次将所有模型组件加载到 CPU,我们可以手动仅在需要相应的模型组件时才加载带有文本编码器或 UNet 的流程。

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", torch_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", torch_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)

可用流程:

流程 任务 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

class diffusers.IFPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None num_inference_steps: int = 100 timesteps: typing.List[int] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None 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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) ~pipelines.stable_diffusion.IFPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示语。如果未定义,则必须传递 prompt_embeds 来代替。
  • num_inference_steps (int, 可选, 默认为 100) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会以较慢的推理速度为代价。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义 timestep。如果未定义,则使用等间距的 num_inference_steps timestep。 必须以降序排列。
  • 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 则忽略)。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 要生成的图像数量。
  • 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 generator,用于使生成过程具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可以用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可以用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • 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。如果未安装依赖项,将从原始提示创建嵌入。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 AttentionProcessor,定义在 diffusers.models.attention_processorself.processor 下。

返回

~pipelines.stable_diffusion.IFPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适宜在工作场所观看”(nsfw)或带有水印的内容。

调用 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: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )

参数

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

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

IFSuperResolutionPipeline

class diffusers.IFSuperResolutionPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler image_noising_scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None height: int = None width: int = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 4.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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 250 clean_caption: bool = True ) ~pipelines.stable_diffusion.IFPipelineOutputtuple

参数

  • prompt (strList[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) — Guidance scale,定义于 Classifier-Free Diffusion Guidance 中。 guidance_scale 定义为 Imagen Paper 中公式 2 的 w。 当 guidance_scale > 1 时,Guidance scale 生效。较高的 guidance scale 会鼓励生成与文本 prompt 更紧密相关的图像,但通常会以降低图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 negative_prompt_embeds。 当不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。 仅适用于 schedulers.DDIMScheduler,对于其他 scheduler 将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或一组 torch generator(s),用于使生成过程确定。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • 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 函数将被调用的频率。 如果未指定,则将在每一步调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • noise_level (int, 可选, 默认为 250) — 要添加到放大图像的噪声量。 必须在范围 [0, 1000)
  • clean_caption (bool, 可选, 默认为 True) — 是否在创建 embeddings 之前清理 caption。 需要安装 beautifulsoup4ftfy。 如果未安装依赖项,则将从原始 prompt 创建 embeddings。

返回

~pipelines.stable_diffusion.IFPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适宜在工作场所观看”(nsfw)或带有水印的内容。

调用 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: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )

参数

  • prompt (strList[str], 可选) — 要编码的 prompt
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器 guidance
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 应生成的图像数量
  • device — (torch.device, 可选): 用于放置结果 embeddings 的 torch 设备
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 negative_prompt_embeds。 代替。 如果未定义,则必须传递 negative_prompt_embeds。 代替。 当不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • clean_caption (bool, 默认为 False) — 如果为 True,该函数将在编码之前预处理和清理提供的 caption。

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

IFImg2ImgPipeline

class diffusers.IFImg2ImgPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 0.7 num_inference_steps: int = 80 timesteps: typing.List[int] = None guidance_scale: float = 10.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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) ~pipelines.stable_diffusion.IFPipelineOutput or tuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示语。如果未定义,则必须传递 prompt_embeds 来替代。
  • image (torch.TensorPIL.Image.Image) — Image,或表示图像批次的张量,将用作处理的起点。
  • 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 (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)
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • 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。如果未安装依赖项,则将从原始提示创建嵌入。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会将其传递给 AttentionProcessor,如 diffusers.models.attention_processorself.processor 下定义的那样。

返回

~pipelines.stable_diffusion.IFPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适宜在工作场所观看”(nsfw)或带有水印的内容。

调用 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: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )

参数

  • prompt (strList[str], 可选) — 要编码的提示语
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器引导
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示应生成的图像数量
  • device — (torch.device, 可选): 用于放置结果嵌入的 torch 设备
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 negative_prompt_embeds。 如果未定义,则必须传递 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。
  • clean_caption (bool, 默认为 False) — 如果为 True,该函数将在编码前预处理和清理提供的 caption。

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

IFImg2ImgSuperResolutionPipeline

class diffusers.IFImg2ImgSuperResolutionPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler image_noising_scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_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, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 0.8 prompt: typing.Union[str, typing.List[str]] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 4.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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 250 clean_caption: bool = True ) ~pipelines.stable_diffusion.IFPipelineOutputtuple

参数

  • image (torch.TensorPIL.Image.Image) — Image,或表示图像批次的 tensor,将用作该过程的起点。
  • original_image (torch.TensorPIL.Image.Image) — image 所基于的原始图像。
  • strength (float, 可选, 默认为 0.8) — 从概念上讲,表示要转换参考 image 的程度。 必须介于 0 和 1 之间。 image 将用作起点,strength 越大,向其中添加的噪声就越多。 去噪步骤的数量取决于最初添加的噪声量。 当 strength 为 1 时,添加的噪声将是最大的,并且去噪过程将运行 num_inference_steps 中指定的完整迭代次数。 因此,值为 1 本质上会忽略 image
  • prompt (strList[str], 可选) — 用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 prompt_embeds
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义 timesteps。 如果未定义,则使用等间距的 num_inference_steps timesteps。 必须按降序排列。
  • guidance_scale (float, 可选, 默认为 4.0) — Guidance scale,定义于 Classifier-Free Diffusion Guidanceguidance_scale 定义为 Imagen Paper 等式 2 中的 w。 通过设置 guidance_scale > 1 启用 Guidance scale。 较高的 guidance scale 鼓励生成与文本 prompt 紧密相关的图像,通常以降低图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 negative_prompt_embeds。 否则将被忽略(即,如果 guidance_scale 小于 1,则忽略)。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η): https://arxiv.org/abs/2010.02502。 仅适用于 schedulers.DDIMScheduler,对于其他 scheduler 将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或一组 torch generator(s) 以使生成具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。 在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion.IFPipelineOutput 而不是普通 tuple。
  • callback (Callable, 可选) — 将在推理期间每 callback_steps 步调用的函数。 该函数将使用以下参数调用: callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 将调用 callback 函数的频率。 如果未指定,则将在每个步骤调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则作为 AttentionProcessor 传递,定义在 diffusers.models.attention_processorself.processor 下。
  • noise_level (int, 可选, 默认为 250) — 要添加到放大图像的噪声量。 必须在 [0, 1000) 范围内
  • clean_caption (bool, 可选, 默认为 True) — 是否在创建 embeddings 之前清理 caption。 需要安装 beautifulsoup4ftfy。 如果未安装依赖项,将从原始 prompt 创建 embeddings。

返回

~pipelines.stable_diffusion.IFPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适宜在工作场所观看”(nsfw)或带有水印的内容。

调用 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: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )

参数

  • prompt (strList[str], 可选) — 要编码的 prompt
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器引导(classifier free guidance)
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 应生成的图像数量
  • device — (torch.device, 可选): 用于放置结果 embeddings 的 torch 设备
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds。如果未定义,则必须传递 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。
  • clean_caption (bool, 默认为 False) — 如果为 True,该函数将在编码前预处理和清理提供的 caption。

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

IFInpaintingPipeline

class diffusers.IFInpaintingPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 1.0 num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 7.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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) ~pipelines.stable_diffusion.IFPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 prompt_embeds
  • image (torch.TensorPIL.Image.Image) — Image,或表示图像批次的 tensor,将用作该过程的起点。
  • mask_image (PIL.Image.Image) — Image,或表示图像批次的 tensor,用于遮罩 image。蒙版中的白色像素将被重新绘制,而黑色像素将保留。如果 mask_image 是 PIL 图像,则在使用前将其转换为单通道(亮度)。如果它是 tensor,则它应包含一个颜色通道 (L) 而不是 3 个,因此预期的形状应为 (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], 可选) — 用于去噪过程的自定义 timesteps。如果未定义,则使用等间距的 num_inference_steps timesteps。必须按降序排列。
  • guidance_scale (float, 可选, 默认为 7.0) — Guidance scale,定义在 Classifier-Free Diffusion Guidance 中。 guidance_scale 定义为 Imagen Paper 的等式 2 中的 w。通过设置 guidance_scale > 1 启用 Guidance scale。较高的 guidance scale 鼓励生成与文本 prompt 紧密相关的图像,但通常以较低的图像质量为代价。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须改为传递 negative_prompt_embeds。当不使用引导时(即,如果 guidance_scale 小于 1 时)将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η):https://arxiv.org/abs/2010.02502。仅适用于 schedulers.DDIMScheduler,对于其他调度器将被忽略。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成确定性的一个或多个 torch generator
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • 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) — 是否在创建 embeddings 之前清理 caption。 需要安装 beautifulsoup4ftfy。 如果未安装依赖项,将从原始 prompt 创建 embeddings。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则传递给 AttentionProcessor,定义在 diffusers.models.attention_processorself.processor 下。

返回

~pipelines.stable_diffusion.IFPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适宜在工作场所观看”(nsfw)或带有水印的内容。

调用 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: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )

参数

  • prompt (strList[str], 可选) — 要编码的 prompt
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器 guidance
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个 prompt 应生成的图像数量
  • device — (torch.device, 可选): 用于放置结果 embeddings 的 torch 设备
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 negative_prompt_embeds。 代替。 如果未定义,则必须传递 negative_prompt_embeds。 代替。 当不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,将从 prompt 输入参数生成文本 embeddings。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的 negative 文本 embeddings。 可用于轻松调整文本输入,例如 prompt 权重。 如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • clean_caption (bool, 默认为 False) — 如果为 True,该函数将在编码之前预处理和清理提供的 caption。

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

IFInpaintingSuperResolutionPipeline

class diffusers.IFInpaintingSuperResolutionPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler image_noising_scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_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, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 0.8 prompt: typing.Union[str, typing.List[str]] = None num_inference_steps: int = 100 timesteps: typing.List[int] = None guidance_scale: float = 4.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 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: 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 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 0 clean_caption: bool = True ) ~pipelines.stable_diffusion.IFPipelineOutputtuple

参数

  • image (torch.TensorPIL.Image.Image) — Image,或表示图像批次的 tensor,将用作该过程的起点。
  • original_image (torch.TensorPIL.Image.Image) — image 从其变化而来的原始图像。
  • mask_image (PIL.Image.Image) — Image,或表示图像批次的 tensor,用于遮罩 image。 蒙版中的白色像素将被重新绘制,而黑色像素将被保留。 如果 mask_image 是 PIL 图像,它将在使用前转换为单通道(亮度)。 如果它是 tensor,则应包含一个颜色通道 (L) 而不是 3 个,因此预期的形状应为 (B, H, W, 1)
  • strength (float, 可选, 默认为 0.8) — 从概念上讲,指示转换参考 image 的程度。 必须介于 0 和 1 之间。 image 将用作起点,strength 越大,添加的噪声就越大。 去噪步骤的数量取决于最初添加的噪声量。 当 strength 为 1 时,添加的噪声将是最大的,并且去噪过程将运行完整的 num_inference_steps 中指定的迭代次数。 因此,值为 1 实质上忽略了 image
  • prompt (strList[str], 可选) — 用于引导图像生成的 prompt 或 prompts。 如果未定义,则必须传递 prompt_embeds。 代替。
  • num_inference_steps (int, 可选, 默认为 100) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义 timesteps。 如果未定义,则使用相等间隔的 num_inference_steps timesteps。 必须按降序排列。
  • guidance_scale (float, 可选, 默认为 4.0) — Guidance scale,定义在 Classifier-Free Diffusion Guidance 中。 guidance_scale 定义为 Imagen Paper 的公式 2 中的 w。 Guidance scale 通过设置 guidance_scale > 1 启用。 较高的 guidance scale 鼓励生成与文本 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 生成器
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • 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 函数的频率。如果未指定,则将在每个步骤调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则作为 self.processor 下定义的 AttentionProcessor 的参数传递,定义在 diffusers.models.attention_processor 中。
  • noise_level (int, 可选, 默认为 0) — 要添加到放大图像的噪声量。必须在范围 [0, 1000)
  • clean_caption (bool, 可选, 默认为 True) — 是否在创建嵌入之前清理标题。需要安装 beautifulsoup4ftfy。如果未安装依赖项,则将从原始提示创建嵌入。

返回

~pipelines.stable_diffusion.IFPipelineOutputtuple

如果 return_dict 为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表,第二个元素是 bool 列表,指示根据 safety_checker,相应的生成图像是否可能表示“不适宜在工作场所观看”(nsfw)或带有水印的内容。

调用 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: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )

参数

  • prompt (strList[str], 可选) — 要编码的提示
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器引导
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示应生成的图像数量
  • device — (torch.device, 可选): 用于放置结果嵌入的 torch 设备
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds。 代替。如果未定义,则必须传递 negative_prompt_embeds。 代替。当不使用引导时忽略(即,如果 guidance_scale 小于 1,则忽略)。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • clean_caption (bool, 默认为 False) — 如果为 True,该函数将在编码之前预处理和清理提供的标题。

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

< > 更新 在 GitHub 上