擴散模型課程文件

🤗 Diffusers 簡介

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Open In Colab

🤗 Diffusers 簡介

diffusers_library

在本 notebook 中,你將訓練你的第一個 diffusion 模型來 生成可愛的蝴蝶圖片🦋。在此過程中,你將學習 🤗 Diffusers 庫的核心元件,這將為我們稍後在課程中將要介紹的更高階應用打下良好基礎。

讓我們深入瞭解!

你將學到什麼

在本 notebook 中你將:

  • 看到一個強大的自定義 diffusion 模型 pipeline 的實際操作(並瞭解如何製作你自己的版本)
  • 透過以下步驟建立你自己的迷你 pipeline:
    • 回顧 diffusion 模型背後的核心思想
    • 從 Hub 載入資料用於訓練
    • 探索我們如何使用 scheduler 為這些資料新增噪聲
    • 建立和訓練 UNet 模型
    • 將各個部分組合成一個可工作的 pipeline
  • 編輯並執行一個用於初始化更長訓練任務的指令碼,該指令碼將處理:
    • 透過 🤗 Accelerate 進行多 GPU 訓練
    • 實驗日誌記錄以跟蹤關鍵統計資料
    • 將最終模型上傳到 Hugging Face Hub

❓如果你有任何問題,請在 Hugging Face Discord 伺服器的 #diffusion-models-class 頻道中提出。如果你還沒有註冊,可以在這裡註冊:https://huggingface.co/join/discord

先決條件

在深入研究本 notebook 之前,你應該:

  • 📖 閱讀第 1 單元的材料
  • 🤗 在 Hugging Face Hub 上建立一個賬戶。如果你還沒有賬戶,可以在這裡建立:https://huggingface.co/join

第 1 步:設定

執行以下單元格以安裝 diffusers 庫以及其他一些依賴項

%pip install -qq -U diffusers datasets transformers accelerate ftfy pyarrow==9.0.0

接下來,訪問 https://huggingface.co/settings/tokens 並建立一個具有寫入許可權的訪問令牌(如果你還沒有的話)

Screenshot from 2022-11-10 12-23-34.png

你可以使用命令列 (huggingface-cli login) 或執行以下單元格來使用此令牌登入

>>> from huggingface_hub import notebook_login

>>> notebook_login()
Login successful
Your token has been saved to /root/.huggingface/token

然後您需要安裝 Git-LFS 才能上傳您的模型檢查點

%%capture
!sudo apt -qq install git-lfs
!git config --global credential.helper store

最後,讓我們匯入將要使用的庫,並定義一些方便的函式,我們將在 notebook 的後面部分使用它們

import numpy as np
import torch
import torch.nn.functional as F
from matplotlib import pyplot as plt
from PIL import Image


def show_images(x):
    """Given a batch of images x, make a grid and convert to PIL"""
    x = x * 0.5 + 0.5  # Map from (-1, 1) back to (0, 1)
    grid = torchvision.utils.make_grid(x)
    grid_im = grid.detach().cpu().permute(1, 2, 0).clip(0, 1) * 255
    grid_im = Image.fromarray(np.array(grid_im).astype(np.uint8))
    return grid_im


def make_grid(images, size=64):
    """Given a list of PIL images, stack them together into a line for easy viewing"""
    output_im = Image.new("RGB", (size * len(images), size))
    for i, im in enumerate(images):
        output_im.paste(im.resize((size, size)), (i * size, 0))
    return output_im


# Mac users may need device = 'mps' (untested)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

好的,我們都準備好了!

Dreambooth: 搶先一睹未來

如果你在過去幾個月裡關注過任何與人工智慧相關的社交媒體,你一定聽說過 Stable Diffusion。它是一個強大的文字條件潛在 diffusion 模型(別擔心,我們將會學習所有這些術語的含義)。但它有一個缺點:除非我們足夠出名,我們的照片遍佈網際網路,否則它不知道你我長什麼樣。

