Verdant commited on
Commit
7e98bde
·
1 Parent(s): 40bae1b

Upload 16 files

Browse files
Files changed (16) hide show
  1. README.md +54 -3
  2. gui.py +75 -0
  3. install-cn.ps1 +57 -0
  4. install.bash +55 -0
  5. install.ps1 +23 -0
  6. interrogate.ps1 +29 -0
  7. resize.ps1 +41 -0
  8. run_gui.ps1 +6 -0
  9. run_gui.sh +7 -0
  10. svd_merge.ps1 +43 -0
  11. tensorboard.ps1 +4 -0
  12. train.ipynb +99 -0
  13. train.ps1 +202 -0
  14. train.sh +153 -0
  15. train_by_toml.ps1 +33 -0
  16. train_by_toml.sh +24 -0
README.md CHANGED
@@ -1,3 +1,54 @@
1
- ---
2
- license: openrail
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA-scripts
2
+
3
+ LoRA training scripts for [kohya-ss/sd-scripts](https://github.com/kohya-ss/sd-scripts.git)
4
+
5
+ ✨NEW: Train GUI
6
+
7
+ ![image](https://user-images.githubusercontent.com/36563862/235594211-76b367d6-788f-4ef4-a258-6559759f371c.png)
8
+
9
+ Follow the installation guide below to install the GUI, then run `run_gui.ps1`(windows) or `run_gui.sh`(linux) to start the GUI.
10
+
11
+
12
+ ## Usage
13
+
14
+ ### Clone repo with submodules
15
+
16
+ ```sh
17
+ git clone --recurse-submodules https://github.com/Akegarasu/lora-scripts
18
+ ```
19
+
20
+ ### Required Dependencies
21
+
22
+ Python 3.10.8 and Git
23
+
24
+ ### Windows
25
+
26
+ #### Installation
27
+
28
+ Run `install.ps1` will automaticilly create a venv for you and install necessary deps.
29
+
30
+ #### Train
31
+
32
+ Edit `train.ps1`, and run it.
33
+
34
+ ### Linux
35
+
36
+ #### Installation
37
+
38
+ Run `install.bash` will create a venv and install necessary deps.
39
+
40
+ #### Train
41
+
42
+ Training script `train.sh` **will not** activate venv for you. You should activate venv first.
43
+
44
+ ```sh
45
+ source venv/bin/activate
46
+ ```
47
+
48
+ Edit `train.sh`, and run it.
49
+
50
+ #### TensorBoard
51
+
52
+ Run `tensorboard.ps1` will start TensorBoard at http://localhost:6006/
53
+
54
+ ![](./assets/tensorboard-example.png)
gui.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ import webbrowser
7
+
8
+ import uvicorn
9
+ from typing import List
10
+
11
+ # from mikazuki.app import app
12
+
13
+ parser = argparse.ArgumentParser(description="GUI for stable diffusion training")
14
+ parser.add_argument("--host", type=str, default="127.0.0.1")
15
+ parser.add_argument("--port", type=int, default=28000, help="Port to run the server on")
16
+ parser.add_argument("--tensorboard-port", type=int, default=6006, help="Port to run the tensorboard")
17
+ parser.add_argument("--dev", action="store_true")
18
+
19
+
20
+ def find_windows_git():
21
+ possible_paths = ["git\\bin\\git.exe", "git\\cmd\\git.exe", "Git\\mingw64\\libexec\\git-core\\git.exe"]
22
+ for path in possible_paths:
23
+ if os.path.exists(path):
24
+ return path
25
+
26
+
27
+ def prepare_frontend():
28
+ if not os.path.exists("./frontend/dist"):
29
+ print("Frontend not found, try clone...")
30
+ print("Checking git installation...")
31
+ if not shutil.which("git"):
32
+ if sys.platform == "win32":
33
+ git_path = find_windows_git()
34
+
35
+ if git_path is not None:
36
+ print(f"Git not found, but found git in {git_path}, add it to PATH")
37
+ os.environ["PATH"] += os.pathsep + os.path.dirname(git_path)
38
+ return
39
+ else:
40
+ print("Git not found, please install git first")
41
+ sys.exit(1)
42
+ subprocess.run(["git", "submodule", "init"])
43
+ subprocess.run(["git", "submodule", "update"])
44
+
45
+
46
+ def remove_warnings():
47
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
48
+ if sys.platform == "win32":
49
+ # disable triton on windows
50
+ os.environ["XFORMERS_FORCE_DISABLE_TRITON"] = "1"
51
+ os.environ["BITSANDBYTES_NOWELCOME"] = "1"
52
+ os.environ["PYTHONWARNINGS"] = "ignore::UserWarning"
53
+
54
+
55
+ def run_tensorboard():
56
+ print("Starting tensorboard...")
57
+ subprocess.Popen([sys.executable, "-m", "tensorboard.main", "--logdir", "logs", "--port", str(args.tensorboard_port)])
58
+
59
+
60
+ def check_dirs(dirs: List):
61
+ for d in dirs:
62
+ if not os.path.exists(d):
63
+ os.makedirs(d)
64
+
65
+
66
+ if __name__ == "__main__":
67
+ args, _ = parser.parse_known_args()
68
+ remove_warnings()
69
+ prepare_frontend()
70
+ run_tensorboard()
71
+ check_dirs(["toml/autosave", "logs"])
72
+ print(f"Server started at http://{args.host}:{args.port}")
73
+ if not args.dev:
74
+ webbrowser.open(f"http://{args.host}:{args.port}")
75
+ uvicorn.run("mikazuki.app:app", host=args.host, port=args.port, log_level="error")
install-cn.ps1 ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ $Env:HF_HOME = "huggingface"
2
+ $Env:PIP_DISABLE_PIP_VERSION_CHECK = 1
3
+ $Env:PIP_NO_CACHE_DIR = 1
4
+ function InstallFail {
5
+ Write-Output "��װʧ�ܡ�"
6
+ Read-Host | Out-Null ;
7
+ Exit
8
+ }
9
+
10
+ function Check {
11
+ param (
12
+ $ErrorInfo
13
+ )
14
+ if (!($?)) {
15
+ Write-Output $ErrorInfo
16
+ InstallFail
17
+ }
18
+ }
19
+
20
+ if (!(Test-Path -Path "venv")) {
21
+ Write-Output "���ڴ������⻷��..."
22
+ python -m venv venv
23
+ Check "�������⻷��ʧ�ܣ����� python �Ƿ�װ����Լ� python �汾�Ƿ�Ϊ64λ�汾��python 3.10����python��Ŀ¼�Ƿ��ڻ�������PATH�ڡ�"
24
+ }
25
+
26
+ .\venv\Scripts\activate
27
+ Check "�������⻷��ʧ�ܡ�"
28
+
29
+ Set-Location .\sd-scripts
30
+ Write-Output "��װ������������ (�ѽ��й��ڼ��٣����ڹ�����޷�ʹ�ü���Դ�뻻�� install.ps1 �ű�)"
31
+ $install_torch = Read-Host "�Ƿ���Ҫ��װ Torch+xformers? [y/n] (Ĭ��Ϊ y)"
32
+ if ($install_torch -eq "y" -or $install_torch -eq "Y" -or $install_torch -eq ""){
33
+ pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 -f https://mirror.sjtu.edu.cn/pytorch-wheels/torch_stable.html -i https://mirrors.bfsu.edu.cn/pypi/web/simple
34
+ Check "torch ��װʧ�ܣ���ɾ�� venv �ļ��к��������С�"
35
+ pip install -U -I --no-deps xformers==0.0.19 -i https://mirrors.bfsu.edu.cn/pypi/web/simple
36
+ Check "xformers ��װʧ�ܡ�"
37
+ }
38
+
39
+ pip install --upgrade -r requirements.txt -i https://mirrors.bfsu.edu.cn/pypi/web/simple
40
+ Check "����������װʧ�ܡ�"
41
+ pip install --upgrade lion-pytorch dadaptation -i https://mirrors.bfsu.edu.cn/pypi/web/simple
42
+ Check "Lion��dadaptation �Ż�����װʧ�ܡ�"
43
+ pip install --upgrade lycoris-lora -i https://mirrors.bfsu.edu.cn/pypi/web/simple
44
+ Check "lycoris ��װʧ�ܡ�"
45
+ pip install --upgrade fastapi uvicorn -i https://mirrors.bfsu.edu.cn/pypi/web/simple
46
+ Check "UI ����������װʧ�ܡ�"
47
+ pip install --upgrade wandb -i https://mirrors.bfsu.edu.cn/pypi/web/simple
48
+ Check "wandb ��װʧ�ܡ�"
49
+
50
+
51
+ Write-Output "��װ bitsandbytes..."
52
+ cp .\bitsandbytes_windows\*.dll ..\venv\Lib\site-packages\bitsandbytes\
53
+ cp .\bitsandbytes_windows\cextension.py ..\venv\Lib\site-packages\bitsandbytes\cextension.py
54
+ cp .\bitsandbytes_windows\main.py ..\venv\Lib\site-packages\bitsandbytes\cuda_setup\main.py
55
+
56
+ Write-Output "��װ���"
57
+ Read-Host | Out-Null ;
install.bash ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/bash
2
+
3
+ script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
4
+ create_venv=true
5
+
6
+ while [ -n "$1" ]; do
7
+ case "$1" in
8
+ --disable-venv)
9
+ create_venv=false
10
+ shift
11
+ ;;
12
+ *)
13
+ shift
14
+ ;;
15
+ esac
16
+ done
17
+
18
+ if $create_venv; then
19
+ echo "Creating python venv..."
20
+ python3 -m venv venv
21
+ source "$script_dir/venv/bin/activate"
22
+ echo "active venv"
23
+ fi
24
+
25
+ echo "Installing torch & xformers..."
26
+
27
+ cuda_version=$(nvcc --version | grep 'release' | sed -n -e 's/^.*release \([0-9]\+\.[0-9]\+\),.*$/\1/p')
28
+ cuda_major_version=$(echo "$cuda_version" | awk -F'.' '{print $1}')
29
+ cuda_minor_version=$(echo "$cuda_version" | awk -F'.' '{print $2}')
30
+
31
+ echo "Cuda Version:$cuda_version"
32
+
33
+ if (( cuda_major_version >= 12 )) || (( cuda_major_version == 11 && cuda_minor_version >= 8 )); then
34
+ echo "install torch 2.0.0+cu118"
35
+ pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 --extra-index-url https://download.pytorch.org/whl/cu118
36
+ pip install xformers==0.0.19
37
+ elif (( cuda_major_version == 11 && cuda_minor_version == 6 )); then
38
+ echo "install torch 1.12.1+cu116"
39
+ pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116
40
+ pip install --upgrade git+https://github.com/facebookresearch/xformers.git@0bad001ddd56c080524d37c84ff58d9cd030ebfd
41
+ pip install triton==2.0.0.dev20221202
42
+ else
43
+ echo "Unsupported cuda version:$cuda_version"
44
+ exit 1
45
+ fi
46
+
47
+ echo "Installing deps..."
48
+ cd "$script_dir/sd-scripts" || exit
49
+
50
+ pip install --upgrade -r requirements.txt
51
+ pip install --upgrade lion-pytorch lycoris-lora dadaptation fastapi uvicorn wandb
52
+
53
+ cd "$script_dir" || exit
54
+
55
+ echo "Install completed"
install.ps1 ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ $Env:HF_HOME = "huggingface"
2
+
3
+ if (!(Test-Path -Path "venv")) {
4
+ Write-Output "Creating venv for python..."
5
+ python -m venv venv
6
+ }
7
+ .\venv\Scripts\activate
8
+
9
+ Write-Output "Installing deps..."
10
+ Set-Location .\sd-scripts
11
+ pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 --extra-index-url https://download.pytorch.org/whl/cu118
12
+ pip install --upgrade -r requirements.txt
13
+ pip install --upgrade xformers==0.0.19
14
+
15
+ Write-Output "Installing bitsandbytes for windows..."
16
+ cp .\bitsandbytes_windows\*.dll ..\venv\Lib\site-packages\bitsandbytes\
17
+ cp .\bitsandbytes_windows\cextension.py ..\venv\Lib\site-packages\bitsandbytes\cextension.py
18
+ cp .\bitsandbytes_windows\main.py ..\venv\Lib\site-packages\bitsandbytes\cuda_setup\main.py
19
+
20
+ pip install --upgrade lion-pytorch dadaptation lycoris-lora fastapi uvicorn wandb
21
+
22
+ Write-Output "Install completed"
23
+ Read-Host | Out-Null ;
interrogate.ps1 ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA interrogate script by @bdsqlsz
2
+
3
+ $v2 = 0 # load Stable Diffusion v2.x model / Stable Diffusion 2.x模型读取
4
+ $sd_model = "./sd-models/sd_model.safetensors" # Stable Diffusion model to load: ckpt or safetensors file | 读取的基础SD模型, 保存格式 cpkt 或 safetensors
5
+ $model = "./output/LoRA.safetensors" # LoRA model to interrogate: ckpt or safetensors file | 需要调查关键字的LORA模型, 保存格式 cpkt 或 safetensors
6
+ $batch_size = 64 # batch size for processing with Text Encoder | 使用 Text Encoder 处理时的批量大小,默认16,推荐64/128
7
+ $clip_skip = 1 # use output of nth layer from back of text encoder (n>=1) | 使用文本编码器倒数第 n 层的输出,n 可以是大于等于 1 的整数
8
+
9
+
10
+ # Activate python venv
11
+ .\venv\Scripts\activate
12
+
13
+ $Env:HF_HOME = "huggingface"
14
+ $ext_args = [System.Collections.ArrayList]::new()
15
+
16
+ if ($v2) {
17
+ [void]$ext_args.Add("--v2")
18
+ }
19
+
20
+ # run interrogate
21
+ accelerate launch --num_cpu_threads_per_process=8 "./sd-scripts/networks/lora_interrogator.py" `
22
+ --sd_model=$sd_model `
23
+ --model=$model `
24
+ --batch_size=$batch_size `
25
+ --clip_skip=$clip_skip `
26
+ $ext_args
27
+
28
+ Write-Output "Interrogate finished"
29
+ Read-Host | Out-Null ;
resize.ps1 ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA resize script by @bdsqlsz
2
+
3
+ $save_precision = "fp16" # precision in saving, default float | 保存精度, 可选 float、fp16、bf16, 默认 float
4
+ $new_rank = 4 # dim rank of output LoRA | dim rank等级, 默认 4
5
+ $model = "./output/lora_name.safetensors" # original LoRA model path need to resize, save as cpkt or safetensors | 需要调整大小的模型路径, 保存格式 cpkt 或 safetensors
6
+ $save_to = "./output/lora_name_new.safetensors" # output LoRA model path, save as ckpt or safetensors | 输出路径, 保存格式 cpkt 或 safetensors
7
+ $device = "cuda" # device to use, cuda for GPU | 使用 GPU跑, 默认 CPU
8
+ $verbose = 1 # display verbose resizing information | rank变更时, 显示详细信息
9
+ $dynamic_method = "" # Specify dynamic resizing method, --new_rank is used as a hard limit for max rank | 动态调节大小,可选"sv_ratio", "sv_fro", "sv_cumulative",默认无
10
+ $dynamic_param = "" # Specify target for dynamic reduction | 动态参数,sv_ratio模式推荐1~2, sv_cumulative模式0~1, sv_fro模式0~1, 比sv_cumulative要高
11
+
12
+
13
+ # Activate python venv
14
+ .\venv\Scripts\activate
15
+
16
+ $Env:HF_HOME = "huggingface"
17
+ $ext_args = [System.Collections.ArrayList]::new()
18
+
19
+ if ($verbose) {
20
+ [void]$ext_args.Add("--verbose")
21
+ }
22
+
23
+ if ($dynamic_method) {
24
+ [void]$ext_args.Add("--dynamic_method=" + $dynamic_method)
25
+ }
26
+
27
+ if ($dynamic_param) {
28
+ [void]$ext_args.Add("--dynamic_param=" + $dynamic_param)
29
+ }
30
+
31
+ # run resize
32
+ accelerate launch --num_cpu_threads_per_process=8 "./sd-scripts/networks/resize_lora.py" `
33
+ --save_precision=$save_precision `
34
+ --new_rank=$new_rank `
35
+ --model=$model `
36
+ --save_to=$save_to `
37
+ --device=$device `
38
+ $ext_args
39
+
40
+ Write-Output "Resize finished"
41
+ Read-Host | Out-Null ;
run_gui.ps1 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .\venv\Scripts\activate
2
+
3
+ $Env:HF_HOME = "huggingface"
4
+ $Env:PYTHONUTF8 = "1"
5
+
6
+ python gui.py
run_gui.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ export HF_HOME=huggingface
4
+ export PYTHONUTF8=1
5
+
6
+ python gui.py "$@"
7
+
svd_merge.ps1 ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA svd_merge script by @bdsqlsz
2
+
3
+ $save_precision = "fp16" # precision in saving, default float | 保存精度, 可选 float、fp16、bf16, 默认 和源文件相同
4
+ $precision = "float" # precision in merging (float is recommended) | 合并时计算精度, 可选 float、fp16、bf16, 推荐float
5
+ $new_rank = 4 # dim rank of output LoRA | dim rank等级, 默认 4
6
+ $models = "./output/modelA.safetensors ./output/modelB.safetensors" # original LoRA model path need to resize, save as cpkt or safetensors | 需要合并的模型路径, 保存格式 cpkt 或 safetensors,多个用空格隔开
7
+ $ratios = "1.0 -1.0" # ratios for each model / LoRA模型合并比例,数量等于模型数量,多个用空格隔开
8
+ $save_to = "./output/lora_name_new.safetensors" # output LoRA model path, save as ckpt or safetensors | 输出路径, 保存格式 cpkt 或 safetensors
9
+ $device = "cuda" # device to use, cuda for GPU | 使用 GPU跑, 默认 CPU
10
+ $new_conv_rank = 0 # Specify rank of output LoRA for Conv2d 3x3, None for same as new_rank | Conv2d 3x3输出,没有默认同new_rank
11
+
12
+ # Activate python venv
13
+ .\venv\Scripts\activate
14
+
15
+ $Env:HF_HOME = "huggingface"
16
+ $Env:XFORMERS_FORCE_DISABLE_TRITON = "1"
17
+ $ext_args = [System.Collections.ArrayList]::new()
18
+
19
+ [void]$ext_args.Add("--models")
20
+ foreach ($model in $models.Split(" ")) {
21
+ [void]$ext_args.Add($model)
22
+ }
23
+
24
+ [void]$ext_args.Add("--ratios")
25
+ foreach ($ratio in $ratios.Split(" ")) {
26
+ [void]$ext_args.Add([float]$ratio)
27
+ }
28
+
29
+ if ($new_conv_rank) {
30
+ [void]$ext_args.Add("--new_conv_rank=" + $new_conv_rank)
31
+ }
32
+
33
+ # run svd_merge
34
+ accelerate launch --num_cpu_threads_per_process=8 "./sd-scripts/networks/svd_merge_lora.py" `
35
+ --save_precision=$save_precision `
36
+ --precision=$precision `
37
+ --new_rank=$new_rank `
38
+ --save_to=$save_to `
39
+ --device=$device `
40
+ $ext_args
41
+
42
+ Write-Output "SVD Merge finished"
43
+ Read-Host | Out-Null ;
tensorboard.ps1 ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ $Env:TF_CPP_MIN_LOG_LEVEL = "3"
2
+
3
+ .\venv\Scripts\activate
4
+ tensorboard --logdir=logs
train.ipynb ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "pycharm": {
8
+ "name": "#%%\n"
9
+ }
10
+ },
11
+ "outputs": [],
12
+ "source": [
13
+ "# Train data path | 设置训练用模型、图片\n",
14
+ "pretrained_model = \"./sd-models/model.ckpt\" # base model path | 底模路径\n",
15
+ "train_data_dir = \"./train/aki\" # train dataset path | 训练数据集路径\n",
16
+ "\n",
17
+ "# Train related params | 训练相关参数\n",
18
+ "resolution = \"512,512\" # image resolution w,h. 图片分辨率,宽,高。支持非正方形,但必须是 64 倍数。\n",
19
+ "batch_size = 1 # batch size\n",
20
+ "max_train_epoches = 10 # max train epoches | 最大训练 epoch\n",
21
+ "save_every_n_epochs = 2 # save every n epochs | 每 N 个 epoch 保存一次\n",
22
+ "network_dim = 32 # network dim | 常用 4~128,不是越大越好\n",
23
+ "network_alpha= 32 # network alpha | 常用与 network_dim 相同的值或者采用较小的值,如 network_dim的一半 防止下溢。默认值为 1,使用较小的 alpha 需要提升学习率。\n",
24
+ "clip_skip = 2 # clip skip | 玄学 一般用 2\n",
25
+ "train_unet_only = 0 # train U-Net only | 仅训练 U-Net,开启这个会牺牲效果大幅减少显存使用。6G显存可以开启\n",
26
+ "train_text_encoder_only = 0 # train Text Encoder only | 仅训练 文本编码器\n",
27
+ "\n",
28
+ "# Learning rate | 学习率\n",
29
+ "lr = \"1e-4\"\n",
30
+ "unet_lr = \"1e-4\"\n",
31
+ "text_encoder_lr = \"1e-5\"\n",
32
+ "lr_scheduler = \"cosine_with_restarts\" # \"linear\", \"cosine\", \"cosine_with_restarts\", \"polynomial\", \"constant\", \"constant_with_warmup\"\n",
33
+ "\n",
34
+ "# Output settings | 输出设置\n",
35
+ "output_name = \"aki\" # output model name | 模型保存名称\n",
36
+ "save_model_as = \"safetensors\" # model save ext | 模型保存格式 ckpt, pt, safetensors"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "execution_count": null,
42
+ "metadata": {
43
+ "pycharm": {
44
+ "name": "#%%\n"
45
+ }
46
+ },
47
+ "outputs": [],
48
+ "source": [
49
+ "!accelerate launch --num_cpu_threads_per_process=8 \"./sd-scripts/train_network.py\" \\\n",
50
+ " --enable_bucket \\\n",
51
+ " --pretrained_model_name_or_path=$pretrained_model \\\n",
52
+ " --train_data_dir=$train_data_dir \\\n",
53
+ " --output_dir=\"./output\" \\\n",
54
+ " --logging_dir=\"./logs\" \\\n",
55
+ " --resolution=$resolution \\\n",
56
+ " --network_module=networks.lora \\\n",
57
+ " --max_train_epochs=$max_train_epoches \\\n",
58
+ " --learning_rate=$lr \\\n",
59
+ " --unet_lr=$unet_lr \\\n",
60
+ " --text_encoder_lr=$text_encoder_lr \\\n",
61
+ " --network_dim=$network_dim \\\n",
62
+ " --network_alpha=$network_alpha \\\n",
63
+ " --output_name=$output_name \\\n",
64
+ " --lr_scheduler=$lr_scheduler \\\n",
65
+ " --train_batch_size=$batch_size \\\n",
66
+ " --save_every_n_epochs=$save_every_n_epochs \\\n",
67
+ " --mixed_precision=\"fp16\" \\\n",
68
+ " --save_precision=\"fp16\" \\\n",
69
+ " --seed=\"1337\" \\\n",
70
+ " --cache_latents \\\n",
71
+ " --clip_skip=$clip_skip \\\n",
72
+ " --prior_loss_weight=1 \\\n",
73
+ " --max_token_length=225 \\\n",
74
+ " --caption_extension=\".txt\" \\\n",
75
+ " --save_model_as=$save_model_as \\\n",
76
+ " --xformers --shuffle_caption --use_8bit_adam"
77
+ ]
78
+ }
79
+ ],
80
+ "metadata": {
81
+ "kernelspec": {
82
+ "display_name": "Python 3",
83
+ "language": "python",
84
+ "name": "python3"
85
+ },
86
+ "language_info": {
87
+ "name": "python",
88
+ "version": "3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)]"
89
+ },
90
+ "orig_nbformat": 4,
91
+ "vscode": {
92
+ "interpreter": {
93
+ "hash": "675b13e958f0d0236d13cdfe08a1df3882cae564fa23a2e7e5eb1f2c6c632b02"
94
+ }
95
+ }
96
+ },
97
+ "nbformat": 4,
98
+ "nbformat_minor": 2
99
+ }
train.ps1 ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA train script by @Akegarasu
2
+
3
+ # Train data path | 设置训练用模型、图片
4
+ $pretrained_model = "./sd-models/model.ckpt" # base model path | 底模路径
5
+ $is_v2_model = 0 # SD2.0 model | SD2.0模型 2.0模型下 clip_skip 默认无效
6
+ $parameterization = 0 # parameterization | 参数化 本参数需要和 V2 参数同步使用 实验性功能
7
+ $train_data_dir = "./train/aki" # train dataset path | 训练数据集路径
8
+ $reg_data_dir = "" # directory for regularization images | 正则化数据集路径,默认不使用正则化图像。
9
+
10
+ # Network settings | 网络设置
11
+ $network_module = "networks.lora" # 在这里将会设置训练的网络种类,默认为 networks.lora 也就是 LoRA 训练。如果你想训练 LyCORIS(LoCon、LoHa) 等,则修改这个值为 lycoris.kohya
12
+ $network_weights = "" # pretrained weights for LoRA network | 若需要从已有的 LoRA 模型上继续训练,请填写 LoRA 模型路径。
13
+ $network_dim = 32 # network dim | 常用 4~128,不是越大越好
14
+ $network_alpha = 32 # network alpha | 常用与 network_dim 相同的值或者采用较小的值,如 network_dim的一半 防止下溢。默认值为 1,使用较小的 alpha 需要提升学习率。
15
+
16
+ # Train related params | 训练相关参数
17
+ $resolution = "512,512" # image resolution w,h. 图片分辨率,宽,高。支持非正方形,但必须是 64 倍数。
18
+ $batch_size = 1 # batch size
19
+ $max_train_epoches = 10 # max train epoches | 最大训练 epoch
20
+ $save_every_n_epochs = 2 # save every n epochs | 每 N 个 epoch 保存一次
21
+
22
+ $train_unet_only = 0 # train U-Net only | 仅训练 U-Net,开启这个会牺牲效果大幅减少显存使用。6G显存可以开启
23
+ $train_text_encoder_only = 0 # train Text Encoder only | 仅训练 文本编码器
24
+ $stop_text_encoder_training = 0 # stop text encoder training | 在第N步时停止训练文本编码器
25
+
26
+ $noise_offset = 0 # noise offset | 在训练中添加噪声偏移来改良生成非常暗或者非常亮的图像,如果启用,推荐参数为 0.1
27
+ $keep_tokens = 0 # keep heading N tokens when shuffling caption tokens | 在随机打乱 tokens 时,保留前 N 个不变。
28
+ $min_snr_gamma = 0 # minimum signal-to-noise ratio (SNR) value for gamma-ray | 伽马射线事件的最小信噪比(SNR)值 默认为 0
29
+
30
+ # Learning rate | 学习率
31
+ $lr = "1e-4"
32
+ $unet_lr = "1e-4"
33
+ $text_encoder_lr = "1e-5"
34
+ $lr_scheduler = "cosine_with_restarts" # "linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"
35
+ $lr_warmup_steps = 0 # warmup steps | 学习率预热步数,lr_scheduler 为 constant 或 adafactor 时该值需要设为0。
36
+ $lr_restart_cycles = 1 # cosine_with_restarts restart cycles | 余弦退火重启次数,仅在 lr_scheduler 为 cosine_with_restarts 时起效。
37
+
38
+ # Output settings | 输出设置
39
+ $output_name = "aki" # output model name | 模型保存名称
40
+ $save_model_as = "safetensors" # model save ext | 模型保存格式 ckpt, pt, safetensors
41
+
42
+ # Resume training state | 恢复训练设置
43
+ $save_state = 0 # save training state | 保存训练状态 名称类似于 <output_name>-??????-state ?????? 表示 epoch 数
44
+ $resume = "" # resume from state | 从某个状态文件夹中恢复训练 需配合上方参数同时使用 由于规范文件限制 epoch 数和全局步数不会保存 即使恢复时它们也从 1 开始 与 network_weights 的具体实现操作并不一致
45
+
46
+ # 其他设置
47
+ $min_bucket_reso = 256 # arb min resolution | arb 最小分辨率
48
+ $max_bucket_reso = 1024 # arb max resolution | arb 最大分辨率
49
+ $persistent_data_loader_workers = 0 # persistent dataloader workers | 容易爆内存,保留加载训练集的worker,减少每个 epoch 之间的停顿
50
+ $clip_skip = 2 # clip skip | 玄学 一般用 2
51
+ $multi_gpu = 0 # multi gpu | 多显卡训练 该参数仅限在显卡数 >= 2 使用
52
+ $lowram = 0 # lowram mode | 低内存模式 该模式下会将 U-net 文本编码器 VAE 转移到 GPU 显存中 启用该模式可能会对显存有一定影响
53
+
54
+ # 优化器设置
55
+ $optimizer_type = "AdamW8bit" # Optimizer type | 优化器类型 默认为 AdamW8bit,可选:AdamW AdamW8bit Lion SGDNesterov SGDNesterov8bit DAdaptation AdaFactor
56
+
57
+ # LyCORIS 训练设置
58
+ $algo = "lora" # LyCORIS network algo | LyCORIS 网络算法 可选 lora、loha、lokr、ia3、dylora。lora即为locon
59
+ $conv_dim = 4 # conv dim | 类似于 network_dim,推荐为 4
60
+ $conv_alpha = 4 # conv alpha | 类似于 network_alpha,可以采用与 conv_dim 一致或者更小的值
61
+ $dropout = "0" # dropout | dropout 概率, 0 为不使用 dropout, 越大则 dropout 越多,推荐 0~0.5, LoHa/LoKr/(IA)^3暂时不支持
62
+
63
+ # 远程记录设置
64
+ $use_wandb = 0 # enable wandb logging | 启用wandb远程记录功能
65
+ $wandb_api_key = "" # wandb api key | API,通过https://wandb.ai/authorize获取
66
+ $log_tracker_name = "" # wandb log tracker name | wandb项目名称,留空则为"network_train"
67
+
68
+ # ============= DO NOT MODIFY CONTENTS BELOW | 请勿修改下方内容 =====================
69
+ # Activate python venv
70
+ .\venv\Scripts\activate
71
+
72
+ $Env:HF_HOME = "huggingface"
73
+ $Env:XFORMERS_FORCE_DISABLE_TRITON = "1"
74
+ $ext_args = [System.Collections.ArrayList]::new()
75
+ $launch_args = [System.Collections.ArrayList]::new()
76
+
77
+ if ($multi_gpu) {
78
+ [void]$launch_args.Add("--multi_gpu")
79
+ }
80
+
81
+ if ($lowram) {
82
+ [void]$ext_args.Add("--lowram")
83
+ }
84
+
85
+ if ($is_v2_model) {
86
+ [void]$ext_args.Add("--v2")
87
+ }
88
+ else {
89
+ [void]$ext_args.Add("--clip_skip=$clip_skip")
90
+ }
91
+
92
+ if ($parameterization) {
93
+ [void]$ext_args.Add("--v_parameterization")
94
+ }
95
+
96
+ if ($train_unet_only) {
97
+ [void]$ext_args.Add("--network_train_unet_only")
98
+ }
99
+
100
+ if ($train_text_encoder_only) {
101
+ [void]$ext_args.Add("--network_train_text_encoder_only")
102
+ }
103
+
104
+ if ($network_weights) {
105
+ [void]$ext_args.Add("--network_weights=" + $network_weights)
106
+ }
107
+
108
+ if ($reg_data_dir) {
109
+ [void]$ext_args.Add("--reg_data_dir=" + $reg_data_dir)
110
+ }
111
+
112
+ if ($optimizer_type) {
113
+ [void]$ext_args.Add("--optimizer_type=" + $optimizer_type)
114
+ }
115
+
116
+ if ($optimizer_type -eq "DAdaptation") {
117
+ [void]$ext_args.Add("--optimizer_args")
118
+ [void]$ext_args.Add("decouple=True")
119
+ }
120
+
121
+ if ($network_module -eq "lycoris.kohya") {
122
+ [void]$ext_args.Add("--network_args")
123
+ [void]$ext_args.Add("conv_dim=$conv_dim")
124
+ [void]$ext_args.Add("conv_alpha=$conv_alpha")
125
+ [void]$ext_args.Add("algo=$algo")
126
+ [void]$ext_args.Add("dropout=$dropout")
127
+ }
128
+
129
+ if ($noise_offset -ne 0) {
130
+ [void]$ext_args.Add("--noise_offset=$noise_offset")
131
+ }
132
+
133
+ if ($stop_text_encoder_training -ne 0) {
134
+ [void]$ext_args.Add("--stop_text_encoder_training=$stop_text_encoder_training")
135
+ }
136
+
137
+ if ($save_state -eq 1) {
138
+ [void]$ext_args.Add("--save_state")
139
+ }
140
+
141
+ if ($resume) {
142
+ [void]$ext_args.Add("--resume=" + $resume)
143
+ }
144
+
145
+ if ($min_snr_gamma -ne 0) {
146
+ [void]$ext_args.Add("--min_snr_gamma=$min_snr_gamma")
147
+ }
148
+
149
+ if ($persistent_data_loader_workers) {
150
+ [void]$ext_args.Add("--persistent_data_loader_workers")
151
+ }
152
+
153
+ if ($use_wandb -eq 1) {
154
+ [void]$ext_args.Add("--log_with=all")
155
+ if ($wandb_api_key) {
156
+ [void]$ext_args.Add("--wandb_api_key=" + $wandb_api_key)
157
+ }
158
+
159
+ if ($log_tracker_name) {
160
+ [void]$ext_args.Add("--log_tracker_name=" + $log_tracker_name)
161
+ }
162
+ }
163
+ else {
164
+ [void]$ext_args.Add("--log_with=tensorboard")
165
+ }
166
+
167
+ # run train
168
+ python -m accelerate.commands.launch $launch_args --num_cpu_threads_per_process=8 "./sd-scripts/train_network.py" `
169
+ --enable_bucket `
170
+ --pretrained_model_name_or_path=$pretrained_model `
171
+ --train_data_dir=$train_data_dir `
172
+ --output_dir="./output" `
173
+ --logging_dir="./logs" `
174
+ --log_prefix=$output_name `
175
+ --resolution=$resolution `
176
+ --network_module=$network_module `
177
+ --max_train_epochs=$max_train_epoches `
178
+ --learning_rate=$lr `
179
+ --unet_lr=$unet_lr `
180
+ --text_encoder_lr=$text_encoder_lr `
181
+ --lr_scheduler=$lr_scheduler `
182
+ --lr_warmup_steps=$lr_warmup_steps `
183
+ --lr_scheduler_num_cycles=$lr_restart_cycles `
184
+ --network_dim=$network_dim `
185
+ --network_alpha=$network_alpha `
186
+ --output_name=$output_name `
187
+ --train_batch_size=$batch_size `
188
+ --save_every_n_epochs=$save_every_n_epochs `
189
+ --mixed_precision="fp16" `
190
+ --save_precision="fp16" `
191
+ --seed="1337" `
192
+ --cache_latents `
193
+ --prior_loss_weight=1 `
194
+ --max_token_length=225 `
195
+ --caption_extension=".txt" `
196
+ --save_model_as=$save_model_as `
197
+ --min_bucket_reso=$min_bucket_reso `
198
+ --max_bucket_reso=$max_bucket_reso `
199
+ --keep_tokens=$keep_tokens `
200
+ --xformers --shuffle_caption $ext_args
201
+ Write-Output "Train finished"
202
+ Read-Host | Out-Null ;
train.sh ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # LoRA train script by @Akegarasu
3
+
4
+ # Train data path | 设置训练用模型、图片
5
+ pretrained_model="./sd-models/model.ckpt" # base model path | 底模路径
6
+ is_v2_model=0 # SD2.0 model | SD2.0模型 2.0模型下 clip_skip 默认无效
7
+ parameterization=0 # parameterization | 参数化 本参数需要和 V2 参数同步使用 实验性功能
8
+ train_data_dir="./train/aki" # train dataset path | 训练数据集路径
9
+ reg_data_dir="" # directory for regularization images | 正则化数据集路径,默认不使用正则化图像。
10
+
11
+ # Network settings | 网络设置
12
+ network_module="networks.lora" # 在这里将会设置训练的网络种类,默认为 networks.lora 也就是 LoRA 训练。如果你想训练 LyCORIS(LoCon、LoHa) 等,则修改这个值为 lycoris.kohya
13
+ network_weights="" # pretrained weights for LoRA network | 若需要从已有的 LoRA 模型上继续训练,请填写 LoRA 模型路径。
14
+ network_dim=32 # network dim | 常用 4~128,不是越大越好
15
+ network_alpha=32 # network alpha | 常用与 network_dim 相同的值或者采用较小的值,如 network_dim的一半 防止下溢。默认值为 1,使用较小的 alpha 需要提升学习率。
16
+
17
+ # Train related params | 训练相关参数
18
+ resolution="512,512" # image resolution w,h. 图片分辨率,宽,高。支持非正方形,但必须是 64 倍数。
19
+ batch_size=1 # batch size
20
+ max_train_epoches=10 # max train epoches | 最大训练 epoch
21
+ save_every_n_epochs=2 # save every n epochs | 每 N 个 epoch 保存一次
22
+
23
+ train_unet_only=0 # train U-Net only | 仅训练 U-Net,开启这个会牺牲效果大幅减少显存使用。6G显存可以开启
24
+ train_text_encoder_only=0 # train Text Encoder only | 仅训练 文本编码器
25
+ stop_text_encoder_training=0 # stop text encoder training | 在第N步时停止训练文本编码器
26
+
27
+ noise_offset="0" # noise offset | 在训练中添加噪声偏移来改良生成非常暗或者非常亮的图像,如果启用,推荐参数为0.1
28
+ keep_tokens=0 # keep heading N tokens when shuffling caption tokens | 在随机打乱 tokens 时,保留前 N 个不变。
29
+ min_snr_gamma=0 # minimum signal-to-noise ratio (SNR) value for gamma-ray | 伽马射线事件的最小信噪比(SNR)值 默认为 0
30
+
31
+ # Learning rate | 学习率
32
+ lr="1e-4"
33
+ unet_lr="1e-4"
34
+ text_encoder_lr="1e-5"
35
+ lr_scheduler="cosine_with_restarts" # "linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup", "adafactor"
36
+ lr_warmup_steps=0 # warmup steps | 学习率预热步数,lr_scheduler 为 constant 或 adafactor 时该值需要设为0。
37
+ lr_restart_cycles=1 # cosine_with_restarts restart cycles | 余弦退火重启次数,仅在 lr_scheduler 为 cosine_with_restarts 时起效。
38
+
39
+ # Output settings | 输出设置
40
+ output_name="aki" # output model name | 模型保存名称
41
+ save_model_as="safetensors" # model save ext | 模型保存格式 ckpt, pt, safetensors
42
+
43
+ # Resume training state | 恢复训练设置
44
+ save_state=0 # save state | 保存训练状态 名称类似于 <output_name>-??????-state ?????? 表示 epoch 数
45
+ resume="" # resume from state | 从某个状态文件夹中恢复训练 需配合上方参数同时使用 由于规范文件限制 epoch 数和全局步数不会保存 即使恢复时它们也从 1 开始 与 network_weights 的具体实现操作并不一致
46
+
47
+ # 其他设置
48
+ min_bucket_reso=256 # arb min resolution | arb 最小分辨率
49
+ max_bucket_reso=1024 # arb max resolution | arb 最大分辨率
50
+ persistent_data_loader_workers=0 # persistent dataloader workers | 容易爆内存,保留加载训练集的worker,减少每个 epoch 之间的停顿
51
+ clip_skip=2 # clip skip | 玄学 一般用 2
52
+
53
+ # 优化器设置
54
+ optimizer_type="AdamW8bit" # Optimizer type | 优化器类型 默认为 AdamW8bit,可选:AdamW AdamW8bit Lion SGDNesterov SGDNesterov8bit DAdaptation AdaFactor
55
+
56
+ # LyCORIS 训练设置
57
+ algo="lora" # LyCORIS network algo | LyCORIS 网络算法 可选 lora、loha、lokr、ia3、dylora。lora即为locon
58
+ conv_dim=4 # conv dim | 类似于 network_dim,推荐为 4
59
+ conv_alpha=4 # conv alpha | 类似于 network_alpha,可以采用与 conv_dim 一致或者更小的值
60
+ dropout="0" # dropout | dropout 概率, 0 为不使用 dropout, 越大则 dropout 越多,推荐 0~0.5, LoHa/LoKr/(IA)^3暂时不支持
61
+
62
+ # 远程记录设置
63
+ use_wandb=0 # use_wandb | 启用wandb远程记录功能
64
+ wandb_api_key="" # wandb_api_key | API,通过https://wandb.ai/authorize获取
65
+ log_tracker_name="" # log_tracker_name | wandb项目名称,留空则为"network_train"
66
+
67
+ # ============= DO NOT MODIFY CONTENTS BELOW | 请勿修改下方内容 =====================
68
+ export HF_HOME="huggingface"
69
+ export TF_CPP_MIN_LOG_LEVEL=3
70
+
71
+ extArgs=()
72
+ launchArgs=()
73
+ if [[ $multi_gpu == 1 ]]; then launchArgs+=("--multi_gpu"); fi
74
+
75
+ if [[ $is_v2_model == 1 ]]; then
76
+ extArgs+=("--v2");
77
+ else
78
+ extArgs+=("--clip_skip $clip_skip");
79
+ fi
80
+
81
+ if [[ $parameterization == 1 ]]; then extArgs+=("--v_parameterization"); fi
82
+
83
+ if [[ $train_unet_only == 1 ]]; then extArgs+=("--network_train_unet_only"); fi
84
+
85
+ if [[ $train_text_encoder_only == 1 ]]; then extArgs+=("--network_train_text_encoder_only"); fi
86
+
87
+ if [[ $network_weights ]]; then extArgs+=("--network_weights $network_weights"); fi
88
+
89
+ if [[ $reg_data_dir ]]; then extArgs+=("--reg_data_dir $reg_data_dir"); fi
90
+
91
+ if [[ $optimizer_type ]]; then extArgs+=("--optimizer_type $optimizer_type"); fi
92
+
93
+ if [[ $optimizer_type == "DAdaptation" ]]; then extArgs+=("--optimizer_args decouple=True"); fi
94
+
95
+ if [[ $save_state == 1 ]]; then extArgs+=("--save_state"); fi
96
+
97
+ if [[ $resume ]]; then extArgs+=("--resume $resume"); fi
98
+
99
+ if [[ $persistent_data_loader_workers == 1 ]]; then extArgs+=("--persistent_data_loader_workers"); fi
100
+
101
+ if [[ $network_module == "lycoris.kohya" ]]; then
102
+ extArgs+=("--network_args conv_dim=$conv_dim conv_alpha=$conv_alpha algo=$algo dropout=$dropout")
103
+ fi
104
+
105
+ if [[ $stop_text_encoder_training -ne 0 ]]; then extArgs+=("--stop_text_encoder_training $stop_text_encoder_training"); fi
106
+
107
+ if [[ $noise_offset != "0" ]]; then extArgs+=("--noise_offset $noise_offset"); fi
108
+
109
+ if [[ $min_snr_gamma -ne 0 ]]; then extArgs+=("--min_snr_gamma $min_snr_gamma"); fi
110
+
111
+ if [[ $use_wandb == 1 ]]; then
112
+ extArgs+=("--log_with=all")
113
+ else
114
+ extArgs+=("--log_with=tensorboard")
115
+ fi
116
+
117
+ if [[ $wandb_api_key ]]; then extArgs+=("--wandb_api_key $wandb_api_key"); fi
118
+
119
+ if [[ $log_tracker_name ]]; then extArgs+=("--log_tracker_name $log_tracker_name"); fi
120
+
121
+ python -m accelerate.commands.launch ${launchArgs[@]} --num_cpu_threads_per_process=8 "./sd-scripts/train_network.py" \
122
+ --enable_bucket \
123
+ --pretrained_model_name_or_path=$pretrained_model \
124
+ --train_data_dir=$train_data_dir \
125
+ --output_dir="./output" \
126
+ --logging_dir="./logs" \
127
+ --log_prefix=$output_name \
128
+ --resolution=$resolution \
129
+ --network_module=$network_module \
130
+ --max_train_epochs=$max_train_epoches \
131
+ --learning_rate=$lr \
132
+ --unet_lr=$unet_lr \
133
+ --text_encoder_lr=$text_encoder_lr \
134
+ --lr_scheduler=$lr_scheduler \
135
+ --lr_warmup_steps=$lr_warmup_steps \
136
+ --lr_scheduler_num_cycles=$lr_restart_cycles \
137
+ --network_dim=$network_dim \
138
+ --network_alpha=$network_alpha \
139
+ --output_name=$output_name \
140
+ --train_batch_size=$batch_size \
141
+ --save_every_n_epochs=$save_every_n_epochs \
142
+ --mixed_precision="fp16" \
143
+ --save_precision="fp16" \
144
+ --seed="1337" \
145
+ --cache_latents \
146
+ --prior_loss_weight=1 \
147
+ --max_token_length=225 \
148
+ --caption_extension=".txt" \
149
+ --save_model_as=$save_model_as \
150
+ --min_bucket_reso=$min_bucket_reso \
151
+ --max_bucket_reso=$max_bucket_reso \
152
+ --keep_tokens=$keep_tokens \
153
+ --xformers --shuffle_caption ${extArgs[@]}
train_by_toml.ps1 ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA train script by @Akegarasu
2
+
3
+ $multi_gpu = 0 # multi gpu | ���Կ�ѵ�� �ò����������Կ��� >= 2 ʹ��
4
+ $config_file = "./toml/default.toml" # config_file | ʹ��toml�ļ�ָ��ѵ������
5
+ $sample_prompts = "./toml/sample_prompts.txt" # sample_prompts | ����prompts�ļ�,���������ò�������
6
+ $utf8 = 1 # utf8 | ʹ��utf-8�����ȡtoml����utf-8�����д�ġ������ĵ�toml���뿪��
7
+
8
+
9
+ # ============= DO NOT MODIFY CONTENTS BELOW | �����޸��·����� =====================
10
+
11
+ # Activate python venv
12
+ .\venv\Scripts\activate
13
+
14
+ $Env:HF_HOME = "huggingface"
15
+
16
+ $ext_args = [System.Collections.ArrayList]::new()
17
+ $launch_args = [System.Collections.ArrayList]::new()
18
+
19
+ if ($multi_gpu) {
20
+ [void]$launch_args.Add("--multi_gpu")
21
+ }
22
+ if ($utf8 -eq 1) {
23
+ $Env:PYTHONUTF8 = 1
24
+ }
25
+
26
+ # run train
27
+ python -m accelerate.commands.launch $launch_args --num_cpu_threads_per_process=8 "./sd-scripts/train_network.py" `
28
+ --config_file=$config_file `
29
+ --sample_prompts=$sample_prompts `
30
+ $ext_args
31
+
32
+ Write-Output "Train finished"
33
+ Read-Host | Out-Null ;
train_by_toml.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # LoRA train script by @Akegarasu
3
+
4
+ multi_gpu=0 # multi gpu | 多显卡训练 该参数仅限在显卡数 >= 2 使用
5
+ config_file="./toml/default.toml" # config_file | 使用toml文件指定训练参数
6
+ sample_prompts="./toml/sample_prompts.txt" # sample_prompts | 采样prompts文件,留空则不启用采样功能
7
+ utf8=1 # utf8 | 使用utf-8编码读取toml;以utf-8编码编写的、含中文的toml必须开启
8
+
9
+ # ============= DO NOT MODIFY CONTENTS BELOW | 请勿修改下方内容 =====================
10
+
11
+ export HF_HOME="huggingface"
12
+ export TF_CPP_MIN_LOG_LEVEL=3
13
+
14
+ extArgs=()
15
+ launchArgs=()
16
+
17
+ if [[ $multi_gpu == 1 ]]; then launchArgs+=("--multi_gpu"); fi
18
+ if [[ $utf8 == 1 ]]; then export PYTHONUTF8=1; fi
19
+
20
+ # run train
21
+ python -m accelerate.commands.launch ${launchArgs[@]} --num_cpu_threads_per_process=8 "./sd-scripts/train_network.py" \
22
+ --config_file=$config_file \
23
+ --sample_prompts=$sample_prompts \
24
+ ${extArgs[@]}