Diffusers 文档

IP-Adapter

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

IP-Adapter

IP-Adapter 是一种轻量级适配器,旨在将基于图像的指导与文本到图像扩散模型集成。该适配器使用图像编码器提取图像特征,然后将其传递到 UNet 中新添加的交叉注意力层并进行微调。原始 UNet 模型和现有的与文本特征对应的交叉注意力层被冻结。解耦图像和文本特征的交叉注意力可以实现更精细和可控的生成。

IP-Adapter 文件通常约为 100MB,因为它们只包含图像嵌入。这意味着您需要先加载模型,然后使用 load_ip_adapter() 加载 IP-Adapter。

IP-Adapter 可用于许多模型,例如 FluxStable Diffusion 3 等。本指南中的示例使用 Stable Diffusion 和 Stable Diffusion XL。

使用 set_ip_adapter_scale() 参数来缩放 IP-Adapter 在生成过程中的影响。值为 1.0 表示模型仅受图像提示的条件限制,而 0.5 通常会在文本和图像提示之间产生平衡的结果。

import torch
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image

pipeline = AutoPipelineForText2Image.from_pretrained(
  "stabilityai/stable-diffusion-xl-base-1.0",
  torch_dtype=torch.float16
).to("cuda")
pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  weight_name="ip-adapter_sdxl.bin"
)
pipeline.set_ip_adapter_scale(0.8)

将图像作为 ip_adapter_image 与文本提示一起传递以生成图像。

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner.png")
pipeline(
    prompt="a polar bear sitting in a chair drinking a milkshake",
    ip_adapter_image=image,
    negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
).images[0]
IP-Adapter image
IP-Adapter 图像
generated image
生成的图像

请查看以下示例,了解如何将 IP-Adapter 用于其他任务。

图像到图像
图像修复
视频
import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
  "stabilityai/stable-diffusion-xl-base-1.0",
  torch_dtype=torch.float16
).to("cuda")
pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  weight_name="ip-adapter_sdxl.bin"
)
pipeline.set_ip_adapter_scale(0.8)

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_bear_1.png")
ip_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_gummy.png")
pipeline(
    prompt="best quality, high quality",
    image=image,
    ip_adapter_image=ip_image,
    strength=0.5,
).images[0]
input image
输入图像
IP-Adapter image
IP-Adapter 图像
generated image
生成的图像

模型变体

IP-Adapter 有两种变体:Plus 和 FaceID。Plus 变体使用补丁嵌入和 ViT-H 图像编码器。FaceID 变体使用通过 InsightFace 生成的人脸嵌入。

IP-Adapter Plus
IP-Adapter FaceID
import torch
from transformers import CLIPVisionModelWithProjection, AutoPipelineForText2Image

image_encoder = CLIPVisionModelWithProjection.from_pretrained(
    "h94/IP-Adapter",
    subfolder="models/image_encoder",
    torch_dtype=torch.float16
)

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    image_encoder=image_encoder,
    torch_dtype=torch.float16
).to("cuda")

pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  weight_name="ip-adapter-plus_sdxl_vit-h.safetensors"
)

图像嵌入

如果管道运行多次,并且有多个图像,则 prepare_ip_adapter_image_embeds 会生成可重复使用的图像嵌入。每次使用管道时加载和编码多个图像效率低下。预先计算图像嵌入,将其保存到磁盘,并在需要时加载它们更高效。

import torch
from diffusers import AutoPipelineForText2Image

pipeline = AutoPipelineForImage2Image.from_pretrained(
  "stabilityai/stable-diffusion-xl-base-1.0",
  torch_dtype=torch.float16
).to("cuda")

image_embeds = pipeline.prepare_ip_adapter_image_embeds(
    ip_adapter_image=image,
    ip_adapter_image_embeds=None,
    device="cuda",
    num_images_per_prompt=1,
    do_classifier_free_guidance=True,
)

torch.save(image_embeds, "image_embeds.ipadpt")

通过将图像嵌入传递给 ip_adapter_image_embeds 参数来重新加载它们。将 image_encoder_folder 设置为 None,因为不再需要图像编码器来生成图像嵌入。

您还可以从其他来源(例如 ComfyUI)加载图像嵌入。

pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  image_encoder_folder=None,
  weight_name="ip-adapter_sdxl.bin"
)
pipeline.set_ip_adapter_scale(0.8)
image_embeds = torch.load("image_embeds.ipadpt")
pipeline(
    prompt="a polar bear sitting in a chair drinking a milkshake",
    ip_adapter_image_embeds=image_embeds,
    negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
    num_inference_steps=100,
    generator=generator,
).images[0]

遮罩

二进制遮罩可以将 IP-Adapter 图像分配到输出图像的特定区域,这对于组合多个 IP-Adapter 图像非常有用。每个 IP-Adapter 图像都需要一个二进制遮罩。

