深度學習
👨‍🏭從零開始實現 Stable Diffusion - 1
00 min
2024-7-16
2024-7-18
type
status
date
slug
password
summary
tags
category
icon
😀
這個系列文章不會講授太多的數學原理,想看數學可以看參考文章,但是想從代碼層面上細講,因為這比推算一個公式簡單多了

參考資料

這個 01 會先從生成手寫數字圖片開始,從基本的Unet模型到DDPM

檢查一下CUDA

這裡很重要的一點是,CUDA版本需要和PyTorch的版本一致,很多人錯誤地安裝這兩個的版本。(比如直接打 pip install torch 這樣是完全錯誤的)
最好的方法:
  1. 先下載 CUDA 11.8 或者 CUDA 12.1
  1. 然後到 https://pytorch.org/ 獲取 pip 下載地址
按照這樣輸入,即可拿到pip安裝指令
按照這樣輸入,即可拿到pip安裝指令
 
出現 Using device: cuda 即可
出現 Using device: cuda 即可
 

下載數據集

notion image

加噪音

沒有學過 diffusion ?
你可以先逐步添加高斯噪声來生成新的數據
noise = torch.rand_like(x) 噪音
noisy_x = (1-amount)*x + amount*noise 加噪
notion image
notion image

UNet

notion image

關鍵信息

  1. 整個模型分成了 down_layer 和 up_layer
  1. skip connection 是指在計算過程中引用回之前層的數據,疊加。可以用棧實現
  1. 1 → 32 → 64 → 64 → 64 → 32 → 1
  1. MaxPool2d 在 down_layer 的第三層不用加,upscale 在 up_layer 的第一層不用加

檢查一下UNet

訓練網絡

流程
  1. 先算加噪的noisy_x
  1. 預算 net(noisy_x)
  1. 計算 loss (用nn.MSELoss)
notion image
notion image
notion image

from diffusers import DDPMScheduler, UNet2DModel

DDPM 待實現

這裡用了DDPM 不過 IndexError: tensors used as indices must be long, int, byte or bool tensors,日後有機會再修復看看。
上一篇
HACK THE BOX 操作手冊
下一篇
如何成为 -10x 工程师 How to be a -10x Engineer

Comments
Loading...