Diffusers 文档
DeepFloyd IF
并获得增强的文档体验
开始使用
DeepFloyd IF
概述
DeepFloyd IF 是一个新颖的、最先进的开源文本到图像模型,具有高度的真实感和语言理解能力。该模型是一个模块化结构,由一个冻结的文本编码器和三个级联像素扩散模块组成:
- 第一阶段:一个基于文本提示生成 64x64 像素图像的基础模型;
- 第二阶段:一个 64x64 像素 => 256x256 像素的超分辨率模型;以及
- 第三阶段:一个 256x256 像素 => 1024x1024 像素的超分辨率模型。第一阶段和第二阶段利用基于 T5 变换器的冻结文本编码器来提取文本嵌入,然后将其馈送到通过交叉注意力和注意力池化增强的 UNet 架构中。第三阶段是 Stability AI 的 x4 Upscaling 模型。结果是一个高效的模型,性能优于当前最先进的模型,在 COCO 数据集上实现了 6.66 的零样本 FID 分数。我们的工作强调了在级联扩散模型第一阶段中使用更大 UNet 架构的潜力,并描绘了文本到图像合成的 promising 未来。
用法
在使用 IF 之前,您需要接受其使用条件。为此:
- 确保拥有 Hugging Face 账户并已登录。
- 接受 DeepFloyd/IF-I-XL-v1.0 模型卡上的许可。在第一阶段模型卡上接受许可将自动接受其他 IF 模型的许可。
- 确保在本地登录。安装
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。具体来说:
可用检查点
阶段 1
阶段 2
阶段 3
文本到图像生成
默认情况下,Diffusers 利用模型 CPU 卸载功能,以低至 14 GB 的 VRAM 运行整个 IF 管道。
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 模型权重可用于文本引导的图像到图像转换或图像变体。在这种情况下,只需确保使用 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", 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 模型权重可用于文本引导的图像到图像转换或图像变体。在这种情况下,只需确保使用 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", 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")
您还可以缩短扩散过程的步数。
这可以通过 num_inference_steps
参数完成。
pipe("<prompt>", num_inference_steps=30)
或者使用 timesteps
参数
from diffusers.pipelines.deepfloyd_if import fast27_timesteps
pipe("<prompt>", timesteps=fast27_timesteps)
在进行图像变体或图像修复时,您还可以通过强度参数减少时间步数。强度参数是要添加到输入图像中的噪声量,它还决定了去噪过程中要运行的步数。较小的值会减少图像的变化,但运行速度会更快。
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
。请注意,我们尚未对 IF 进行穷尽测试 torch.compile
,它可能无法提供预期结果。
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>")
对于像 Google Colab 免费版这样受限于 CPU RAM 的机器,我们无法一次性将所有模型组件加载到 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.IFPipelineOutput
或 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
输入参数生成。 - 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 字典,如果指定,它将作为参数传递给AttentionProcessor
,其定义位于 diffusers.models.attention_processor 中的self.processor
。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否则返回一个 tuple
。返回元组时,第一个元素是生成的图像列表,第二个元素是布尔值列表,根据 safety_checker
指示相应生成的图像是否可能表示“不适合工作”(nsfw) 或带有水印的内容。
调用管道进行生成时调用的函数。
示例
>>> 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 (
str
或List[str]
, 可选) — 待编码的提示词 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用无分类器引导 - 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
输入参数生成。 - 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.IFPipelineOutput
或 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) — 如 无分类器扩散引导 中定义的引导比例。guidance_scale
定义为 Imagen 论文 中公式 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
输入参数生成。 - 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 字典,如果指定,它将作为参数传递给AttentionProcessor
,其定义位于 diffusers.models.attention_processor 中的self.processor
。 - noise_level (
int
, 可选, 默认为 250) — 添加到放大图像中的噪声量。必须在[0, 1000)
范围内。 - clean_caption (
bool
, 可选, 默认为True
) — 是否在创建嵌入之前清理标题。需要安装beautifulsoup4
和ftfy
。如果未安装依赖项,嵌入将从原始提示词创建。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否则返回一个 tuple
。返回元组时,第一个元素是生成的图像列表,第二个元素是布尔值列表,根据 safety_checker
指示相应生成的图像是否可能表示“不适合工作”(nsfw) 或带有水印的内容。
调用管道进行生成时调用的函数。
示例
>>> 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 (
str
或List[str]
, 可选) — 待编码的提示词 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用无分类器引导 - 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
输入参数生成。 - clean_caption (bool, 默认为
False
) — 如果为True
,函数将在编码前对提供的标题进行预处理和清理。
将提示编码为文本编码器隐藏状态。
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
或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示词。如果未定义,则必须传递prompt_embeds
。 - image (
torch.Tensor
或PIL.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) — 如 无分类器扩散引导 中定义的引导比例。guidance_scale
定义为 Imagen 论文 中公式 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
输入参数生成 negative_prompt_embeds。 - 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 字典,如果指定,将作为self.processor
中定义的AttentionProcessor
的参数传递给 diffusers.models.attention_processor。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否则返回一个 tuple
。返回元组时,第一个元素是生成的图像列表,第二个元素是布尔值列表,根据 safety_checker
指示相应生成的图像是否可能表示“不适合工作”(nsfw) 或带有水印的内容。
调用管道进行生成时调用的函数。
示例
>>> 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
< source >( 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 (
str
或List[str]
, 可选) — 要编码的提示词 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导。 - 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
输入参数生成 negative_prompt_embeds。 - clean_caption (bool, 默认为
False
) — 如果为True
,函数将在编码前对提供的字幕进行预处理和清理。
将提示编码为文本编码器隐藏状态。
IFImg2ImgSuperResolutionPipeline
class diffusers.IFImg2ImgSuperResolutionPipeline
< source >( 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__
< source >( 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.IFPipelineOutput
或 tuple
参数
- image (
torch.Tensor
或PIL.Image.Image
) — 将用作过程起点的图像或表示图像批次的张量。 - 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
输入参数生成 negative_prompt_embeds。 - 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 字典,如果指定,将作为self.processor
中定义的AttentionProcessor
的参数传递给 diffusers.models.attention_processor。 - noise_level (
int
, 可选, 默认为 250) — 添加到升级图像中的噪声量。必须在[0, 1000)
范围内。 - clean_caption (
bool
, 可选, 默认为True
) — 是否在创建嵌入之前清理字幕。需要安装beautifulsoup4
和ftfy
。如果未安装依赖项,嵌入将从原始提示词创建。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否则返回一个 tuple
。返回元组时,第一个元素是生成的图像列表,第二个元素是布尔值列表,根据 safety_checker
指示相应生成的图像是否可能表示“不适合工作”(nsfw) 或带有水印的内容。
调用管道进行生成时调用的函数。
示例
>>> 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
< source >( 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 (
str
或List[str]
, 可选) — 要编码的提示词 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导。 - 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
输入参数生成 negative_prompt_embeds。 - clean_caption (bool, 默认为
False
) — 如果为True
,函数将在编码前对提供的字幕进行预处理和清理。
将提示编码为文本编码器隐藏状态。
IFInpaintingPipeline
class diffusers.IFInpaintingPipeline
< source >( 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__
< source >( 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.IFPipelineOutput
或 tuple
参数
- prompt (
str
或List[str]
, 可选) — 用于引导图像生成的提示词。如果未定义,则必须传入prompt_embeds
。 - image (
torch.Tensor
或PIL.Image.Image
) —Image
,或表示图像批次的张量,将用作过程的起始点。 - mask_image (
PIL.Image.Image
) —Image
,或表示图像批次的张量,用于遮盖image
。遮罩中的白色像素将被重新绘制,而黑色像素将保留。如果mask_image
是 PIL 图像,它在使用前将被转换为单通道(亮度)。如果是张量,它应该包含一个颜色通道 (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]
, 可选) — 用于去噪过程的自定义时间步。如果未定义,将使用等间距的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
输入参数生成负面提示词嵌入。 - 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
如果 return_dict
为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否则返回一个 tuple
。返回元组时,第一个元素是生成的图像列表,第二个元素是布尔值列表,根据 safety_checker
指示相应生成的图像是否可能表示“不适合工作”(nsfw) 或带有水印的内容。
调用管道进行生成时调用的函数。
示例
>>> 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
< source >( 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 (
str
或List[str]
, 可选) — 要编码的提示词 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用无分类器引导 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示词应生成的图像数量 - device — (
torch.device
, 可选): 放置结果嵌入的 torch 设备 - negative_prompt (
str
或List[str]
, 可选) — 不用于引导图像生成的提示词。如果未定义,则必须传入negative_prompt_embeds
。当不使用引导时(即,如果guidance_scale
小于1
),则忽略此参数。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从prompt
输入参数生成文本嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,将从negative_prompt
输入参数生成负面提示词嵌入。 - clean_caption (bool, 默认为
False
) — 如果为True
,函数将在编码前对提供的标题进行预处理和清理。
将提示编码为文本编码器隐藏状态。
IFInpaintingSuperResolutionPipeline
class diffusers.IFInpaintingSuperResolutionPipeline
< source >( 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__
< source >( 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.IFPipelineOutput
或 tuple
参数
- image (
torch.Tensor
或PIL.Image.Image
) —Image
,或表示图像批次的张量,将用作过程的起始点。 - original_image (
torch.Tensor
或PIL.Image.Image
) —image
变体自的原始图像。 - mask_image (
PIL.Image.Image
) —Image
,或表示图像批次的张量,用于遮盖image
。遮罩中的白色像素将被重新绘制,而黑色像素将保留。如果mask_image
是 PIL 图像,它在使用前将被转换为单通道(亮度)。如果是张量,它应该包含一个颜色通道 (L) 而不是 3 个,因此预期形状为(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
输入参数生成负面提示词嵌入。 - 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
如果 return_dict
为 True,则返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否则返回一个 tuple
。返回元组时,第一个元素是生成的图像列表,第二个元素是布尔值列表,根据 safety_checker
指示相应生成的图像是否可能表示“不适合工作”(nsfw) 或带有水印的内容。
调用管道进行生成时调用的函数。
示例
>>> 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
< source >( 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 (
str
或List[str]
, 可选) — 要编码的提示词 - do_classifier_free_guidance (
bool
, 可选, 默认为True
) — 是否使用分类器自由引导 - 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
输入参数生成 negative_prompt_embeds。 - clean_caption (bool, 默认为
False
) — 如果为True
,函数将在编码前预处理并清理提供的标题。
将提示编码为文本编码器隐藏状态。