Dreambooth 讓我們能夠建立我們自己的模型變體,使其對特定的人臉、物體或風格有額外的瞭解。Corridor Crew 製作了一個出色的影片,使用這項技術來講述具有一致角色的故事,這是這項技術能做什麼的一個很好的例子。

>>> from IPython.display import YouTubeVideo

>>> YouTubeVideo("W4Mcuh38wyM")

這是一個使用在一個名為“土豆頭先生”的流行兒童玩具的 5 張照片上訓練的模型的例子。

首先,我們載入 pipeline。這將從 Hub 下載模型權重等。由於這將為一個單行演示下載數 GB 的資料,歡迎你跳過此單元格,只欣賞示例輸出!

from diffusers import StableDiffusionPipeline

# Check out https://huggingface.co/sd-dreambooth-library for loads of models from the community
model_id = "sd-dreambooth-library/mr-potato-head"

# Load the pipeline
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to(device)

一旦 pipeline 載入完成,我們就可以生成影像

>>> prompt = "an abstract oil painting of sks mr potato head by picasso"
>>> image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
>>> image

練習: 嘗試使用不同的提示詞自己動手試試。sks 標記在這裡代表新概念的唯一識別符號——如果省略它會發生什麼?你也可以嘗試改變取樣步數(可以設定多低?)和 guidance_scale,它決定了模型將多大程度上嘗試匹配提示詞。

那個神奇的 pipeline 中發生了很多事情!到課程結束時,你將瞭解這一切是如何工作的。現在,讓我們來看看如何從頭開始訓練一個 diffusion 模型。

MVP (最小可行 Pipeline)

🤗 Diffusers 的核心 API 分為三個主要元件

  1. Pipelines: 高階類,旨在以使用者友好的方式從流行的已訓練 diffusion 模型中快速生成樣本。
  2. Models: 用於訓練新 diffusion 模型的流行架構,例如 UNet
  3. Schedulers: 在*推理*期間從噪聲生成影像以及為*訓練*生成噪聲影像的各種技術。

Pipelines 對終端使用者來說非常棒,但如果你來這裡參加這門課程,我們假設你想知道幕後發生了什麼!所以,在本 notebook 的其餘部分,我們將構建我們自己的 pipeline,能夠生成小的蝴蝶圖片。這是最終結果的演示:

>>> from diffusers import DDPMPipeline

>>> # Load the butterfly pipeline
>>> butterfly_pipeline = DDPMPipeline.from_pretrained("johnowhitaker/ddpm-butterflies-32px").to(device)

>>> # Create 8 images
>>> images = butterfly_pipeline(batch_size=8).images

>>> # View the result
>>> make_grid(images)

也許沒有 DreamBooth 示例那麼令人印象深刻,但我們是從頭開始訓練,使用的資料量大約是訓練 Stable Diffusion 的 0.0001%。說到訓練,回想一下本單元的介紹,訓練一個 diffusion 模型大致如下:

  1. 從訓練資料中載入一些影像
  2. 新增不同程度的噪聲。
  3. 將輸入的噪聲版本輸入模型
  4. 評估模型在去噪這些輸入方面的表現如何
  5. 利用這些資訊更新模型權重,然後重複

我們將在接下來的幾節中逐一探討這些步驟,直到我們有一個完整的訓練迴圈工作,然後我們將探討如何從訓練好的模型中取樣,以及如何將所有東西打包成一個 pipeline 以便輕鬆分享。讓我們從資料開始……

第 2 步:下載訓練資料集

對於這個例子,我們將使用 Hugging Face Hub 上的一個影像資料集。具體來說,是這個包含 1000 張蝴蝶圖片的集合。這是一個非常小的資料集,所以我們也包括了一些更大選項的註釋程式碼行。如果你更喜歡使用自己的影像集合,也可以使用註釋掉的程式碼示例來從資料夾載入圖片。

