type
status
date
slug
password
summary
tags
category
icon
這個系列文章不會講授太多的數學原理,想看數學可以看參考文章,但是想從代碼層面上細講,因為這比推算一個公式簡單多了
參考資料
這個 01 會先從生成手寫數字圖片開始,從基本的Unet模型到DDPM
檢查一下CUDA
這裡很重要的一點是,CUDA版本需要和PyTorch的版本一致,很多人錯誤地安裝這兩個的版本。(比如直接打
pip install torch
這樣是完全錯誤的)最好的方法:
- 先下載 CUDA 11.8 或者 CUDA 12.1
- 然後到 https://pytorch.org/ 獲取 pip 下載地址


下載數據集

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

UNet

關鍵信息
- 整個模型分成了 down_layer 和 up_layer
- skip connection 是指在計算過程中引用回之前層的數據,疊加。可以用棧實現
- 1 → 32 → 64 → 64 → 64 → 32 → 1
- MaxPool2d 在 down_layer 的第三層不用加,upscale 在 up_layer 的第一層不用加
檢查一下UNet
訓練網絡
流程
- 先算加噪的noisy_x
- 預算 net(noisy_x)
- 計算 loss (用nn.MSELoss)



from diffusers import DDPMScheduler, UNet2DModel
DDPM 待實現
這裡用了DDPM 不過 IndexError: tensors used as indices must be long, int, byte or bool tensors,日後有機會再修復看看。
- Author:tom-ci
- URL:https://www.tomciheng.com//article/sd-01
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!