加载 IPAdapterMaskProcessor 以预处理图像遮罩。为获得最佳效果,请提供输出 heightwidth 以确保不同宽高比的遮罩大小合适。如果输入遮罩已与生成图像的宽高比匹配,则无需设置 heightwidth

import torch
from diffusers import AutoPipelineForText2Image
from diffusers.image_processor import IPAdapterMaskProcessor
from diffusers.utils import load_image

pipeline = AutoPipelineForImage2Image.from_pretrained(
  "stabilityai/stable-diffusion-xl-base-1.0",
  torch_dtype=torch.float16
).to("cuda")

mask1 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_mask1.png")
mask2 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_mask2.png")

processor = IPAdapterMaskProcessor()
masks = processor.preprocess([mask1, mask2], height=1024, width=1024)
mask 1
遮罩 1
mask 2
遮罩 2

将 IP-Adapter 图像及其比例作为列表提供。将预处理的遮罩传递给管道中的 cross_attention_kwargs

face_image1 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_girl1.png")
face_image2 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_girl2.png")

pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  weight_name=["ip-adapter-plus-face_sdxl_vit-h.safetensors"]
)
pipeline.set_ip_adapter_scale([[0.7, 0.7]])

ip_images = [[face_image1, face_image2]]
masks = [masks.reshape(1, masks.shape[0], masks.shape[2], masks.shape[3])]

pipeline(
  prompt="2 girls",
  ip_adapter_image=ip_images,
  negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
  cross_attention_kwargs={"ip_adapter_masks": masks}
).images[0]
IP-Adapter image 1
IP-Adapter 图像 1
IP-Adapter image 2
IP-Adapter 图像 2
Generated image with mask
带遮罩生成
Generated image without mask
不带遮罩生成

应用

以下部分介绍了一些流行的 IP-Adapter 应用。

人脸模型

人脸生成并保留其细节可能具有挑战性。为了帮助生成更准确的人脸,有一些检查点专门以裁剪过的人脸图像为条件。您可以在 h94/IP-Adapter 仓库或 h94/IP-Adapter-FaceID 仓库中找到人脸模型。FaceID 检查点使用 InsightFace 的 FaceID 嵌入,而不是 CLIP 图像嵌入。

我们建议将 DDIMSchedulerEulerDiscreteScheduler 用于人脸模型。

h94/IP-Adapter
h94/IP-Adapter-FaceID
import torch
from diffusers import StableDiffusionPipeline, DDIMScheduler
from diffusers.utils import load_image

pipeline = StableDiffusionPipeline.from_pretrained(
  "stable-diffusion-v1-5/stable-diffusion-v1-5",
  torch_dtype=torch.float16,
).to("cuda")
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="models", 
  weight_name="ip-adapter-full-face_sd15.bin"
)

pipeline.set_ip_adapter_scale(0.5)
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_einstein_base.png")

pipeline(
    prompt="A photo of Einstein as a chef, wearing an apron, cooking in a French restaurant",
    ip_adapter_image=image,
    negative_prompt="lowres, bad anatomy, worst quality, low quality",
    num_inference_steps=100,
).images[0]
IP-Adapter image
IP-Adapter 图像
generated image
生成的图像

多个 IP-Adapter

结合多个 IP-Adapter 可以生成更多样式的图像。例如,您可以使用 IP-Adapter Face 生成一致的人脸和角色,并使用 IP-Adapter Plus 以特定样式生成这些人脸。

使用 CLIPVisionModelWithProjection 加载图像编码器。

import torch
from diffusers import AutoPipelineForText2Image, DDIMScheduler
from transformers import CLIPVisionModelWithProjection
from diffusers.utils import load_image

image_encoder = CLIPVisionModelWithProjection.from_pretrained(
    "h94/IP-Adapter",
    subfolder="models/image_encoder",
    torch_dtype=torch.float16,
)

加载基础模型、调度器和以下 IP-Adapter。

pipeline = AutoPipelineForText2Image.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    image_encoder=image_encoder,
)
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  weight_name=["ip-adapter-plus_sdxl_vit-h.safetensors", "ip-adapter-plus-face_sdxl_vit-h.safetensors"]
)
pipeline.set_ip_adapter_scale([0.7, 0.3])
# enable_model_cpu_offload to reduce memory usage
pipeline.enable_model_cpu_offload()

加载图像和包含特定样式图像的文件夹以应用样式。

face_image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/women_input.png")
style_folder = "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy"
style_images = [load_image(f"{style_folder}/img{i}.png") for i in range(10)]
Face image
人脸图像
Style images
样式图像

将样式和人脸图像作为列表传递给 ip_adapter_image

generator = torch.Generator(device="cpu").manual_seed(0)

pipeline(
    prompt="wonderwoman",
    ip_adapter_image=[style_images, face_image],
    negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
).images[0]
Generated image
生成的图像

即时生成