import torchvision
from datasets import load_dataset
from torchvision import transforms

dataset = load_dataset("huggan/smithsonian_butterflies_subset", split="train")

# Or load images from a local folder
# dataset = load_dataset("imagefolder", data_dir="path/to/folder")

# We'll train on 32-pixel square images, but you can try larger sizes too
image_size = 32
# You can lower your batch size if you're running out of GPU memory
batch_size = 64

# Define data augmentations
preprocess = transforms.Compose(
    [
        transforms.Resize((image_size, image_size)),  # Resize
        transforms.RandomHorizontalFlip(),  # Randomly flip (data augmentation)
        transforms.ToTensor(),  # Convert to tensor (0, 1)
        transforms.Normalize([0.5], [0.5]),  # Map to (-1, 1)
    ]
)


def transform(examples):
    images = [preprocess(image.convert("RGB")) for image in examples["image"]]
    return {"images": images}


dataset.set_transform(transform)

# Create a dataloader from the dataset to serve up the transformed images in batches
train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True)

我們可以抓取一批影像並像這樣檢視其中的一些

>>> xb = next(iter(train_dataloader))["images"].to(device)[:8]
>>> print("X shape:", xb.shape)
>>> show_images(xb).resize((8 * 64, 64), resample=Image.NEAREST)
X shape: torch.Size([8, 3, 32, 32])

我們堅持使用一個包含 32 畫素影像的小資料集,以使本 notebook 中的訓練時間可控。

第 3 步:定義 Scheduler

我們的訓練計劃是獲取這些輸入影像並向其新增噪聲,然後將噪聲影像輸入模型。在推理過程中,我們將使用模型的預測來迭代地去除噪聲。在 diffusers 中,這兩個過程都由 scheduler 處理。

