跳到正文
Hugging Face Blog·· 2023-04-26精选AI 评分62

如何在免费版 Google Colab 上用 diffusers 运行 IF 文生图模型

Running IF with 🧨 diffusers on a Free Tier Google Colab

AI 导读

Hugging Face 博客介绍如何在免费版 Google Colab(13GB CPU 内存、15GB T4 显存)上用 diffusers 运行 DeepFloyd 的 IF 文生图模型。

推荐理由

原文给出在免费 Colab 上分阶段加载 IF 的完整代码与显存取舍,可迁移到其他大模型的低显存部署。

正文 · AI 翻译

Open In Colab

TL;DR:我们展示如何在免费层级的 Google Colab 上使用 🧨 diffusers 运行最强大的开源文本到图像模型之一 IF。

你也可以直接在 Hugging Face Space 中探索该模型的能力。

if-collage
图片压缩自官方 IF GitHub 仓库。

引言

IF 是一个基于像素的文本到图像生成模型,由 DeepFloyd 于 2023 年 4 月下旬发布。其模型架构深受 Google 闭源的 Imagen 启发。

与 Stable Diffusion 等现有文本到图像模型相比,IF 有两个显著优势:

  • 该模型直接在“像素空间”(即未压缩图像上)运行,而不是像 Stable Diffusion 那样在潜在空间中执行去噪过程。
  • 该模型基于 T5-XXL 的输出进行训练,这是一个比 Stable Diffusion 用作文本编码器的 CLIP 更强大的文本编码器。

因此,IF 更擅长生成具有高频细节的图像(例如人脸和手),并且是首个能够可靠生成带文字图像的开源图像生成模型。

在像素空间运行并使用更强大的文本编码器的缺点是,IF 的参数量显著更高。T5、IF 的文本到图像 UNet 以及 IF 的放大 UNet 分别有 45 亿、43 亿和 12 亿参数。相比之下,Stable Diffusion 2.1 的文本编码器和 UNet 分别只有 4 亿和 9 亿参数。

尽管如此,如果针对低内存使用优化模型,在消费级硬件上运行 IF 是可能的。我们将在本博客文章中展示如何使用 🧨 diffusers 做到这一点。

在 1.) 中,我们解释如何使用 IF 进行文本到图像生成,在 2.) 和 3.) 中,我们介绍 IF 的图像变体和图像修复能力。

💡 注意:我们在这里用速度换取内存收益,以便在免费层级的 Google Colab 上运行 IF。如果你可以使用 A100 等高端 GPU,我们建议将所有模型组件保留在 GPU 上以获得最大速度,如官方 IF 演示中所示。

💡 注意:一些较大的图像已被压缩,以便在博客格式中更快加载。使用官方模型时,它们的质量应该更好!

让我们开始吧 🚀!


IF 的文本生成能力

目录

接受许可

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

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

在 Python shell 中运行登录函数

from huggingface_hub import login

login()

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

优化 IF 以在内存受限硬件上运行

最先进的机器学习不应只掌握在少数精英手中。 民主化机器学习意味着让模型不仅能在最新最强的硬件上运行。

深度学习社区已经创建了世界级的工具,可以在消费级硬件上运行资源密集型模型:

Diffusers 无缝集成了上述库,在优化大型模型时提供了简单的 API。

免费版 Google Colab 既受限于 CPU 内存(13 GB RAM),也受限于 GPU 显存(T4 为 15 GB RAM),这使得运行整个超过 100 亿参数的 IF 模型颇具挑战!

让我们以完整的 float32 精度来梳理 IF 模型各组件的尺寸:

我们无法以 float32 运行该模型,因为 T5 和第一阶段 UNet 的权重各自都大于可用的 CPU 内存。

在 float16 下,T5、第一阶段和第二阶段 UNet 的组件大小分别为 11GB、8.6GB 和 1.25GB,这对 GPU 来说是可行的,但在加载 T5 时我们仍然会遇到 CPU 内存溢出错误(部分 CPU 被其他进程占用)。

