煉丹!訓練 stable diffusion 來生成LoRA定制模型

AI作畫

LoRA,英文全稱Low-Rank Adaptation of Large Language Models,直譯為大語言模型的低階適應,這是微軟的研究人員為了解決大語言模型微調而開發(fā)的一項技術。
比如,GPT-3有1750億參數,為了讓它能干特定領域的活兒,需要做微調,但是如果直接對GPT-3做微調,成本太高太麻煩了。

LoRA的做法是,凍結預訓練好的模型權重參數,然后在每個Transformer(Transforme就是GPT的那個T)塊里注入可訓練的層,由于不需要對模型的權重參數重新計算梯度,所以,大大減少了需要訓練的計算量。
研究發(fā)現,LoRA的微調質量與全模型微調相當,要做個比喻的話,就好比是大模型的一個小模型,或者說是一個插件。

根據顯卡性能不同,訓練一般需要一個到幾個小時的時間,這個過程俗稱煉丹!

主要步驟有以下這些,話不多說,開整!

1. 顯卡

首先是要有顯卡了,推薦8G顯存以上的N卡。然后就是裝GPU驅動,可以參考我以前文章centos中docker使用GPU

2. 訓練環(huán)境

自從有了docker,我就不喜歡在宿主機上裝一堆開發(fā)環(huán)境了,所以這次就直接使用stable-diffusion-webui帶webui打包好的鏡像,也方便訓練完成以后測試。推薦一下 kestr3l/stable-diffusion-webui 這個鏡像,是基于 nvidia/cuda:11.7.1-devel-ubuntu22.04 鏡像,本人親自測試過,可用的。
附一個我用的 docker-compose.yml 文件

version: "3"
services: 
  sd-webui:
    image: kestr3l/stable-diffusion-webui:1.1.0
    container_name: sd-webui
    restart: always
    ports:
      - "7860:7860"
      - "7861:7861"
    ulimits:
      memlock: -1
      stack: 67108864
    shm_size: 4G
    deploy:
      resources:
        limits:
          cpus: "8.00"
          memory: 16G
        reservations:
          devices:
            - capabilities: [gpu]
    volumes:
      # 這里主要是方便映射下載的模型文件
      - ./models:/home/user/stable-diffusion-webui/models:cached
      # 修改容器的默認啟動腳本,方便我們手動控制
      - ./entrypoint-debug.sh:/usr/local/bin/entrypoint.sh:cached

entrypoint-debug.sh文件內容:

#! /bin/sh
python3

可以去 civitai 下載 stable diffusion 的模型,放到宿主機的 ./models/Stable-diffusion 目錄下面,也可以去下載一些LoRA模型丟在./models/Lora 目錄下。

模型準備完畢了就可以跑個 stable diffusion 圖形化界面試試看, 執(zhí)行./webui.sh -f --listen 命令,啟動之前會下載安裝很多依賴包,國內環(huán)境不太順,可以上代理安裝。

如果輸出以下內容,則表示安裝成功:

root@cebe51b82933:/home/user/stable-diffusion-webui# ./webui.sh -f --listen

################################################################
Install script for stable-diffusion + Web UI
Tested on Debian 11 (Bullseye)
################################################################

################################################################
Running on root user
################################################################

################################################################
Repo already cloned, using it as install directory
################################################################

################################################################
Create and activate python venv
################################################################

################################################################
Launching launch.py...
################################################################
./webui.sh: line 168: lspci: command not found
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0]
Commit hash: <none>
Installing requirements for Web UI
Launching Web UI with arguments: --listen
No module 'xformers'. Proceeding without it.
LatentDiffusion: Running in eps-prediction mode
DiffusionWrapper has 859.52 M params.
Loading weights [fc2511737a] from /home/user/stable-diffusion-webui/models/Stable-diffusion/chilloutmix_NiPrunedFp32Fix.safetensors
Applying cross attention optimization (Doggettx).
Textual inversion embeddings loaded(0): 
Model loaded in 16.0s (0.8s create model, 14.9s load weights).
Running on local URL:  http://0.0.0.0:7860

To create a public link, set `share=True` in `launch()`.

打開瀏覽器訪問:http://127.0.0.1:7860 或者 http://內網ip:7860 就可以AI繪畫了


AI作畫
AI美女
AI美女