噪聲排程決定了在不同時間步長新增多少噪聲。以下是我們如何使用“DDPM”訓練和取樣的預設設定建立一個 scheduler(基於論文 “Denoising Diffusion Probabilistic Models”

from diffusers import DDPMScheduler

noise_scheduler = DDPMScheduler(num_train_timesteps=1000)

DDPM 論文描述了一個在每個“時間步”新增少量噪聲的破壞過程。給定某個時間步的 $x_{t-1}$,我們可以透過以下方式得到下一個(稍微更嘈雜的)版本 $x_t$

$q(\mathbf{x}t \vert \mathbf{x}{t-1}) = \mathcal{N}(\mathbf{x}t; \sqrt{1 - \beta_t} \mathbf{x}{t-1}, \betat\mathbf{I}) \quad q(\mathbf{x}{1:T} \vert \mathbf{x}0) = \prod^T{t=1} q(\mathbf{x}t \vert \mathbf{x}{t-1})$

也就是說,我們取 $x{t-1}$,將其乘以 $\sqrt{1 - \beta_t}$ 並加上乘以 $\beta_t$ 的噪聲。這個 $\beta$ 是根據某個排程為每個 t 定義的,並決定了每個時間步新增多少噪聲。現在,我們不一定想做這個操作 500 次來得到 $x{500}$,所以我們有另一個公式來在給定 $x_0$ 的情況下得到任意 t 的 $x_t$

$\begin{aligned} q(\mathbf{x}t \vert \mathbf{x}_0) &= \mathcal{N}(\mathbf{x}_t; \sqrt{\bar{\alpha}_t} \mathbf{x}_0, {(1 - \bar{\alpha}_t)} \mathbf{I}) \end{aligned}$ 其中 $\bar{\alpha}_t = \prod{i=1}^T \alpha_i$ 且 $\alpha_i = 1-\beta_i$

數學符號總是看起來很嚇人!幸運的是,scheduler 為我們處理了所有這些。我們可以繪製 $\sqrt{\bar{\alpha}_t}$ (標記為 sqrt_alpha_prod) 和 $\sqrt{(1 - \bar{\alpha}_t)}$ (標記為 sqrt_one_minus_alpha_prod) 來檢視輸入 (x) 和噪聲在不同時間步是如何縮放和混合的

>>> plt.plot(noise_scheduler.alphas_cumprod.cpu() ** 0.5, label=r"${\sqrt{\bar{\alpha}_t}}$")
>>> plt.plot((1 - noise_scheduler.alphas_cumprod.cpu()) ** 0.5, label=r"$\sqrt{(1 - \bar{\alpha}_t)}$")
>>> plt.legend(fontsize="x-large")

練習: 你可以透過在此處替換為註釋掉的選項之一,來探索此圖如何隨 beta_start、beta_end 和 beta_schedule 的不同設定而變化

# One with too little noise added:
# noise_scheduler = DDPMScheduler(num_train_timesteps=1000, beta_start=0.001, beta_end=0.004)
# The 'cosine' schedule, which may be better for small image sizes:
# noise_scheduler = DDPMScheduler(num_train_timesteps=1000, beta_schedule='squaredcos_cap_v2')

無論你選擇哪個 scheduler,我們現在都可以使用 noise_scheduler.add_noise 函式來新增不同數量的噪聲,如下所示

>>> timesteps = torch.linspace(0, 999, 8).long().to(device)
>>> noise = torch.randn_like(xb)
>>> noisy_xb = noise_scheduler.add_noise(xb, noise, timesteps)
>>> print("Noisy X shape", noisy_xb.shape)
>>> show_images(noisy_xb).resize((8 * 64, 64), resample=Image.NEAREST)
Noisy X shape torch.Size([8, 3, 32, 32])

再次強調,請在這裡探索使用不同噪聲排程和引數的效果。這個影片 非常好地更詳細地解釋了上面的一些數學知識,並且是對其中一些概念的極好介紹。

第 4 步:定義模型

現在我們來到了核心元件:模型本身。

大多數 diffusion 模型使用的架構都是 U-net 的某種變體,我們這裡也將使用它。

簡而言之

  • 模型讓輸入影像通過幾個 ResNet 層的塊,每個塊都將影像尺寸減半
  • 然後透過相同數量的塊再次將其上取樣。
  • 存在將下采樣路徑上的特徵連線到上取樣路徑中相應層的跳躍連線。

該模型的一個關鍵特徵是它預測的影像大小與輸入相同,這正是我們這裡所需要的。

Diffusers 為我們提供了一個方便的 UNet2DModel 類,它可以在 PyTorch 中建立所需的架構。

讓我們為我們期望的影像大小建立一個 U-net。請注意,down_block_types 對應於下采樣塊(上圖中的綠色部分),而 up_block_types 是上取樣塊(圖中的紅色部分)

from diffusers import UNet2DModel

# Create a model
model = UNet2DModel(
    sample_size=image_size,  # the target image resolution
    in_channels=3,  # the number of input channels, 3 for RGB images
    out_channels=3,  # the number of output channels
    layers_per_block=2,  # how many ResNet layers to use per UNet block
    block_out_channels=(64, 128, 128, 256),  # More channels -> more parameters
    down_block_types=(
        "DownBlock2D",  # a regular ResNet downsampling block
        "DownBlock2D",
        "AttnDownBlock2D",  # a ResNet downsampling block with spatial self-attention
        "AttnDownBlock2D",
    ),
    up_block_types=(
        "AttnUpBlock2D",
        "AttnUpBlock2D",  # a ResNet upsampling block with spatial self-attention
        "UpBlock2D",
        "UpBlock2D",  # a regular ResNet upsampling block
    ),
)
model.to(device)

在處理更高解析度的輸入時,你可能需要使用更多的下采樣和上取樣塊,並將注意力層僅保留在最低解析度(底部)層,以減少記憶體使用。我們稍後將討論如何透過實驗找到最適合你用例的設定。

我們可以檢查傳入一批資料和一些隨機時間步是否能產生與輸入資料形狀相同的輸出

with torch.no_grad():
    model_prediction = model(noisy_xb, timesteps).sample
model_prediction.shape

在下一節中,我們將看到如何訓練這個模型。

第 5 步:建立訓練迴圈

是時候訓練了!下面是 PyTorch 中一個典型的最佳化迴圈,我們逐批處理資料,並在每一步使用最佳化器(在這裡是學習率為 0.0004 的 AdamW 最佳化器)更新模型的引數。

對於每一批資料,我們:

  • 取樣一些隨機時間步
  • 相應地給資料加噪聲
  • 將加噪資料輸入模型
  • 使用均方誤差作為我們的損失函式,將模型預測與目標(在這裡是噪聲)進行比較
  • 透過 loss.backward()optimizer.step() 更新模型引數

在此過程中,我們還記錄了損失隨時間的變化,以便稍後繪圖。

注意:此程式碼執行近 10 分鐘——如果你趕時間,可以隨意跳過這兩個單元格並使用預訓練模型。或者,你可以透過上面模型定義減少每層通道數來探索如何加快速度。

官方 diffusers 訓練示例 在這個資料集上以更高解析度訓練了一個更大的模型,對於想了解一個不那麼簡化的訓練迴圈是什麼樣子的,這是一個很好的參考。

>>> # Set the noise scheduler
>>> noise_scheduler = DDPMScheduler(num_train_timesteps=1000, beta_schedule="squaredcos_cap_v2")

>>> # Training loop
>>> optimizer = torch.optim.AdamW(model.parameters(), lr=4e-4)

>>> losses = []

>>> for epoch in range(30):
...     for step, batch in enumerate(train_dataloader):
...         clean_images = batch["images"].to(device)
...         # Sample noise to add to the images
...         noise = torch.randn(clean_images.shape).to(clean_images.device)
...         bs = clean_images.shape[0]

...         # Sample a random timestep for each image
...         timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bs,), device=clean_images.device).long()