因此,我们通过使用 bitsandbytes 8位量化进一步降低 T5 的精度,这允许以低至 8 GB 的大小保存 T5 检查点。

现在每个组件都能单独放入 CPU 和 GPU 内存中,我们需要确保组件在需要时能独占所有 CPU 和 GPU 内存。

Diffusers 支持模块化加载单个组件,即我们可以在不加载 UNet 的情况下加载文本编码器。这种模块化加载将确保我们在管道的给定步骤中只加载所需的组件,以避免耗尽可用的 CPU 内存和 GPU 显存。

让我们试一试 🚀

t2i_64

可用资源

免费版 Google Colab 提供约 13 GB 的 CPU 内存:

!grep MemTotal /proc/meminfo
MemTotal:       13297192 kB

以及具有 15 GB 显存的 NVIDIA T4:

!nvidia-smi
Sun Apr 23 23:14:19 2023       
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.85.12    Driver Version: 525.85.12    CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla T4            Off  | 00000000:00:04.0 Off |                    0 |
| N/A   72C    P0    32W /  70W |   1335MiB / 15360MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
                                                                                
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
+-----------------------------------------------------------------------------+

安装依赖项

某些优化可能需要最新版本的依赖项。如果遇到问题,请仔细检查并升级版本。

! pip install --upgrade \
  diffusers~=0.16 \
  transformers~=4.28 \
  safetensors~=0.3 \
  sentencepiece~=0.1 \
  accelerate~=0.18 \
  bitsandbytes~=0.38 \
  torch~=2.0 -q

1. 文本到图像生成

我们将使用 Diffusers 逐步介绍 IF 的文本到图像生成。我们将简要解释 API 和优化,但更深入的说明可以在 Diffusers、Transformers、Accelerate 和 bitsandbytes 的官方文档中找到。

1.1 加载文本编码器

我们将使用 8 位量化加载 T5。Transformers 通过 load_in_8bit 标志直接支持 bitsandbytes。

标志 variant="8bit" 将下载预量化的权重。

我们还使用 device_map 标志来允许 transformers 将模型层卸载到 CPU 或磁盘。Transformers 大模型支持任意设备映射,可用于将模型参数直接分别加载到可用设备。传递 "auto" 将自动创建设备映射。更多信息请参阅 transformers 文档。

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

1.2 创建文本嵌入

用于访问扩散模型的 Diffusers API 是 DiffusionPipeline 类及其子类。每个 DiffusionPipeline 实例都是一组完全自包含的方法和模型,用于运行扩散网络。我们可以通过将替代实例作为关键字参数传递给 from_pretrained 来覆盖它使用的模型。

在这种情况下,我们为 unet 参数传递了 None,因此不会加载 UNet。这允许我们在不将 UNet 加载到内存的情况下运行扩散过程的文本嵌入部分。

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

IF 还附带了一个超分辨率管道。我们将保存提示嵌入,以便稍后可以直接将它们传递给超分辨率管道。这将允许超分辨率管道在没有文本编码器的情况下加载。

与其让 宇航员只是骑着马,不如也给他们一个牌子!

让我们定义一个合适的提示:

prompt = "a photograph of an astronaut riding a horse holding a sign that says Pixel's in space"

并通过 8 位量化的 T5 模型运行它:

prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

1.3 释放内存

一旦提示嵌入创建完成,我们就不再需要文本编码器了。然而,它仍然在 GPU 的内存中。我们需要移除它,以便加载 UNet。

释放 PyTorch 内存并非易事。我们必须对指向 GPU 上实际分配内存的 Python 对象进行垃圾回收。

首先,使用 Python 关键字 del 删除所有引用已分配 GPU 内存的 Python 对象

del text_encoder
del pipe

删除 Python 对象不足以释放 GPU 内存。垃圾回收才是实际释放 GPU 内存的时候。