潜在一致性模型 (LCM) 可以在 4 步或更少步中生成图像,与需要更多步数的其他扩散模型不同,这使其感觉“即时”。IP-Adapter 与 LCM 模型兼容,可即时生成图像。

加载 IP-Adapter 权重并使用 load_lora_weights() 加载 LoRA 权重。

import torch
from diffusers import DiffusionPipeline, LCMScheduler
from diffusers.utils import load_image

pipeline = DiffusionPipeline.from_pretrained(
  "sd-dreambooth-library/herge-style",
  torch_dtype=torch.float16
)

pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="models",
  weight_name="ip-adapter_sd15.bin"
)
pipeline.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
pipeline.scheduler = LCMScheduler.from_config(pipeline.scheduler.config)
# enable_model_cpu_offload to reduce memory usage
pipeline.enable_model_cpu_offload()

尝试使用较低的 IP-Adapter 比例来更多地根据您要应用的样式来条件生成,并记住在您的提示中使用特殊标记来触发其生成。

pipeline.set_ip_adapter_scale(0.4)

prompt = "herge_style woman in armor, best quality, high quality"

ip_adapter_image = load_image("https://user-images.githubusercontent.com/24734142/266492875-2d50d223-8475-44f0-a7c6-08b51cb53572.png")
pipeline(
    prompt=prompt,
    ip_adapter_image=ip_adapter_image,
    num_inference_steps=4,
    guidance_scale=1,
).images[0]
Generated image
生成的图像

结构控制

对于结构控制,将 IP-Adapter 与以深度图、边缘图、姿态估计等为条件的 ControlNet 结合使用。

下面的示例加载了一个以深度图为条件的 ControlNetModel 检查点,并将其与 IP-Adapter 结合使用。

import torch
from diffusers.utils import load_image
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel

controlnet = ControlNetModel.from_pretrained(
  "lllyasviel/control_v11f1p_sd15_depth",
  torch_dtype=torch.float16
)

pipeline = StableDiffusionControlNetPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    controlnet=controlnet,
    torch_dtype=torch.float16
).to("cuda")
pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="models",
  weight_name="ip-adapter_sd15.bin"
)

将深度图和 IP-Adapter 图像传递给流水线。

pipeline(
  prompt="best quality, high quality",
  image=depth_map,
  ip_adapter_image=ip_adapter_image,
  negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
).images[0]
IP-Adapter image
IP-Adapter 图像
Depth map
深度图
Generated image
生成的图像

样式和布局控制

为了进行样式和布局控制,将 IP-Adapter 与 InstantStyle 结合使用。InstantStyle 将 *样式*(颜色、纹理、整体感觉)和 *内容* 分开。它只在模型的样式特定块中应用样式,以防止其扭曲图像的其他区域。这可以生成具有更强和更一致样式以及更好布局控制的图像。

IP-Adapter 仅针对模型的特定部分激活。使用 set_ip_adapter_scale() 方法可以缩放 IP-Adapter 在不同层中的影响。以下示例激活 IP-Adapter 在模型的下行 block_2 和上行 block_0 的第二层中。下行 block_2 是 IP-Adapter 注入布局信息的地方,而上行 block_0 是注入样式的地方。

import torch
from diffusers import AutoPipelineForText2Image
from diffusers.utils import load_image

pipeline = AutoPipelineForText2Image.from_pretrained(
  "stabilityai/stable-diffusion-xl-base-1.0",
  torch_dtype=torch.float16
).to("cuda")
pipeline.load_ip_adapter(
  "h94/IP-Adapter",
  subfolder="sdxl_models",
  weight_name="ip-adapter_sdxl.bin"
)

scale = {
    "down": {"block_2": [0.0, 1.0]},
    "up": {"block_0": [0.0, 1.0, 0.0]},
}
pipeline.set_ip_adapter_scale(scale)

加载样式图像并生成图像。

style_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg")

pipeline(
    prompt="a cat, masterpiece, best quality, high quality",
    ip_adapter_image=style_image,
    negative_prompt="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry",
    guidance_scale=5,
).images[0]
Style image
样式图像
Generated image
生成的图像

您还可以将 IP-Adapter 插入到所有模型层中。这倾向于生成更注重图像提示的图像,并可能降低生成图像的多样性。仅在上行 block_0 或样式层中激活 IP-Adapter。

您无需在 scale 字典中指定所有层。未包含的层将设置为 0,这意味着 IP-Adapter 已禁用。

scale = {
    "up": {"block_0": [0.0, 1.0, 0.0]},
}
pipeline.set_ip_adapter_scale(scale)

pipeline(
    prompt="a cat, masterpiece, best quality, high quality",
    ip_adapter_image=style_image,
    negative_prompt="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry",
    guidance_scale=5,
).images[0]
Generated image (style only)
样式层生成图像
Generated image (IP-Adapter only)
所有层生成图像
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.