...         # Add noise to the clean images according to the noise magnitude at each timestep
...         noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)

...         # Get the model prediction
...         noise_pred = model(noisy_images, timesteps, return_dict=False)[0]

...         # Calculate the loss
...         loss = F.mse_loss(noise_pred, noise)
...         loss.backward(loss)
...         losses.append(loss.item())

...         # Update the model parameters with the optimizer
...         optimizer.step()
...         optimizer.zero_grad()

...     if (epoch + 1) % 5 == 0:
...         loss_last_epoch = sum(losses[-len(train_dataloader) :]) / len(train_dataloader)
...         print(f"Epoch:{epoch+1}, loss: {loss_last_epoch}")
Epoch:5, loss: 0.16273280512541533
Epoch:10, loss: 0.11161588924005628
Epoch:15, loss: 0.10206522420048714
Epoch:20, loss: 0.08302505919709802
Epoch:25, loss: 0.07805309211835265
Epoch:30, loss: 0.07474562455900013

繪製損失圖,我們看到模型在初期迅速改善,然後以較慢的速度繼續變好(如果我們使用對數刻度,如右圖所示,則更明顯)

>>> fig, axs = plt.subplots(1, 2, figsize=(12, 4))
>>> axs[0].plot(losses)
>>> axs[1].plot(np.log(losses))
>>> plt.show()

作為執行上述訓練程式碼的替代方案,你可以像這樣使用 pipeline 中的模型

# Uncomment to instead load the model I trained earlier:
# model = butterfly_pipeline.unet

第 6 步:生成影像

我們如何用這個模型生成影像?

選項 1:建立一個 pipeline:

from diffusers import DDPMPipeline

image_pipe = DDPMPipeline(unet=model, scheduler=noise_scheduler)
>>> pipeline_output = image_pipe()
>>> pipeline_output.images[0]

我們可以像這樣將 pipeline 儲存到本地資料夾