此外,我们将调用 torch.cuda.empty_cache()。这个方法并非严格必要,因为缓存的 CUDA 内存将立即可用于进一步分配。清空缓存允许我们在 Colab UI 中验证内存是否可用。

我们将使用一个辅助函数 flush() 来刷新内存。

import gc
import torch

def flush():
    gc.collect()
    torch.cuda.empty_cache()

并运行它

flush()

1.4 阶段 1:主扩散过程

利用我们现在可用的 GPU 内存,我们可以仅使用 UNet 重新加载 DiffusionPipeline 来运行主扩散过程。

variant 和 torch_dtype 标志被 Diffusers 用于以 16 位浮点格式下载和加载权重。

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

通常,我们直接将文本提示传递给 DiffusionPipeline.__call__。然而,我们之前计算了文本嵌入,可以改为传递它们。

IF 还附带了一个超分辨率扩散过程。设置 output_type="pt" 将返回原始的 PyTorch 张量而不是 PIL 图像。这样,我们可以将 PyTorch 张量保留在 GPU 上,并直接将它们传递给阶段 2 的超分辨率管道。

让我们定义一个随机生成器并运行阶段 1 的扩散过程。

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

让我们手动将原始张量转换为 PIL 并预览最终结果。阶段 1 的输出是一个 64x64 的图像。

from diffusers.utils import pt_to_pil

pil_image = pt_to_pil(image)
pipe.watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)

pil_image[0]

t2i_64

再次,我们移除 Python 指针并释放 CPU 和 GPU 内存:

del pipe
flush()

1.5 阶段 2:超分辨率 64x64 到 256x256

IF 附带了一个单独的上采样扩散过程。

我们使用单独的管道运行每个扩散过程。

如果需要,超分辨率管道可以加载文本编码器。然而,我们通常会从第一个 IF 管道获得预先计算的文本嵌入。如果是这样,加载管道时不带文本编码器。

创建管道

pipe = DiffusionPipeline.from_pretrained(
    "DeepFloyd/IF-II-L-v1.0", 
    text_encoder=None, # no use of text encoder => memory savings!
    variant="fp16", 
    torch_dtype=torch.float16, 
    device_map="auto"
)

并运行它,重用预先计算的文本嵌入

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

再次,我们可以检查中间结果。

pil_image = pt_to_pil(image)
pipe.watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)

pil_image[0]

t2i_upscaled

再次,我们删除 Python 指针并释放内存

del pipe
flush()

1.6 阶段 3:超分辨率 256x256 到 1024x1024

IF 的第二个超分辨率模型是之前发布的 Stability AI 的 x4 放大器。

让我们创建管道并使用 device_map="auto" 直接将其加载到 GPU 上。

pipe = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-x4-upscaler", 
    torch_dtype=torch.float16, 
    device_map="auto"
)

🧨 diffusers 让独立开发的扩散模型可以轻松组合,因为 pipeline 可以串联在一起。这里我们只需取之前的 PyTorch tensor 输出,并将其作为 image=image 传给第 3 阶段 pipeline。

💡 注意:x4 Upscaler 不使用 T5,并且有自己的文本编码器。因此,我们不能使用之前创建的 prompt embeddings,而必须传入原始 prompt。

pil_image = pipe(prompt, generator=generator, image=image).images

与 IF pipelines 不同,Stable Diffusion x4 upscaler pipeline 的输出默认不会添加 IF 水印。

我们可以改为手动添加水印。

from diffusers.pipelines.deepfloyd_if import IFWatermarker

watermarker = IFWatermarker.from_pretrained("DeepFloyd/IF-I-XL-v1.0", subfolder="watermarker")
watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)

查看输出图像

pil_image[0]

t2i_upscaled_2

瞧!在免费版 Google Colab 中生成了一张漂亮的 1024x1024 图像。

