1. AutoPipeline 是什么?
diffusers
库提供了许多用于基本任务的管道(Pipeline),如生成图像、视频、音频和修复。除此之外,还有专门的管道用于适配器和功能,如放大、超分辨率等。
不同的管道类甚至可以使用相同的检查点(Checkpoint),因为它们共享相同的预训练模型组件。由于有如此多的管道,选择使用哪个管道类可能会让人感到不知所措。
为了解决这个问题,diffusers
提供了 AutoPipeline
。
AutoPipeline
让你只需要关心你要完成的任务类型(例如:文生图、图生图、图像修复等),而不需要去记住和选择具体的 DiffusionPipeline
实现类。它会自动根据你加载的模型和传入的参数来选择最合适的管道。
2. 代码示例
示例 1: 文生图 (Text-to-Image) 与图生图 (Image-to-Image)
这个示例展示了如何使用 AutoPipeline
先进行文生图,然后利用已加载的模型高效地切换到图生图任务。
import torch
from diffusers import AutoPipelineForText2Image,AutoPipelineForImage2Image,AutoPipelineForInpainting
from diffusers.utils import load_image
device="cuda"
# Diffusers 提供了许多用于基本任务的管道,如生成图像、视频、音频和修复。
# 除此之外,还有专门的管道用于适配器和功能,如放大、超分辨率等。
# 不同的管道类甚至可以使用相同的检查点,因为它们共享相同的预训练模型!由于有如此多的管道,选择使用哪个管道类可能会让人感到不知所措。
# 所以有了AutoPipeline
# AutoPipeline 让你知道是什么任务就行 (文生图,图生图等),而不需要去记住DiffusionPipeline 这些实际的类
def demo1(): # 使用文生图的autopipeline和图生图的autopipeline
pipeline=AutoPipelineForText2Image.from_pretrained(
"dreamlike-art/dreamlike-photoreal-2.0",
torch_dtype=torch.float16,
use_safetensors=True
).to(device)
prompt="cinematic photo of Godzilla eating sushi with a cat in a izakaya, 35mm photograph, film, professional, 4k, highly detailed"
gen_seed=torch.Generator(device=device).manual_seed(37)
image=pipeline(prompt,generator=gen_seed).images[0]
image.save('./test.png')
# 图生图autopipeline
# 使用from_pipe而不是from_pretrained,因为checkpoint都是同一个,这样可以重用已加载到内存中的模型组件,避免重复下载和加载,效率更高。
# 这种方法之所以可行,是因为像Stable Diffusion这样的基础模型本身就同时支持文生图和图生图两种任务。
pipeline2=AutoPipelineForImage2Image.from_pipe(pipeline).to(device)
init_image=load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-text2img.png")
prompt2 = "cinematic photo of Godzilla eating burgers with a cat in a fast food restaurant, 35mm photograph, film, professional, 4k, highly detailed"
gen_seed2=torch.Generator(device=device).manual_seed(53)
image2=pipeline2(prompt2,image=init_image,generator=gen_seed2).images[0]
image2.save("./test2.png")
示例 2: 图像重绘 (Inpainting)
这个示例展示了如何使用 AutoPipelineForInpainting
来修复或替换图像的特定部分。
def demo2(): # 使用重绘的autopipeline
pipeline=AutoPipelineForInpainting.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
torch_dtype=torch.float16,
use_safetensors=True
).to(device)
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-img2img.png")
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-mask.png") # 重绘需要指明重绘的部分(遮罩)
prompt = "cinematic photo of a owl, 35mm photograph, film, professional, 4k, highly detailed"
# 修正:将 Generator 的设备与 pipeline 的设备保持一致
generator = torch.Generator(device=device).manual_seed(38)
image=pipeline(prompt,image=init_image,mask_image=mask_image,generator=generator, strength=0.4).images[0]
image.save("./test.png")