image_pipe.save_pretrained("my_pipeline")

檢查資料夾內容

>>> !ls my_pipeline/
model_index.json  scheduler  unet

schedulerunet 子資料夾包含重新建立這些元件所需的一切。例如,在 unet 資料夾內,你會找到模型權重(diffusion_pytorch_model.bin)以及一個指定 UNet 架構的配置檔案。

>>> !ls my_pipeline/unet/
config.json  diffusion_pytorch_model.bin

總而言之,這些檔案包含了重新建立 pipeline 所需的一切。你可以手動將它們上傳到 hub 與他人分享 pipeline,或者在下一節中檢視透過 API 執行此操作的程式碼。

選項 2:編寫取樣迴圈

如果你檢查 pipeline 的 forward 方法,你就能看到執行 image_pipe() 時發生了什麼

# ??image_pipe.forward

我們從隨機噪聲開始,按從最多噪聲到最少噪聲的順序遍歷 scheduler 的時間步,每一步根據模型預測去除少量噪聲

>>> # Random starting point (8 random images):
>>> sample = torch.randn(8, 3, 32, 32).to(device)

>>> for i, t in enumerate(noise_scheduler.timesteps):

...     # Get model pred
...     with torch.no_grad():
...         residual = model(sample, t).sample

...     # Update sample with step
...     sample = noise_scheduler.step(residual, t, sample).prev_sample

>>> show_images(sample)

noise_scheduler.step() 函式執行了適當更新 sample 所需的數學運算。有許多采樣方法——在下一個單元中,我們將看到如何透過更換不同的取樣器來加速現有模型的影像生成,並更多地討論從 diffusion 模型中取樣的理論。

第 7 步:將你的模型推送到 Hub

在上面的例子中,我們將我們的 pipeline 儲存到了一個本地資料夾。要將我們的模型推送到 Hub,我們需要一個模型倉庫來推送我們的檔案。我們將根據我們想給模型的模型 ID 來確定倉庫名稱(你可以隨意用自己的選擇替換 model_name;它只需要包含你的使用者名稱,這正是函式 get_full_repo_name() 所做的)

from huggingface_hub import get_full_repo_name

model_name = "sd-class-butterflies-32"
hub_model_id = get_full_repo_name(model_name)
hub_model_id

接下來,在 🤗 Hub 上建立一個模型倉庫並推送我們的模型

from huggingface_hub import HfApi, create_repo

create_repo(hub_model_id)
api = HfApi()
api.upload_folder(folder_path="my_pipeline/scheduler", path_in_repo="", repo_id=hub_model_id)
api.upload_folder(folder_path="my_pipeline/unet", path_in_repo="", repo_id=hub_model_id)
api.upload_file(
    path_or_fileobj="my_pipeline/model_index.json",
    path_in_repo="model_index.json",
    repo_id=hub_model_id,
)

最後要做的是建立一個漂亮的模型卡片,這樣我們的蝴蝶生成器就能在 Hub 上被輕鬆找到(隨意擴充套件和編輯描述!)

from huggingface_hub import ModelCard

content = f"""
---
license: mit
tags:
- pytorch
- diffusers
- unconditional-image-generation
- diffusion-models-class
---

# Model Card for Unit 1 of the [Diffusion Models Class 🧨](https://github.com/huggingface/diffusion-models-class)

This model is a diffusion model for unconditional image generation of cute 🦋.

## Usage

```python
from diffusers import DDPMPipeline

pipeline = DDPMPipeline.from_pretrained('{hub_model_id}')
image = pipeline().images[0]
image

"""

card = ModelCard(content) card.push_to_hub(hub_model_id)


Now that the model is on the Hub, you can download it from anywhere by using the `from_pretrained()` method of the `DDPMPipeline` as follows"