我们已经展示了 🧨 diffusers 如何轻松分解并以模块化方式加载资源密集型扩散模型。

💡 注意:我们不建议在生产环境中使用上述设置。8bit 量化、手动释放模型权重以及磁盘卸载都会以内存换时间(即推理速度)。如果重复使用 diffusion pipeline,这一点尤其明显。在生产环境中,我们建议使用 40GB A100,并将所有模型组件保留在 GPU 上。参见官方 IF 演示。

2. 图像变体

相同的 IF checkpoints 也可用于文本引导的图像变体和 inpainting。核心扩散过程与 text-to-image 生成相同,只是初始的 noised image 是从要变体或 inpainting 的图像创建的。

要运行图像变体,请使用 IFImg2ImgPipeline.from_pretrained() 和 IFImg2ImgSuperResolution.from_pretrained() 加载相同的 checkpoints。

内存优化的 API 全都一样!

让我们释放上一节的内存。

del pipe
flush()

对于图像变体,我们从想要调整的初始图像开始。

在本节中,我们将改编著名的“Slaps Roof of Car”梗图。让我们从互联网下载它。

import requests

url = "https://i.kym-cdn.com/entries/icons/original/000/026/561/car.jpg"
response = requests.get(url)

并将其加载为 PIL Image

from PIL import Image
from io import BytesIO

original_image = Image.open(BytesIO(response.content)).convert("RGB")
original_image = original_image.resize((768, 512))
original_image

iv_sample

图像变体 pipeline 同时接受 PIL images 和原始 tensors。有关预期输入的更深入文档,请查看 docstrings,这里。

2.1 文本编码器

图像变体由文本引导,因此我们可以定义 prompt 并使用 T5 的 Text Encoder 对其进行编码。

我们再次将文本编码器加载为 8bit 精度。

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

对于图像变体,我们使用 IFImg2ImgPipeline 加载 checkpoint。使用 DiffusionPipeline.from_pretrained(...) 时,checkpoints 会加载到其默认 pipeline 中。IF 的默认 pipeline 是 text-to-image IFPipeline。使用非默认 pipeline 加载 checkpoints 时,必须显式指定 pipeline。

from diffusers import IFImg2ImgPipeline

pipe = IFImg2ImgPipeline.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0", 
    text_encoder=text_encoder, 
    unet=None, 
    device_map="auto"
)

让我们把这位推销员变成动漫角色。

prompt = "anime style"

和之前一样,我们使用 T5 创建文本 embeddings

prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

并释放 GPU 和 CPU 内存。

首先,移除 Python 指针

del text_encoder
del pipe

然后释放内存

flush()

2.2 第 1 阶段:主扩散过程

接下来,我们只将第 1 阶段 UNet 权重加载到 pipeline 对象中,就像上一节所做的那样。

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

图像变体 pipeline 同时需要原始图像和 prompt embeddings。

我们可以选择使用 strength 参数来配置变化程度。strength 直接控制添加的噪声量。更高的 strength 意味着更多噪声,也就意味着更多变化。

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

让我们再次检查中间的 64x64。

pil_image = pt_to_pil(image)
pipe.watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)

pil_image[0]

iv_sample_1

看起来不错!我们可以释放内存并再次放大图像。

del pipe
flush()

2.3 第 2 阶段:超分辨率

对于超分辨率,使用 IFImg2ImgSuperResolutionPipeline 和与之前相同的 checkpoint 加载 checkpoint。

from diffusers import IFImg2ImgSuperResolutionPipeline

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

💡 注意:图像变体超分辨率流程需要生成的图像以及原始图像。

你也可以在此图像上使用 Stable Diffusion x4 放大器。请随意使用第 1.6 节中的代码片段进行尝试。

image = pipe(
    image=image,
    original_image=original_image,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds, 
    generator=generator,
).images[0]
image

iv_sample_2

很好!让我们释放内存,看看最终的修复流程。

del pipe
flush()

3. 修复