不得不說 chilloutmix_NiPrunedFp32Fix 模型生成的圖片是針不戳??!

3. 安裝訓練圖形化界面

為了降低訓練門檻,這里選用的是基于Gradio做的一個WebGui圖形化界面,該項目在GitHub上叫Kohya's GUI。

# 下載項目
git clone https://github.com/bmaltais/kohya_ss.git
# 執(zhí)行安裝腳本
cd kohya_ss
bash ubuntu_setup.sh

由于是在docker內部執(zhí)行,ubuntu_setup.sh 腳本可能有問題,所以我一般是直接進入容器,手動單條執(zhí)行

apt install python3-tk
python3 -m venv venv
source venv/bin/activate
pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116
pip install --use-pep517 --upgrade -r requirements.txt
pip install -U -I --no-deps https://github.com/C43H66N12O12S2/stable-diffusion-webui/releases/download/linux/xformers-0.0.14.dev0-cp310-cp310-linux_x86_64.whl

執(zhí)行accelerate config命令,生成對應配置文件,選項如下:

(venv) root@cebe51b82933:/home/user/kohya_ss# accelerate config
2023-03-13 06:45:22.678222: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-03-13 06:45:22.922383: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2023-03-13 06:45:23.593040: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/local/cuda-11.7/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64
2023-03-13 06:45:23.593158: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/local/cuda-11.7/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64
2023-03-13 06:45:23.593177: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
--------------------------------------------------------------------------------------------------In which compute environment are you running?
This machine                                                                                      
--------------------------------------------------------------------------------------------------Which type of machine are you using?                                                              
No distributed training                                                                           
Do you want to run your training on CPU only (even if a GPU is available)? [yes/NO]:NO            
Do you wish to optimize your script with torch dynamo?[yes/NO]:NO                                 
Do you want to use DeepSpeed? [yes/NO]: NO                                                        
What GPU(s) (by id) should be used for training on this machine as a comma-seperated list? [all]:all                                                                                                
--------------------------------------------------------------------------------------------------Do you wish to use FP16 or BF16 (mixed precision)?
fp16                                                                                              
accelerate configuration saved at /root/.cache/huggingface/accelerate/default_config.yaml

4. 啟動訓練圖形化界面

執(zhí)行命令python kohya_gui.py --listen 0.0.0.0 --server_port 7861 --inbrowser --share

(venv) root@cebe51b82933:/home/user/kohya_ss# python kohya_gui.py --listen 0.0.0.0 --server_port 7861 --inbrowser --share                                                                         
Load CSS...
Running on local URL:  http://0.0.0.0:7861
Running on public URL: https://49257631b1b39d3db5.gradio.live

This share link expires in 72 hours. For free permanent hosting and GPU upgrades (NEW!), check out Spaces: https://huggingface.co/spaces

這時候瀏覽器就可以打開http://127.0.0.1:7861 端口了,界面如下:


訓練web界面

5. 準備要訓練的圖片

找到你要用來訓練的一些圖片放到統(tǒng)一文件夾下,建議15張以上,我這里就用湯唯的照片:


原始圖片文件夾

然后打開stable diffusion webui來預處理這些圖片:


預處理圖片

點擊Preprocess按鈕,等待處理完成。順利的的話會在dest文件夾下生成512*512的圖片,和描述詞文件

image.png

6. 開始訓練

我們去訓練的界面,需要設置一堆參數,直接看圖吧

基礎模型選擇
文件夾選擇
訓練參數配置

建議新建立文件夾,比如我這里叫train_lora,在文件夾里創(chuàng)建image、log和model三個文件夾,其中,image里存放的圖片就是預處理生成的圖片。
image里的預處理圖片不能直接放在里面,需要在里面創(chuàng)建一個文件夾,文件夾的命名非常有講究。
已知,LoRa的訓練需要至少1500步,而每張圖片至少需要訓練100步。
如果我們有15張或者15張以上張圖片,文件夾就需要寫上100_Hunzi。
如果訓練的圖片不夠15張,比如10張,就需要改為150_Hunzi,以此類推。
這部分很重要,一定要算清楚。
當然,這也正是LoRa強大的地方,用這么少的圖片即可完成訓練。

點擊訓練按鈕,開始煉丹:


煉丹

生成的丹就在train_lora/model文件夾下面:


image.png

最終使用這個丹的生成的圖片效果展示:


image.png
image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容