```python
>>> from diffusers import DDPMPipeline

>>> image_pipe = DDPMPipeline.from_pretrained(hub_model_id)
>>> pipeline_output = image_pipe()
>>> pipeline_output.images[0]

太好了,它能工作!

使用 🤗 Accelerate 進行擴充套件

本 notebook 是為了學習目的而製作的,因此我儘量保持程式碼的最小化和整潔。因此,我們省略了一些你可能需要的東西,比如如果你要嘗試在更多資料上訓練一個更大的模型,例如多 GPU 支援、進度和示例影像的日誌記錄、支援更大批次的梯度檢查點、自動上傳模型等等。幸運的是,大多數這些功能都可以在這裡的示例訓練指令碼中找到。

你可以像這樣下載檔案

!wget https://github.com/huggingface/diffusers/raw/main/examples/unconditional_image_generation/train_unconditional.py

開啟檔案,你會看到模型的定義位置以及可用的設定。我用以下命令運行了該指令碼

# Let's give our new model a name for the Hub
model_name = "sd-class-butterflies-64"
hub_model_id = get_full_repo_name(model_name)
hub_model_id
!accelerate launch train_unconditional.py \
  --dataset_name="huggan/smithsonian_butterflies_subset" \
  --resolution=64 \
  --output_dir={model_name} \
  --train_batch_size=32 \
  --num_epochs=50 \
  --gradient_accumulation_steps=1 \
  --learning_rate=1e-4 \
  --lr_warmup_steps=500 \
  --mixed_precision="no"

和之前一樣,讓我們將模型推送到 Hub 並建立一個漂亮的模型卡片(並隨意根據你的意願編輯它!)

create_repo(hub_model_id)
api = HfApi()
api.upload_folder(folder_path=f"{model_name}/scheduler", path_in_repo="", repo_id=hub_model_id)
api.upload_folder(folder_path=f"{model_name}/unet", path_in_repo="", repo_id=hub_model_id)
api.upload_file(
    path_or_fileobj=f"{model_name}/model_index.json",
    path_in_repo="model_index.json",
    repo_id=hub_model_id,
)

content = f"""
---
license: mit
tags:
- pytorch
- diffusers
- unconditional-image-generation
- diffusion-models-class
---

# Model Card for Unit 1 of the [Diffusion Models Class 🧨](https://github.com/huggingface/diffusion-models-class)

This model is a diffusion model for unconditional image generation of cute 🦋.

## Usage

```python
from diffusers import DDPMPipeline

pipeline = DDPMPipeline.from_pretrained('{hub_model_id}')
image = pipeline().images[0]
image

"""

card = ModelCard(content) card.push_to_hub(hub_model_id)


About 45 minutes later, this is the result:

```python
>>> pipeline = DDPMPipeline.from_pretrained(hub_model_id).to(device)
>>> images = pipeline(batch_size=8).images
>>> make_grid(images)

練習: 看看你是否能找到在儘可能短的時間內獲得良好結果的訓練/模型設定,並與社群分享你的發現。深入研究指令碼,看看你是否能理解程式碼,並對任何看起來令人困惑的地方尋求澄清。

進一步探索的途徑

希望這讓你體驗到了 🤗 Diffusers 庫能做什麼!一些可能的後續步驟:

  • 嘗試在一個新的資料集上訓練一個無條件的 diffusion 模型——如果你能自己建立一個就更好了。你可以在 Hub 上的 HugGan 組織中找到一些很棒的影像資料集來完成這個任務。只要確保如果你不想等待很長時間模型訓練,就對它們進行下采樣!
  • 嘗試使用這個 Space這個 notebook 來嘗試 DreamBooth,建立你自己的定製化 Stable Diffusion pipeline
  • 修改訓練指令碼以探索不同的 UNet 超引數(層數、通道數等)、不同的噪聲排程等。
  • 檢視從零開始實現 Diffusion 模型 notebook,以不同視角瞭解我們在本單元中涵蓋的核心思想

祝你好運,敬請期待第 2 單元!

< > 在 GitHub 上更新

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