IF 修复流程与图像变体相同,只是仅对图像的一个选定区域进行去噪。

我们使用图像掩码指定要修复的区域。

让我们展示 IF 惊人的“字母生成”能力。我们可以用不同的标语替换这个标志文本。

首先,让我们下载图像

import requests

url = "https://i.imgflip.com/5j6x75.jpg"
response = requests.get(url)

并将其转换为 PIL 图像

from PIL import Image
from io import BytesIO

original_image = Image.open(BytesIO(response.content)).convert("RGB")
original_image = original_image.resize((512, 768))
original_image

inpainting_sample

我们将对标志进行掩码,以便替换其文本。

为方便起见,我们预先生成了掩码并将其加载到 HF 数据集中。

让我们下载它。

from huggingface_hub import hf_hub_download

mask_image = hf_hub_download("diffusers/docs-images", repo_type="dataset", filename="if/sign_man_mask.png")
mask_image = Image.open(mask_image)

mask_image

masking_sample

💡 注意:你可以通过手动创建灰度图像来自己创建掩码。

from PIL import Image
import numpy as np

height = 64
width = 64

example_mask = np.zeros((height, width), dtype=np.int8)

# Set masked pixels to 255
example_mask[20:30, 30:40] = 255

# Make sure to create the image in mode 'L'
# meaning single channel grayscale
example_mask = Image.fromarray(example_mask, mode='L')

example_mask

masking_by_hand

现在我们可以开始修复了 🎨🖌

3.1. 文本编码器

同样,我们首先加载文本编码器

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

这次,我们使用文本编码器权重初始化 IFInpaintingPipeline 修复流程。

from diffusers import IFInpaintingPipeline

pipe = IFInpaintingPipeline.from_pretrained(
    "DeepFloyd/IF-I-XL-v1.0", 
    text_encoder=text_encoder, 
    unet=None, 
    device_map="auto"
)

好的,让我们让这个人为更多层做广告吧。

prompt = 'the text, "just stack more layers"'

定义提示后,我们可以创建提示嵌入

prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)

和之前一样,我们释放内存

del text_encoder
del pipe
flush()

3.2 阶段 1:主扩散过程

和之前一样,我们现在仅使用 UNet 加载阶段 1 流程。

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

现在,我们需要传入输入图像、掩码图像和提示嵌入。

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

让我们看看中间输出。

pil_image = pt_to_pil(image)
pipe.watermarker.apply_watermark(pil_image, pipe.unet.config.sample_size)

pil_image[0]

inpainted_output

看起来不错!文本相当一致!

让我们释放内存,以便对图像进行放大

del pipe
flush()

3.3 阶段 2:超分辨率

对于超分辨率,使用 IFInpaintingSuperResolutionPipeline 加载检查点。

from diffusers import IFInpaintingSuperResolutionPipeline

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

修复超分辨率流程需要生成的图像、原始图像、掩码图像和提示嵌入。

让我们进行最后的去噪运行。

image = pipe(
    image=image,
    original_image=original_image,
    mask_image=mask_image,
    prompt_embeds=prompt_embeds,
    negative_prompt_embeds=negative_embeds, 
    generator=generator,
).images[0]
image

inpainted_final_output

很好,模型生成的文本没有出现任何拼写错误!

结论

IF 在 32 位浮点精度下总共使用 40 GB 的权重。我们展示了仅使用开源模型和库,IF 可以在免费的 Google Colab 实例上运行。

机器学习生态系统从共享开放工具和开放模型中受益匪浅。仅此笔记本就使用了来自 DeepFloyd、StabilityAI 和 Google 的模型。所使用的库——Diffusers、Transformers、Accelerate 和 bitsandbytes——都受益于来自不同组织的无数贡献者。

非常感谢 DeepFloyd 团队创建并开源了 IF,并为优秀机器学习的民主化做出了贡献 🤗。

来源:Hugging Face Blog · huggingface.co