zengxi123 commited on
Commit
fb83c5b
1 Parent(s): 216dad1

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .augmentignore +15 -0
  2. .dockerignore +15 -0
  3. .env +1 -0
  4. .gitattributes +4 -35
  5. .github/FUNDING.yml +3 -0
  6. .github/dependabot.yml +7 -0
  7. .github/workflows/docker_publish.yml +91 -0
  8. .github/workflows/typos.yaml +21 -0
  9. .gitignore +54 -0
  10. .gitmodules +3 -0
  11. .hadolint.yml +6 -0
  12. .release +1 -0
  13. Dockerfile +147 -0
  14. LICENSE.md +201 -0
  15. README.md +449 -12
  16. SECURITY.md +14 -0
  17. _typos.toml +34 -0
  18. assets/js/localization.js +103 -0
  19. assets/js/script.js +104 -0
  20. assets/style.css +47 -0
  21. config example.toml +185 -0
  22. config_files/accelerate/default_config.yaml +22 -0
  23. config_files/accelerate/runpod.yaml +22 -0
  24. dataset/images/.gitkeep +0 -0
  25. dataset/logs/.gitkeep +0 -0
  26. dataset/outputs/.gitkeep +0 -0
  27. dataset/regularization/.gitkeep +0 -0
  28. deprecated/dreambooth_gui.py +110 -0
  29. deprecated/finetune_gui.py +97 -0
  30. deprecated/lora_gui.py +118 -0
  31. deprecated/textual_inversion_gui.py +110 -0
  32. deprecated/utilities_gui.py +69 -0
  33. docker-compose.yaml +57 -0
  34. docs/Finetuning/top_level.md +28 -0
  35. docs/LoRA/options.md +752 -0
  36. docs/LoRA/top_level.md +26 -0
  37. docs/config_README-ja.md +283 -0
  38. docs/fine_tune_README_ja.md +140 -0
  39. docs/gen_img_README-ja.md +487 -0
  40. docs/image_folder_structure.md +59 -0
  41. docs/train_README-ja.md +1008 -0
  42. docs/train_README-zh.md +912 -0
  43. docs/train_README.md +1007 -0
  44. docs/train_db_README-ja.md +167 -0
  45. docs/train_db_README-zh.md +162 -0
  46. docs/train_lllite_README-ja.md +214 -0
  47. docs/train_lllite_README.md +217 -0
  48. docs/train_network_README-ja.md +486 -0
  49. docs/train_network_README-zh.md +466 -0
  50. docs/train_ti_README-ja.md +105 -0
.augmentignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ .cache
3
+ .vscode
4
+ __pycache__
5
+ bitsandbytes_windows
6
+ cudnn_windows
7
+ data
8
+ dataset
9
+ docs
10
+ examples
11
+ outputs
12
+ SmilingWolf
13
+ test
14
+ v2_inference
15
+ venv
.dockerignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .cache/
2
+ cudnn_windows/
3
+ bitsandbytes_windows/
4
+ bitsandbytes_windows_deprecated/
5
+ dataset/
6
+ __pycache__/
7
+ venv/
8
+ **/.hadolint.yml
9
+ **/*.log
10
+ **/.git
11
+ **/.gitignore
12
+ **/.env
13
+ **/.github
14
+ **/.vscode
15
+ **/*.ps1
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ TENSORBOARD_PORT=6006
.gitattributes CHANGED
@@ -1,35 +1,4 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.sh text eol=lf
2
+ *.ps1 text eol=crlf
3
+ *.bat text eol=crlf
4
+ *.cmd text eol=crlf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.github/FUNDING.yml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # These are supported funding model platforms
2
+
3
+ github: [bmaltais]
.github/dependabot.yml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ---
2
+ version: 2
3
+ updates:
4
+ - package-ecosystem: "github-actions"
5
+ directory: "/"
6
+ schedule:
7
+ interval: "monthly"
.github/workflows/docker_publish.yml ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Check this guide for more information about publishing to ghcr.io with GitHub Actions:
2
+ # https://docs.github.com/en/packages/managing-github-packages-using-github-actions-workflows/publishing-and-installing-a-package-with-github-actions#upgrading-a-workflow-that-accesses-ghcrio
3
+
4
+ # Build the Docker image and push it to the registry
5
+ name: docker_publish
6
+
7
+ on:
8
+ # Trigger the workflow on tags push that match the pattern v*, for example v1.0.0
9
+ push:
10
+ tags:
11
+ - "v*"
12
+
13
+ # Allows you to run this workflow manually from the Actions tab
14
+ workflow_dispatch:
15
+
16
+ jobs:
17
+ # Only run this job on tags
18
+ docker-tag:
19
+ runs-on: ubuntu-latest
20
+ if: startsWith(github.ref, 'refs/tags/')
21
+
22
+ # Sets the permissions granted to the GITHUB_TOKEN for the actions in this job.
23
+ permissions:
24
+ contents: read
25
+ packages: write
26
+
27
+ steps:
28
+ - name: Checkout
29
+ uses: actions/checkout@v4
30
+ with:
31
+ submodules: true
32
+
33
+ # We require additional space due to the large size of our image. (~10GB)
34
+ - name: Free Disk Space (Ubuntu)
35
+ uses: jlumbroso/free-disk-space@main
36
+ with:
37
+ tool-cache: true
38
+ android: true
39
+ dotnet: true
40
+ haskell: true
41
+ large-packages: true
42
+ docker-images: true
43
+ swap-storage: true
44
+
45
+ - name: Docker meta:${{ github.ref_name }}
46
+ id: meta
47
+ uses: docker/metadata-action@v5
48
+ with:
49
+ images: ghcr.io/${{ github.repository_owner }}/kohya-ss-gui
50
+ flavor: |
51
+ latest=auto
52
+ prefix=
53
+ suffix=
54
+ # https://github.com/docker/metadata-action/tree/v5/?tab=readme-ov-file#tags-input
55
+ tags: |
56
+ type=semver,pattern=v{{major}}
57
+ type=semver,pattern={{raw}}
58
+
59
+ - name: Set up QEMU
60
+ uses: docker/setup-qemu-action@v3
61
+
62
+ - name: Set up Docker Buildx
63
+ uses: docker/setup-buildx-action@v3
64
+
65
+ # You may need to manage write and read access of GitHub Actions for repositories in the container settings.
66
+ - name: Login to GitHub Container Registry
67
+ uses: docker/login-action@v3
68
+ with:
69
+ registry: ghcr.io
70
+ username: ${{ github.repository_owner }}
71
+ password: ${{ secrets.GITHUB_TOKEN }}
72
+
73
+ - name: Build and push
74
+ uses: docker/build-push-action@v5
75
+ id: publish
76
+ with:
77
+ context: .
78
+ file: ./Dockerfile
79
+ push: true
80
+ target: final
81
+ tags: ${{ steps.meta.outputs.tags }}
82
+ labels: ${{ steps.meta.outputs.labels }}
83
+ build-args: |
84
+ VERSION=${{ github.ref_name }}
85
+ RELEASE=${{ github.run_number }}
86
+ platforms: linux/amd64
87
+ # Cache to regietry instead of gha to avoid the capacity limit.
88
+ cache-from: type=registry,ref=ghcr.io/${{ github.repository_owner }}/kohya-ss-gui:cache
89
+ cache-to: type=registry,ref=ghcr.io/${{ github.repository_owner }}/kohya-ss-gui:cache,mode=max
90
+ sbom: true
91
+ provenance: true
.github/workflows/typos.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ # yamllint disable rule:line-length
3
+ name: Typos
4
+
5
+ on: # yamllint disable-line rule:truthy
6
+ push:
7
+ pull_request:
8
+ types:
9
+ - opened
10
+ - synchronize
11
+ - reopened
12
+
13
+ jobs:
14
+ build:
15
+ runs-on: ubuntu-latest
16
+
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+
20
+ - name: typos-action
21
+ uses: crate-ci/[email protected]
.gitignore ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ venv
3
+ venv2
4
+ __pycache__
5
+ *.egg-info
6
+ build
7
+ wd14_tagger_model
8
+
9
+ # IDE and Editor specific
10
+ .vscode
11
+
12
+ # CUDNN for Windows
13
+ cudnn_windows
14
+
15
+ # Cache and temporary files
16
+ .cache
17
+ .DS_Store
18
+
19
+ # Scripts and executables
20
+ locon
21
+ gui-user.bat
22
+ gui-user.ps1
23
+
24
+ # Version control
25
+ SmilingWolf
26
+ wandb
27
+
28
+ # Setup and logs
29
+ setup.log
30
+ logs
31
+
32
+ # Miscellaneous
33
+ uninstall.txt
34
+
35
+ # Test files
36
+ test/output
37
+ test/log*
38
+ test/*.json
39
+ test/ft
40
+
41
+ # Temporary requirements
42
+ requirements_tmp_for_setup.txt
43
+
44
+ *.npz
45
+ presets/*/user_presets/*
46
+ inputs
47
+ outputs
48
+ dataset/**
49
+ !dataset/**/
50
+ !dataset/**/.gitkeep
51
+ models
52
+ data
53
+ config.toml
54
+ sd-scripts
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "sd-scripts"]
2
+ path = sd-scripts
3
+ url = https://github.com/kohya-ss/sd-scripts.git
.hadolint.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ignored:
2
+ - DL3042 # Avoid use of cache directory with pip. Use `pip install --no-cache-dir <package>`
3
+ - DL3013 # Pin versions in pip. Instead of `pip install <package>` use `pip install <package>==<version>`
4
+ - DL3008 # Pin versions in apt get install. Instead of `apt-get install <package>` use `apt-get install <package>=<version>`
5
+ - DL4006 # Set the SHELL option -o pipefail before RUN with a pipe in it
6
+ - SC2015 # Note that A && B || C is not if-then-else. C may run when A is true.
.release ADDED
@@ -0,0 +1 @@
 
 
1
+ v24.1.3
Dockerfile ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ ARG UID=1000
3
+ ARG VERSION=EDGE
4
+ ARG RELEASE=0
5
+
6
+ FROM python:3.10-slim as build
7
+
8
+ # RUN mount cache for multi-arch: https://github.com/docker/buildx/issues/549#issuecomment-1788297892
9
+ ARG TARGETARCH
10
+ ARG TARGETVARIANT
11
+
12
+ WORKDIR /app
13
+
14
+ # Install under /root/.local
15
+ ENV PIP_USER="true"
16
+ ARG PIP_NO_WARN_SCRIPT_LOCATION=0
17
+ ARG PIP_ROOT_USER_ACTION="ignore"
18
+
19
+ # Install build dependencies
20
+ RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
21
+ --mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
22
+ apt-get update && apt-get upgrade -y && \
23
+ apt-get install -y --no-install-recommends python3-launchpadlib git curl
24
+
25
+ # Install PyTorch
26
+ # The versions must align and be in sync with the requirements_linux_docker.txt
27
+ # hadolint ignore=SC2102
28
+ RUN --mount=type=cache,id=pip-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/root/.cache/pip \
29
+ pip install -U --extra-index-url https://download.pytorch.org/whl/cu121 --extra-index-url https://pypi.nvidia.com \
30
+ torch==2.1.2 torchvision==0.16.2 \
31
+ xformers==0.0.23.post1 \
32
+ ninja \
33
+ pip setuptools wheel
34
+
35
+ # Install requirements
36
+ RUN --mount=type=cache,id=pip-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/root/.cache/pip \
37
+ --mount=source=requirements_linux_docker.txt,target=requirements_linux_docker.txt \
38
+ --mount=source=requirements.txt,target=requirements.txt \
39
+ --mount=source=setup/docker_setup.py,target=setup.py \
40
+ --mount=source=sd-scripts,target=sd-scripts,rw \
41
+ pip install -r requirements_linux_docker.txt -r requirements.txt
42
+
43
+ # Replace pillow with pillow-simd (Only for x86)
44
+ ARG TARGETPLATFORM
45
+ RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
46
+ --mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
47
+ if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
48
+ apt-get update && apt-get install -y --no-install-recommends zlib1g-dev libjpeg62-turbo-dev build-essential && \
49
+ pip uninstall -y pillow && \
50
+ CC="cc -mavx2" pip install -U --force-reinstall pillow-simd; \
51
+ fi
52
+
53
+ FROM python:3.10-slim as final
54
+
55
+ ARG TARGETARCH
56
+ ARG TARGETVARIANT
57
+
58
+ ENV NVIDIA_VISIBLE_DEVICES all
59
+ ENV NVIDIA_DRIVER_CAPABILITIES compute,utility
60
+
61
+ WORKDIR /tmp
62
+
63
+ ENV CUDA_VERSION=12.1.1
64
+ ENV NV_CUDA_CUDART_VERSION=12.1.105-1
65
+ ENV NVIDIA_REQUIRE_CUDA=cuda>=12.1
66
+ ENV NV_CUDA_COMPAT_PACKAGE=cuda-compat-12-1
67
+
68
+ # Install CUDA partially
69
+ ADD https://developer.download.nvidia.com/compute/cuda/repos/debian11/x86_64/cuda-keyring_1.0-1_all.deb .
70
+ RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
71
+ --mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
72
+ dpkg -i cuda-keyring_1.0-1_all.deb && \
73
+ rm cuda-keyring_1.0-1_all.deb && \
74
+ sed -i 's/^Components: main$/& contrib/' /etc/apt/sources.list.d/debian.sources && \
75
+ apt-get update && \
76
+ apt-get install -y --no-install-recommends \
77
+ # Installing the whole CUDA typically increases the image size by approximately **8GB**.
78
+ # To decrease the image size, we opt to install only the necessary libraries.
79
+ # Here is the package list for your reference: https://developer.download.nvidia.com/compute/cuda/repos/debian11/x86_64
80
+ # !If you experience any related issues, replace the following line with `cuda-12-1` to obtain the complete CUDA package.
81
+ cuda-cudart-12-1=${NV_CUDA_CUDART_VERSION} ${NV_CUDA_COMPAT_PACKAGE} libcusparse-12-1 libnvjitlink-12-1
82
+
83
+ # Install runtime dependencies
84
+ RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
85
+ --mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
86
+ apt-get update && \
87
+ apt-get install -y --no-install-recommends libgl1 libglib2.0-0 libjpeg62 libtcl8.6 libtk8.6 libgoogle-perftools-dev dumb-init
88
+
89
+ # Fix missing libnvinfer7
90
+ RUN ln -s /usr/lib/x86_64-linux-gnu/libnvinfer.so /usr/lib/x86_64-linux-gnu/libnvinfer.so.7 && \
91
+ ln -s /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so.7
92
+
93
+ # Create user
94
+ ARG UID
95
+ RUN groupadd -g $UID $UID && \
96
+ useradd -l -u $UID -g $UID -m -s /bin/sh -N $UID
97
+
98
+ # Create directories with correct permissions
99
+ RUN install -d -m 775 -o $UID -g 0 /dataset && \
100
+ install -d -m 775 -o $UID -g 0 /licenses && \
101
+ install -d -m 775 -o $UID -g 0 /app
102
+
103
+ # Copy licenses (OpenShift Policy)
104
+ COPY --link --chmod=775 LICENSE.md /licenses/LICENSE.md
105
+
106
+ # Copy dependencies and code (and support arbitrary uid for OpenShift best practice)
107
+ COPY --link --chown=$UID:0 --chmod=775 --from=build /root/.local /home/$UID/.local
108
+ COPY --link --chown=$UID:0 --chmod=775 . /app
109
+
110
+ ENV PATH="/usr/local/cuda/lib:/usr/local/cuda/lib64:/home/$UID/.local/bin:$PATH"
111
+ ENV PYTHONPATH="${PYTHONPATH}:/home/$UID/.local/lib/python3.10/site-packages"
112
+ ENV LD_LIBRARY_PATH="/usr/local/cuda/lib:/usr/local/cuda/lib64:${LD_LIBRARY_PATH}"
113
+ ENV LD_PRELOAD=libtcmalloc.so
114
+ ENV PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
115
+ # Rich logging
116
+ # https://rich.readthedocs.io/en/stable/console.html#interactive-mode
117
+ ENV FORCE_COLOR="true"
118
+ ENV COLUMNS="100"
119
+
120
+ WORKDIR /app
121
+
122
+ VOLUME [ "/dataset" ]
123
+
124
+ # 7860: Kohya GUI
125
+ EXPOSE 7860
126
+
127
+ USER $UID
128
+
129
+ STOPSIGNAL SIGINT
130
+
131
+ # Use dumb-init as PID 1 to handle signals properly
132
+ ENTRYPOINT ["dumb-init", "--"]
133
+ CMD ["python3", "kohya_gui.py", "--listen", "0.0.0.0", "--server_port", "7860", "--headless"]
134
+
135
+ ARG VERSION
136
+ ARG RELEASE
137
+ LABEL name="bmaltais/kohya_ss" \
138
+ vendor="bmaltais" \
139
+ maintainer="bmaltais" \
140
+ # Dockerfile source repository
141
+ url="https://github.com/bmaltais/kohya_ss" \
142
+ version=${VERSION} \
143
+ # This should be a number, incremented with each change
144
+ release=${RELEASE} \
145
+ io.k8s.display-name="kohya_ss" \
146
+ summary="Kohya's GUI: This repository provides a Gradio GUI for Kohya's Stable Diffusion trainers(https://github.com/kohya-ss/sd-scripts)." \
147
+ description="The GUI allows you to set the training parameters and generate and run the required CLI commands to train the model. This is the docker image for Kohya's GUI. For more information about this tool, please visit the following website: https://github.com/bmaltais/kohya_ss."
LICENSE.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2022] [kohya-ss]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,12 +1,449 @@
1
- ---
2
- title: Kohya Ss
3
- emoji: 📈
4
- colorFrom: purple
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 4.38.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: kohya_ss
3
+ app_file: kohya_gui.py
4
+ sdk: gradio
5
+ sdk_version: 4.26.0
6
+ ---
7
+ # Kohya's GUI
8
+
9
+ This repository primarily provides a Gradio GUI for [Kohya's Stable Diffusion trainers](https://github.com/kohya-ss/sd-scripts). However, support for Linux OS is also offered through community contributions. macOS support is not optimal at the moment but might work if the conditions are favorable.
10
+
11
+ The GUI allows you to set the training parameters and generate and run the required CLI commands to train the model.
12
+
13
+ ## Table of Contents
14
+
15
+ - [Kohya's GUI](#kohyas-gui)
16
+ - [Table of Contents](#table-of-contents)
17
+ - [🦒 Colab](#-colab)
18
+ - [Installation](#installation)
19
+ - [Windows](#windows)
20
+ - [Windows Pre-requirements](#windows-pre-requirements)
21
+ - [Setup Windows](#setup-windows)
22
+ - [Optional: CUDNN 8.9.6.50](#optional-cudnn-89650)
23
+ - [Linux and macOS](#linux-and-macos)
24
+ - [Linux Pre-requirements](#linux-pre-requirements)
25
+ - [Setup Linux](#setup-linux)
26
+ - [Install Location](#install-location)
27
+ - [Runpod](#runpod)
28
+ - [Manual installation](#manual-installation)
29
+ - [Pre-built Runpod template](#pre-built-runpod-template)
30
+ - [Docker](#docker)
31
+ - [Get your Docker ready for GPU support](#get-your-docker-ready-for-gpu-support)
32
+ - [Windows](#windows-1)
33
+ - [Linux, OSX](#linux-osx)
34
+ - [Design of our Dockerfile](#design-of-our-dockerfile)
35
+ - [Use the pre-built Docker image](#use-the-pre-built-docker-image)
36
+ - [Local docker build](#local-docker-build)
37
+ - [ashleykleynhans runpod docker builds](#ashleykleynhans-runpod-docker-builds)
38
+ - [Upgrading](#upgrading)
39
+ - [Windows Upgrade](#windows-upgrade)
40
+ - [Linux and macOS Upgrade](#linux-and-macos-upgrade)
41
+ - [Starting GUI Service](#starting-gui-service)
42
+ - [Launching the GUI on Windows](#launching-the-gui-on-windows)
43
+ - [Launching the GUI on Linux and macOS](#launching-the-gui-on-linux-and-macos)
44
+ - [Custom Path Defaults](#custom-path-defaults)
45
+ - [LoRA](#lora)
46
+ - [Sample image generation during training](#sample-image-generation-during-training)
47
+ - [Troubleshooting](#troubleshooting)
48
+ - [Page File Limit](#page-file-limit)
49
+ - [No module called tkinter](#no-module-called-tkinter)
50
+ - [LORA Training on TESLA V100 - GPU Utilization Issue](#lora-training-on-tesla-v100---gpu-utilization-issue)
51
+ - [Issue Summary](#issue-summary)
52
+ - [Potential Solutions](#potential-solutions)
53
+ - [SDXL training](#sdxl-training)
54
+ - [Masked loss](#masked-loss)
55
+ - [Change History](#change-history)
56
+
57
+ ## 🦒 Colab
58
+
59
+ This Colab notebook was not created or maintained by me; however, it appears to function effectively. The source can be found at: <https://github.com/camenduru/kohya_ss-colab>.
60
+
61
+ I would like to express my gratitude to camendutu for their valuable contribution. If you encounter any issues with the Colab notebook, please report them on their repository.
62
+
63
+ | Colab | Info |
64
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ |
65
+ | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/camenduru/kohya_ss-colab/blob/main/kohya_ss_colab.ipynb) | kohya_ss_gui_colab |
66
+
67
+ ## Installation
68
+
69
+ ### Windows
70
+
71
+ #### Windows Pre-requirements
72
+
73
+ To install the necessary dependencies on a Windows system, follow these steps:
74
+
75
+ 1. Install [Python 3.10.11](https://www.python.org/ftp/python/3.10.11/python-3.10.11-amd64.exe).
76
+ - During the installation process, ensure that you select the option to add Python to the 'PATH' environment variable.
77
+
78
+ 2. Install [CUDA 11.8 toolkit](https://developer.nvidia.com/cuda-11-8-0-download-archive?target_os=Windows&target_arch=x86_64).
79
+
80
+ 3. Install [Git](https://git-scm.com/download/win).
81
+
82
+ 4. Install the [Visual Studio 2015, 2017, 2019, and 2022 redistributable](https://aka.ms/vs/17/release/vc_redist.x64.exe).
83
+
84
+ #### Setup Windows
85
+
86
+ To set up the project, follow these steps:
87
+
88
+ 1. Open a terminal and navigate to the desired installation directory.
89
+
90
+ 2. Clone the repository by running the following command:
91
+
92
+ ```shell
93
+ git clone --recursive https://github.com/bmaltais/kohya_ss.git
94
+ ```
95
+
96
+ 3. Change into the `kohya_ss` directory:
97
+
98
+ ```shell
99
+ cd kohya_ss
100
+ ```
101
+
102
+ 4. Run one of the following setup script by executing the following command:
103
+
104
+ For systems with only python 3.10.11 installed:
105
+
106
+ ```shell
107
+ .\setup.bat
108
+ ```
109
+
110
+ For systems with only more than one python release installed:
111
+
112
+ ```shell
113
+ .\setup-3.10.bat
114
+ ```
115
+
116
+ During the accelerate config step, use the default values as proposed during the configuration unless you know your hardware demands otherwise. The amount of VRAM on your GPU does not impact the values used.
117
+
118
+ #### Optional: CUDNN 8.9.6.50
119
+
120
+ The following steps are optional but will improve the learning speed for owners of NVIDIA 30X0/40X0 GPUs. These steps enable larger training batch sizes and faster training speeds.
121
+
122
+ 1. Run `.\setup.bat` and select `2. (Optional) Install cudnn files (if you want to use the latest supported cudnn version)`.
123
+
124
+ ### Linux and macOS
125
+
126
+ #### Linux Pre-requirements
127
+
128
+ To install the necessary dependencies on a Linux system, ensure that you fulfill the following requirements:
129
+
130
+ - Ensure that `venv` support is pre-installed. You can install it on Ubuntu 22.04 using the command:
131
+
132
+ ```shell
133
+ apt install python3.10-venv
134
+ ```
135
+
136
+ - Install the CUDA 11.8 Toolkit by following the instructions provided in [this link](https://developer.nvidia.com/cuda-11-8-0-download-archive?target_os=Linux&target_arch=x86_64).
137
+
138
+ - Make sure you have Python version 3.10.9 or higher (but lower than 3.11.0) installed on your system.
139
+
140
+ #### Setup Linux
141
+
142
+ To set up the project on Linux or macOS, perform the following steps:
143
+
144
+ 1. Open a terminal and navigate to the desired installation directory.
145
+
146
+ 2. Clone the repository by running the following command:
147
+
148
+ ```shell
149
+ git clone --recursive https://github.com/bmaltais/kohya_ss.git
150
+ ```
151
+
152
+ 3. Change into the `kohya_ss` directory:
153
+
154
+ ```shell
155
+ cd kohya_ss
156
+ ```
157
+
158
+ 4. If you encounter permission issues, make the `setup.sh` script executable by running the following command:
159
+
160
+ ```shell
161
+ chmod +x ./setup.sh
162
+ ```
163
+
164
+ 5. Run the setup script by executing the following command:
165
+
166
+ ```shell
167
+ ./setup.sh
168
+ ```
169
+
170
+ Note: If you need additional options or information about the runpod environment, you can use `setup.sh -h` or `setup.sh --help` to display the help message.
171
+
172
+ #### Install Location
173
+
174
+ The default installation location on Linux is the directory where the script is located. If a previous installation is detected in that location, the setup will proceed there. Otherwise, the installation will fall back to `/opt/kohya_ss`. If `/opt` is not writable, the fallback location will be `$HOME/kohya_ss`. Finally, if none of the previous options are viable, the installation will be performed in the current directory.
175
+
176
+ For macOS and other non-Linux systems, the installation process will attempt to detect the previous installation directory based on where the script is run. If a previous installation is not found, the default location will be `$HOME/kohya_ss`. You can override this behavior by specifying a custom installation directory using the `-d` or `--dir` option when running the setup script.
177
+
178
+ If you choose to use the interactive mode, the default values for the accelerate configuration screen will be "This machine," "None," and "No" for the remaining questions. These default answers are the same as the Windows installation.
179
+
180
+ ### Runpod
181
+
182
+ #### Manual installation
183
+
184
+ To install the necessary components for Runpod and run kohya_ss, follow these steps:
185
+
186
+ 1. Select the Runpod pytorch 2.0.1 template. This is important. Other templates may not work.
187
+
188
+ 2. SSH into the Runpod.
189
+
190
+ 3. Clone the repository by running the following command:
191
+
192
+ ```shell
193
+ cd /workspace
194
+ git clone --recursive https://github.com/bmaltais/kohya_ss.git
195
+ ```
196
+
197
+ 4. Run the setup script:
198
+
199
+ ```shell
200
+ cd kohya_ss
201
+ ./setup-runpod.sh
202
+ ```
203
+
204
+ 5. Run the GUI with:
205
+
206
+ ```shell
207
+ ./gui.sh --share --headless
208
+ ```
209
+
210
+ or with this if you expose 7860 directly via the runpod configuration:
211
+
212
+ ```shell
213
+ ./gui.sh --listen=0.0.0.0 --headless
214
+ ```
215
+
216
+ 6. Connect to the public URL displayed after the installation process is completed.
217
+
218
+ #### Pre-built Runpod template
219
+
220
+ To run from a pre-built Runpod template, you can:
221
+
222
+ 1. Open the Runpod template by clicking on <https://runpod.io/gsc?template=ya6013lj5a&ref=w18gds2n>.
223
+
224
+ 2. Deploy the template on the desired host.
225
+
226
+ 3. Once deployed, connect to the Runpod on HTTP 3010 to access the kohya_ss GUI. You can also connect to auto1111 on HTTP 3000.
227
+
228
+ ### Docker
229
+
230
+ #### Get your Docker ready for GPU support
231
+
232
+ ##### Windows
233
+
234
+ Once you have installed [**Docker Desktop**](https://www.docker.com/products/docker-desktop/), [**CUDA Toolkit**](https://developer.nvidia.com/cuda-downloads), [**NVIDIA Windows Driver**](https://www.nvidia.com.tw/Download/index.aspx), and ensured that your Docker is running with [**WSL2**](https://docs.docker.com/desktop/wsl/#turn-on-docker-desktop-wsl-2), you are ready to go.
235
+
236
+ Here is the official documentation for further reference.
237
+ <https://docs.nvidia.com/cuda/wsl-user-guide/index.html#nvidia-compute-software-support-on-wsl-2>
238
+ <https://docs.docker.com/desktop/wsl/use-wsl/#gpu-support>
239
+
240
+ ##### Linux, OSX
241
+
242
+ Install an NVIDIA GPU Driver if you do not already have one installed.
243
+ <https://docs.nvidia.com/datacenter/tesla/tesla-installation-notes/index.html>
244
+
245
+ Install the NVIDIA Container Toolkit with this guide.
246
+ <https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html>
247
+
248
+ #### Design of our Dockerfile
249
+
250
+ - It is required that all training data is stored in the `dataset` subdirectory, which is mounted into the container at `/dataset`.
251
+ - Please note that the file picker functionality is not available. Instead, you will need to manually input the folder path and configuration file path.
252
+ - TensorBoard has been separated from the project.
253
+ - TensorBoard is not included in the Docker image.
254
+ - The "Start TensorBoard" button has been hidden.
255
+ - TensorBoard is launched from a distinct container [as shown here](/docker-compose.yaml#L41).
256
+ - The browser won't be launched automatically. You will need to manually open the browser and navigate to [http://localhost:7860/](http://localhost:7860/) and [http://localhost:6006/](http://localhost:6006/)
257
+ - This Dockerfile has been designed to be easily disposable. You can discard the container at any time and restart it with the new code version.
258
+
259
+ #### Use the pre-built Docker image
260
+
261
+ ```bash
262
+ git clone --recursive https://github.com/bmaltais/kohya_ss.git
263
+ cd kohya_ss
264
+ docker compose up -d
265
+ ```
266
+
267
+ To update the system, do `docker compose down && docker compose up -d --pull always`
268
+
269
+ #### Local docker build
270
+
271
+ > [!IMPORTANT]
272
+ > Clone the Git repository ***recursively*** to include submodules:
273
+ > `git clone --recursive https://github.com/bmaltais/kohya_ss.git`
274
+
275
+ ```bash
276
+ git clone --recursive https://github.com/bmaltais/kohya_ss.git
277
+ cd kohya_ss
278
+ docker compose up -d --build
279
+ ```
280
+
281
+ > [!NOTE]
282
+ > Building the image may take up to 20 minutes to complete.
283
+
284
+ To update the system, ***checkout to the new code version*** and rebuild using `docker compose down && docker compose up -d --build --pull always`
285
+
286
+ > If you are running on Linux, an alternative Docker container port with fewer limitations is available [here](https://github.com/P2Enjoy/kohya_ss-docker).
287
+
288
+ #### ashleykleynhans runpod docker builds
289
+
290
+ You may want to use the following repositories when running on runpod:
291
+
292
+ - Standalone Kohya_ss template: <https://github.com/ashleykleynhans/kohya-docker>
293
+ - Auto1111 + Kohya_ss GUI template: <https://github.com/ashleykleynhans/stable-diffusion-docker>
294
+
295
+ ## Upgrading
296
+
297
+ To upgrade your installation to a new version, follow the instructions below.
298
+
299
+ ### Windows Upgrade
300
+
301
+ If a new release becomes available, you can upgrade your repository by running the following commands from the root directory of the project:
302
+
303
+ 1. Pull the latest changes from the repository:
304
+
305
+ ```powershell
306
+ git pull
307
+ ```
308
+
309
+ 2. Run the setup script:
310
+
311
+ ```powershell
312
+ .\setup.bat
313
+ ```
314
+
315
+ ### Linux and macOS Upgrade
316
+
317
+ To upgrade your installation on Linux or macOS, follow these steps:
318
+
319
+ 1. Open a terminal and navigate to the root directory of the project.
320
+
321
+ 2. Pull the latest changes from the repository:
322
+
323
+ ```bash
324
+ git pull
325
+ ```
326
+
327
+ 3. Refresh and update everything:
328
+
329
+ ```bash
330
+ ./setup.sh
331
+ ```
332
+
333
+ ## Starting GUI Service
334
+
335
+ To launch the GUI service, you can use the provided scripts or run the `kohya_gui.py` script directly. Use the command line arguments listed below to configure the underlying service.
336
+
337
+ ```text
338
+ --listen: Specify the IP address to listen on for connections to Gradio.
339
+ --username: Set a username for authentication.
340
+ --password: Set a password for authentication.
341
+ --server_port: Define the port to run the server listener on.
342
+ --inbrowser: Open the Gradio UI in a web browser.
343
+ --share: Share the Gradio UI.
344
+ --language: Set custom language
345
+ ```
346
+
347
+ ### Launching the GUI on Windows
348
+
349
+ On Windows, you can use either the `gui.ps1` or `gui.bat` script located in the root directory. Choose the script that suits your preference and run it in a terminal, providing the desired command line arguments. Here's an example:
350
+
351
+ ```powershell
352
+ gui.ps1 --listen 127.0.0.1 --server_port 7860 --inbrowser --share
353
+ ```
354
+
355
+ or
356
+
357
+ ```powershell
358
+ gui.bat --listen 127.0.0.1 --server_port 7860 --inbrowser --share
359
+ ```
360
+
361
+ ### Launching the GUI on Linux and macOS
362
+
363
+ To launch the GUI on Linux or macOS, run the `gui.sh` script located in the root directory. Provide the desired command line arguments as follows:
364
+
365
+ ```bash
366
+ gui.sh --listen 127.0.0.1 --server_port 7860 --inbrowser --share
367
+ ```
368
+
369
+ ## Custom Path Defaults
370
+
371
+ The repository now provides a default configuration file named `config.toml`. This file is a template that you can customize to suit your needs.
372
+
373
+ To use the default configuration file, follow these steps:
374
+
375
+ 1. Copy the `config example.toml` file from the root directory of the repository to `config.toml`.
376
+ 2. Open the `config.toml` file in a text editor.
377
+ 3. Modify the paths and settings as per your requirements.
378
+
379
+ This approach allows you to easily adjust the configuration to suit your specific needs to open the desired default folders for each type of folder/file input supported in the GUI.
380
+
381
+ You can specify the path to your config.toml (or any other name you like) when running the GUI. For instance: ./gui.bat --config c:\my_config.toml
382
+
383
+ ## LoRA
384
+
385
+ To train a LoRA, you can currently use the `train_network.py` code. You can create a LoRA network by using the all-in-one GUI.
386
+
387
+ Once you have created the LoRA network, you can generate images using auto1111 by installing [this extension](https://github.com/kohya-ss/sd-webui-additional-networks).
388
+
389
+ ## Sample image generation during training
390
+
391
+ A prompt file might look like this, for example:
392
+
393
+ ```txt
394
+ # prompt 1
395
+ masterpiece, best quality, (1girl), in white shirts, upper body, looking at viewer, simple background --n low quality, worst quality, bad anatomy, bad composition, poor, low effort --w 768 --h 768 --d 1 --l 7.5 --s 28
396
+
397
+ # prompt 2
398
+ masterpiece, best quality, 1boy, in business suit, standing at street, looking back --n (low quality, worst quality), bad anatomy, bad composition, poor, low effort --w 576 --h 832 --d 2 --l 5.5 --s 40
399
+ ```
400
+
401
+ Lines beginning with `#` are comments. You can specify options for the generated image with options like `--n` after the prompt. The following options can be used:
402
+
403
+ - `--n`: Negative prompt up to the next option.
404
+ - `--w`: Specifies the width of the generated image.
405
+ - `--h`: Specifies the height of the generated image.
406
+ - `--d`: Specifies the seed of the generated image.
407
+ - `--l`: Specifies the CFG scale of the generated image.
408
+ - `--s`: Specifies the number of steps in the generation.
409
+
410
+ The prompt weighting such as `( )` and `[ ]` is working.
411
+
412
+ ## Troubleshooting
413
+
414
+ If you encounter any issues, refer to the troubleshooting steps below.
415
+
416
+ ### Page File Limit
417
+
418
+ If you encounter an X error related to the page file, you may need to increase the page file size limit in Windows.
419
+
420
+ ### No module called tkinter
421
+
422
+ If you encounter an error indicating that the module `tkinter` is not found, try reinstalling Python 3.10 on your system.
423
+
424
+ ### LORA Training on TESLA V100 - GPU Utilization Issue
425
+
426
+ #### Issue Summary
427
+
428
+ When training LORA on a TESLA V100, users reported low GPU utilization. Additionally, there was difficulty in specifying GPUs other than the default for training.
429
+
430
+ #### Potential Solutions
431
+
432
+ - **GPU Selection:** Users can specify GPU IDs in the setup configuration to select the desired GPUs for training.
433
+ - **Improving GPU Load:** Utilizing `adamW8bit` optimizer and increasing the batch size can help achieve 70-80% GPU utilization without exceeding GPU memory limits.
434
+
435
+ ## SDXL training
436
+
437
+ The documentation in this section will be moved to a separate document later.
438
+
439
+ ## Masked loss
440
+
441
+ The masked loss is supported in each training script. To enable the masked loss, specify the `--masked_loss` option.
442
+
443
+ The feature is not fully tested, so there may be bugs. If you find any issues, please open an Issue.
444
+
445
+ ControlNet dataset is used to specify the mask. The mask images should be the RGB images. The pixel value 255 in R channel is treated as the mask (the loss is calculated only for the pixels with the mask), and 0 is treated as the non-mask. The pixel values 0-255 are converted to 0-1 (i.e., the pixel value 128 is treated as the half weight of the loss). See details for the dataset specification in the [LLLite documentation](./docs/train_lllite_README.md#preparing-the-dataset).
446
+
447
+ ## Change History
448
+
449
+ See release information.
SECURITY.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Versions that are currently being supported with security updates.
6
+
7
+ | Version | Supported |
8
+ | ------- | ------------------ |
9
+ | 23.2.x | :white_check_mark: |
10
+ | < 23.1.x | :x: |
11
+
12
+ ## Reporting a Vulnerability
13
+
14
+ Please open an issue if you discover a security issue.
_typos.toml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Files for typos
2
+ # Instruction: https://github.com/marketplace/actions/typos-action#getting-started
3
+
4
+ [default.extend-identifiers]
5
+
6
+ [default.extend-words]
7
+ NIN="NIN"
8
+ parms="parms"
9
+ nin="nin"
10
+ extention="extention" # Intentionally left
11
+ nd="nd"
12
+ shs="shs"
13
+ sts="sts"
14
+ scs="scs"
15
+ cpc="cpc"
16
+ coc="coc"
17
+ cic="cic"
18
+ msm="msm"
19
+ usu="usu"
20
+ ici="ici"
21
+ lvl="lvl"
22
+ dii="dii"
23
+ muk="muk"
24
+ ori="ori"
25
+ hru="hru"
26
+ rik="rik"
27
+ koo="koo"
28
+ yos="yos"
29
+ wn="wn"
30
+ parm = "parm"
31
+
32
+
33
+ [files]
34
+ extend-exclude = ["_typos.toml", "venv"]
assets/js/localization.js ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ var re_num = /^[.\d]+$/;
2
+ var re_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u;
3
+
4
+ var original_lines = {};
5
+ var translated_lines = {};
6
+
7
+ function hasLocalization() {
8
+ return window.localization && Object.keys(window.localization).length > 0;
9
+ }
10
+
11
+ function textNodesUnder(el) {
12
+ var n, a = [], walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false);
13
+ while ((n = walk.nextNode())) a.push(n);
14
+ return a;
15
+ }
16
+
17
+ function canBeTranslated(node, text) {
18
+ if (!text) return false;
19
+ if (!node.parentElement) return false;
20
+
21
+ var parentType = node.parentElement.nodeName;
22
+ if (parentType == 'SCRIPT' || parentType == 'STYLE' || parentType == 'TEXTAREA') return false;
23
+
24
+ if (parentType == 'OPTION' || parentType == 'SPAN') {
25
+ var pnode = node;
26
+ for (var level = 0; level < 4; level++) {
27
+ pnode = pnode.parentElement;
28
+ if (!pnode) break;
29
+ }
30
+ }
31
+
32
+ if (re_num.test(text)) return false;
33
+ if (re_emoji.test(text)) return false;
34
+ return true;
35
+ }
36
+
37
+ function getTranslation(text) {
38
+ if (!text) return undefined;
39
+
40
+ if (translated_lines[text] === undefined) {
41
+ original_lines[text] = 1;
42
+ }
43
+
44
+ var tl = localization[text];
45
+ if (tl !== undefined) {
46
+ translated_lines[tl] = 1;
47
+ }
48
+
49
+ return tl;
50
+ }
51
+
52
+ function processTextNode(node) {
53
+ var text = node.textContent.trim();
54
+
55
+ if (!canBeTranslated(node, text)) return;
56
+
57
+ var tl = getTranslation(text);
58
+ if (tl !== undefined) {
59
+ node.textContent = tl;
60
+ }
61
+ }
62
+
63
+ function processNode(node) {
64
+ console.log(node.nodeType + " " + node.nodeName + " " + node.nodeValue)
65
+ if (node.nodeType == 3) {
66
+ processTextNode(node);
67
+ return;
68
+ }
69
+
70
+ if (node.title) {
71
+ let tl = getTranslation(node.title);
72
+ if (tl !== undefined) {
73
+ node.title = tl;
74
+ }
75
+ }
76
+
77
+ if (node.placeholder) {
78
+ let tl = getTranslation(node.placeholder);
79
+ if (tl !== undefined) {
80
+ node.placeholder = tl;
81
+ }
82
+ }
83
+
84
+ textNodesUnder(node).forEach(function(node) {
85
+ processTextNode(node);
86
+ });
87
+ }
88
+
89
+ document.addEventListener("DOMContentLoaded", function() {
90
+ if (!hasLocalization()) {
91
+ return;
92
+ }
93
+
94
+ onUiUpdate(function(m) {
95
+ m.forEach(function(mutation) {
96
+ mutation.addedNodes.forEach(function(node) {
97
+ processNode(node);
98
+ });
99
+ });
100
+ });
101
+
102
+ processNode(gradioApp());
103
+ });
assets/js/script.js ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function gradioApp() {
2
+ const elems = document.getElementsByTagName('gradio-app');
3
+ const elem = elems.length == 0 ? document : elems[0];
4
+
5
+ if (elem !== document) {
6
+ elem.getElementById = function(id) {
7
+ return document.getElementById(id);
8
+ };
9
+ }
10
+ return elem.shadowRoot ? elem.shadowRoot : elem;
11
+ }
12
+
13
+ /**
14
+ * Get the currently selected top-level UI tab button (e.g. the button that says "Extras").
15
+ */
16
+ function get_uiCurrentTab() {
17
+ return gradioApp().querySelector('#tabs > .tab-nav > button.selected');
18
+ }
19
+
20
+ /**
21
+ * Get the first currently visible top-level UI tab content (e.g. the div hosting the "txt2img" UI).
22
+ */
23
+ function get_uiCurrentTabContent() {
24
+ return gradioApp().querySelector('#tabs > .tabitem[id^=tab_]:not([style*="display: none"])');
25
+ }
26
+
27
+ var uiUpdateCallbacks = [];
28
+ var uiAfterUpdateCallbacks = [];
29
+ var uiLoadedCallbacks = [];
30
+ var uiTabChangeCallbacks = [];
31
+ var uiAfterUpdateTimeout = null;
32
+ var uiCurrentTab = null;
33
+
34
+ /**
35
+ * Register callback to be called at each UI update.
36
+ * The callback receives an array of MutationRecords as an argument.
37
+ */
38
+ function onUiUpdate(callback) {
39
+ uiUpdateCallbacks.push(callback);
40
+ }
41
+
42
+
43
+
44
+ function executeCallbacks(queue, arg) {
45
+ for (const callback of queue) {
46
+ try {
47
+ callback(arg);
48
+ } catch (e) {
49
+ console.error("error running callback", callback, ":", e);
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Schedule the execution of the callbacks registered with onAfterUiUpdate.
56
+ * The callbacks are executed after a short while, unless another call to this function
57
+ * is made before that time. IOW, the callbacks are executed only once, even
58
+ * when there are multiple mutations observed.
59
+ */
60
+ function scheduleAfterUiUpdateCallbacks() {
61
+ clearTimeout(uiAfterUpdateTimeout);
62
+ uiAfterUpdateTimeout = setTimeout(function() {
63
+ executeCallbacks(uiAfterUpdateCallbacks);
64
+ }, 200);
65
+ }
66
+
67
+ var executedOnLoaded = false;
68
+
69
+ document.addEventListener("DOMContentLoaded", function() {
70
+ var mutationObserver = new MutationObserver(function(m) {
71
+ if (!executedOnLoaded && gradioApp().querySelector('#txt2img_prompt')) {
72
+ executedOnLoaded = true;
73
+ executeCallbacks(uiLoadedCallbacks);
74
+ }
75
+
76
+ executeCallbacks(uiUpdateCallbacks, m);
77
+ scheduleAfterUiUpdateCallbacks();
78
+ const newTab = get_uiCurrentTab();
79
+ if (newTab && (newTab !== uiCurrentTab)) {
80
+ uiCurrentTab = newTab;
81
+ executeCallbacks(uiTabChangeCallbacks);
82
+ }
83
+ });
84
+ mutationObserver.observe(gradioApp(), {childList: true, subtree: true});
85
+ });
86
+
87
+ /**
88
+ * Add a ctrl+enter as a shortcut to start a generation
89
+ */
90
+ document.addEventListener('keydown', function(e) {
91
+ var handled = false;
92
+ if (e.key !== undefined) {
93
+ if ((e.key == "Enter" && (e.metaKey || e.ctrlKey || e.altKey))) handled = true;
94
+ } else if (e.keyCode !== undefined) {
95
+ if ((e.keyCode == 13 && (e.metaKey || e.ctrlKey || e.altKey))) handled = true;
96
+ }
97
+ if (handled) {
98
+ var button = get_uiCurrentTabContent().querySelector('button[id$=_generate]');
99
+ if (button) {
100
+ button.click();
101
+ }
102
+ e.preventDefault();
103
+ }
104
+ });
assets/style.css ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #open_folder_small{
2
+ min-width: auto;
3
+ flex-grow: 0;
4
+ padding-left: 0.25em;
5
+ padding-right: 0.25em;
6
+ padding: 0.5em;
7
+ font-size: 1.5em;
8
+ }
9
+
10
+ #open_folder{
11
+ height: auto;
12
+ flex-grow: 0;
13
+ padding-left: 0.25em;
14
+ padding-right: 0.25em;
15
+ }
16
+
17
+ #number_input{
18
+ min-width: min-content;
19
+ flex-grow: 0.3;
20
+ padding-left: 0.75em;
21
+ padding-right: 0.75em;
22
+ }
23
+
24
+ .ver-class {
25
+ color: #808080;
26
+ font-size: small;
27
+ text-align: right;
28
+ padding-right: 1em;
29
+ }
30
+
31
+ #myDropdown {
32
+ height: auto;
33
+ width: 33%;
34
+ flex-grow: 0;
35
+ }
36
+
37
+ #myTensorButton {
38
+ background: radial-gradient(ellipse, #3a99ff, #52c8ff);
39
+ color: white;
40
+ border: #296eb8;
41
+ }
42
+
43
+ #myTensorButtonStop {
44
+ background: radial-gradient(ellipse, #52c8ff, #3a99ff);
45
+ color: black;
46
+ border: #296eb8;
47
+ }
config example.toml ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy this file and name it config.toml
2
+ # Edit the values to suit your needs
3
+
4
+ [settings]
5
+ use_shell = false # Use shell furing process run of sd-scripts oython code. Most secure is false but some systems may require it to be true to properly run sd-scripts.
6
+
7
+ # Default folders location
8
+ [model]
9
+ models_dir = "./models" # Pretrained model name or path
10
+ output_name = "new model" # Trained model output name
11
+ train_data_dir = "./data" # Image folder (containing training images subfolders) / Image folder (containing training images)
12
+ dataset_config = "./test.toml" # Dataset config file (Optional. Select the toml configuration file to use for the dataset)
13
+ training_comment = "Some training comment" # Training comment
14
+ save_model_as = "safetensors" # Save model as (ckpt, safetensors, diffusers, diffusers_safetensors)
15
+ save_precision = "bf16" # Save model precision (fp16, bf16, float)
16
+
17
+ [folders]
18
+ output_dir = "./outputs" # Output directory for trained model
19
+ reg_data_dir = "./data/reg" # Regularisation directory
20
+ logging_dir = "./logs" # Logging directory
21
+
22
+ [configuration]
23
+ config_dir = "./presets" # Load/Save Config file
24
+
25
+ [accelerate_launch]
26
+ dynamo_backend = "no" # Dynamo backend
27
+ dynamo_mode = "default" # Dynamo mode
28
+ dynamo_use_dynamic = false # Dynamo use dynamic
29
+ dynamo_use_fullgraph = false # Dynamo use fullgraph
30
+ extra_accelerate_launch_args = "" # Extra accelerate launch args
31
+ gpu_ids = "" # GPU IDs
32
+ main_process_port = 0 # Main process port
33
+ mixed_precision = "fp16" # Mixed precision (fp16, bf16, fp8)
34
+ multi_gpu = false # Multi GPU
35
+ num_cpu_threads_per_process = 2 # Number of CPU threads per process
36
+ num_machines = 1 # Number of machines
37
+ num_processes = 1 # Number of processes
38
+
39
+ [basic]
40
+ cache_latents = true # Cache latents
41
+ cache_latents_to_disk = false # Cache latents to disk
42
+ caption_extension = ".txt" # Caption extension
43
+ enable_bucket = true # Enable bucket
44
+ epoch = 1 # Epoch
45
+ learning_rate = 0.0001 # Learning rate
46
+ learning_rate_te = 0.0001 # Learning rate text encoder
47
+ learning_rate_te1 = 0.0001 # Learning rate text encoder 1
48
+ learning_rate_te2 = 0.0001 # Learning rate text encoder 2
49
+ lr_scheduler = "cosine" # LR Scheduler
50
+ lr_scheduler_args = "" # LR Scheduler args
51
+ lr_warmup = 0 # LR Warmup (% of total steps)
52
+ lr_scheduler_num_cycles = 1 # LR Scheduler num cycles
53
+ lr_scheduler_power = 1.0 # LR Scheduler power
54
+ max_bucket_reso = 2048 # Max bucket resolution
55
+ max_grad_norm = 1.0 # Max grad norm
56
+ max_resolution = "512,512" # Max resolution
57
+ max_train_steps = 0 # Max train steps
58
+ max_train_epochs = 0 # Max train epochs
59
+ min_bucket_reso = 256 # Min bucket resolution
60
+ optimizer = "AdamW8bit" # Optimizer (AdamW, AdamW8bit, Adafactor, DAdaptation, DAdaptAdaGrad, DAdaptAdam, DAdaptAdan, DAdaptAdanIP, DAdaptAdamPreprint, DAdaptLion, DAdaptSGD, Lion, Lion8bit, PagedAdam
61
+ optimizer_args = "" # Optimizer args
62
+ save_every_n_epochs = 1 # Save every n epochs
63
+ save_every_n_steps = 1 # Save every n steps
64
+ seed = 1234 # Seed
65
+ stop_text_encoder_training = 0 # Stop text encoder training (% of total steps)
66
+ train_batch_size = 1 # Train batch size
67
+
68
+ [advanced]
69
+ adaptive_noise_scale = 0 # Adaptive noise scale
70
+ additional_parameters = "" # Additional parameters
71
+ bucket_no_upscale = true # Don't upscale bucket resolution
72
+ bucket_reso_steps = 64 # Bucket resolution steps
73
+ caption_dropout_every_n_epochs = 0 # Caption dropout every n epochs
74
+ caption_dropout_rate = 0 # Caption dropout rate
75
+ color_aug = false # Color augmentation
76
+ clip_skip = 1 # Clip skip
77
+ debiased_estimation_loss = false # Debiased estimation loss
78
+ flip_aug = false # Flip augmentation
79
+ fp8_base = false # FP8 base training (experimental)
80
+ full_bf16 = false # Full bf16 training (experimental)
81
+ full_fp16 = false # Full fp16 training (experimental)
82
+ gradient_accumulation_steps = 1 # Gradient accumulation steps
83
+ gradient_checkpointing = false # Gradient checkpointing
84
+ huber_c = 0.1 # The huber loss parameter. Only used if one of the huber loss modes (huber or smooth l1) is selected with loss_type
85
+ huber_schedule = "snr" # The type of loss to use and whether it's scheduled based on the timestep
86
+ ip_noise_gamma = 0 # IP noise gamma
87
+ ip_noise_gamma_random_strength = false # IP noise gamma random strength (true, false)
88
+ keep_tokens = 0 # Keep tokens
89
+ log_tracker_config_dir = "./logs" # Log tracker configs directory
90
+ log_tracker_name = "" # Log tracker name
91
+ loss_type = "l2" # Loss type (l2, huber, smooth_l1)
92
+ masked_loss = false # Masked loss
93
+ max_data_loader_n_workers = 0 # Max data loader n workers (string)
94
+ max_timestep = 1000 # Max timestep
95
+ max_token_length = 150 # Max token length ("75", "150", "225")
96
+ mem_eff_attn = false # Memory efficient attention
97
+ min_snr_gamma = 0 # Min SNR gamma
98
+ min_timestep = 0 # Min timestep
99
+ multires_noise_iterations = 0 # Multires noise iterations
100
+ multires_noise_discount = 0 # Multires noise discount
101
+ no_token_padding = false # Disable token padding
102
+ noise_offset = 0 # Noise offset
103
+ noise_offset_random_strength = false # Noise offset random strength (true, false)
104
+ noise_offset_type = "Original" # Noise offset type ("Original", "Multires")
105
+ persistent_data_loader_workers = false # Persistent data loader workers
106
+ prior_loss_weight = 1.0 # Prior loss weight
107
+ random_crop = false # Random crop
108
+ save_every_n_steps = 0 # Save every n steps
109
+ save_last_n_steps = 0 # Save last n steps
110
+ save_last_n_steps_state = 0 # Save last n steps state
111
+ save_state = false # Save state
112
+ save_state_on_train_end = false # Save state on train end
113
+ scale_v_pred_loss_like_noise_pred = false # Scale v pred loss like noise pred
114
+ shuffle_caption = false # Shuffle captions
115
+ state_dir = "./outputs" # Resume from saved training state
116
+ log_with = "" # Logger to use ["wandb", "tensorboard", "all", ""]
117
+ vae_batch_size = 0 # VAE batch size
118
+ vae_dir = "./models/vae" # VAEs folder path
119
+ v_pred_like_loss = 0 # V pred like loss weight
120
+ wandb_api_key = "" # Wandb api key
121
+ wandb_run_name = "" # Wandb run name
122
+ weighted_captions = false # Weighted captions
123
+ xformers = "xformers" # CrossAttention (none, sdp, xformers)
124
+
125
+ # This next section can be used to set default values for the Dataset Preparation section
126
+ # The "Destination training direcroty" field will be equal to "train_data_dir" as specified above
127
+ [dataset_preparation]
128
+ class_prompt = "class" # Class prompt
129
+ images_folder = "/some/folder/where/images/are" # Training images directory
130
+ instance_prompt = "instance" # Instance prompt
131
+ reg_images_folder = "/some/folder/where/reg/images/are" # Regularisation images directory
132
+ reg_images_repeat = 1 # Regularisation images repeat
133
+ util_regularization_images_repeat_input = 1 # Regularisation images repeat input
134
+ util_training_images_repeat_input = 40 # Training images repeat input
135
+
136
+ [huggingface]
137
+ async_upload = false # Async upload
138
+ huggingface_path_in_repo = "" # Huggingface path in repo
139
+ huggingface_repo_id = "" # Huggingface repo id
140
+ huggingface_repo_type = "" # Huggingface repo type
141
+ huggingface_repo_visibility = "" # Huggingface repo visibility
142
+ huggingface_token = "" # Huggingface token
143
+ resume_from_huggingface = "" # Resume from huggingface (ex: {repo_id}/{path_in_repo}:{revision}:{repo_type})
144
+ save_state_to_huggingface = false # Save state to huggingface
145
+
146
+ [samples]
147
+ sample_every_n_steps = 0 # Sample every n steps
148
+ sample_every_n_epochs = 0 # Sample every n epochs
149
+ sample_prompts = "" # Sample prompts
150
+ sample_sampler = "euler_a" # Sampler to use for image sampling
151
+
152
+ [sdxl]
153
+ sdxl_cache_text_encoder_outputs = false # Cache text encoder outputs
154
+ sdxl_no_half_vae = true # No half VAE
155
+
156
+ [wd14_caption]
157
+ always_first_tags = "" # comma-separated list of tags to always put at the beginning, e.g. 1girl,1boy
158
+ append_tags = false # Append TAGs
159
+ batch_size = 8 # Batch size
160
+ caption_extension = ".txt" # Extension for caption file (e.g., .caption, .txt)
161
+ caption_separator = ", " # Caption Separator
162
+ character_tag_expand = false # Expand tag tail parenthesis to another tag for character tags. `chara_name_(series)` becomes `chara_name, series`
163
+ character_threshold = 0.35 # Character threshold
164
+ debug = false # Debug mode
165
+ force_download = false # Force model re-download when switching to onnx
166
+ frequency_tags = false # Frequency tags
167
+ general_threshold = 0.35 # General threshold
168
+ max_data_loader_n_workers = 2 # Max dataloader workers
169
+ onnx = true # ONNX
170
+ recursive = false # Recursive
171
+ remove_underscore = false # Remove underscore
172
+ repo_id = "SmilingWolf/wd-convnext-tagger-v3" # Repo id for wd14 tagger on Hugging Face
173
+ tag_replacement = "" # Tag replacement in the format of `source1,target1;source2,target2; ...`. Escape `,` and `;` with `\`. e.g. `tag1,tag2;tag3,tag4`
174
+ thresh = 0.36 # Threshold
175
+ train_data_dir = "" # Image folder to caption (containing the images to caption)
176
+ undesired_tags = "" # comma-separated list of tags to remove, e.g. 1girl,1boy
177
+ use_rating_tags = false # Use rating tags
178
+ use_rating_tags_as_last_tag = false # Use rating tags as last tagging tags
179
+
180
+ [metadata]
181
+ metadata_title = "" # Title for model metadata (default is output_name)
182
+ metadata_author = "" # Author name for model metadata
183
+ metadata_description = "" # Description for model metadata
184
+ metadata_license = "" # License for model metadata
185
+ metadata_tags = "" # Tags for model metadata
config_files/accelerate/default_config.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ command_file: null
2
+ commands: null
3
+ compute_environment: LOCAL_MACHINE
4
+ deepspeed_config: {}
5
+ distributed_type: 'NO'
6
+ downcast_bf16: 'no'
7
+ dynamo_backend: 'NO'
8
+ fsdp_config: {}
9
+ gpu_ids: all
10
+ machine_rank: 0
11
+ main_process_ip: null
12
+ main_process_port: null
13
+ main_training_function: main
14
+ megatron_lm_config: {}
15
+ mixed_precision: 'no'
16
+ num_machines: 1
17
+ num_processes: 1
18
+ rdzv_backend: static
19
+ same_network: true
20
+ tpu_name: null
21
+ tpu_zone: null
22
+ use_cpu: false
config_files/accelerate/runpod.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ command_file: null
2
+ commands: null
3
+ compute_environment: LOCAL_MACHINE
4
+ deepspeed_config: {}
5
+ distributed_type: 'NO'
6
+ downcast_bf16: 'no'
7
+ dynamo_backend: 'NO'
8
+ fsdp_config: {}
9
+ gpu_ids: all
10
+ machine_rank: 0
11
+ main_process_ip: null
12
+ main_process_port: null
13
+ main_training_function: main
14
+ megatron_lm_config: {}
15
+ mixed_precision: 'no'
16
+ num_machines: 1
17
+ num_processes: 1
18
+ rdzv_backend: static
19
+ same_network: true
20
+ tpu_name: null
21
+ tpu_zone: null
22
+ use_cpu: false
dataset/images/.gitkeep ADDED
File without changes
dataset/logs/.gitkeep ADDED
File without changes
dataset/outputs/.gitkeep ADDED
File without changes
dataset/regularization/.gitkeep ADDED
File without changes
deprecated/dreambooth_gui.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gradio as gr
3
+ import os
4
+
5
+ from kohya_gui.dreambooth_gui import dreambooth_tab
6
+ from kohya_gui.utilities import utilities_tab
7
+
8
+ from kohya_gui.custom_logging import setup_logging
9
+ from kohya_gui.localization_ext import add_javascript
10
+
11
+
12
+ # Set up logging
13
+ log = setup_logging()
14
+
15
+
16
+ def UI(**kwargs):
17
+ add_javascript(kwargs.get("language"))
18
+ css = ""
19
+
20
+ headless = kwargs.get("headless", False)
21
+ log.info(f"headless: {headless}")
22
+
23
+ if os.path.exists("./assets/style.css"):
24
+ with open(os.path.join("./assets/style.css"), "r", encoding="utf8") as file:
25
+ log.info("Load CSS...")
26
+ css += file.read() + "\n"
27
+
28
+ interface = gr.Blocks(css=css, title="Kohya_ss GUI", theme=gr.themes.Default())
29
+
30
+ with interface:
31
+ with gr.Tab("Dreambooth"):
32
+ (
33
+ train_data_dir_input,
34
+ reg_data_dir_input,
35
+ output_dir_input,
36
+ logging_dir_input,
37
+ ) = dreambooth_tab(headless=headless)
38
+ with gr.Tab("Utilities"):
39
+ utilities_tab(
40
+ train_data_dir_input=train_data_dir_input,
41
+ reg_data_dir_input=reg_data_dir_input,
42
+ output_dir_input=output_dir_input,
43
+ logging_dir_input=logging_dir_input,
44
+ enable_copy_info_button=True,
45
+ headless=headless,
46
+ )
47
+
48
+ # Show the interface
49
+ launch_kwargs = {}
50
+ username = kwargs.get("username")
51
+ password = kwargs.get("password")
52
+ server_port = kwargs.get("server_port", 0)
53
+ inbrowser = kwargs.get("inbrowser", False)
54
+ share = kwargs.get("share", False)
55
+ server_name = kwargs.get("listen")
56
+
57
+ launch_kwargs["server_name"] = server_name
58
+ if username and password:
59
+ launch_kwargs["auth"] = (username, password)
60
+ if server_port > 0:
61
+ launch_kwargs["server_port"] = server_port
62
+ if inbrowser:
63
+ launch_kwargs["inbrowser"] = inbrowser
64
+ if share:
65
+ launch_kwargs["share"] = share
66
+ interface.launch(**launch_kwargs)
67
+
68
+
69
+ if __name__ == "__main__":
70
+ # torch.cuda.set_per_process_memory_fraction(0.48)
71
+ parser = argparse.ArgumentParser()
72
+ parser.add_argument(
73
+ "--listen",
74
+ type=str,
75
+ default="127.0.0.1",
76
+ help="IP to listen on for connections to Gradio",
77
+ )
78
+ parser.add_argument(
79
+ "--username", type=str, default="", help="Username for authentication"
80
+ )
81
+ parser.add_argument(
82
+ "--password", type=str, default="", help="Password for authentication"
83
+ )
84
+ parser.add_argument(
85
+ "--server_port",
86
+ type=int,
87
+ default=0,
88
+ help="Port to run the server listener on",
89
+ )
90
+ parser.add_argument("--inbrowser", action="store_true", help="Open in browser")
91
+ parser.add_argument("--share", action="store_true", help="Share the gradio UI")
92
+ parser.add_argument(
93
+ "--headless", action="store_true", help="Is the server headless"
94
+ )
95
+ parser.add_argument(
96
+ "--language", type=str, default=None, help="Set custom language"
97
+ )
98
+
99
+ args = parser.parse_args()
100
+
101
+ UI(
102
+ username=args.username,
103
+ password=args.password,
104
+ inbrowser=args.inbrowser,
105
+ server_port=args.server_port,
106
+ share=args.share,
107
+ listen=args.listen,
108
+ headless=args.headless,
109
+ language=args.language,
110
+ )
deprecated/finetune_gui.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gradio as gr
3
+ import os
4
+
5
+ from kohya_gui.utilities import utilities_tab
6
+ from kohya_gui.finetune_gui import finetune_tab
7
+
8
+ from kohya_gui.custom_logging import setup_logging
9
+ from kohya_gui.localization_ext import add_javascript
10
+
11
+ # Set up logging
12
+ log = setup_logging()
13
+
14
+
15
+ def UI(**kwargs):
16
+ add_javascript(kwargs.get("language"))
17
+ css = ""
18
+
19
+ headless = kwargs.get("headless", False)
20
+ log.info(f"headless: {headless}")
21
+
22
+ if os.path.exists("./assets/style.css"):
23
+ with open(os.path.join("./assets/style.css"), "r", encoding="utf8") as file:
24
+ log.info("Load CSS...")
25
+ css += file.read() + "\n"
26
+
27
+ interface = gr.Blocks(css=css, title="Kohya_ss GUI", theme=gr.themes.Default())
28
+
29
+ with interface:
30
+ with gr.Tab("Finetune"):
31
+ finetune_tab(headless=headless)
32
+ with gr.Tab("Utilities"):
33
+ utilities_tab(enable_dreambooth_tab=False, headless=headless)
34
+
35
+ # Show the interface
36
+ launch_kwargs = {}
37
+ username = kwargs.get("username")
38
+ password = kwargs.get("password")
39
+ server_port = kwargs.get("server_port", 0)
40
+ inbrowser = kwargs.get("inbrowser", False)
41
+ share = kwargs.get("share", False)
42
+ server_name = kwargs.get("listen")
43
+
44
+ launch_kwargs["server_name"] = server_name
45
+ if username and password:
46
+ launch_kwargs["auth"] = (username, password)
47
+ if server_port > 0:
48
+ launch_kwargs["server_port"] = server_port
49
+ if inbrowser:
50
+ launch_kwargs["inbrowser"] = inbrowser
51
+ if share:
52
+ launch_kwargs["share"] = share
53
+ interface.launch(**launch_kwargs)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ # torch.cuda.set_per_process_memory_fraction(0.48)
58
+ parser = argparse.ArgumentParser()
59
+ parser.add_argument(
60
+ "--listen",
61
+ type=str,
62
+ default="127.0.0.1",
63
+ help="IP to listen on for connections to Gradio",
64
+ )
65
+ parser.add_argument(
66
+ "--username", type=str, default="", help="Username for authentication"
67
+ )
68
+ parser.add_argument(
69
+ "--password", type=str, default="", help="Password for authentication"
70
+ )
71
+ parser.add_argument(
72
+ "--server_port",
73
+ type=int,
74
+ default=0,
75
+ help="Port to run the server listener on",
76
+ )
77
+ parser.add_argument("--inbrowser", action="store_true", help="Open in browser")
78
+ parser.add_argument("--share", action="store_true", help="Share the gradio UI")
79
+ parser.add_argument(
80
+ "--headless", action="store_true", help="Is the server headless"
81
+ )
82
+ parser.add_argument(
83
+ "--language", type=str, default=None, help="Set custom language"
84
+ )
85
+
86
+ args = parser.parse_args()
87
+
88
+ UI(
89
+ username=args.username,
90
+ password=args.password,
91
+ inbrowser=args.inbrowser,
92
+ server_port=args.server_port,
93
+ share=args.share,
94
+ listen=args.listen,
95
+ headless=args.headless,
96
+ language=args.language,
97
+ )
deprecated/lora_gui.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gradio as gr
3
+ import os
4
+
5
+ from kohya_gui.utilities import utilities_tab
6
+ from kohya_gui.lora_gui import lora_tab
7
+
8
+ from kohya_gui.custom_logging import setup_logging
9
+ from kohya_gui.localization_ext import add_javascript
10
+
11
+ # Set up logging
12
+ log = setup_logging()
13
+
14
+
15
+ def UI(**kwargs):
16
+ try:
17
+ # Your main code goes here
18
+ while True:
19
+ add_javascript(kwargs.get("language"))
20
+ css = ""
21
+
22
+ headless = kwargs.get("headless", False)
23
+ log.info(f"headless: {headless}")
24
+
25
+ if os.path.exists("./assets/style.css"):
26
+ with open(os.path.join("./assets/style.css"), "r", encoding="utf8") as file:
27
+ log.info("Load CSS...")
28
+ css += file.read() + "\n"
29
+
30
+ interface = gr.Blocks(
31
+ css=css, title="Kohya_ss GUI", theme=gr.themes.Default()
32
+ )
33
+
34
+ with interface:
35
+ with gr.Tab("LoRA"):
36
+ (
37
+ train_data_dir_input,
38
+ reg_data_dir_input,
39
+ output_dir_input,
40
+ logging_dir_input,
41
+ ) = lora_tab(headless=headless)
42
+ with gr.Tab("Utilities"):
43
+ utilities_tab(
44
+ train_data_dir_input=train_data_dir_input,
45
+ reg_data_dir_input=reg_data_dir_input,
46
+ output_dir_input=output_dir_input,
47
+ logging_dir_input=logging_dir_input,
48
+ enable_copy_info_button=True,
49
+ headless=headless,
50
+ )
51
+
52
+ # Show the interface
53
+ launch_kwargs = {}
54
+ username = kwargs.get("username")
55
+ password = kwargs.get("password")
56
+ server_port = kwargs.get("server_port", 0)
57
+ inbrowser = kwargs.get("inbrowser", False)
58
+ share = kwargs.get("share", False)
59
+ server_name = kwargs.get("listen")
60
+
61
+ launch_kwargs["server_name"] = server_name
62
+ if username and password:
63
+ launch_kwargs["auth"] = (username, password)
64
+ if server_port > 0:
65
+ launch_kwargs["server_port"] = server_port
66
+ if inbrowser:
67
+ launch_kwargs["inbrowser"] = inbrowser
68
+ if share:
69
+ launch_kwargs["share"] = share
70
+ log.info(launch_kwargs)
71
+ interface.launch(**launch_kwargs)
72
+ except KeyboardInterrupt:
73
+ # Code to execute when Ctrl+C is pressed
74
+ print("You pressed Ctrl+C!")
75
+
76
+
77
+ if __name__ == "__main__":
78
+ # torch.cuda.set_per_process_memory_fraction(0.48)
79
+ parser = argparse.ArgumentParser()
80
+ parser.add_argument(
81
+ "--listen",
82
+ type=str,
83
+ default="127.0.0.1",
84
+ help="IP to listen on for connections to Gradio",
85
+ )
86
+ parser.add_argument(
87
+ "--username", type=str, default="", help="Username for authentication"
88
+ )
89
+ parser.add_argument(
90
+ "--password", type=str, default="", help="Password for authentication"
91
+ )
92
+ parser.add_argument(
93
+ "--server_port",
94
+ type=int,
95
+ default=0,
96
+ help="Port to run the server listener on",
97
+ )
98
+ parser.add_argument("--inbrowser", action="store_true", help="Open in browser")
99
+ parser.add_argument("--share", action="store_true", help="Share the gradio UI")
100
+ parser.add_argument(
101
+ "--headless", action="store_true", help="Is the server headless"
102
+ )
103
+ parser.add_argument(
104
+ "--language", type=str, default=None, help="Set custom language"
105
+ )
106
+
107
+ args = parser.parse_args()
108
+
109
+ UI(
110
+ username=args.username,
111
+ password=args.password,
112
+ inbrowser=args.inbrowser,
113
+ server_port=args.server_port,
114
+ share=args.share,
115
+ listen=args.listen,
116
+ headless=args.headless,
117
+ language=args.language,
118
+ )
deprecated/textual_inversion_gui.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gradio as gr
3
+ import os
4
+
5
+ from kohya_gui.textual_inversion_gui import ti_tab
6
+ from kohya_gui.utilities import utilities_tab
7
+
8
+ from kohya_gui.custom_logging import setup_logging
9
+ from kohya_gui.localization_ext import add_javascript
10
+
11
+
12
+ # Set up logging
13
+ log = setup_logging()
14
+
15
+
16
+ def UI(**kwargs):
17
+ add_javascript(kwargs.get("language"))
18
+ css = ""
19
+
20
+ headless = kwargs.get("headless", False)
21
+ log.info(f"headless: {headless}")
22
+
23
+ if os.path.exists("./assets/style.css"):
24
+ with open(os.path.join("./assets/style.css"), "r", encoding="utf8") as file:
25
+ log.info("Load CSS...")
26
+ css += file.read() + "\n"
27
+
28
+ interface = gr.Blocks(css=css, title="Kohya_ss GUI", theme=gr.themes.Default())
29
+
30
+ with interface:
31
+ with gr.Tab("Dreambooth TI"):
32
+ (
33
+ train_data_dir_input,
34
+ reg_data_dir_input,
35
+ output_dir_input,
36
+ logging_dir_input,
37
+ ) = ti_tab(headless=headless)
38
+ with gr.Tab("Utilities"):
39
+ utilities_tab(
40
+ train_data_dir_input=train_data_dir_input,
41
+ reg_data_dir_input=reg_data_dir_input,
42
+ output_dir_input=output_dir_input,
43
+ logging_dir_input=logging_dir_input,
44
+ enable_copy_info_button=True,
45
+ headless=headless,
46
+ )
47
+
48
+ # Show the interface
49
+ launch_kwargs = {}
50
+ username = kwargs.get("username")
51
+ password = kwargs.get("password")
52
+ server_port = kwargs.get("server_port", 0)
53
+ inbrowser = kwargs.get("inbrowser", False)
54
+ share = kwargs.get("share", False)
55
+ server_name = kwargs.get("listen")
56
+
57
+ launch_kwargs["server_name"] = server_name
58
+ if username and password:
59
+ launch_kwargs["auth"] = (username, password)
60
+ if server_port > 0:
61
+ launch_kwargs["server_port"] = server_port
62
+ if inbrowser:
63
+ launch_kwargs["inbrowser"] = inbrowser
64
+ if share:
65
+ launch_kwargs["share"] = share
66
+ interface.launch(**launch_kwargs)
67
+
68
+
69
+ if __name__ == "__main__":
70
+ # torch.cuda.set_per_process_memory_fraction(0.48)
71
+ parser = argparse.ArgumentParser()
72
+ parser.add_argument(
73
+ "--listen",
74
+ type=str,
75
+ default="127.0.0.1",
76
+ help="IP to listen on for connections to Gradio",
77
+ )
78
+ parser.add_argument(
79
+ "--username", type=str, default="", help="Username for authentication"
80
+ )
81
+ parser.add_argument(
82
+ "--password", type=str, default="", help="Password for authentication"
83
+ )
84
+ parser.add_argument(
85
+ "--server_port",
86
+ type=int,
87
+ default=0,
88
+ help="Port to run the server listener on",
89
+ )
90
+ parser.add_argument("--inbrowser", action="store_true", help="Open in browser")
91
+ parser.add_argument("--share", action="store_true", help="Share the gradio UI")
92
+ parser.add_argument(
93
+ "--headless", action="store_true", help="Is the server headless"
94
+ )
95
+ parser.add_argument(
96
+ "--language", type=str, default=None, help="Set custom language"
97
+ )
98
+
99
+ args = parser.parse_args()
100
+
101
+ UI(
102
+ username=args.username,
103
+ password=args.password,
104
+ inbrowser=args.inbrowser,
105
+ server_port=args.server_port,
106
+ share=args.share,
107
+ listen=args.listen,
108
+ headless=args.headless,
109
+ language=args.language,
110
+ )
deprecated/utilities_gui.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gradio as gr
3
+ import os
4
+
5
+ from kohya_gui.utilities import utilities_tab
6
+
7
+ from kohya_gui.custom_logging import setup_logging
8
+ from kohya_gui.localization_ext import add_javascript
9
+
10
+
11
+ # Set up logging
12
+ log = setup_logging()
13
+
14
+
15
+ def UI(**kwargs):
16
+ css = ''
17
+
18
+ if os.path.exists('./assets/style.css'):
19
+ with open(os.path.join('./assets/style.css'), 'r', encoding='utf8') as file:
20
+ print('Load CSS...')
21
+ css += file.read() + '\n'
22
+
23
+ interface = gr.Blocks(css=css)
24
+
25
+ with interface:
26
+ utilities_tab()
27
+
28
+ # Show the interface
29
+ launch_kwargs = {}
30
+ if not kwargs.get('username', None) == '':
31
+ launch_kwargs['auth'] = (
32
+ kwargs.get('username', None),
33
+ kwargs.get('password', None),
34
+ )
35
+ if kwargs.get('server_port', 0) > 0:
36
+ launch_kwargs['server_port'] = kwargs.get('server_port', 0)
37
+ if kwargs.get('inbrowser', False):
38
+ launch_kwargs['inbrowser'] = kwargs.get('inbrowser', False)
39
+ print(launch_kwargs)
40
+ interface.launch(**launch_kwargs)
41
+
42
+
43
+ if __name__ == '__main__':
44
+ # torch.cuda.set_per_process_memory_fraction(0.48)
45
+ parser = argparse.ArgumentParser()
46
+ parser.add_argument(
47
+ '--username', type=str, default='', help='Username for authentication'
48
+ )
49
+ parser.add_argument(
50
+ '--password', type=str, default='', help='Password for authentication'
51
+ )
52
+ parser.add_argument(
53
+ '--server_port',
54
+ type=int,
55
+ default=0,
56
+ help='Port to run the server listener on',
57
+ )
58
+ parser.add_argument(
59
+ '--inbrowser', action='store_true', help='Open in browser'
60
+ )
61
+
62
+ args = parser.parse_args()
63
+
64
+ UI(
65
+ username=args.username,
66
+ password=args.password,
67
+ inbrowser=args.inbrowser,
68
+ server_port=args.server_port,
69
+ )
docker-compose.yaml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ kohya-ss-gui:
3
+ container_name: kohya-ss-gui
4
+ image: ghcr.io/bmaltais/kohya-ss-gui:latest
5
+ user: 1000:0
6
+ build:
7
+ context: .
8
+ args:
9
+ - UID=1000
10
+ cache_from:
11
+ - ghcr.io/bmaltais/kohya-ss-gui:cache
12
+ cache_to:
13
+ - type=inline
14
+ ports:
15
+ - 7860:7860
16
+ environment:
17
+ SAFETENSORS_FAST_GPU: 1
18
+ TENSORBOARD_PORT: ${TENSORBOARD_PORT:-6006}
19
+ tmpfs:
20
+ - /tmp
21
+ volumes:
22
+ - /tmp/.X11-unix:/tmp/.X11-unix
23
+ - ./dataset:/dataset
24
+ - ./dataset/images:/app/data
25
+ - ./dataset/logs:/app/logs
26
+ - ./dataset/outputs:/app/outputs
27
+ - ./dataset/regularization:/app/regularization
28
+ - ./.cache/config:/app/config
29
+ - ./.cache/user:/home/1000/.cache
30
+ - ./.cache/triton:/home/1000/.triton
31
+ - ./.cache/nv:/home/1000/.nv
32
+ - ./.cache/keras:/home/1000/.keras
33
+ - ./.cache/config:/home/1000/.config # For backward compatibility
34
+ deploy:
35
+ resources:
36
+ reservations:
37
+ devices:
38
+ - driver: nvidia
39
+ capabilities: [gpu]
40
+ device_ids: ["all"]
41
+
42
+ tensorboard:
43
+ container_name: tensorboard
44
+ image: tensorflow/tensorflow:latest-gpu
45
+ ports:
46
+ # !Please change the port in .env file
47
+ - ${TENSORBOARD_PORT:-6006}:6006
48
+ volumes:
49
+ - ./dataset/logs:/app/logs
50
+ command: tensorboard --logdir=/app/logs --bind_all
51
+ deploy:
52
+ resources:
53
+ reservations:
54
+ devices:
55
+ - driver: nvidia
56
+ capabilities: [gpu]
57
+ device_ids: ["all"]
docs/Finetuning/top_level.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Finetuning Resource Guide
2
+
3
+ This guide is a resource compilation to facilitate the development of robust LoRA models.
4
+
5
+ -Need to add resources here
6
+
7
+ ## Guidelines for SDXL Finetuning
8
+
9
+ - Set the `Max resolution` to at least 1024x1024, as this is the standard resolution for SDXL.
10
+ - The fine-tuning can be done with 24GB GPU memory with the batch size of 1.
11
+ - Train U-Net only.
12
+ - Use gradient checkpointing.
13
+ - Use `--cache_text_encoder_outputs` option and caching latents.
14
+ - Use Adafactor optimizer. RMSprop 8bit or Adagrad 8bit may work. AdamW 8bit doesn't seem to work.
15
+ - PyTorch 2 seems to use slightly less GPU memory than PyTorch 1.
16
+
17
+ Example of the optimizer settings for Adafactor with the fixed learning rate:
18
+ ```
19
+ optimizer_type = "adafactor"
20
+ optimizer_args = [ "scale_parameter=False", "relative_step=False", "warmup_init=False" ]
21
+ lr_scheduler = "constant_with_warmup"
22
+ lr_warmup_steps = 100
23
+ learning_rate = 4e-7 # SDXL original learning rate
24
+ ```
25
+
26
+ ## Resource Contributions
27
+
28
+ If you have valuable resources to add, kindly create a PR on Github.
docs/LoRA/options.md ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Explaining LoRA Learning Settings Using Kohya_ss for Stable Diffusion Understanding by Anyone
2
+
3
+ To understand the meaning of each setting in kohya_ss, it is necessary to know how LoRA performs additional learning.
4
+
5
+ We will also explain what the "model," which is the target of additional learning, is.
6
+
7
+ ## What is a "model"
8
+
9
+ Stable Diffusion loads and uses modules called " models ". A model is, so to speak, a "brain", and its true identity is " weight information of a neural network ".
10
+
11
+ A neural network is made up of many " neurons ", and the clusters of neurons form many layers of " layers ". Neurons in one layer are connected to neurons in another layer by lines, and the strength of the connection is " weight ". It is this "weight" that holds a huge amount of picture information.
12
+
13
+ ### LoRA adds a small neural net
14
+
15
+ LoRA is a kind of "additional learning", but additional learning is to upgrade the neural network.
16
+
17
+ An additional learning method called "DreamBooth" uses this method.
18
+
19
+ With this method, if you want to publish the additional training data, you need to distribute the whole model that has been updated with additional training.
20
+
21
+ Models are typically 2G to 5G bytes in size, making them difficult to distribute.
22
+
23
+ In contrast, LoRA learning leaves the model alone and creates a new “small neural net ” for each position you want to learn. Additional training is done on this small neural net .
24
+
25
+ When you want to distribute LoRA, you only need to distribute this small neural network , so the data size is small.
26
+
27
+ ### Structure of a small neural net
28
+
29
+ LoRA's small neural net consists of three layers. The number of neurons in the "input layer" on the left and the "output layer" on the right is the same as the number of neurons in the "input layer" and "output layer" of the target neural network . The number of neurons in the middle layer (middle layer) is called the "rank number" (or the number of dimensions), and this number can be freely determined when learning.
30
+
31
+ ### LoRA Learning Target 1: U-Net
32
+
33
+ U-Net is divided into "Down" (left half), "Mid" (bottom) and "Up" (right half).
34
+
35
+ And it consists of 25 blocks in total: Down12 block, Mid1 block, and Up12 block. The neural net added here is simply called "UNet" in Kohya_ss.
36
+
37
+ ### LoRA Learning Object 2: Text Encoder
38
+
39
+ This isn't the only time LoRA adds neural nets .
40
+
41
+ The block called "Cross Attention" in the figure above receives text information from a module called "Text Encoder ". This "text encoder " has the role of converting the prompt, which is text data, into a string of numbers (vector).
42
+
43
+ There is only one text encoder , which is shared by all Attention Blocks in U-Net. This text encoder is originally treated as a "finished product" within Stable Diffusion and is not subject to model learning, but it is also subject to additional learning by LoRA.
44
+
45
+ The LoRA updated text encoder is used in all Attention blocks, so any neural nets added here will have a huge impact on the final image.
46
+
47
+ The neural network added here is called "Text Encoder" in Kohya_ss.
48
+
49
+ ## Basic training parameters
50
+
51
+ ### LoRA type
52
+
53
+ Specifies the type of LoRA learning. The LoRA explained above is the "standard" type. "DyLoRA" learns multiple ranks below the specified rank at the same time, so it is convenient when you want to select the optimum rank. LoHa is highly efficient LoRA, and LoCon extends learning to U-Net's Res block.
54
+
55
+ There is no problem with the Standard type at first. If you are having trouble learning, try another type.
56
+
57
+ ### LoRA network weights
58
+
59
+ If you want to use the already learned LoRA file for additional learning, specify the LoRA file here.
60
+
61
+ The LoRA specified here will be read at the start of learning, and learning will start from this LoRA state. LoRA after learning is saved as another file, so the LoRA file specified here will not be overwritten.
62
+
63
+ ### DIM from weights
64
+
65
+ This is an option only when doing additional training with LoRA network weights.
66
+
67
+ As shown in the figure above, LoRA adds a small neural network , but the number of neurons (number of ranks) in the middle layer can be freely set with Network Rank (described later).
68
+
69
+ However, turning this option on will set the number of ranks of the created LoRA to the same number of ranks as the LoRA specified in LoRA network weights. When this is turned on, the specification of Network Rank is ignored.
70
+
71
+ For example, when the number of LoRA ranks used for additional learning is 32, the number of LoRA ranks to be created will also be set to 32.
72
+
73
+ Default is off.
74
+
75
+ ### Train batch size
76
+
77
+ Specify a batch size. A batch is "the number of images to read at once". A batch size of 2 will train two images at a time simultaneously. If multiple different pictures are learned at the same time, the tuning accuracy for each picture will drop, but since it will be learning that comprehensively captures the characteristics of multiple pictures, the final result may instead be better.
78
+
79
+ (If you tune too much to a specific picture, it will become LoRA that is not applicable.)
80
+
81
+ Since multiple pictures are learned at once, the higher the batch size, the shorter the learning time. However, the tuning accuracy decreases and the number of weight changes decreases, so there is a possibility that the learning may be insufficient in some cases.
82
+
83
+ (There is also a report that when increasing the batch size, it is better to increase the learning rate (described later). For example, if the batch size is 2, the learning rate should be doubled.)
84
+
85
+ Also, the higher the batch size, the more memory is consumed. Let's decide according to the size of VRAM of your PC.
86
+
87
+ With 6GB of VRAM, a batch size of 2 would be barely possible.
88
+
89
+ Default is 1.
90
+
91
+ *Since all the images read at the same time for each batch must be the same size, if the sizes of the training images are different, the number of images that are processed simultaneously may be less than the number of batches specified here.
92
+
93
+ ### Epoch
94
+
95
+ One epoch is "one set of learning".
96
+
97
+ For example, let's say you want to learn by reading 50 images each 10 times. In this case, 1 epoch is 50x10 = 500 trainings. If it is 2 epochs, this will be repeated twice, so it will be 500x2 = 1000 times of learning.
98
+
99
+ After training for the specified number of epochs, a LoRA file will be created and saved to the specified location.
100
+
101
+ For LoRA, 2-3 epochs of learning is sufficient.
102
+
103
+ ### Save every N epochs
104
+
105
+ You can save the progress as a LoRA file for each epoch number specified here.
106
+
107
+ For example, if you specify 10 in "Epoch" and specify 2 in "Save every N epochs", the LoRA file will be saved in the specified folder every 2 epochs (at the end of 2, 4, 6, 8 epochs).
108
+
109
+ If you don't need to create an intermediate LoRA, set the value here to the same value as "Epoch".
110
+
111
+ ### Caption Extension
112
+
113
+ If you have prepared a caption file for each image, specify the extension of the caption file here.
114
+
115
+ If this is blank, the extension will be ".caption". If the extension of the caption file is ".txt", specify ".txt" here.
116
+
117
+ If you don't have a caption file, you can ignore it.
118
+
119
+ ### Mixed precision
120
+
121
+ Specifies the type of mixed precision for the weight data during training.
122
+
123
+ The weight data is originally in 32-bit units (when no is selected), but if necessary, learning by mixing 16-bit unit data will lead to considerable memory savings and speedup. fp16 is a data format with half the precision , and bf16 is a data format devised to handle the same numerical width as 32-bit data .
124
+
125
+ You can get LoRA with a sufficiently high accuracy at fp16.
126
+
127
+ ### Save precision
128
+
129
+ Specifies the type of weight data to save in the LoRA file.
130
+
131
+ float is 32-bit, fp16 and bf16 are 16-bit units. The two below have smaller file sizes.
132
+
133
+ The default is fp16.
134
+
135
+ ### Number of CPU threads per core
136
+
137
+ The number of threads per CPU core during training. Basically, the higher the number, the higher the efficiency, but it is necessary to adjust the settings according to the specifications.
138
+
139
+ Default is 2.
140
+
141
+ ### Seeds
142
+
143
+ During learning, there are a number of random processes such as ``in what order to read the images'' and``how much noise to put on the training images (details omitted)''.
144
+
145
+ Seed is like an ID for determining the random processing procedure, and if the same Seed is specified, the same random procedure will be used each time, making it easier to reproduce the learning results.
146
+
147
+ However, there are random processes that do not use this seed (such as randomly cropping images), so specifying the same seed does not always give the same learning results.
148
+
149
+ Default is blank. If not specified, Seed will be set appropriately when training is executed.
150
+
151
+ If you want to reproduce the result as much as possible, there is no loss by setting a number (such as 1234) appropriately.
152
+
153
+ ### Cache latents
154
+
155
+ The training image is read into VRAM, "compressed" to a state called Latent before entering U-Net, and is trained in VRAM in this state. Normally, images are "compressed" each time they are loaded, but you can specify that "compressed" images are kept in main memory by checking Cache latents.
156
+
157
+ Keeping it in the main memory saves VRAM space and speeds up, but you can't process the image before "compression", so you can't use augmentation (described later) other than flip_aug. Also, random crop (described later), which crops the image in a random range each time, cannot be used.
158
+
159
+ Default is on.
160
+
161
+ ### Cache latents to disk
162
+
163
+ Similar to the Cache latents option, but checking this allows you to specify that compressed image data be saved to disk as temporary files.
164
+
165
+ This temporary file can be reused even after restarting kohya_ss, so if you want to do LoRA learning with the same data many times, turning on this option will increase learning efficiency.
166
+
167
+ However, if you turn this on, you will not be able to use augmentation and random crop other than flip_aug.
168
+
169
+ Default is off.
170
+
171
+ ### Learning rate
172
+
173
+ Specify the learning rate. " Learning" is to change the thickness (weight) of the wiring in the neural network so that a picture that looks exactly like the given picture can be made, but every time a picture is given, the wiring is changed. If you tune too much only to the given picture, you will not be able to draw other pictures at all.
174
+
175
+ To avoid this, we change the weights slightly each time to incorporate a little bit more of the given picture. The "learning rate" determines the amount of this "just a little".
176
+
177
+ The default value is 0.0001.
178
+
179
+ ### LR Scheduler
180
+
181
+ You can change the learning rate in the middle of learning. A scheduler is a setting for how to change the learning rate. Possible values include:
182
+
183
+ - `adafactor`: Select this to set the optimizer (described later) to Adafactor . Learn while automatically adjusting the learning rate according to the situation to save VRAM
184
+ - `constant`: the learning rate does not change from beginning to end
185
+ - `constant_with_warmup`: Start with a learning rate of 0 and gradually increase it toward the set value of Learning rate during warm-up, and use the set value of Learning rate during main learning.
186
+ - `cosine` : Gradually decrease the learning rate toward 0 while drawing a wave (cosine curve)
187
+ - `cosine _with_restarts`: repeat cosine many times (see also description of LR number of cycles)
188
+ - `linear`: Start at the Learning rate setting and decrease linearly towards 0
189
+ - `polynomial`: Same behavior as linear, but a bit more complicated to reduce (see also LR power description)
190
+ Set to constant if you want the learning rate to be fixed at the Learning rate setting.
191
+
192
+ Default is cosine
193
+
194
+ ### LR warmup
195
+
196
+ If you have selected constant_with_warmup in the scheduler, set here how many times to warm up.
197
+
198
+ The number specified here is a percentage of the total number of steps.
199
+
200
+ For example, if you train 50 images 10 times with a batch size of 1 and do this for 2 epochs, the total number of steps is 50x10x2=1000. If you set LR warmup to 10, the first 10% of the 1000 total steps, or 100 steps, will be the warmup.
201
+
202
+ You can ignore this if your scheduler is not constant_with_warmup.
203
+
204
+ Default is 10.
205
+
206
+ ### Optimizer
207
+
208
+ The optimizer is a setting for "how to update the neural net weights during training ". Various methods have been proposed for smart learning, but the most commonly used in LoRA learning is "AdamW" (32-bit) or "AdamW8bit". AdamW8bit uses less VRAM and has enough accuracy, so if you get lost, use this.
209
+
210
+ In addition, "Adafactor", which adjusts the learning rate appropriately according to the progress of learning while incorporating Adam's method, is also often used (Learning rate setting is ignored when using Adafactor).
211
+
212
+ "DAdapt" is an optimizer that adjusts the learning rate, and "Lion" is a relatively new optimizer , but it has not been fully verified yet. There is a report that "SGDNesterov" has good learning accuracy but slows down.
213
+
214
+ The default is "AdamW8bit". There is no problem basically as it is.
215
+
216
+ ### Optimizer extra arguments
217
+
218
+ If you want more granularity for a given optimizer , write the command here.
219
+
220
+ You can usually leave this field blank.
221
+
222
+ ### Text Encoder learning rate
223
+
224
+ Sets the learning rate for the text encoder . As I wrote earlier, the effect of additional training on text encoders affects the entire U-Net.
225
+
226
+ Therefore, it is usually set lower than the learning rate (Unet learning rate) for each block of U-Net.
227
+
228
+ The default value is 0.00005(5e-5).
229
+
230
+ If you specify a number here, it takes precedence over the Learning rate value.
231
+
232
+ ### Unet learning rate
233
+
234
+ Sets the learning rate for U-Net. This is the learning rate when performing additional learning on each attention block (and other blocks depending on the setting) in U-Net.
235
+
236
+ The default value is 0.0001.
237
+
238
+ If you specify a number here, it takes precedence over the Learning rate value.
239
+
240
+ ### Network Rank (Dimension)
241
+
242
+ Specifies the number of neurons in the hidden layer of the "additional small neural net " described earlier in the article (see the figure above for details).
243
+
244
+ The larger the number of neurons , the more learning information can be stored, but the possibility of learning unnecessary information other than the learning target increases, and the LoRA file size also increases.
245
+
246
+ Generally, it is often set to a maximum of about 128, but there are reports that 32 is sufficient.
247
+
248
+ When making LoRA on a trial basis, it may be better to start from around 2 to 8.
249
+
250
+ Default is 8.
251
+
252
+ ### Network alpha
253
+
254
+ This was introduced as a convenience measure to prevent weights from being rounded to 0 when saving LoRA.
255
+
256
+ Due to the structure of LoRA, the weight value of the neural network tends to be small, and if it becomes too small, it may become indistinguishable from zero (that is, the same as not learning anything). Therefore, a technique was proposed in which the actual (stored) weight value is kept large, but the weight is always weakened at a constant rate during learning to make the weight value appear smaller. Network alpha determines this "weight weakening rate".
257
+
258
+ The smaller the Network alpha value, the larger the stored LoRA neural net weights.
259
+
260
+ How much the weight weakens when used (usage strength) is calculated by "Network_Alpha/Network_Rank" (roughly a value between 0 and 1) and is closely related to the Network Rank number.
261
+
262
+ If the accuracy of LoRA after learning is not good enough, the weight data may be too small and collapsed to 0. In such a case, try lowering the Network Alpha value (=increasing the save weight value).
263
+
264
+ The default is 1 (that is, maximize the stored weight value).
265
+
266
+ If Network Alpha and Network Rank have the same value, the effect will be turned off.
267
+
268
+ *Network Alpha value must not exceed Network Rank value. It is possible to specify a higher number, but there is a high probability that it will result in an unintended LoRA.
269
+
270
+ Also, when setting the Network Alpha, you should consider the effect on the learning rate.
271
+
272
+ For example, with an Alpha of 16 and a Rank of 32, the strength of the weight used is 16/32 = 0.5, meaning that the learning rate is only half as powerful as the Learning Rate setting.
273
+
274
+ If Alpha and Rank are the same number, the strength used will be 1 and will have no effect on the learning rate.
275
+
276
+ ### Max resolution
277
+
278
+ Specify the maximum resolution of training images in the order of "width, height". If the training images exceed the resolution specified here, they will be scaled down to this resolution.
279
+
280
+ The default is "512,512". Many models use images of this size, so it is safe to use images of this size when learning LoRA.
281
+
282
+ ### Stop text encoder training
283
+
284
+ You can stop learning the text encoder in the middle. As I wrote above, updating the text encoder has a big impact on the whole, so it is easy to fall into overfitting (tuning too much to the training image and other images can not be drawn), and it is also overfitting to stop learning at a moderate point is one way to prevent
285
+
286
+ The number specified here is a percentage of the total training step. Once learning reaches this percentage, the text encoder stops learning.
287
+
288
+ For example, if the total number of steps is 1000 and you specify 80 here, the text encoder will finish training when the learning progress is 80%, i.e. 1000x0.8=800 steps.
289
+
290
+ Training of U-Net continues with 200 remaining steps.
291
+
292
+ If this is 0, the text encoder training will not stop until the end.
293
+
294
+ ### Enable buckets
295
+
296
+ " bucket " is a "bucket" (container) as the name suggests. The training images used in LoRA do not have to be of the same size, but images of different sizes cannot be trained at the same time. Therefore, it is necessary to sort the images into "buckets" according to their size before training. Put similar sized images in the same bucket and different sized images in different buckets.
297
+
298
+ Default is on.
299
+
300
+ If your training images are all the same size, you can turn this option off, but leaving it on has no effect.
301
+
302
+ *If you turn off Enable buckets when the size of the training images is not unified, the training images will be enlarged or reduced to have the same size.
303
+
304
+ Enlargement and reduction are performed while maintaining the aspect ratio of the image. If the aspect ratio is not the same as the standard size, the vertical or horizontal size of the image after scaling may exceed the standard size. For example, if the base size is 512x512 ( 1 aspect ratio ) and the image size is 1536x1024 ( 1.5 aspect ratio ), the image will be scaled down to 768x512 ( 1.5 aspect ratio remains).
305
+
306
+ ## Advanced Configuration
307
+
308
+ After this are the options in the Advanced Configuration section.
309
+
310
+ ### Weights, Blocks, Conv
311
+
312
+ These are the "learning weight" and "rank" settings for each block in U-Net. Selecting each tab will bring up the corresponding configuration screen.
313
+
314
+ *These settings are for advanced users. If you have no preference, you can leave all fields blank.
315
+
316
+ #### Weights: Down LR weights/Mid LR weights/Up LR weights
317
+
318
+ As you can see from the U-Net structure diagram, U-Net consists of 12 IN blocks, 1 MID block, and 12 OUT blocks, a total of 25 blocks.
319
+
320
+ If you want different learning rate weights for each block, you can set them here individually.
321
+
322
+ The weight here is the "strength of learning" represented by a numerical value of 0 to 1. If it is 0, it is "not learning at all", and if it is 1, it is "learning at the learning rate set in Learning rate". can vary the intensity of learning.
323
+
324
+ A weight of 0.5 means half the learning rate.
325
+
326
+ "Down LR weights" specify the weights for each of the 12 IN blocks.
327
+
328
+ "Mid LR weights" specifies the weights of the MID block.
329
+
330
+ "Up LR weights" specify the weight of each of the 12 OUT blocks.
331
+
332
+ #### Weights: Blocks LR zero threshold
333
+
334
+ I explained that "LoRA adds neural nets ", but it doesn't make sense to add neural nets with too small weights (i.e. barely learned). Therefore, you can set "Do not add neural nets to blocks with too small weights ".
335
+
336
+ Blocks that do not exceed the weight value set here will not be added to the neural net . For example, if you specify 0.1 here, the neural net will not be added to blocks with weights less than or equal to 0.1 (note that exclusions also include the specified value!).
337
+
338
+ The default is blank, which is 0 (do nothing).
339
+
340
+ #### Blocks: Block dims, Block alphas
341
+
342
+ Here you can set different rank (dim) and alpha values ​​for each of the 25 blocks IN0~11, MID, OUT0~11.
343
+
344
+ See Network Rank, Network alpha for rank and alpha values.
345
+
346
+ Blocks with higher rank are expected to hold more information.
347
+
348
+ You must always specify 25 numbers for this parameter value, but since LoRA targets attention blocks, IN0, IN3, IN6, IN9, IN10, IN11, IN11, OUT0, and IN1 do not have attention blocks. , IN2 settings (1st, 4th, 7th, 11th, 12th, 14th, 15th, 16th digits) are ignored during learning.
349
+
350
+ *This is a setting for advanced users. If you don't care, you can leave it blank. If not specified here, "Network Rank(Dimension)" value and "Network Alpha" value will be applied to all blocks.
351
+
352
+ #### Conv: Conv dims, Conv, alphas
353
+
354
+ The attention block that LoRA learns from has a neural network called "Conv ", which is also updated by additional learning (see the diagram of the attention layer structure at the top of the article). This is a process called "convolution", and the size of the "filter" used there is 1x1 square.
355
+
356
+ Read this article about convolutions .
357
+
358
+ On the other hand, some of the blocks other than Attention (Res, Down blocks) and some of the Attention blocks in OUT are convoluted using a 3x3 square filter. Originally, that is not the learning target of LoRA, but by specifying it with this parameter, the 3x3 convolution of the Res block can also be the learning target.
359
+
360
+ Since there are more learning targets, there is a possibility that more precise LoRA learning can be performed.
361
+
362
+ The setting method is the same as "Blocks: Blocks dims, Blocks alphas".
363
+
364
+ A 3x3 conv exists on all 25 layers.
365
+
366
+ *This is a setting for advanced users. If you don't care, you can leave it blank.
367
+
368
+ ### No token padding
369
+
370
+ Captions attached to training images are processed every 75 tokens tokens " can basically be regarded as "words").
371
+
372
+ If the caption length is less than 75 tokens align to 75 tokens This is called "padding".
373
+
374
+ Here you can specify not to pad tokens
375
+
376
+ Default is off. You can basically leave it off.
377
+
378
+ ### Gradient accumulation steps
379
+
380
+ Changing the weights (that is, "learning") is usually done for each batch read, but it is also possible to do multiple batches of training at once. This option specifies how many batches to learn at once.
381
+
382
+ This has a similar effect (not the "same effect"!) as increasing the number of batches.
383
+
384
+ For example, if the batch size is 4, the number of images read simultaneously in one batch is 4. In other words, one learning is performed every four readings. If we set the Gradient accumulation steps to 2, training will be performed once every 2 batches, resulting in 1 learning per 8 reads. This works similarly (but not the same!) as batch number 8.
385
+
386
+ If you increase this value, the number of times of learning will decrease, so the processing will be faster, but it will consume more memory.
387
+
388
+ Default is 1.
389
+
390
+ ### Weighted captions
391
+
392
+ Currently, the most popular Stable Diffusion usage environment is "Stable Diffusion WebUI", which has a unique prompt description method. For example, if you want to emphasize "Black" very strongly when specifying " black cat " at the prompt, put the word you want to emphasize in parentheses like "(black:1.2) cat" and put ": number" after the word , Words are emphasized by multiples of that number.
393
+
394
+ This option allows this notation to be used in the training image captions as well.
395
+
396
+ If you want to write complex captions, it's a good idea to give it a try.
397
+
398
+ Default is off.
399
+
400
+ ### Prior loss weight
401
+
402
+ The prior loss weight determines how much importance is given to the " regularization images" (see the description of the Regularization folder above for details) during training .
403
+
404
+ If this value is low, the regularization images are considered less important, and LoRA is generated that is more characteristic of the training images.
405
+
406
+ This setting has no meaning if you are not using a regularized image.
407
+
408
+ This is a value between 0 and 1, and defaults to 1 ( also respects regularized images).
409
+
410
+ ### LR number of cycles
411
+
412
+ If you select " Cosine with restart" or "Polynomial" for the scheduler, this option specifies how many cycles the scheduler runs during training.
413
+
414
+ If the number of this option is 2 or greater, the scheduler will run multiple times during a single training run.
415
+
416
+ In both Cosine with restart and Polynomial, the learning rate gradually decreases to 0 as learning progresses, but if the number of cycles is 2 or more, the learning rate is reset and restarted when the learning rate reaches 0.
417
+
418
+ The figure below (source) is an example of the change in learning rate for Cosine with restart (purple) and Polynomial (light green).
419
+
420
+ The purple example has the number of cycles set to 4. The light green example has a cycle number of 1.
421
+
422
+ Since the specified number of cycles is executed within the determined learning step, the more the number of cycles increases, the more the learning rate changes.
423
+
424
+ Default is blank, leaving blank equals 1.
425
+
426
+ Example of learning rate movement
427
+ Cosine with restart "LR number of cycle = 4" (purple)
428
+ Polynomial "LR power = 2" (light green)
429
+
430
+ ### LR power
431
+
432
+ This is an option when the scheduler is set to Polynomial. The higher this number, the steeper the initial learning rate drops. (The slope of the light green line in the image above becomes steeper).
433
+
434
+ When power is 1, it has the same shape as the linear scheduler.
435
+
436
+ If the number is too large, the learning rate will stick close to 0, resulting in insufficient learning, so be careful.
437
+
438
+ Defaults to blank, leaving blank equals 1 (that is, the same as the linear scheduler).
439
+
440
+ ### Additional parameters
441
+
442
+ If you want to tweak learning setting parameters that are not displayed in the kohya_ss GUI , enter them here as commands.
443
+
444
+ You can usually leave this field blank.
445
+
446
+ ### Save every N steps
447
+
448
+ A LoRA file is created and saved each time the number of steps specified here is completed.
449
+
450
+ For example, when the total number of learning steps is 1000, if you specify 200 here, LoRA files will be saved at the end of 200, 400, 600, and 800 steps.
451
+
452
+ See also "Save every N epochs" for saving intermediate LoRA.
453
+
454
+ Default is 0 (do not save intermediate LoRA).
455
+
456
+ ### Save last N steps
457
+
458
+ This is an option when Save every N steps is specified to save LoRA during learning.
459
+
460
+ If you want to keep only recent LoRA files and discard old LoRA files, you can set "how many recent steps of LoRA files to keep" here.
461
+
462
+ For example, if the total number of training steps is 600 and the Save every N steps option is specified to save every 100 steps. Then LoRA files will be saved at the 100th, 200th, 300th, 400th, and 500th steps, but if Save every N steps is set to 300, only the last 300 steps of LoRA files will be saved. In other words, at the 500th step, LoRA older than the 200th (=500-300) step (that is, LoRA at the 100th step) is deleted.
463
+
464
+ Default is 0.
465
+
466
+ ### Keep n tokens
467
+
468
+ If your training images have captions, you can randomly shuffle the comma-separated words in the captions (see Shuffle caption option for details). However, if you have words that you want to keep at the beginning, you can use this option to specify "Keep the first 0 words at the beginning".
469
+
470
+ The number of first words specified here will always be fixed at the beginning.
471
+
472
+ Default is 0. This option does nothing if the shuffle caption option is off.
473
+
474
+ - A "word" here is a piece of text separated by commas. No matter how many words the delimited text contains, it counts as "one word".
475
+
476
+ In the case of " black cat , eating, sitting", " black cat " is one word.
477
+
478
+ ### Clip skip
479
+
480
+ The text encoder uses a mechanism called "CLIP", which is made up of 12 similar layers.
481
+
482
+ Texts ( tokens ) are originally converted to numeric sequences (vectors) through these 12 layers, and the vectors coming out of the last layer are sent to the U-Net Attention block.
483
+
484
+ However, the model developed independently by the service "Novel AI", commonly known as "Novel AI model", adopted a unique specification that uses the vector output by the second to last layer instead of the last layer. The same is true for models derived from Novel AI models. Therefore, it is necessary to specify "Which layer of CLIP is the vector from which the base model used for learning is used?"
485
+
486
+ "Clip skip" specifies the layer number of this "Xth from the end".
487
+
488
+ Setting this to 2 sends the penultimate layer's output vector to the Attention block. If 1, the output vector of the last layer is used.
489
+
490
+ If the base model is a Novel AI model (or a mix of them), 2 should be fine. In other cases, 1 is fine.
491
+
492
+ ### Max Token Length
493
+
494
+ Specifies the length of the maximum token included in the caption .
495
+
496
+ The "tokens" here are not the number of words, but the number of tokens Note that commas also count as one token.
497
+
498
+ It's unlikely that you'll use more than 75 tokens in your caption, but if you find your caption to be too long, specify a higher number here.
499
+
500
+ ### Full fp16 training (experimental)
501
+
502
+ When the option "Mixed precision" described above is turned on (fp16 or bf16), a mixture of 32-bit and 16-bit data is used during training, but when this option is turned on, all weight data is 16-bit (fp16 format). Although it saves memory, the accuracy of some data is halved, so there is a possibility that the learning accuracy will also drop.
503
+
504
+ Default is off. You should leave it off unless you really want to save memory.
505
+
506
+ ### Gradient checkpointing
507
+
508
+ Normally, during training, we modify and update the weights of a large number of neural nets all at once each time an image is loaded. By fixing this "gradually" rather than "all at once," you can save memory by reducing computation.
509
+
510
+ This option specifies that the weight calculation should be done incrementally. Turning this on or off will have no effect on LoRA's learning results.
511
+
512
+ Default is off.
513
+
514
+ ### Shuffle caption
515
+
516
+ If the training images have captions, most of the captions are written in the form of words separated by commas, such as " black cat , eating, sitting". The Shuffle caption option randomly changes the order of these comma-separated words each time.
517
+
518
+ Words in captions are generally given more weight the closer they are to the beginning. Therefore, if the word order is fixed, backward words may not be learned well, and forward words may have unintended associations with training images. It is hoped that this bias can be corrected by reordering the words each time the image is loaded.
519
+
520
+ This option has no meaning if the caption is written in sentences instead of comma separated.
521
+
522
+ Default is off.
523
+
524
+ - A "word" here is a piece of text separated by commas. No matter how many words the delimited text contains, it counts as "one word".
525
+
526
+ In the case of " black cat , eating, sitting", " black cat " is one word.
527
+
528
+ ### Persistent data loaders
529
+
530
+ The data required for training is discarded and reloaded after each epoch. This is an option to keep it instead of throwing it away. Turning this option on speeds up the start of training for new epochs, but uses more memory to hold the data.
531
+
532
+ Default is off.
533
+
534
+ ### Memory efficient attention
535
+
536
+ If this is checked, VRAM usage is suppressed and attention block processing is performed. It's slower than the next option "xformers". Turn it on if you don't have enough VRAM.
537
+
538
+ Default is off.
539
+
540
+ ### Use xformers
541
+
542
+ Using a Python library called "xformers" will trade attention blocking for less VRAM usage at the cost of some speed. Turn it on if you don't have enough VRAM.
543
+
544
+ Default is on.
545
+
546
+ ### Color augmentation
547
+
548
+ "augmentation" means "padded image". By slightly processing the training images each time, we artificially increase the number of types of training images.
549
+
550
+ When Color Augmentation is turned on, the Hue of the image is changed randomly each time. LoRA learned from this is expected to have a slight range in color tone.
551
+
552
+ Not available if the Cache latents option is on.
553
+
554
+ Default is off.
555
+
556
+ ### Flip augmentation
557
+
558
+ If this option is turned on, the image will be horizontally flipped randomly. It can learn left and right angles, which is useful when you want to learn symmetrical people and objects .
559
+
560
+ Default is off.
561
+
562
+ ### Min SNR gamma
563
+
564
+ In LoRA learning, learning is performed by putting noise of various strengths on the training image (details about this are omitted), but depending on the difference in strength of the noise on which it is placed, learning will be stable by moving closer to or farther from the learning target. not, and the Min SNR gamma was introduced to compensate for that. Especially when learning images with little noise on them, it may deviate greatly from the target, so try to suppress this jump.
565
+
566
+ I won't go into details because it's confusing, but you can set this value from 0 to 20, and the default is 0.
567
+
568
+ According to the paper that proposed this method, the optimal value is 5.
569
+
570
+ I don't know how effective it is, but if you're unsatisfied with the learning results, try different values.
571
+
572
+ ### Don't upscale bucket resolution
573
+
574
+ The Bucket size defaults to 256-1024 pixels (or a maximum resolution if specified with the Max resolution option, which takes precedence). Images that fall outside this size range, either vertically or horizontally, will be scaled (preserving the aspect ratio ) to fit within the specified range.
575
+
576
+ However, when this option is turned on, the bucket size range setting is ignored and the buckets are automatically prepared according to the size of the training images, so all training images are loaded unscaled. . However, even at this time, some parts of the image may be cropped to fit the Bucket resolution steps (described later).
577
+
578
+ Default is on.
579
+
580
+ ### Bucket resolution steps
581
+
582
+ If using buckets , specify the resolution interval for each bucket here.
583
+
584
+ For example, if you specify 64 here, each training image will be sorted into separate buckets by 64 pixels according to their size. This sorting is done for each vertical and horizontal.
585
+
586
+ If the image size does not fit the specified size of the bucket, the protruding part will be cut off.
587
+
588
+ For example, if the maximum resolution is 512 pixels and the bucket step size is every 64 pixels , then the buckets will be 512, 448, 384... but a 500 pixel image will be put into a 448 pixel bucket, with an extra 52 pixels are clipped.
589
+
590
+ Default is 64 pixels .
591
+
592
+ - If this number is too small, the buckets will be divided too finely, and in the worst case, it will be like "one bucket for each image".
593
+
594
+ Note that we always load images from the same bucket for each batch, so having too few images in a bucket will unintentionally reduce the number of batches.
595
+
596
+ ### Random crop instead of center crop
597
+
598
+ As mentioned above, half-sized images are sorted into buckets and then partly cropped to align the size, but usually it is cropped so as to keep the center of the image.
599
+
600
+ When this option is on, it randomly determines which part of the picture is cut. Turn on this option if you want to extend the learning range beyond the center of the image.
601
+
602
+ *This option cannot be used when the cache latents option is on.
603
+
604
+ ### Noise offset type
605
+
606
+ This is an option to specify which method to use when adding additional noise to training images. At the time of learning, we always add noise to the image (details are omitted here), but it is preferable that this noise is "hard to predict" noise, so adding more noise makes it more "predictable". "hard" noise.
607
+
608
+ Default is Original. Multires adds noise in a slightly more complicated way.
609
+
610
+ #### Noise offset
611
+
612
+ This is an option when "Original" is selected for Noise offset type. If you enter a value greater than 0 here, additional noise will be added. Values ​​range from 0 to 1, where 0 adds no noise at all. A value of 1 adds strong noise.
613
+
614
+ It has been reported that adding about 0.1 noise makes LoRA's colors more vivid (brighter and darker). Default is 0.
615
+
616
+ #### A daptive noise scale
617
+
618
+ Used in combination with the Noise offset option. Specifying a number here will further adjust the amount of additional noise specified by Noise offset to be amplified or attenuated. The amount of amplification (or attenuation) is automatically adjusted depending on how noisy the image is currently. Values ​​range from -1 to 1, with positive values ​​increasing the amount of added noise and negative values ​​decreasing the amount of added noise.
619
+
620
+ Default is 0.
621
+
622
+ #### Multires noise iterations
623
+
624
+ This is an option when "Multires" is selected for Noise offset type. If you enter a value greater than 0 here, additional noise will be added.
625
+
626
+ Multires creates noise of various resolutions and adds them together to create the final additive noise. Here you specify how many "various resolutions" to create.
627
+
628
+ Default is 0, when 0 there is no additional noise. It is recommended to set it to 6 if you want to use it.
629
+
630
+ #### Multires noise discount
631
+
632
+ Pair with the Multires noise iterations option. It is a numerical value for weakening the noise amount of each resolution to some extent. A value between 0 and 1, the lower the number, the weaker the noise. By the way, the amount of attenuation differs depending on the resolution, and noise with low resolution is attenuated a lot.
633
+
634
+ Default is 0, if 0 it will be set to 0.3 when used. 0.8 is usually recommended. If the number of training images is relatively small, it seems to be good to lower it to about 0.3.
635
+
636
+ ### Dropout caption every n epochs
637
+
638
+ Normally, images and captions are trained in pairs, but it is possible to train only "images without captions" without using captions for each specific epoch.
639
+
640
+ This option allows you to specify "Don't use captions every 0 epochs ( Dropout )".
641
+
642
+ For example, if you specify 2 here, image learning without captions will be performed every 2 epochs (2nd epoch, 4th epoch, 6th epoch...).
643
+
644
+ When learning images without captions, LoRA is expected to learn more comprehensive image features. It can also be expected to have the effect of not associating too many image features with specific words. However, if you don't use too many captions, the LoRA may become a LoRA without prompts, so be careful.
645
+
646
+ The default is 0, which means no caption dropout .
647
+
648
+ ### Rate of caption dropout
649
+
650
+ It is similar to Dropout caption every n epochs above, but you can learn as "images without captions" without using captions for a certain percentage of the entire learning process.
651
+
652
+ Here you can set the percentage of images without captions. 0 is the setting for "always use captions during learning", and 1 is the setting for "never use captions during learning".
653
+
654
+ It is random which images are learned as "images without captions".
655
+
656
+ For example, if 20 images are read 50 times each and LoRA learning is performed for only 1 epoch, the total number of image learning is 20 images x 50 times x 1 epoch = 1000 times. At this time, if the Rate of caption dropout is set to 0.1, 1000 times x 0.1 = 100 times will be learned as "images without captions".
657
+
658
+ Default is 0, which trains all images with captions.
659
+
660
+ ### VAE batch size
661
+
662
+ If you turn on the Cache latents option, you can keep the "compressed" image data in the main memory. size. Since the number of images specified by batch size is learned at once, it is normal to match the VAE batch size with this.
663
+
664
+ Default is 0, in which case it is set to the same number as Batch size.
665
+
666
+ ### Save training state
667
+
668
+ LoRA will take a long time to train if there are many training images, number of iterations, and number of epochs.
669
+
670
+ If you turn on this option, you can interrupt the study in the middle and resume the study from where you left off at a later date.
671
+
672
+ Intermediate learning data is saved in a folder called "last-state".
673
+
674
+ ### Resume from saved training state
675
+
676
+ Specify the location of the "last-state" folder here if you want to resume learning that has been interrupted.
677
+
678
+ In order to resume learning, the intermediate progress data of learning must be saved.
679
+
680
+ ### Max train epoch
681
+
682
+ Specify the maximum number of epochs for training. It is basic to specify the number of epochs with the Epoch option, but learning will always end when the number of epochs specified here is reached.
683
+
684
+ Default is blank. You can leave this field blank.
685
+
686
+ ### Max num workers for DataLoader
687
+
688
+ This option specifies the number of CPU processes to use when reading data for training. Increasing this number will enable subprocesses and increase the speed of reading data, but increasing the number too much may actually result in inefficiency.
689
+
690
+ Note that no matter how large the number is specified, it will not exceed the number of concurrently executing threads of the CPU used.
691
+
692
+ The default is 0, which loads data only in the CPU's main process.
693
+
694
+ ### WANDB API Key
695
+
696
+ There is a machine learning service called " WandB " (Weights&Biases) . This is a service that displays the progress of learning in graphs to find the optimal settings, records and shares learning logs online, and kohya_ss can now use this service.
697
+
698
+ However, you will need an account for this service. After creating an account, you can get an " API key" from <https://app.wandb.ai/authorize> . If you enter the acquired API key here, you will be automatically logged in when learning and you will be able to link with WandB services.
699
+
700
+ I won't go into details about WandB, but if you want to become a "LoRA craftsman", give it a try.
701
+
702
+ ### WANDB Logging
703
+
704
+ Here you can specify whether or not to record learning progress logs using the WandB service.
705
+
706
+ The default is off, and when off, it logs in the form of a tool called 'tensorboard'.
707
+
708
+ ## Sample images config
709
+
710
+ If you want to check what image generation with LoRA looks like while learning, enter the image generation prompt here.
711
+
712
+ However, since LoRA has a relatively short learning time, there may not be much need for image generation tests.
713
+
714
+ ### Sample every n steps
715
+
716
+ Specify at what step you want to generate an image during learning. For example, specifying 100 will generate an image every 100 steps.
717
+
718
+ Default is 0, if 0 no image is generated.
719
+
720
+ ### Sample every n epochs
721
+
722
+ Specifies the number of epochs to generate images during training. For example, 2 will generate an image every 2 epochs.
723
+
724
+ Default is 0, if 0 no image is generated.
725
+
726
+ ### Sample sampler
727
+
728
+ Specifies the sampler to use for image generation . Many of the samplers specified here are the same as the samplers provided in the Stable Diffusion Web UI , so please refer to the web UI explanation site for details.
729
+
730
+ The default is euler_a.
731
+
732
+ ### Sample prompts
733
+
734
+ Enter the prompt here.
735
+
736
+ However, you can enter other settings here than just prompts. If you want to enter other settings, specify the setting by combining two minus letters and alphabets like "--n". For example, if you want to put "white, dog" in the negative prompt, write "--n white, dog".
737
+
738
+ Here are some commonly used settings:
739
+
740
+ --n: negative prompt
741
+
742
+ --w: image width
743
+
744
+ --h: image height
745
+
746
+ --d: Seeds
747
+
748
+ --l: CFG Scale
749
+
750
+ --s: number of steps
751
+
752
+ Default is blank. When the field is blank, the description example is displayed in faint color, so please refer to it.
docs/LoRA/top_level.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA Resource Guide
2
+
3
+ This guide is a resource compilation to facilitate the development of robust LoRA models.
4
+
5
+ Access EDG's tutorials here: https://ko-fi.com/post/EDGs-tutorials-P5P6KT5MT
6
+
7
+ ## Guidelines for SDXL LoRA Training
8
+
9
+ - Set the `Max resolution` to at least 1024x1024, as this is the standard resolution for SDXL.
10
+ - Use a GPU that has at least 12GB memory for the LoRA training process.
11
+ - We strongly recommend using the `--network_train_unet_only` option for SDXL LoRA to avoid unforeseen training results caused by dual text encoders in SDXL.
12
+ - PyTorch 2 tends to use less GPU memory than PyTorch 1.
13
+
14
+ Here's an example configuration for the Adafactor optimizer with a fixed learning rate:
15
+
16
+ ```
17
+ optimizer_type = "adafactor"
18
+ optimizer_args = [ "scale_parameter=False", "relative_step=False", "warmup_init=False" ]
19
+ lr_scheduler = "constant_with_warmup"
20
+ lr_warmup_steps = 100
21
+ learning_rate = 4e-7 # This is the standard learning rate for SDXL
22
+ ```
23
+
24
+ ## Resource Contributions
25
+
26
+ If you have valuable resources to add, kindly create a PR on Github.
docs/config_README-ja.md ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ For non-Japanese speakers: this README is provided only in Japanese in the current state. Sorry for inconvenience. We will provide English version in the near future.
2
+
3
+ `--dataset_config` で渡すことができる設定ファイルに関する説明です。
4
+
5
+ ## 概要
6
+
7
+ 設定ファイルを渡すことにより、ユーザが細かい設定を行えるようにします。
8
+
9
+ * 複数のデータセットが設定可能になります
10
+ * 例えば `resolution` をデータセットごとに設定して、それらを混合して学習できます。
11
+ * DreamBooth の手法と fine tuning の手法の両方に対応している学習方法では、DreamBooth 方式と fine tuning 方式のデータセットを混合することが可能です。
12
+ * サブセットごとに設定を変更することが可能になります
13
+ * データセットを画像ディレクトリ別またはメタデータ別に分割したものがサブセットです。いくつかのサブセットが集まってデータセットを構成します。
14
+ * `keep_tokens` や `flip_aug` 等のオプションはサブセットごとに設定可能です。一方、`resolution` や `batch_size` といったオプションはデータセットごとに設定可能で、同じデータセットに属するサブセットでは値が共通になります。詳しくは後述します。
15
+
16
+ 設定ファイルの形式は JSON か TOML を利用できます。記述のしやすさを考えると [TOML](https://toml.io/ja/v1.0.0-rc.2) を利用するのがオススメです。以下、TOML の利用を前提に説明します。
17
+
18
+ TOML で記述した設定ファイルの例です。
19
+
20
+ ```toml
21
+ [general]
22
+ shuffle_caption = true
23
+ caption_extension = '.txt'
24
+ keep_tokens = 1
25
+
26
+ # これは DreamBooth 方式のデータセット
27
+ [[datasets]]
28
+ resolution = 512
29
+ batch_size = 4
30
+ keep_tokens = 2
31
+
32
+ [[datasets.subsets]]
33
+ image_dir = 'C:\hoge'
34
+ class_tokens = 'hoge girl'
35
+ # このサブセットは keep_tokens = 2 (所属する datasets の値が使われる)
36
+
37
+ [[datasets.subsets]]
38
+ image_dir = 'C:\fuga'
39
+ class_tokens = 'fuga boy'
40
+ keep_tokens = 3
41
+
42
+ [[datasets.subsets]]
43
+ is_reg = true
44
+ image_dir = 'C:\reg'
45
+ class_tokens = 'human'
46
+ keep_tokens = 1
47
+
48
+ # これは fine tuning 方式のデータセット
49
+ [[datasets]]
50
+ resolution = [768, 768]
51
+ batch_size = 2
52
+
53
+ [[datasets.subsets]]
54
+ image_dir = 'C:\piyo'
55
+ metadata_file = 'C:\piyo\piyo_md.json'
56
+ # このサブセットは keep_tokens = 1 (general の値が使われる)
57
+ ```
58
+
59
+ この例では、3 つのディレクトリを DreamBooth 方式のデータセットとして 512x512 (batch size 4) で学習させ、1 つのディレクトリを fine tuning 方式のデータセットとして 768x768 (batch size 2) で学習させることになります。
60
+
61
+ ## データセット・サブセットに関する設定
62
+
63
+ データセット・サブセットに関する設定は、登録可能な箇所がいくつかに分かれています。
64
+
65
+ * `[general]`
66
+ * 全データセットまたは全サブセットに適用されるオプションを指定する箇所です。
67
+ * データセットごとの設定及びサブセットごとの設定に同名のオプションが存在していた場合には、データセット・サブセットごとの設定が優先されます。
68
+ * `[[datasets]]`
69
+ * `datasets` はデータセットに関する設定の登録箇所になります。各データセットに個別に適用されるオプションを指定する箇所です。
70
+ * サブセットごとの設定が存在していた場合には、サブセットごとの設定が優先されます。
71
+ * `[[datasets.subsets]]`
72
+ * `datasets.subsets` はサブセットに関する設定の登録箇所になります。各サブセットに個別に適用されるオプションを指定する箇所です。
73
+
74
+ 先程の例における、画像ディレクトリと登録箇所の対応に関するイメージ図です。
75
+
76
+ ```
77
+ C:\
78
+ ├─ hoge -> [[datasets.subsets]] No.1 ┐ ┐
79
+ ├─ fuga -> [[datasets.subsets]] No.2 |-> [[datasets]] No.1 |-> [general]
80
+ ├─ reg -> [[datasets.subsets]] No.3 ┘ |
81
+ └─ piyo -> [[datasets.subsets]] No.4 --> [[datasets]] No.2 ┘
82
+ ```
83
+
84
+ 画像ディレクトリがそれぞれ1つの `[[datasets.subsets]]` に対応しています。そして `[[datasets.subsets]]` が1つ以上組み合わさって1つの `[[datasets]]` を構成します。`[general]` には全ての `[[datasets]]`, `[[datasets.subsets]]` が属します。
85
+
86
+ 登録箇所ごとに指定可能なオプションは異なりますが、同名のオプションが指定された場合は下位の登録箇所にある値が優先されます。先程の例の `keep_tokens` オプションの扱われ方を確認してもらうと理解しやすいかと思います。
87
+
88
+ 加えて、学習方法が対応している手法によっても指定可能なオプションが変化します。
89
+
90
+ * DreamBooth 方式専用のオプション
91
+ * fine tuning 方式専用のオプション
92
+ * caption dropout の手法が使える場合のオプション
93
+
94
+ DreamBooth の手法と fine tuning の手法の両方とも利用可能な学習方法では、両者を併用することができます。
95
+ 併用する際の注意点として、DreamBooth 方式なのか fine tuning 方式なのかはデータセット単位で判別を行っているため、同じデータセット中に DreamBooth 方式のサブセットと fine tuning 方式のサブセットを混在させることはできません。
96
+ つまり、これらを併用したい場合には異なる方式のサブセットが異なるデータセットに所属するように設定する必要があります。
97
+
98
+ プログラムの挙動としては、後述する `metadata_file` オプションが存在していたら fine tuning 方式のサブセットだと判断します。
99
+ そのため、同一のデータセットに所属するサブセットについて言うと、「全てが `metadata_file` オプションを持つ」か「全てが `metadata_file` オプションを持たない」かのどちらかになっていれば問題ありません。
100
+
101
+ 以下、利用可能なオプションを説明します。コマンドライン引数と名称が同一のオプションについては、基本的に説明を割愛します。他の README を参照してください。
102
+
103
+ ### 全学習方法で共通のオプション
104
+
105
+ 学習方法によらずに指定可能なオプションです。
106
+
107
+ #### データセット向けオプション
108
+
109
+ データセットの設定に関わるオプションです。`datasets.subsets` には記述できません。
110
+
111
+ | オプション名 | 設定例 | `[general]` | `[[datasets]]` |
112
+ | ---- | ---- | ---- | ---- |
113
+ | `batch_size` | `1` | o | o |
114
+ | `bucket_no_upscale` | `true` | o | o |
115
+ | `bucket_reso_steps` | `64` | o | o |
116
+ | `enable_bucket` | `true` | o | o |
117
+ | `max_bucket_reso` | `1024` | o | o |
118
+ | `min_bucket_reso` | `128` | o | o |
119
+ | `resolution` | `256`, `[512, 512]` | o | o |
120
+
121
+ * `batch_size`
122
+ * コマンドライン引数の `--train_batch_size` と同等です。
123
+
124
+ これらの設定はデータセットごとに固定です。
125
+ つまり、データセットに所属するサブセットはこれらの設定を共有することになります。
126
+ 例えば解像度が異なるデータセットを用意したい場合は、上に挙げた例のように別々のデータセットとして定義すれば別々の解像度を設定可能です。
127
+
128
+ #### サブセット向けオプション
129
+
130
+ サブセットの設定に関わるオプションです。
131
+
132
+ | オプション名 | 設定例 | `[general]` | `[[datasets]]` | `[[dataset.subsets]]` |
133
+ | ---- | ---- | ---- | ---- | ---- |
134
+ | `color_aug` | `false` | o | o | o |
135
+ | `face_crop_aug_range` | `[1.0, 3.0]` | o | o | o |
136
+ | `flip_aug` | `true` | o | o | o |
137
+ | `keep_tokens` | `2` | o | o | o |
138
+ | `num_repeats` | `10` | o | o | o |
139
+ | `random_crop` | `false` | o | o | o |
140
+ | `shuffle_caption` | `true` | o | o | o |
141
+ | `caption_prefix` | `“masterpiece, best quality, ”` | o | o | o |
142
+ | `caption_suffix` | `“, from side”` | o | o | o |
143
+
144
+ * `num_repeats`
145
+ * サブセットの画像の繰り返し回数を指定します。fine tuning における `--dataset_repeats` に相当しますが、`num_repeats` はどの学習方法でも指定可能です。
146
+ * `caption_prefix`, `caption_suffix`
147
+ * キャプションの前、後に付与する文字列を指定します。シャッフルはこれらの文字列を含めた状態で行われます。`keep_tokens` を指定する場合には注意してください。
148
+
149
+ ### DreamBooth 方式専用のオプション
150
+
151
+ DreamBooth 方式のオプションは、サブセット向けオプションのみ存在します。
152
+
153
+ #### サブセット向けオプション
154
+
155
+ DreamBooth 方式のサブセットの設定に関わるオプションです。
156
+
157
+ | オプション名 | 設定例 | `[general]` | `[[datasets]]` | `[[dataset.subsets]]` |
158
+ | ---- | ---- | ---- | ---- | ---- |
159
+ | `image_dir` | `‘C:\hoge’` | - | - | o(必須) |
160
+ | `caption_extension` | `".txt"` | o | o | o |
161
+ | `class_tokens` | `“sks girl”` | - | - | o |
162
+ | `is_reg` | `false` | - | - | o |
163
+
164
+ まず注意点として、 `image_dir` には画像ファイルが直下に置かれているパスを指定する必要があります。従来の DreamBooth の手法ではサブディレクトリに画像を置く必要がありましたが、そちらとは仕様に互換性がありません。また、`5_cat` のようなフォルダ名にしても、画像の繰り返し回数とクラス名は反映されません。これらを個別に設定したい場合、`num_repeats` と `class_tokens` で明示的に指定する必要があ��ことに注意してください。
165
+
166
+ * `image_dir`
167
+ * 画像ディレクトリのパスを指定します。指定必須オプションです。
168
+ * 画像はディレクトリ直下に置かれている必要があります。
169
+ * `class_tokens`
170
+ * クラストークンを設定します。
171
+ * 画像に対応する caption ファイルが存在しない場合にのみ学習時に利用されます。利用するかどうかの判定は画像ごとに行います。`class_tokens` を指定しなかった場合に caption ファイルも見つからなかった場合にはエラーになります。
172
+ * `is_reg`
173
+ * サブセットの画像が正規化用かどうかを指定します。指定しなかった場合は `false` として、つまり正規化画像ではないとして扱います。
174
+
175
+ ### fine tuning 方式専用のオプション
176
+
177
+ fine tuning 方式のオプションは、サブセット向けオプションのみ存在します。
178
+
179
+ #### サブセット向けオプション
180
+
181
+ fine tuning 方式のサブセットの設定に関わるオプションです。
182
+
183
+ | オプション名 | 設定例 | `[general]` | `[[datasets]]` | `[[dataset.subsets]]` |
184
+ | ---- | ---- | ---- | ---- | ---- |
185
+ | `image_dir` | `‘C:\hoge’` | - | - | o |
186
+ | `metadata_file` | `'C:\piyo\piyo_md.json'` | - | - | o(必須) |
187
+
188
+ * `image_dir`
189
+ * 画像ディレクトリのパスを指定します。DreamBooth の手法の方とは異なり指定は必須ではありませんが、設定することを推奨します。
190
+ * 指定する必要がない状況としては、メタデータファイルの生成時に `--full_path` を付与して実行していた場合です。
191
+ * 画像はディレクトリ直下に置かれている必要があります。
192
+ * `metadata_file`
193
+ * サブセットで利用されるメタデータファイルのパスを指定します。指定必須オプションです。
194
+ * コマンドライン引数の `--in_json` と同等です。
195
+ * サブセットごとにメタデータファイルを指定する必要がある仕様上、ディレクトリを跨いだメタデータを1つのメタデータファイルとして作成することは避けた方が良いでしょう。画像ディレクトリごとにメタデータファイルを用意し、それらを別々のサブセットとして登録することを強く推奨します。
196
+
197
+ ### caption dropout の手法が使える場合に指定可能なオプション
198
+
199
+ caption dropout の手法が使える場合のオプションは、サブセット向けオプションのみ存在します。
200
+ DreamBooth 方式か fine tuning 方式かに関わらず、caption dropout に対応している学習方法であれば指定可能です。
201
+
202
+ #### サブセット向けオプション
203
+
204
+ caption dropout が使えるサブセットの設定に関わるオプションです。
205
+
206
+ | オプション名 | `[general]` | `[[datasets]]` | `[[dataset.subsets]]` |
207
+ | ---- | ---- | ---- | ---- |
208
+ | `caption_dropout_every_n_epochs` | o | o | o |
209
+ | `caption_dropout_rate` | o | o | o |
210
+ | `caption_tag_dropout_rate` | o | o | o |
211
+
212
+ ## 重複したサブセットが存在する時の挙動
213
+
214
+ DreamBooth 方式のデータセットの場合、その中にある `image_dir` が同一のサブセットは重複していると見なされます。
215
+ fine tuning 方式のデータセットの場合は、その中にある `metadata_file` が同一のサブセットは重複していると見なされます。
216
+ データセット中に重複したサブセットが存在する場合、2個目以降は無視されます。
217
+
218
+ 一方、異なるデータセットに所属している場合は、重複しているとは見なされません。
219
+ 例えば、以下のように同一の `image_dir` を持つサブセットを別々のデータセットに入れた場合には、重複していないと見なします。
220
+ これは、同じ画像でも異なる解像度で学習したい場合に役立ちます。
221
+
222
+ ```toml
223
+ # 別々のデータセットに存在している場合は重複とは見なされず、両方とも学習に使われる
224
+
225
+ [[datasets]]
226
+ resolution = 512
227
+
228
+ [[datasets.subsets]]
229
+ image_dir = 'C:\hoge'
230
+
231
+ [[datasets]]
232
+ resolution = 768
233
+
234
+ [[datasets.subsets]]
235
+ image_dir = 'C:\hoge'
236
+ ```
237
+
238
+ ## コマンドライン引数との併用
239
+
240
+ 設定ファイルのオプションの中には、コマンドライン引数のオプションと役割が重複しているものがあります。
241
+
242
+ 以下に挙げるコマンドライン引数のオプションは、設定ファイルを渡した場合には無視されます。
243
+
244
+ * `--train_data_dir`
245
+ * `--reg_data_dir`
246
+ * `--in_json`
247
+
248
+ 以下に挙げるコマンドライン引数のオプションは、コマンドライン引数と設定ファイルで同時に指定された場合、コマンドライン引数の値よりも設定ファイルの値が優先されます。特に断りがなければ同名のオプションとなります。
249
+
250
+ | コマンドライン引数のオプション | 優先される設定ファイルのオプション |
251
+ | ---------------------------------- | ---------------------------------- |
252
+ | `--bucket_no_upscale` | |
253
+ | `--bucket_reso_steps` | |
254
+ | `--caption_dropout_every_n_epochs` | |
255
+ | `--caption_dropout_rate` | |
256
+ | `--caption_extension` | |
257
+ | `--caption_tag_dropout_rate` | |
258
+ | `--color_aug` | |
259
+ | `--dataset_repeats` | `num_repeats` |
260
+ | `--enable_bucket` | |
261
+ | `--face_crop_aug_range` | |
262
+ | `--flip_aug` | |
263
+ | `--keep_tokens` | |
264
+ | `--min_bucket_reso` | |
265
+ | `--random_crop` | |
266
+ | `--resolution` | |
267
+ | `--shuffle_caption` | |
268
+ | `--train_batch_size` | `batch_size` |
269
+
270
+ ## エラーの手引き
271
+
272
+ 現在、外部ライブラリを利用して設定ファイルの記述が正しいかどうかをチェックしているのですが、整備が行き届いておらずエラーメッセージがわかりづらいという問題があります。
273
+ 将来的にはこの問題の改善に取り組む予定です。
274
+
275
+ 次善策として、頻出のエラーとその対処法について載せておきます。
276
+ 正しいはずなのにエラーが出る場合、エラー内容がどうしても分からない場合は、バグかもしれないのでご連絡ください。
277
+
278
+ * `voluptuous.error.MultipleInvalid: required key not provided @ ...`: 指定必須のオプションが指定されていないというエラーです。指定を忘れているか、オプション名を間違って記述している可能性が高いです。
279
+ * `...` の箇所にはエラーが発生した場所が載っています。例えば `voluptuous.error.MultipleInvalid: required key not provided @ data['datasets'][0]['subsets'][0]['image_dir']` のようなエラーが出たら、0 番目の `datasets` 中の 0 番目の `subsets` の設定に `image_dir` が存在しないということになります。
280
+ * `voluptuous.error.MultipleInvalid: expected int for dictionary value @ ...`: 指定する値の形式が不正というエラーです。値の形式が間違っている可能性が高いです。`int` の部分は対象となるオプションによって変わります。この README に載っているオプションの「設定例」が役立つかもしれません。
281
+ * `voluptuous.error.MultipleInvalid: extra keys not allowed @ ...`: 対応していないオプション名が存在している場合に発生するエラーです。オプション名を間違って記述しているか、誤って紛れ込んでいる可能性が高いです。
282
+
283
+
docs/fine_tune_README_ja.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NovelAIの提案した学習手法、自動キャプションニング、タグ付け、Windows+VRAM 12GB(SD v1.xの場合)環境等に対応したfine tuningです。ここでfine tuningとは、モデルを画像とキャプションで学習することを指します(LoRAやTextual Inversion、Hypernetworksは含みません)
2
+
3
+ [学習についての共通ドキュメント](./train_README-ja.md) もあわせてご覧ください。
4
+
5
+ # 概要
6
+
7
+ Diffusersを用いてStable DiffusionのU-Netのfine tuningを行います。NovelAIの記事にある以下の改善に対応しています(Aspect Ratio BucketingについてはNovelAIのコードを参考にしましたが、最終的なコードはすべてオリジナルです)。
8
+
9
+ * CLIP(Text Encoder)の最後の層ではなく最後から二番目の層の出力を用いる。
10
+ * 正方形以外の解像度での学習(Aspect Ratio Bucketing) 。
11
+ * トークン長を75から225に拡張する。
12
+ * BLIPによるキャプショニング(キャプションの自動作成)、DeepDanbooruまたはWD14Taggerによる自動タグ付けを行う。
13
+ * Hypernetworkの学習にも対応する。
14
+ * Stable Diffusion v2.0(baseおよび768/v)に対応。
15
+ * VAEの出力をあらかじめ取得しディスクに保存しておくことで、学習の省メモリ化、高速化を図る。
16
+
17
+ デフォルトではText Encoderの学習は行いません。モデル全体のfine tuningではU-Netだけを学習するのが一般的なようです(NovelAIもそのようです)。オプション指定でText Encoderも学習対象とできます。
18
+
19
+ # 追加機能について
20
+
21
+ ## CLIPの出力の変更
22
+
23
+ プロンプトを画像に反映するため、テキストの特徴量への変換を行うのがCLIP(Text Encoder)です。Stable DiffusionではCLIPの最後の層の出力を用いていますが、それを最後から二番目の層の出力を用いるよう変更できます。NovelAIによると、これによりより正確にプロンプトが反映されるようになるとのことです。
24
+ 元のまま、最後の層の出力を用いることも可能です。
25
+
26
+ ※Stable Diffusion 2.0では最後から二番目の層をデフォルトで使います。clip_skipオプションを指定しないでください。
27
+
28
+ ## 正方形以外の解像度での学習
29
+
30
+ Stable Diffusionは512\*512で学習されていますが、それに加えて256\*1024や384\*640といった解像度でも学習します。これによりトリミングされる部分が減り、より正しくプロンプトと画像の関係が学習されることが期待されます。
31
+ 学習解像度はパラメータとして与えられた解像度の面積(=メモリ使用量)を超えない範囲で、64ピクセル単位で縦横に調整、作成されます。
32
+
33
+ 機械学習では入力サイズをすべて統一するのが一般的ですが、特に制約があるわけではなく、実際は同一のバッチ内で統一されていれば大丈夫です。NovelAIの言うbucketingは、あらかじめ教師データを、アスペクト比に応じた学習解像度ごとに分類しておくことを指しているようです。そしてバッチを各bucket内の画像で作成することで、バッチの画像サイズを統一します。
34
+
35
+ ## トークン長の75から225への拡張
36
+
37
+ Stable Diffusionでは最大75トークン(開始・終了を含むと77トークン)ですが、それを225トークンまで拡張します。
38
+ ただしCLIPが受け付ける最大長は75トークンですので、225トークンの場合、単純に三分割してCLIPを呼び出してから結果を連結しています。
39
+
40
+ ※これが望ましい実装なのかどうかはいまひとつわかりません。とりあえず動いてはいるようです。特に2.0では何も参考になる実装がないので独自に実装してあります。
41
+
42
+ ※Automatic1111氏のWeb UIではカンマを意識して分割、といったこともしているようですが、私の場合はそこまでしておらず単純な分割です。
43
+
44
+ # 学習の手順
45
+
46
+ あらかじめこのリポジトリのREADMEを参照し、環境整備を行ってください。
47
+
48
+ ## データの準備
49
+
50
+ [学習データの準備について](./train_README-ja.md) を参照してください。fine tuningではメタデータを用いるfine tuning方式のみ対応しています。
51
+
52
+ ## 学習の実行
53
+ たとえば以下のように実行します。以下は省メモリ化のための設定です。それぞれの行を必要に応じて書き換えてください。
54
+
55
+ ```
56
+ accelerate launch --num_cpu_threads_per_process 1 fine_tune.py
57
+ --pretrained_model_name_or_path=<.ckptまたは.safetensordまたはDiffusers版モデルのディレクトリ>
58
+ --output_dir=<学習したモデルの出力先フォルダ>
59
+ --output_name=<学習したモデル出力時のフ���イル名>
60
+ --dataset_config=<データ準備で作成した.tomlファイル>
61
+ --save_model_as=safetensors
62
+ --learning_rate=5e-6 --max_train_steps=10000
63
+ --use_8bit_adam --xformers --gradient_checkpointing
64
+ --mixed_precision=fp16
65
+ ```
66
+
67
+ `num_cpu_threads_per_process` には通常は1を指定するとよいようです。
68
+
69
+ `pretrained_model_name_or_path` に追加学習を行う元となるモデルを指定します。Stable Diffusionのcheckpointファイル(.ckptまたは.safetensors)、Diffusersのローカルディスクにあるモデルディレクトリ、DiffusersのモデルID("stabilityai/stable-diffusion-2"など)が指定できます。
70
+
71
+ `output_dir` に学習後のモデルを保存するフォルダを指定します。`output_name` にモデルのファイル名を拡張子を除いて指定します。`save_model_as` でsafetensors形式での保存を指定しています。
72
+
73
+ `dataset_config` に `.toml` ファイルを指定します。ファイル内でのバッチサイズ指定は、当初はメモリ消費を抑えるために `1` としてください。
74
+
75
+ 学習させるステップ数 `max_train_steps` を10000とします。学習率 `learning_rate` はここでは5e-6を指定しています。
76
+
77
+ 省メモリ化のため `mixed_precision="fp16"` を指定します(RTX30 シリーズ以降では `bf16` も指定できます。環境整備時にaccelerateに行った設定と合わせてください)。また `gradient_checkpointing` を指定します。
78
+
79
+ オプティマイザ(モデルを学習データにあうように最適化=学習させるクラス)にメモリ消費の少ない 8bit AdamW を使うため、 `optimizer_type="AdamW8bit"` を指定します。
80
+
81
+ `xformers` オプションを指定し、xformersのCrossAttentionを用います。xformersをインストールしていない場合やエラーとなる場合(環境にもよりますが `mixed_precision="no"` の場合など)、代わりに `mem_eff_attn` オプションを指定すると省メモリ版CrossAttentionを使用します(速度は遅くなります)。
82
+
83
+ ある程度メモリがある場合は、`.toml` ファイルを編集してバッチサイズをたとえば `4` くらいに増やしてください(高速化と精度向上の可能性があります)。
84
+
85
+ ### よく使われるオプションについて
86
+
87
+ 以下の場合にはオプションに関するドキュメントを参照してください。
88
+
89
+ - Stable Diffusion 2.xまたはそこからの派生モデルを学習する
90
+ - clip skipを2以上を前提としたモデルを学習する
91
+ - 75トークンを超えたキャプションで学習する
92
+
93
+ ### バッチサイズについて
94
+
95
+ モデル全体を学習するためLoRA等の学習に比べるとメモリ消費量は多くなります(DreamBoothと同じ)。
96
+
97
+ ### 学習率について
98
+
99
+ 1e-6から5e-6程度が一般的なようです。他のfine tuningの例なども参照してみてください。
100
+
101
+ ### 以前の形式のデータセット指定をした場合のコマンドライン
102
+
103
+ 解像度やバッチサイズをオプションで指定します。コマンドラインの例は以下の通りです。
104
+
105
+ ```
106
+ accelerate launch --num_cpu_threads_per_process 1 fine_tune.py
107
+ --pretrained_model_name_or_path=model.ckpt
108
+ --in_json meta_lat.json
109
+ --train_data_dir=train_data
110
+ --output_dir=fine_tuned
111
+ --shuffle_caption
112
+ --train_batch_size=1 --learning_rate=5e-6 --max_train_steps=10000
113
+ --use_8bit_adam --xformers --gradient_checkpointing
114
+ --mixed_precision=bf16
115
+ --save_every_n_epochs=4
116
+ ```
117
+
118
+ <!--
119
+ ### 勾配をfp16とした学習(実験的機能)
120
+ full_fp16オプションを指定すると勾配を通常のfloat32からfloat16(fp16)に変更して学習します(mixed precisionではなく完全なfp16学習になるようです)。これによりSD1.xの512*512サイズでは8GB未満、SD2.xの512*512サイズで12GB未満のVRAM使用量で学習できるようです。
121
+
122
+ あらかじめaccelerate configでfp16を指定し、オプションでmixed_precision="fp16"としてください(bf16では動作しません)。
123
+
124
+ メモリ使用量を最小化するためには、xformers、use_8bit_adam、gradient_checkpointingの各オプションを指定し、train_batch_sizeを1としてください。
125
+ (余裕があるようならtrain_batch_sizeを段階的に増やすと若干精度が上がるはずです。)
126
+
127
+ PyTorchのソースにパッチを当てて無理やり実現しています(PyTorch 1.12.1と1.13.0で確認)。精度はかなり落ちますし、途中で学習失敗する確率も高くなります。学習率やステップ数の設定もシビアなようです。それらを認識したうえで自己責任でお使いください。
128
+ -->
129
+
130
+ # fine tuning特有のその他の主なオプション
131
+
132
+ すべてのオプションについては別文書を参照してください。
133
+
134
+ ## `train_text_encoder`
135
+ Text Encoderも学習対象とします。メモリ使用量が若干増加します。
136
+
137
+ 通常のfine tuningではText Encoderは学習対象としませんが(恐らくText Encoderの出力に従うようにU-Netを学習するため)、学習データ数が少ない場合には、DreamBoothのようにText Encoder側に学習させるのも有効的なようです。
138
+
139
+ ## `diffusers_xformers`
140
+ スクリプト独自のxformers置換機能ではなくDiffusersのxformers機能を利用します。Hypernetworkの学習はできなくなります。
docs/gen_img_README-ja.md ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SD 1.xおよび2.xのモデル、当リポジトリで学習したLoRA、ControlNet(v1.0のみ動作確認)などに対応した、Diffusersベースの推論(画像生成)スクリプトです。コマンドラインから用います。
2
+
3
+ # 概要
4
+
5
+ * Diffusers (v0.10.2) ベースの推論(画像生成)スクリプト。
6
+ * SD 1.xおよび2.x (base/v-parameterization)モデルに対応。
7
+ * txt2img、img2img、inpaintingに対応。
8
+ * 対話モード、およびファイルからのプロンプト読み込み、連続生成に対応。
9
+ * プロンプト1行あたりの生成枚数を指定可能。
10
+ * 全体の繰り返し回数を指定可能。
11
+ * `fp16`だけでなく`bf16`にも対応。
12
+ * xformersに対応し高速生成が可能。
13
+ * xformersにより省メモリ生成を行いますが、Automatic 1111氏のWeb UIほど最適化していないため、512*512の画像生成でおおむね6GB程度のVRAMを使用します。
14
+ * プロンプトの225トークンへの拡張。ネガティブプロンプト、重みづけに対応。
15
+ * Diffusersの各種samplerに対応(Web UIよりもsampler数は少ないです)。
16
+ * Text Encoderのclip skip(最後からn番目の層の出力を用いる)に対応。
17
+ * VAEの別途読み込み。
18
+ * CLIP Guided Stable Diffusion、VGG16 Guided Stable Diffusion、Highres. fix、upscale対応。
19
+ * Highres. fixはWeb UIの実装を全く確認していない独自実装のため、出力結果は異なるかもしれません。
20
+ * LoRA対応。適用率指定、複数LoRA同時利用、重みのマージに対応。
21
+ * Text EncoderとU-Netで別の適用率を指定することはできません。
22
+ * Attention Coupleに対応。
23
+ * ControlNet v1.0に対応。
24
+ * 途中でモデルを切り替えることはできませんが、バッチファイルを組むことで対応できます。
25
+ * 個人的に欲しくなった機能をいろいろ追加。
26
+
27
+ 機能追加時にすべてのテストを行っているわけではないため、以前の機能に影響が出て一部機能が動かない可能性があります。何か問題があればお知らせください。
28
+
29
+ # 基本的な使い方
30
+
31
+ ## 対話モードでの画像生成
32
+
33
+ 以下のように入力してください。
34
+
35
+ ```batchfile
36
+ python gen_img_diffusers.py --ckpt <モデル名> --outdir <画像出力先> --xformers --fp16 --interactive
37
+ ```
38
+
39
+ `--ckpt`オプションにモデル(Stable Diffusionのcheckpointファイル、またはDiffusersのモデルフォルダ)、`--outdir`オプションに画像の出力先フォルダを指定します。
40
+
41
+ `--xformers`オプションでxformersの使用を指定します(xformersを使わない場合は外してください)。`--fp16`オプションでfp16(単精度)での推論を行います。RTX 30系のGPUでは `--bf16`オプションでbf16(bfloat16)での推論を行うこともできます。
42
+
43
+ `--interactive`オプションで対話モードを指定しています。
44
+
45
+ Stable Diffusion 2.0(またはそこからの追加学習モデル)を使う場合は`--v2`オプションを追加してください。v-parameterizationを使うモデル(`768-v-ema.ckpt`およびそこからの追加学習モデル)を使う場合はさらに`--v_parameterization`を追加してください。
46
+
47
+ `--v2`の指定有無が間違っているとモデル読み込み時にエラーになります。`--v_parameterization`の指定有無が間違っていると茶色い画像が表示されます。
48
+
49
+ `Type prompt:`と表示されたらプロンプトを入力してください。
50
+
51
+ ![image](https://user-images.githubusercontent.com/52813779/235343115-f3b8ac82-456d-4aab-9724-0cc73c4534aa.png)
52
+
53
+ ※画像が表示されずエラーになる場合、headless(画面表示機能なし)のOpenCVがインストールされているかもしれません。`pip install opencv-python`として通常のOpenCVを入れてください。または`--no_preview`オプションで画像表示を止めてください。
54
+
55
+ 画像ウィンドウを選択してから何らかのキーを押すとウィンドウが閉じ、次のプロンプトが入力できます。プロンプトでCtrl+Z、エンターの順に打鍵するとスクリプトを閉じます。
56
+
57
+ ## 単一のプロンプトで画像を一括生成
58
+
59
+ 以下のように入力します(実際には1行で入力します)。
60
+
61
+ ```batchfile
62
+ python gen_img_diffusers.py --ckpt <モデル名> --outdir <画像出力先>
63
+ --xformers --fp16 --images_per_prompt <生成枚数> --prompt "<プロンプト>"
64
+ ```
65
+
66
+ `--images_per_prompt`オプションで、プロンプト1件当たりの生成枚数を指定します。`--prompt`オプションでプロンプトを指定します。スペースを含む場合はダブルクォーテーションで囲んでください。
67
+
68
+ `--batch_size`オプションでバッチサイズを指定できます(後述)。
69
+
70
+ ## ファ���ルからプロンプトを読み込み一括生成
71
+
72
+ 以下のように入力します。
73
+
74
+ ```batchfile
75
+ python gen_img_diffusers.py --ckpt <モデル名> --outdir <画像出力先>
76
+ --xformers --fp16 --from_file <プロンプトファイル名>
77
+ ```
78
+
79
+ `--from_file`オプションで、プロンプトが記述されたファイルを指定します。1行1プロンプトで記述してください。`--images_per_prompt`オプションを指定して1行あたり生成枚数を指定できます。
80
+
81
+ ## ネガティブプロンプト、重みづけの使用
82
+
83
+ プロンプトオプション(プロンプト内で`--x`のように指定、後述)で`--n`を書くと、以降がネガティブプロンプトとなります。
84
+
85
+ またAUTOMATIC1111氏のWeb UIと同様の `()` や` []` 、`(xxx:1.3)` などによる重みづけが可能です(実装はDiffusersの[Long Prompt Weighting Stable Diffusion](https://github.com/huggingface/diffusers/blob/main/examples/community/README.md#long-prompt-weighting-stable-diffusion)からコピーしたものです)。
86
+
87
+ コマンドラインからのプロンプト指定、ファイルからのプロンプト読み込みでも同様に指定できます。
88
+
89
+ ![image](https://user-images.githubusercontent.com/52813779/235343128-e79cd768-ec59-46f5-8395-fce9bdc46208.png)
90
+
91
+ # 主なオプション
92
+
93
+ コマンドラインから指定してください。
94
+
95
+ ## モデルの指定
96
+
97
+ - `--ckpt <モデル名>`:モデル名を指定します。`--ckpt`オプションは必須です。Stable Diffusionのcheckpointファイル、またはDiffusersのモデルフォルダ、Hugging FaceのモデルIDを指定できます。
98
+
99
+ - `--v2`:Stable Diffusion 2.x系のモデルを使う場合に指定します。1.x系の場合には指定不要です。
100
+
101
+ - `--v_parameterization`:v-parameterizationを使うモデルを使う場合に指定します(`768-v-ema.ckpt`およびそこからの追加学習モデル、Waifu Diffusion v1.5など)。
102
+
103
+ `--v2`の指定有無が間違っているとモデル読み込み時にエラーになります。`--v_parameterization`の指定有無が間違っていると茶色い画像が表示されます。
104
+
105
+ - `--vae`:使用するVAEを指定します。未指定時はモデル内のVAEを使用します。
106
+
107
+ ## 画像生成と出力
108
+
109
+ - `--interactive`:インタラクティブモードで動作します。プロンプトを入力すると画像が生成されます。
110
+
111
+ - `--prompt <プロンプト>`:プロンプトを指定します。スペースを含む場合はダブルクォーテーションで囲んでください。
112
+
113
+ - `--from_file <プロンプトファイル名>`:プロンプトが記述されたファイルを指定します。1行1プロンプトで記述してください。なお画像サイズやguidance scaleはプロンプトオプション(後述)で指定できます。
114
+
115
+ - `--W <画像幅>`:画像の幅を指定します。デフォルトは`512`です。
116
+
117
+ - `--H <画像高さ>`:画像の高さを指定します。デフォルトは`512`です。
118
+
119
+ - `--steps <ステップ数>`:サンプリングステップ数を指定します。デフォルトは`50`です。
120
+
121
+ - `--scale <ガイダンススケール>`:unconditionalガイダンススケールを指定します。デフォルトは`7.5`です。
122
+
123
+ - `--sampler <サンプラー名>`:サンプラーを指定します。デフォルトは`ddim`です。Diffusersで提供されているddim、pndm、dpmsolver、dpmsolver+++、lms、euler、euler_a、が指定可能です(後ろの三つはk_lms、k_euler、k_euler_aでも指定できます)。
124
+
125
+ - `--outdir <画像出力先フォルダ>`:画像の出力先を指定します。
126
+
127
+ - `--images_per_prompt <生成枚数>`:プロンプト1件当たりの生成枚数を指定します。デフォルトは`1`です。
128
+
129
+ - `--clip_skip <スキップ数>`:CLIPの後ろから何番目の層を使うかを指定します。省略時は最後の層を使います。
130
+
131
+ - `--max_embeddings_multiples <倍数>`:CLIPの入出力長をデフォルト(75)の何倍にするかを指定します。未指定時は75のままです。たとえば3を指定すると入出力長が225になります。
132
+
133
+ - `--negative_scale` : uncoditioningのguidance scaleを個別に指定します。[gcem156氏のこちらの記事](https://note.com/gcem156/n/ne9a53e4a6f43)を参考に実装したものです。
134
+
135
+ ## メモリ使用量や生成速度の調整
136
+
137
+ - `--batch_size <バッチサイズ>`:バッチサイズを指定します。デフォルトは`1`です。バッチサイズが大きいとメモリを多く消費しますが、生成速度が速くなります。
138
+
139
+ - `--vae_batch_size <VAEのバッチサイズ>`:VAEのバッチサイズを指定します。デフォルトはバッチサイズと同じです。
140
+ VAEのほうがメモリを多く消費するため、デノイジング後(stepが100%になった後)でメモリ不足になる場合があります。このような場合にはVAEのバッチサイズを小さくしてください。
141
+
142
+ - `--xformers`:xformersを使う場合に指定します。
143
+
144
+ - `--fp16`:fp16(単精度)での推論を行います。`fp16`と`bf16`をどちらも指定しない場合はfp32(単精度)での推論を行います。
145
+
146
+ - `--bf16`:bf16(bfloat16)での推論を行います。RTX 30系のGPUでのみ指定可能です。`--bf16`オプションはRTX 30系以外のGPUではエラーになります。`fp16`よりも`bf16`のほうが推論結果がNaNになる(真っ黒の画像になる)可能性が低いようです。
147
+
148
+ ## 追加ネットワーク(LoRA等)の使用
149
+
150
+ - `--network_module`:使用する追加ネットワークを指定します。LoRAの場合は`--network_module networks.lora`と指定します。複数のLoRAを使用する場合は`--network_module networks.lora networks.lora networks.lora`のように指定します。
151
+
152
+ - `--network_weights`:使用する追加ネットワークの重みファイルを指定します。`--network_weights model.safetensors`のように指定します。複数のLoRAを使用する場合は`--network_weights model1.safetensors model2.safetensors model3.safetensors`のように指定します。引数の数は`--network_module`で指定した数と同じにしてください。
153
+
154
+ - `--network_mul`:使用する追加ネットワークの重みを何倍にするかを指定します。デフォルトは`1`です。`--network_mul 0.8`のように指定します。複数のLoRAを使用する場合は`--network_mul 0.4 0.5 0.7`のように指定します。引数の数は`--network_module`で指定した数と同じにしてください。
155
+
156
+ - `--network_merge`:使用する追加ネットワークの重みを`--network_mul`に指定した重みであらかじめマージします。`--network_pre_calc` と同時に使用できません。プロンプトオプションの`--am`、およびRegional LoRAは使用できなくなりますが、LoRA未使用時と同じ程度まで生成が高速化されます。
157
+
158
+ - `--network_pre_calc`:使用する追加ネットワークの重みを生成ごとにあらかじめ計算します。プロンプトオプションの`--am`が使用できます。LoRA未使用時と同じ程度まで生成は高速化されますが、生成前に重みを計算する時間が必要で、またメモリ使用量も若干増加します。Regional LoRA使用時は無効になります 。
159
+
160
+ # 主なオプションの指定例
161
+
162
+ 次は同一プロンプトで64枚をバッチサイズ4で一括生成する例です。
163
+
164
+ ```batchfile
165
+ python gen_img_diffusers.py --ckpt model.ckpt --outdir outputs
166
+ --xformers --fp16 --W 512 --H 704 --scale 12.5 --sampler k_euler_a
167
+ --steps 32 --batch_size 4 --images_per_prompt 64
168
+ --prompt "beautiful flowers --n monochrome"
169
+ ```
170
+
171
+ 次はファイルに書かれたプロンプトを、それぞれ10枚ずつ、バッチサイズ4で一括生成する例です。
172
+
173
+ ```batchfile
174
+ python gen_img_diffusers.py --ckpt model.ckpt --outdir outputs
175
+ --xformers --fp16 --W 512 --H 704 --scale 12.5 --sampler k_euler_a
176
+ --steps 32 --batch_size 4 --images_per_prompt 10
177
+ --from_file prompts.txt
178
+ ```
179
+
180
+ Textual Inversion(後述)およびLoRAの使用例です。
181
+
182
+ ```batchfile
183
+ python gen_img_diffusers.py --ckpt model.safetensors
184
+ --scale 8 --steps 48 --outdir txt2img --xformers
185
+ --W 512 --H 768 --fp16 --sampler k_euler_a
186
+ --textual_inversion_embeddings goodembed.safetensors negprompt.pt
187
+ --network_module networks.lora networks.lora
188
+ --network_weights model1.safetensors model2.safetensors
189
+ --network_mul 0.4 0.8
190
+ --clip_skip 2 --max_embeddings_multiples 1
191
+ --batch_size 8 --images_per_prompt 1 --interactive
192
+ ```
193
+
194
+ # プロンプトオプション
195
+
196
+ プロンプト内で、`--n`のように「ハイフンふたつ+アルファベットn文字」でプロンプトから各種オプションの指定が可能です。対話モード、コマンドライン、ファイル、いずれからプロンプトを指定する場合でも有効です。
197
+
198
+ プロンプトのオプション指定`--n`の前後にはスペースを入れてください。
199
+
200
+ - `--n`:ネガティブプロンプトを指定します。
201
+
202
+ - `--w`:画像幅を指定します。コマンドラインからの指定を上書きします。
203
+
204
+ - `--h`:画像高さを指定します。コマンドラインからの指定を上書きします。
205
+
206
+ - `--s`:ステップ数を指定します。コマンドラインからの指定を上書きします。
207
+
208
+ - `--d`:この画像の乱数seedを指定します。`--images_per_prompt`を指定している場合は「--d 1,2,3,4」のようにカンマ区切りで複数指定してください。
209
+ ※様々な理由により、Web UIとは同じ乱数seedでも生成される画像が異���る場合があります。
210
+
211
+ - `--l`:guidance scaleを指定します。コマンドラインからの指定を上書きします。
212
+
213
+ - `--t`:img2img(後述)のstrengthを指定します。コマンドラインからの指定を上書きします。
214
+
215
+ - `--nl`:ネガティブプロンプトのguidance scaleを指定します(後述)。コマンドラインからの指定を上書きします。
216
+
217
+ - `--am`:追加ネットワークの重みを指定します。コマンドラインからの指定を上書きします。複数の追加ネットワークを使用する場合は`--am 0.8,0.5,0.3`のように __カンマ区切りで__ 指定します。
218
+
219
+ ※これらのオプションを指定すると、バッチサイズよりも小さいサイズでバッチが実行される場合があります(これらの値が異なると一括生成できないため)。(あまり気にしなくて大丈夫ですが、ファイルからプロンプトを読み込み生成する場合は、これらの値が同一のプロンプトを並べておくと効率が良くなります。)
220
+
221
+ 例:
222
+ ```
223
+ (masterpiece, best quality), 1girl, in shirt and plated skirt, standing at street under cherry blossoms, upper body, [from below], kind smile, looking at another, [goodembed] --n realistic, real life, (negprompt), (lowres:1.1), (worst quality:1.2), (low quality:1.1), bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, normal quality, jpeg artifacts, signature, watermark, username, blurry --w 960 --h 640 --s 28 --d 1
224
+ ```
225
+
226
+ ![image](https://user-images.githubusercontent.com/52813779/235343446-25654172-fff4-4aaf-977a-20d262b51676.png)
227
+
228
+ # img2img
229
+
230
+ ## オプション
231
+
232
+ - `--image_path`:img2imgに利用する画像を指定します。`--image_path template.png`のように指定します。フォルダを指定すると、そのフォルダの画像を順次利用します。
233
+
234
+ - `--strength`:img2imgのstrengthを指定します。`--strength 0.8`のように指定します。デフォルトは`0.8`です。
235
+
236
+ - `--sequential_file_name`:ファイル名を連番にするかどうかを指定します。指定すると生成されるファイル名が`im_000001.png`からの連番になります。
237
+
238
+ - `--use_original_file_name`:指定すると生成ファイル名がオリジナルのファイル名と同じになります。
239
+
240
+ ## コマンドラインからの実行例
241
+
242
+ ```batchfile
243
+ python gen_img_diffusers.py --ckpt trinart_characters_it4_v1_vae_merged.ckpt
244
+ --outdir outputs --xformers --fp16 --scale 12.5 --sampler k_euler --steps 32
245
+ --image_path template.png --strength 0.8
246
+ --prompt "1girl, cowboy shot, brown hair, pony tail, brown eyes,
247
+ sailor school uniform, outdoors
248
+ --n lowres, bad anatomy, bad hands, error, missing fingers, cropped,
249
+ worst quality, low quality, normal quality, jpeg artifacts, (blurry),
250
+ hair ornament, glasses"
251
+ --batch_size 8 --images_per_prompt 32
252
+ ```
253
+
254
+ `--image_path`オプションにフォルダを指定すると、そのフォルダの画像を順次読み込みます。生成される枚数は画像枚数ではなく、プロンプト数になりますので、`--images_per_promptPPオプションを指定してimg2imgする画像の枚数とプロンプト数を合わせてください。
255
+
256
+ ファイルはファイル名でソートして読み込みます。なおソート順は文字列順となりますので(`1.jpg→2.jpg→10.jpg`ではなく`1.jpg→10.jpg→2.jpg`の順)、頭を0埋めするなどしてご対応ください(`01.jpg→02.jpg→10.jpg`)。
257
+
258
+ ## img2imgを利用したupscale
259
+
260
+ img2img時にコマンドラインオプションの`--W`と`--H`で生成画像サイズを指定すると、元画像をそのサイズにリサイズしてからimg2imgを行います。
261
+
262
+ またimg2imgの元画像がこのスクリプトで生成した画像の場合、プロンプトを省略すると、元画像のメタデータからプロンプトを取得しそのまま用います。これによりHighres. fixの2nd stageの動作だけを行うことができます。
263
+
264
+ ## img2img時のinpainting
265
+
266
+ 画像およびマスク画像を指定してinpaintingできます(inpaintingモデルには対応しておらず、単にマスク領域を対象にimg2imgするだけです)。
267
+
268
+ オプションは以下の通りです。
269
+
270
+ - `--mask_image`:マスク画像を指定します。`--img_path`と同様にフォルダを指定すると、そのフォルダの画像を順次利用します。
271
+
272
+ マスク画像はグレースケール画像で、白の部分がinpaintingされます。境界をグラデーションしておくとなんとなく滑らかになりますのでお勧めです。
273
+
274
+ ![image](https://user-images.githubusercontent.com/52813779/235343795-9eaa6d98-02ff-4f32-b089-80d1fc482453.png)
275
+
276
+ # その他の機能
277
+
278
+ ## Textual Inversion
279
+
280
+ `--textual_inversion_embeddings`オプションで使用するembeddingsを指定します(複数指定可)。拡張子を除いたファイル名をプロンプト内で使用することで、そのembeddingsを利用します(Web UIと同様の使用法です)。ネガティブプロンプト内でも使用できます。
281
+
282
+ モデルとして、当リポジトリで学習したTextual Inversionモデル、およびWeb UIで学習したTextual Inversionモデル(画像埋め込みは非対応)を利用できます
283
+
284
+ ## Extended Textual Inversion
285
+
286
+ `--textual_inversion_embeddings`の代わりに`--XTI_embeddings`オプションを指定してください。使用法は`--textual_inversion_embeddings`と同じです。
287
+
288
+ ## Highres. fix
289
+
290
+ AUTOMATIC1111氏のWeb UIにある機能の類似機能です(独自実装のためもしかしたらいろいろ異なるかもしれません)。最初に小さめの画像を生成し、その画像を元にimg2imgすることで、画像全体の破綻を防ぎつつ大きな解像度の画像を生成します。
291
+
292
+ 2nd stageのstep数は`--steps` と`--strength`オプションの値から計算されます(`steps*strength`)。
293
+
294
+ img2imgと併用できません。
295
+
296
+ 以下のオプションがあります。
297
+
298
+ - `--highres_fix_scale`:Highres. fixを有効にして、1st stageで生成する画像のサイズを、倍率で指定します。最終出力が1024x1024で、最初に512x512の画像を生成する場合は`--highres_fix_scale 0.5`のように指定します。Web UI出の指定の逆数になっていますのでご注意ください。
299
+
300
+ - `--highres_fix_steps`:1st stageの画像のステップ数を指定します。デフォルトは`28`です。
301
+
302
+ - `--highres_fix_save_1st`:1st stageの画像を保存するかどうかを指定します。
303
+
304
+ - `--highres_fix_latents_upscaling`:指定すると2nd stageの画像生成時に1st stageの画像をlatentベースでupscalingします(bilinearのみ対応)。未指定時は画像をLANCZOS4でupscalingします。
305
+
306
+ - `--highres_fix_upscaler`:2nd stageに任意のupscalerを利用します。現在は`--highres_fix_upscaler tools.latent_upscaler` のみ対応しています。
307
+
308
+ - `--highres_fix_upscaler_args`:`--highres_fix_upscaler`で指定したupscalerに渡す引数を指定します。
309
+ `tools.latent_upscaler`の場合は、`--highres_fix_upscaler_args "weights=D:\Work\SD\Models\others\etc\upscaler-v1-e100-220.safetensors"`のように重みファイルを指定します。
310
+
311
+ コマンドラインの例です。
312
+
313
+ ```batchfile
314
+ python gen_img_diffusers.py --ckpt trinart_characters_it4_v1_vae_merged.ckpt
315
+ --n_iter 1 --scale 7.5 --W 1024 --H 1024 --batch_size 1 --outdir ../txt2img
316
+ --steps 48 --sampler ddim --fp16
317
+ --xformers
318
+ --images_per_prompt 1 --interactive
319
+ --highres_fix_scale 0.5 --highres_fix_steps 28 --strength 0.5
320
+ ```
321
+
322
+ ## ControlNet
323
+
324
+ 現在はControlNet 1.0のみ動作確認しています。プリプロセスはCannyのみサポートしています。
325
+
326
+ 以下のオプションがあります。
327
+
328
+ - `--control_net_models`:ControlNetのモデルファイルを指定します。
329
+ 複数指定すると、それらをstepごとに切り替えて利用します(Web UIのControlNet拡張の実装と異なります)。diffと通常の両方をサポートします。
330
+
331
+ - `--guide_image_path`:ControlNetに使うヒント画像を指定します。`--img_path`と同様にフォルダを指定すると、そのフォルダの画像を順次利用します。Canny以外のモデルの場合には、あらかじめプリプロセスを行っておいてください。
332
+
333
+ - `--control_net_preps`:ControlNetのプリプロセスを指定します。`--control_net_models`と同様に複数指定可能です。現在はcannyのみ対応しています。対象モデルでプリプロセスを使用しない場合は `none` を指定します。
334
+ cannyの場合 `--control_net_preps canny_63_191`のように、閾値1と2を'_'で区切って指定できます。
335
+
336
+ - `--control_net_weights`:ControlNetの適用時の重みを指定します(`1.0`で通常、`0.5`なら半分の影響力で適用)。`--control_net_models`と同様に複数指定可能です。
337
+
338
+ - `--control_net_ratios`:ControlNetを適用するstepの範囲を指定します。`0.5`の場合は、step数の半分までControlNetを適用します。`--control_net_models`と同様に複数指定可能です。
339
+
340
+ コマンドラインの例です。
341
+
342
+ ```batchfile
343
+ python gen_img_diffusers.py --ckpt model_ckpt --scale 8 --steps 48 --outdir txt2img --xformers
344
+ --W 512 --H 768 --bf16 --sampler k_euler_a
345
+ --control_net_models diff_control_sd15_canny.safetensors --control_net_weights 1.0
346
+ --guide_image_path guide.png --control_net_ratios 1.0 --interactive
347
+ ```
348
+
349
+ ## Attention Couple + Reginal LoRA
350
+
351
+ プロンプトをいくつかの部分に分割し、それぞれのプロンプトを画像内のどの領域に適用するかを指定できる機能です。個別のオプションはありませんが、`mask_path`とプロンプトで指定します。
352
+
353
+ まず、プロンプトで` AND `を利用して、複数部分を定義します。最初の3つに対して領域指定ができ、以降の部分は画像全体へ適用されます。ネガティブプロンプトは画像全体に適用されます。
354
+
355
+ 以下ではANDで3つの部分を定義しています。
356
+
357
+ ```
358
+ shs 2girls, looking at viewer, smile AND bsb 2girls, looking back AND 2girls --n bad quality, worst quality
359
+ ```
360
+
361
+ 次にマスク画像を用意します。マスク画像はカラーの画像で、RGBの各チャネルがプロンプトのANDで区切られた部分に対応します。またあるチャネルの値がすべて0の場合、画像全体に適用されます。
362
+
363
+ 上記の例では、Rチャネルが`shs 2girls, looking at viewer, smile`、Gチャネルが`bsb 2girls, looking back`に、Bチャネルが`2girls`に対応します。次のようなマスク画像を使用すると、Bチャネルに指定がありませんので、`2girls`は画像全体に適用されます。
364
+
365
+ ![image](https://user-images.githubusercontent.com/52813779/235343061-b4dc9392-3dae-4831-8347-1e9ae5054251.png)
366
+
367
+ マスク画像は`--mask_path`で指定します。現在は1枚のみ対応しています。指定した画像サイズに自動的にリサイズされ適用されます。
368
+
369
+ ControlNetと組み合わせることも可能です(細かい位置指定にはControlNetとの組み合わせを推奨します)。
370
+
371
+ LoRAを指定すると、`--network_weights`で指定した複数のLoRAがそれぞれANDの各部分に対応します。現在の制約として、LoRAの数はANDの部分の数と同じである必要があります。
372
+
373
+ ## CLIP Guided Stable Diffusion
374
+
375
+ DiffusersのCommunity Examplesの[こちらのcustom pipeline](https://github.com/huggingface/diffusers/blob/main/examples/community/README.md#clip-guided-stable-diffusion)からソースをコピー、変更したものです。
376
+
377
+ 通常のプロンプトによる生成指定に加えて、追加でより大規模のCLIPでプロンプトのテキストの特徴量を取得し、生成中の画像の特徴量がそのテキストの特徴量に近づくよう、生成される画像をコントロールします(私のざっくりとした理解です)。大きめのCLIPを使いますのでVRAM使用量はかなり増加し(VRAM 8GBでは512*512でも厳しいかもしれません)、生成時間も掛かります。
378
+
379
+ なお選択できるサンプラーはDDIM、PNDM、LMSのみとなります。
380
+
381
+ `--clip_guidance_scale`オプションにどの程度、CLIPの特徴量を反映するかを数値で指定します。先のサンプルでは100になっていますので、そのあたりから始めて増減すると良いようです。
382
+
383
+ デフォルトではプロンプトの先頭75トークン(重みづけの特殊文字を除く)がCLIPに渡されます。プロンプトの`--c`オプションで、通常のプロンプトではなく、CLIPに渡すテキストを別に指定できます(たとえばCLIPはDreamBoothのidentifier(識別子)や「1girl」などのモデル特有の単語は認識できないと思われますので、それらを省いたテキストが良いと思われます)。
384
+
385
+ コマンドラインの例です。
386
+
387
+ ```batchfile
388
+ python gen_img_diffusers.py --ckpt v1-5-pruned-emaonly.ckpt --n_iter 1
389
+ --scale 2.5 --W 512 --H 512 --batch_size 1 --outdir ../txt2img --steps 36
390
+ --sampler ddim --fp16 --opt_channels_last --xformers --images_per_prompt 1
391
+ --interactive --clip_guidance_scale 100
392
+ ```
393
+
394
+ ## CLIP Image Guided Stable Diffusion
395
+
396
+ テキストではなくCLIPに別の画像を渡し、その特徴量に近づくよう生成をコントロールする機能です。`--clip_image_guidance_scale`オプションで適用量の数値を、`--guide_image_path`オプションでguideに使用する画像(ファイルまたはフォルダ)を指定してください。
397
+
398
+ コマンドラインの例です。
399
+
400
+ ```batchfile
401
+ python gen_img_diffusers.py --ckpt trinart_characters_it4_v1_vae_merged.ckpt
402
+ --n_iter 1 --scale 7.5 --W 512 --H 512 --batch_size 1 --outdir ../txt2img
403
+ --steps 80 --sampler ddim --fp16 --opt_channels_last --xformers
404
+ --images_per_prompt 1 --interactive --clip_image_guidance_scale 100
405
+ --guide_image_path YUKA160113420I9A4104_TP_V.jpg
406
+ ```
407
+
408
+ ### VGG16 Guided Stable Diffusion
409
+
410
+ 指定した画像に近づくように画像生成する機能です。通常のプロンプトによる生成指定に加えて、追加でVGG16の特徴量を取得し、生成中の画像が指定したガイド画像に近づくよう、生成される画像をコントロールします。img2imgでの使用をお勧めします(通常の生成では画像がぼやけた感じになります)。CLIP Guided Stable Diffusionの仕組みを流用した独自の機能です。またアイデアはVGGを利用したスタイル変換から拝借しています。
411
+
412
+ なお選択できるサンプラーはDDIM、PNDM、LMSのみとなります。
413
+
414
+ `--vgg16_guidance_scale`オプションにどの程度、VGG16特徴量を反映するかを数値で指定します。試した感じでは100くらいから始めて増減すると良いようです。`--guide_image_path`オプションでguideに使用する画像(ファイルまたはフォルダ)を指定してください。
415
+
416
+ 複数枚の画像を一括でimg2img変換し、元画像をガイド画像とする場合、`--guide_image_path`と`--image_path`に同じ値を指定すればOKです。
417
+
418
+ コマンドラインの例です。
419
+
420
+ ```batchfile
421
+ python gen_img_diffusers.py --ckpt wd-v1-3-full-pruned-half.ckpt
422
+ --n_iter 1 --scale 5.5 --steps 60 --outdir ../txt2img
423
+ --xformers --sampler ddim --fp16 --W 512 --H 704
424
+ --batch_size 1 --images_per_prompt 1
425
+ --prompt "picturesque, 1girl, solo, anime face, skirt, beautiful face
426
+ --n lowres, bad anatomy, bad hands, error, missing fingers,
427
+ cropped, worst quality, low quality, normal quality,
428
+ jpeg artifacts, blurry, 3d, bad face, monochrome --d 1"
429
+ --strength 0.8 --image_path ..\src_image
430
+ --vgg16_guidance_scale 100 --guide_image_path ..\src_image
431
+ ```
432
+
433
+ `--vgg16_guidance_layerPで特徴量取得に使用するVGG16のレイヤー番号を指定できます(デフォルトは20でconv4-2のReLUです)。上の層ほど画風を表現し、下の層ほどコンテンツを表現するといわれています。
434
+
435
+ ![image](https://user-images.githubusercontent.com/52813779/235343813-3c1f0d7a-4fb3-4274-98e4-b92d76b551df.png)
436
+
437
+ # その他のオプション
438
+
439
+ - `--no_preview` : 対話モードでプレビュー画像を表示しません。OpenCVがインストールされていない場合や、出力されたファイルを直接確認する場合に指定してください。
440
+
441
+ - `--n_iter` : 生成を繰り返す回数を指定します。デフォルトは1です。プロンプトをファイルから読み込むとき、複数回の生成を行いたい場合に指定します。
442
+
443
+ - `--tokenizer_cache_dir` : トークナイザーのキャッシュディレクトリを指定します。(作業中)
444
+
445
+ - `--seed` : 乱数seedを指定します。1枚生成時はその画像のseed、複数枚生成時は各画像のseedを生成するための乱数のseedになります(`--from_file`で複数画像生成するとき、`--seed`オプションを指定すると複数回実行したときに各画像が同じseedになります)。
446
+
447
+ - `--iter_same_seed` : プロンプトに乱数seedの指定がないとき、`--n_iter`の繰り返し内ではすべて同じseedを使います。`--from_file`で指定した複数のプロンプト間でseedを統一して比較するときに使います。
448
+
449
+ - `--diffusers_xformers` : Diffuserのxformersを使用します。
450
+
451
+ - `--opt_channels_last` : 推論時にテンソルのチャンネルを最後に配置します。場合によっては高速化されることがあります。
452
+
453
+ - `--network_show_meta` : 追加ネットワークのメタデータを表示します。
454
+
455
+
456
+ ---
457
+
458
+ # About Gradual Latent
459
+
460
+ Gradual Latent is a Hires fix that gradually increases the size of the latent. `gen_img.py`, `sdxl_gen_img.py`, and `gen_img_diffusers.py` have the following options.
461
+
462
+ - `--gradual_latent_timesteps`: Specifies the timestep to start increasing the size of the latent. The default is None, which means Gradual Latent is not used. Please try around 750 at first.
463
+ - `--gradual_latent_ratio`: Specifies the initial size of the latent. The default is 0.5, which means it starts with half the default latent size.
464
+ - `--gradual_latent_ratio_step`: Specifies the ratio to increase the size of the latent. The default is 0.125, which means the latent size is gradually increased to 0.625, 0.75, 0.875, 1.0.
465
+ - `--gradual_latent_ratio_every_n_steps`: Specifies the interval to increase the size of the latent. The default is 3, which means the latent size is increased every 3 steps.
466
+
467
+ Each option can also be specified with prompt options, `--glt`, `--glr`, `--gls`, `--gle`.
468
+
469
+ __Please specify `euler_a` for the sampler.__ Because the source code of the sampler is modified. It will not work with other samplers.
470
+
471
+ It is more effective with SD 1.5. It is quite subtle with SDXL.
472
+
473
+ # Gradual Latent について
474
+
475
+ latentのサイズを徐々に大きくしていくHires fixです。`gen_img.py` 、``sdxl_gen_img.py` 、`gen_img_diffusers.py` に以下のオプションが追加されています。
476
+
477
+ - `--gradual_latent_timesteps` : latentのサイズを大きくし始めるタイムステップを指定します。デフォルトは None で、Gradual Latentを使用しません。750 くらいから始めてみてください。
478
+ - `--gradual_latent_ratio` : latentの初期サイズを指定します。デフォルトは 0.5 で、デフォルトの latent サイズの半分のサイズから始めます。
479
+ - `--gradual_latent_ratio_step`: latentのサイズを大きくする割合を指定します。デフォルトは 0.125 で、latentのサイズを 0.625, 0.75, 0.875, 1.0 と徐々に大きくします。
480
+ - `--gradual_latent_ratio_every_n_steps`: latentのサイズを大きくする間隔を指定します。デフォルトは 3 で、3ステップごとに latent のサイズを大きくします。
481
+
482
+ それぞれのオプションは、プロンプトオプション、`--glt`、`--glr`、`--gls`、`--gle` でも指定できます。
483
+
484
+ サンプラーに手を加えているため、__サンプラーに `euler_a` を指定してください。__ 他のサンプラーでは動作しません。
485
+
486
+ SD 1.5 のほうが効果があります。SDXL ではかなり微妙です。
487
+
docs/image_folder_structure.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Drambootd, Lora and TI image folder structure
2
+
3
+ To ensure successful training with Kohya, it is crucial to follow a specific folder structure that provides the necessary image repeats. Please adhere to the following structure precisely:
4
+
5
+ Folder Structure Example:
6
+
7
+ ```txt
8
+ c:
9
+ |
10
+ ├──images
11
+ | |
12
+ | ├── 30_cat
13
+ | | |
14
+ | | ├── image1.jpg
15
+ | | ├── image1.txt
16
+ | | ├── image2.png
17
+ | | └── image2.txt
18
+ | |
19
+ | ├── 30_dog
20
+ | | |
21
+ | | ├── image1.jpg
22
+ | | ├── image1.txt
23
+ | | ├── image2.png
24
+ | | └── image2.txt
25
+ | |
26
+ | └── 40_black mamba
27
+ | |
28
+ | ├── image1.jpg
29
+ | ├── image1.txt
30
+ | ├── image2.png
31
+ | └── image2.txt
32
+ |
33
+ ├──regularization
34
+ | |
35
+ | ├── 1_cat
36
+ | | |
37
+ | | ├── reg1.jpg
38
+ | | ├── reg2.jpg
39
+ | |
40
+ | ├── 1_dog
41
+ | | |
42
+ | | ├── reg1.jpg
43
+ | | ├── reg2.jpg
44
+ | |
45
+ | └── 1_black mamba
46
+ | |
47
+ | ├── reg1.jpg
48
+ | ├── reg2.jpg
49
+
50
+ ```
51
+
52
+ Please note the following important information regarding file extensions and their impact on concept names during model training:
53
+
54
+ If a file with a .txt or .caption extension and the same name as an image is present in the image subfolder, it will take precedence over the concept name during the model training process.
55
+ For example, if there is an image file named image1.jpg in the 30_cat subfolder, and there is a corresponding text file named image1.txt or image1.caption in the same subfolder, the concept name used during training will be determined by the content of that text file rather than the subfolder name.
56
+
57
+ Ensure that the content of such text files accurately reflects the desired concept name or any relevant caption information associated with the corresponding image.
58
+
59
+ By considering this information and maintaining the proper folder structure, including any necessary text or caption files, you can ensure a smooth and effective training process with Kohya.
docs/train_README-ja.md ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __ドキュメント更新中のため記述に誤りがあるかもしれません。__
2
+
3
+ # 学習について、共通編
4
+
5
+ 当リポジトリではモデルのfine tuning、DreamBooth、およびLoRAとTextual Inversion([XTI:P+](https://github.com/kohya-ss/sd-scripts/pull/327)を含む)の学習をサポートします。この文書ではそれらに共通する、学習データの準備方法やオプション等について説明します。
6
+
7
+ # 概要
8
+
9
+ あらかじめこのリポジトリのREADMEを参照し、環境整備を行ってください。
10
+
11
+
12
+ 以下について説明します。
13
+
14
+ 1. 学習データの準備について(設定ファイルを用いる新形式)
15
+ 1. 学習で使われる用語のごく簡単な解説
16
+ 1. 以前の指定形式(設定ファイルを用いずコマンドラインから指定)
17
+ 1. 学習途中のサンプル画像生成
18
+ 1. 各スクリプトで共通の、よく使われるオプション
19
+ 1. fine tuning 方式のメタデータ準備:キャプションニングなど
20
+
21
+ 1.だけ実行すればとりあえず学習は可能です(学習については各スクリプトのドキュメントを参照)。2.以降は必要に応じて参照してください。
22
+
23
+
24
+ # 学習データの準備について
25
+
26
+ 任意のフォルダ(複数でも可)に学習データの画像ファイルを用意しておきます。`.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp` をサポートします。リサイズなどの前処理は基本的に必要ありません。
27
+
28
+ ただし学習解像度(後述)よりも極端に小さい画像は使わないか、あらかじめ超解像AIなどで拡大しておくことをお勧めします。また極端に大きな画像(3000x3000ピクセル程度?)よりも大きな画像はエラーになる場合があるようですので事前に縮小してください。
29
+
30
+ 学習時には、モデルに学ばせる画像データを整理し、スクリプトに対して指定する必要があります。学習データの数、学習対象、キャプション(画像の説明)が用意できるか否かなどにより、いくつかの方法で学習データを指定できます。以下の方式があります(それぞれの名前は一般的なものではなく、当リポジトリ独自の定義です)。正則化画像については後述します。
31
+
32
+ 1. DreamBooth、class+identifier方式(正則化画像使用可)
33
+
34
+ 特定の単語 (identifier) に学習対象を紐づけるように学習します。キャプションを用意する必要はありません。たとえば特定のキャラを学ばせる場合に使うとキャプションを用意する必要がない分、手軽ですが、髪型や服装、背景など学習データの全要素が identifier に紐づけられて学習されるため、生成時のプロンプトで服が変えられない、といった事態も起こりえます。
35
+
36
+ 1. DreamBooth、キャプション方式(正則化画像使用可)
37
+
38
+ 画像ごとにキャプションが記録されたテキストファイルを用意して学習します。たとえば特定のキャラを学ばせると、画像の詳細をキャプションに記述することで(白い服を着たキャラA、赤い服を着たキャラA、など)キャラとそれ以外の要素が分離され、より厳密にモデルがキャラだけを学ぶことが期待できます。
39
+
40
+ 1. fine tuning方式(正則化画像使用不可)
41
+
42
+ あらかじめキャプションをメタデータファイルにまとめます。タグとキャプションを分けて管理したり、学習を高速化するためlatentsを事前キャッシュしたりなどの機能をサポートします(いずれも別文書で説明しています)。(fine tuning方式という名前ですが fine tuning 以外でも使えます。)
43
+
44
+ 学習したいものと使用できる指定方法の組み合わせは以下の通りです。
45
+
46
+ | 学習対象または方法 | スクリプト | DB / class+identifier | DB / キャプション | fine tuning |
47
+ | ----- | ----- | ----- | ----- | ----- |
48
+ | モデルをfine tuning | `fine_tune.py`| x | x | o |
49
+ | モデルをDreamBooth | `train_db.py`| o | o | x |
50
+ | LoRA | `train_network.py`| o | o | o |
51
+ | Textual Invesion | `train_textual_inversion.py`| o | o | o |
52
+
53
+ ## どれを選ぶか
54
+
55
+ LoRA、Textual Inversionについては、手軽にキャプションファイルを用意せずに学習したい場合はDreamBooth class+identifier、用意できるならDreamBooth キャプション方式がよいでしょう。学習データの枚数が多く、かつ正則化画像を使用しない場合はfine tuning方式も検討してください。
56
+
57
+ DreamBoothについても同様ですが、fine tuning方式は使えません。fine tuningの場合はfine tuning方式のみです。
58
+
59
+ # 各方式の指定方法について
60
+
61
+ ここではそれぞれの指定方法で典型的なパターンについてだけ説明します。より詳細な指定方法については [データセット設定](./config_README-ja.md) をご覧ください。
62
+
63
+ # DreamBooth、class+identifier方式(正則化画像使用可)
64
+
65
+ この方式では、各画像は `class identifier` というキャプションで学習されたのと同じことになります(`shs dog` など)。
66
+
67
+ ## step 1. identifierとclassを決める
68
+
69
+ 学ばせたい対象を結びつける単語identifierと、対象の属するclassを決めます。
70
+
71
+ (instanceなどいろいろな呼び方がありますが、とりあえず元の論文に合わせます。)
72
+
73
+ 以下ごく簡単に説明します(詳しくは調べてください)。
74
+
75
+ classは学習対象の一般的な種別です。たとえば特定の犬種を学ばせる場合には、classはdogになります。アニメキャラならモデルによりboyやgirl、1boyや1girlになるでしょう。
76
+
77
+ identifierは学習対象を識別して学習するためのものです。任意の単語で構いませんが、元論文によると「tokinizerで1トークンになる3文字以下でレアな単語」が良いとのことです。
78
+
79
+ identifierとclassを使い、たとえば「shs dog」などでモデルを学習することで、学習させたい対象をclassから識別して学習できます。
80
+
81
+ 画像生成時には「shs dog」とすれば学ばせた犬種の画像が生成されます。
82
+
83
+ (identifierとして私が最近使っているものを参考までに挙げると、``shs sts scs cpc coc cic msm usu ici lvl cic dii muk ori hru rik koo yos wny`` などです。本当は Danbooru Tag に含まれないやつがより望ましいです。)
84
+
85
+ ## step 2. 正則化画像を使うか否かを決め、使う場合には正則化画像を生成する
86
+
87
+ 正則化画像とは、前述のclass全体が、学習対象に引っ張られることを防ぐための画像です(language drift)。正則化画像を使わないと、たとえば `shs 1girl` で特定のキャラクタを学ばせると、単なる `1girl` というプロンプトで生成してもそのキャラに似てきます。これは `1girl` が学習時のキャプションに含まれているためです。
88
+
89
+ 学習対象の画像と正則化画像を同時に学ばせることで、class は class のままで留まり、identifier をプロンプトにつけた時だけ学習対象が生成されるようになります。
90
+
91
+ LoRAやDreamBoothで特定のキャラだけ出てくればよい場合は、正則化画像を用いなくても良いといえます。
92
+
93
+ Textual Inversionでは用いなくてよいでしょう(学ばせる token string がキャプションに含まれない場合はなにも学習されないため)。
94
+
95
+ 正則化画像としては、学習対象のモデルで、class 名だけで生成した画像を用いるのが一般的です(たとえば `1girl`)。ただし生成画像の品質が悪い場合には、プロンプトを工夫したり、ネットから別途ダウンロードした画像を用いることもできます。
96
+
97
+ (正則化画像も学習されるため、その品質はモデルに影響します。)
98
+
99
+ 一般的には数百枚程度、用意するのが望ましいようです(枚数が少ないと class 画像が一般化されずそれらの特徴を学んでしまいます)。
100
+
101
+ 生成画像を使う場合、通常、生成画像のサイズは学習解像度(より正確にはbucketの解像度、後述)にあわせてください。
102
+
103
+ ## step 2. 設定ファイルの記述
104
+
105
+ テキストファイルを作成し、拡張子を `.toml` にします。たとえば以下のように記述します。
106
+
107
+ (`#` で始まっている部分はコメントですので、このままコピペしてそのままでもよいですし、削除しても問題ありません。)
108
+
109
+ ```toml
110
+ [general]
111
+ enable_bucket = true # Aspect Ratio Bucketingを使うか否か
112
+
113
+ [[datasets]]
114
+ resolution = 512 # 学習解像度
115
+ batch_size = 4 # バッチサイズ
116
+
117
+ [[datasets.subsets]]
118
+ image_dir = 'C:\hoge' # 学習用画像を入れたフォルダを指定
119
+ class_tokens = 'hoge girl' # identifier class を指定
120
+ num_repeats = 10 # 学習用画像の繰り返し回数
121
+
122
+ # 以下は正則化画像を用いる場合のみ記述する。用いない場合は削除する
123
+ [[datasets.subsets]]
124
+ is_reg = true
125
+ image_dir = 'C:\reg' # 正則化画像を入れたフォルダを指定
126
+ class_tokens = 'girl' # class を指定
127
+ num_repeats = 1 # 正則化画像の繰り返し回数、基本的には1でよい
128
+ ```
129
+
130
+ 基本的には以下の場所のみ書き換えれば学習できます。
131
+
132
+ 1. 学習���像度
133
+
134
+ 数値1つを指定すると正方形(`512`なら512x512)、鍵カッコカンマ区切りで2つ指定すると横×縦(`[512,768]`なら512x768)になります。SD1.x系ではもともとの学習解像度は512です。`[512,768]` 等の大きめの解像度を指定すると縦長、横長画像生成時の破綻を小さくできるかもしれません。SD2.x 768系では `768` です。
135
+
136
+ 1. バッチサイズ
137
+
138
+ 同時に何件のデータを学習するかを指定します。GPUのVRAMサイズ、学習解像度によって変わってきます。詳しくは後述します。またfine tuning/DreamBooth/LoRA等でも変わってきますので各スクリプトの説明もご覧ください。
139
+
140
+ 1. フォルダ指定
141
+
142
+ 学習用画像、正則化画像(使用する場合のみ)のフォルダを指定します。画像データが含まれているフォルダそのものを指定します。
143
+
144
+ 1. identifier と class の指定
145
+
146
+ 前述のサンプルの通りです。
147
+
148
+ 1. 繰り返し回数
149
+
150
+ 後述します。
151
+
152
+ ### 繰り返し回数について
153
+
154
+ 繰り返し回数は、正則化画像の枚数と学習用画像の枚数を調整するために用いられます。正則化画像の枚数は学習用画像よりも多いため、学習用画像を繰り返して枚数を合わせ、1対1の比率で学習できるようにします。
155
+
156
+ 繰り返し回数は「 __学習用画像の繰り返し回数×学習用画像の枚数≧正則化画像の繰り返し回数×正則化画像の枚数__ 」となるように指定してください。
157
+
158
+ (1 epoch(データが一周すると1 epoch)のデータ数が「学習用画像の繰り返し回数×学習用画像の枚数」となります。正則化画像の枚数がそれより多いと、余った部分の正則化画像は使用されません。)
159
+
160
+ ## step 3. 学習
161
+
162
+ それぞれのドキュメントを参考に学習を行ってください。
163
+
164
+ # DreamBooth、キャプション方式(正則化画像使用可)
165
+
166
+ この方式では各画像はキャプションで学習されます。
167
+
168
+ ## step 1. キャプションファイルを準備する
169
+
170
+ 学習用画像のフォルダに、画像と同じファイル名で、拡張子 `.caption`(設定で変えられます)のファイルを置いてください。それぞれのファイルは1行のみとしてください。エンコーディングは `UTF-8` です。
171
+
172
+ ## step 2. 正則化画像を使うか否かを決め、使う場合には正則化画像を生成する
173
+
174
+ class+identifier形式と同様です。なお正則化画像にもキャプションを付けることができますが、通常は不要でしょう。
175
+
176
+ ## step 2. 設定ファイルの記述
177
+
178
+ テキストファイルを作成し、拡張子を `.toml` にします。たとえば以下のように記述します。
179
+
180
+ ```toml
181
+ [general]
182
+ enable_bucket = true # Aspect Ratio Bucketingを使うか否か
183
+
184
+ [[datasets]]
185
+ resolution = 512 # 学習解像度
186
+ batch_size = 4 # バッチサイズ
187
+
188
+ [[datasets.subsets]]
189
+ image_dir = 'C:\hoge' # 学習用画像を入れたフォルダを指定
190
+ caption_extension = '.caption' # キャプションファイルの拡張子 .txt を使う場合には書き換える
191
+ num_repeats = 10 # 学習用画像の繰り返し回数
192
+
193
+ # 以下は正則化画像を用いる場合のみ記述する。用いない場合は削除する
194
+ [[datasets.subsets]]
195
+ is_reg = true
196
+ image_dir = 'C:\reg' # 正則化画像を入れたフォルダを指定
197
+ class_tokens = 'girl' # class を指定
198
+ num_repeats = 1 # 正則化画像の繰り返し回数、基本的には1でよい
199
+ ```
200
+
201
+ 基本的には以下を場所のみ書き換えれば学習できます。特に記述がない部分は class+identifier 方式と同じです。
202
+
203
+ 1. 学習解像度
204
+ 1. バッチサイズ
205
+ 1. フォルダ指定
206
+ 1. キャプションファイルの拡張子
207
+
208
+ 任意の拡張子を指定できます。
209
+ 1. 繰り返し回数
210
+
211
+ ## step 3. 学習
212
+
213
+ それぞれのドキュメントを参考に学習を行ってください。
214
+
215
+ # fine tuning 方式
216
+
217
+ ## step 1. メタデータを準備する
218
+
219
+ キャプションやタグをまとめた管理用ファイルをメタデータと呼びます。json形式で拡張子は `.json`
220
+ です。作成方法は長くなりますのでこの文書の末尾に書きました。
221
+
222
+ ## step 2. 設定ファイルの記述
223
+
224
+ テキストファイルを作成し、拡張子を `.toml` にします。たとえば以下のように記述します。
225
+
226
+ ```toml
227
+ [general]
228
+ shuffle_caption = true
229
+ keep_tokens = 1
230
+
231
+ [[datasets]]
232
+ resolution = 512 # 学習解像度
233
+ batch_size = 4 # バッチサイズ
234
+
235
+ [[datasets.subsets]]
236
+ image_dir = 'C:\piyo' # 学習用画像を入れたフォルダを指定
237
+ metadata_file = 'C:\piyo\piyo_md.json' # メタデータファイル名
238
+ ```
239
+
240
+ 基本的には以下を場所のみ書き換えれば学習できます。特に記述がない部分は DreamBooth, class+identifier 方式と同じです。
241
+
242
+ 1. 学習解像度
243
+ 1. バッチサイズ
244
+ 1. フォルダ指定
245
+ 1. メタデータファイル名
246
+
247
+ 後述の方法で作成したメタデータファイルを指定します。
248
+
249
+
250
+ ## step 3. 学習
251
+
252
+ それぞれのドキュメントを参考に学習を行ってください。
253
+
254
+ # 学習で使われる用語のごく簡単な解説
255
+
256
+ 細かいことは省略していますし私も完全には理解していないため、詳しくは各自お調べください。
257
+
258
+ ## fine tuning(ファインチューニング)
259
+
260
+ モデルを学習して微調整することを指します。使われ方によって意味が異なってきますが、狭義のfine tuningはStable Diffusionの場合、モデルを画像とキャプションで学習することです。DreamBoothは狭義のfine tuningのひとつの特殊なやり方と言えます。広義のfine tuningは、LoRAやTextual Inversion、Hypernetworksなどを含み、モデルを学習することすべてを含みます。
261
+
262
+ ## ステップ
263
+
264
+ ざっくりいうと学習データで1回計算すると1ステップです。「学習データのキャプションを今のモデルに流してみて、出てくる画像を学習データの画像と比較し、学習データに近づくようにモデルをわずかに変更する」のが1ステップです。
265
+
266
+ ## バッチサイズ
267
+
268
+ バッチサイズは1ステップで何件のデータをまとめて計算するかを指定する値です。まとめて計算するため速度は相対的に向上します。また一般的には精度も高くなるといわれています。
269
+
270
+ `バッチサイズ×ステップ数` が学習に使われるデータの件数になります。そのため、バッチサイズを増やした分だけステップ数を減らすとよいでしょう。
271
+
272
+ (ただし、たとえば「バッチサイズ1で1600ステップ」と「バッチサイズ4で400ステップ」は同じ結果にはなりません。同じ学習率の場合、一般的には後者のほうが学習不足になります。学習率を多少大きくするか(たとえば `2e-6` など)、ステップ数をたとえば500ステップにするなどして工夫してください。)
273
+
274
+ バッチサイズを大きくするとその分だけGPUメモリを消費します。メモリが足りなくなるとエラーになりますし、エラーにならないギリギリでは学習速度が低下します。タスクマネージャーや `nvidia-smi` コマンドで使用メモリ量を確認しながら調整するとよいでしょう。
275
+
276
+ なお、バッチは「一塊のデータ」位の意味です。
277
+
278
+ ## 学習率
279
+
280
+ ざっくりいうと1ステップごとにどのくらい変化させるかを表します。大きな値を指定するとそれだけ速く学習が進みますが、変化しすぎてモデルが壊れたり、最適な状態にまで至れない場合があります。小さい値を指定すると学習速度は遅くなり、また最適な状態にやはり至れない場合があります。
281
+
282
+ fine tuning、DreamBoooth、LoRAそれぞれで大きく異なり、また学習データや学習させたいモデル、バッチサイズやステップ数によっても変わってきます。一般的な値から初めて学習状態を見ながら増減してください。
283
+
284
+ デフォルトでは学習全体を通して学習率は固定です。スケジューラの指定で学習率をどう変化させるか決められますので、それらによっても結果は変わってきます。
285
+
286
+ ## エポック(epoch)
287
+
288
+ 学習データが一通り学習されると(データが一周すると)1 epochです。繰り返し回数を指定した場合は、その繰り返し後のデータが一周すると1 epochです。
289
+
290
+ 1 epochのステップ数は、基本的には `データ件数÷バッチサイズ` ですが、Aspect Ratio Bucketing を使うと微妙に増えます(異なるbucketのデータは同じバッチにできないため、ステップ数が増えます)。
291
+
292
+ ## Aspect Ratio Bucketing
293
+
294
+ Stable Diffusion のv1は512\*512で学習されていますが、それに加えて256\*1024や384\*640といった解像度でも学習します。これによりトリミングされる部分が減り、より正しくキャプションと画像の関係が学習されることが期待されます。
295
+
296
+ また任意の解像度で学習するため、事前に画像データの縦横比を統一しておく必要がなくなりま��。
297
+
298
+ 設定で有効、無効が切り替えられますが、ここまでの設定ファイルの記述例では有効になっています(`true` が設定されています)。
299
+
300
+ 学習解像度はパラメータとして与えられた解像度の面積(=メモリ使用量)を超えない範囲で、64ピクセル単位(デフォルト、変更可)で縦横に調整、作成されます。
301
+
302
+ 機械学習では入力サイズをすべて統一するのが一般的ですが、特に制約があるわけではなく、実際は同一のバッチ内で統一されていれば大丈夫です。NovelAIの言うbucketingは、あらかじめ教師データを、アスペクト比に応じた学習解像度ごとに分類しておくことを指しているようです。そしてバッチを各bucket内の画像で作成することで、バッチの画像サイズを統一します。
303
+
304
+ # 以前の指定形式(設定ファイルを用いずコマンドラインから指定)
305
+
306
+ `.toml` ファイルを指定せずコマンドラインオプションで指定する方法です。DreamBooth class+identifier方式、DreamBooth キャプション方式、fine tuning方式があります。
307
+
308
+ ## DreamBooth、class+identifier方式
309
+
310
+ フォルダ名で繰り返し回数を指定します。また `train_data_dir` オプションと `reg_data_dir` オプションを用います。
311
+
312
+ ### step 1. 学習用画像の準備
313
+
314
+ 学習用画像を格納するフォルダを作成します。 __さらにその中に__ 、以下の名前でディレクトリを作成します。
315
+
316
+ ```
317
+ <繰り返し回数>_<identifier> <class>
318
+ ```
319
+
320
+ 間の``_``を忘れないでください。
321
+
322
+ たとえば「sls frog」というプロンプトで、データを20回繰り返す場合、「20_sls frog」となります。以下のようになります。
323
+
324
+ ![image](https://user-images.githubusercontent.com/52813779/210770636-1c851377-5936-4c15-90b7-8ac8ad6c2074.png)
325
+
326
+ ### 複数class、複数対象(identifier)の学習
327
+
328
+ 方法は単純で、学習用画像のフォルダ内に ``繰り返し回数_<identifier> <class>`` のフォルダを複数、正則化画像フォルダにも同様に ``繰り返し回数_<class>`` のフォルダを複数、用意してください。
329
+
330
+ たとえば「sls frog」と「cpc rabbit」を同時に学習する場合、以下のようになります。
331
+
332
+ ![image](https://user-images.githubusercontent.com/52813779/210777933-a22229db-b219-4cd8-83ca-e87320fc4192.png)
333
+
334
+ classがひとつで対象が複数の場合、正則化画像フォルダはひとつで構いません。たとえば1girlにキャラAとキャラBがいる場合は次のようにします。
335
+
336
+ - train_girls
337
+ - 10_sls 1girl
338
+ - 10_cpc 1girl
339
+ - reg_girls
340
+ - 1_1girl
341
+
342
+ ### step 2. 正則化画像の準備
343
+
344
+ 正則化画像を使う場合の手順です。
345
+
346
+ 正則化画像を格納するフォルダを作成します。 __さらにその中に__ ``<繰り返し回数>_<class>`` という名前でディレクトリを作成します。
347
+
348
+ たとえば「frog」というプロンプトで、データを繰り返さない(1回だけ)場合、以下のようになります。
349
+
350
+ ![image](https://user-images.githubusercontent.com/52813779/210770897-329758e5-3675-49f1-b345-c135f1725832.png)
351
+
352
+
353
+ ### step 3. 学習の実行
354
+
355
+ 各学習スクリプトを実行します。 `--train_data_dir` オプションで前述の学習用データのフォルダを(__画像を含むフォルダではなく、その親フォルダ__)、`--reg_data_dir` オプションで正則化画像のフォルダ(__画像を含むフォルダではなく、その親フォルダ__)を指定してください。
356
+
357
+ ## DreamBooth、キャプション方式
358
+
359
+ 学習用画像、正則化画像のフォルダに、画像と同じファイル名で、拡張子.caption(オプションで変えられます)のファイルを置くと、そのファイルからキャプションを読み込みプロンプトとして学習します。
360
+
361
+ ※それらの画像の学習に、フォルダ名(identifier class)は使用されなくなります。
362
+
363
+ キャプションファイルの拡張子はデフォルトで.captionです。学習スクリプトの `--caption_extension` オプションで変更できます。`--shuffle_caption` オプションで学習時のキャプションについて、カンマ区切りの各部分をシャッフルしながら学習します。
364
+
365
+ ## fine tuning 方式
366
+
367
+ メタデータを作るところまでは設定ファイルを使う場合と同様です。`in_json` オプションでメタデータファイルを指定します。
368
+
369
+ # 学習途中でのサンプル出力
370
+
371
+ 学習中のモデルで試しに画像生成することで学習の進み方を確認できます。学習スクリプトに以下のオプションを指定します。
372
+
373
+ - `--sample_every_n_steps` / `--sample_every_n_epochs`
374
+
375
+ サンプル出��するステップ数またはエポック数を指定します。この数ごとにサンプル出力します。両方指定するとエポック数が優先されます。
376
+
377
+ - `--sample_at_first`
378
+
379
+ 学習開始前にサンプル出力します。学習前との比較ができます。
380
+
381
+ - `--sample_prompts`
382
+
383
+ サンプル出力用プロンプトのファイルを指定します。
384
+
385
+ - `--sample_sampler`
386
+
387
+ サンプル出力に使うサンプラーを指定します。
388
+ `'ddim', 'pndm', 'heun', 'dpmsolver', 'dpmsolver++', 'dpmsingle', 'k_lms', 'k_euler', 'k_euler_a', 'k_dpm_2', 'k_dpm_2_a'`が選べます。
389
+
390
+ サンプル出力を行うにはあらかじめプロンプトを記述したテキストファイルを用意しておく必要があります。1行につき1プロンプトで記述します。
391
+
392
+ たとえば以下のようになります。
393
+
394
+ ```txt
395
+ # prompt 1
396
+ masterpiece, best quality, 1girl, in white shirts, upper body, looking at viewer, simple background --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 768 --h 768 --d 1 --l 7.5 --s 28
397
+
398
+ # prompt 2
399
+ masterpiece, best quality, 1boy, in business suit, standing at street, looking back --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 576 --h 832 --d 2 --l 5.5 --s 40
400
+ ```
401
+
402
+ 先頭が `#` の行はコメントになります。`--n` のように 「`--` + 英小文字」で生成画像へのオプションを指定できます。以下が使えます。
403
+
404
+ - `--n` 次のオプションまでをネガティブプロンプトとします。
405
+ - `--w` 生成画像の横幅を指定します。
406
+ - `--h` 生成画像の高さを指定します。
407
+ - `--d` 生成画像のseedを指定します。
408
+ - `--l` 生成画像のCFG scaleを指定します。
409
+ - `--s` 生成時のステップ数を指定します。
410
+
411
+
412
+ # 各スクリプトで共通の、よく使われるオプション
413
+
414
+ スクリプトの更新後、ドキュメントの更新が追い付いていない場合があります。その場合は `--help` オプションで使用できるオプションを確認してください。
415
+
416
+ ## 学習に使うモデル指定
417
+
418
+ - `--v2` / `--v_parameterization`
419
+
420
+ 学習対象モデルとしてHugging Faceのstable-diffusion-2-base、またはそこからのfine tuningモデルを使う場合(推論時に `v2-inference.yaml` を使うように指示されているモデルの場合)は `--v2` オプションを、stable-diffusion-2や768-v-ema.ckpt、およびそれらのfine tuningモデルを使う場合(推論時に `v2-inference-v.yaml` を使うモデルの場合)は `--v2` と `--v_parameterization` の両方のオプションを指定してください。
421
+
422
+ Stable Diffusion 2.0では大きく以下の点が変わっています。
423
+
424
+ 1. 使用するTokenizer
425
+ 2. 使用するText Encoderおよび使用する出力層(2.0は最後から二番目の層を使う)
426
+ 3. Text Encoderの出力次元数(768->1024)
427
+ 4. U-Netの構造(CrossAttentionのhead数など)
428
+ 5. v-parameterization(サンプリング方法が変更されているらしい)
429
+
430
+ このうちbaseでは1~4が、baseのつかない方(768-v)では1~5が採用されています。1~4を有効にするのがv2オプション、5を有効にするのがv_parameterizationオプションです。
431
+
432
+ - `--pretrained_model_name_or_path`
433
+
434
+ 追加学習を行う元となるモデルを指定します。Stable Diffusionのcheckpointファイル(.ckptまたは.safetensors)、Diffusersのローカルディスクにあるモデルディレクトリ、DiffusersのモデルID("stabilityai/stable-diffusion-2"など)が指定できます。
435
+
436
+ ## 学習に関する設定
437
+
438
+ - `--output_dir`
439
+
440
+ 学習後のモデルを保存するフォルダを指定します。
441
+
442
+ - `--output_name`
443
+
444
+ モデルのファイル名を拡張子を除いて指定します。
445
+
446
+ - `--dataset_config`
447
+
448
+ データセットの設定を記述した `.toml` ファイルを指定します。
449
+
450
+ - `--max_train_steps` / `--max_train_epochs`
451
+
452
+ 学習するステップ数やエポック数を指定します。両方指定するとエポック数のほうが優先されます。
453
+
454
+ - `--mixed_precision`
455
+
456
+ 省メモリ化のため mixed precision (混合精度)で学習します。`--mixed_precision="fp16"` のように指定します。mixed precision なし(デフォルト)と比べて精度が低くなる可能性がありますが、学習に必要なGPUメモリ量が大きく減ります。
457
+
458
+ (RTX30 シリーズ以降では `bf16` も指定できます。環境整備時にaccelerateに行った設定と合わせてください)。
459
+
460
+ - `--gradient_checkpointing`
461
+
462
+ 学習時の重みの計算をまとめて行うのではなく少しずつ行うことで、学習に必要なGPUメモリ量を減らします。オンオフは精度には影響しませんが、オンにするとバッチサイズを大きくできるため、そちらでの影響はあります。
463
+
464
+ また一般的にはオンにすると速度は低下しますが、バッチサイズを大きくできるので、トータルでの学習時間はむしろ速くなるかもしれません。
465
+
466
+ - `--xformers` / `--mem_eff_attn`
467
+
468
+ xformersオプションを指定するとxformersのCrossAttentionを用います。xformersをインストールしていない場合やエラーとなる場合(環境にもよりますが `mixed_precision="no"` の場合など)、代わりに `mem_eff_attn` オプションを指定すると省メモリ版CrossAttentionを使用します(xformersよりも速度は遅くなります)。
469
+
470
+ - `--clip_skip`
471
+
472
+ `2` を指定すると、Text Encoder (CLIP) の後ろから二番目の層の出力を用います。1またはオプション省略時は最後の層を用います。
473
+
474
+ ※SD2.0はデフォルトで後ろから二番目の層を使うため、SD2.0の学習では指定しないでください。
475
+
476
+ 学習対象のモデルがもともと二番目の層を使うように学習されている場合は、2を指定するとよいでしょう。
477
+
478
+ そうではなく最後の層を使用していた場合はモデル全体がそれを前提に学習されています。そのため改めて二番目の層を使用して学習すると、望ましい学習結果を得るにはある程度の枚数の教師データ、長めの学習が必要になるかもしれません。
479
+
480
+ - `--max_token_length`
481
+
482
+ デフォルトは75です。`150` または `225` を指定することでトークン長を拡張して学習できます。長いキャプションで学習する場合に指定してください。
483
+
484
+ ただし学習時のトークン拡張の仕様は Automatic1111 氏のWeb UIとは微妙に異なるため(分割の仕様など)、必要なければ75で学習することをお勧めします。
485
+
486
+ clip_skipと同様に、モデルの学習状態と異なる長さで学習するには、ある程度の教師データ枚数、長めの学習時間が必要になると思われます。
487
+
488
+ - `--weighted_captions`
489
+
490
+ 指定するとAutomatic1111氏のWeb UIと同様の重み付きキャプションが有効になります。「Textual Inversion と XTI」以外の学習に使用できます。キャプションだけでなく DreamBooth 手法の token string でも有効です。
491
+
492
+ 重みづけキャプションの記法はWeb UIとほぼ同じで、(abc)や[abc]、(abc:1.23)などが使用できます。入れ子も可能です。括弧内にカンマを含めるとプロンプトのshuffle/dropoutで括弧の対応付けがおかしくなるため、括弧内にはカンマを含めないでください。
493
+
494
+ - `--persistent_data_loader_workers`
495
+
496
+ Windows環境で指定するとエポック間の待ち時間が大幅に短縮されます。
497
+
498
+ - `--max_data_loader_n_workers`
499
+
500
+ データ読み込みのプロセス数を指定します。プロセス数が多いとデータ読み込みが速くなりGPUを効率的に利用できますが、メインメモリを消費します。デフォルトは「`8` または `CPU同時実行スレッド数-1` の小さいほう」なので、メインメモリに余裕がない場合や、GPU使用率が90%程度以上なら、それらの数値を見ながら `2` または `1` 程度まで下げてください。
501
+
502
+ - `--logging_dir` / `--log_prefix`
503
+
504
+ 学習ログの保存に関するオプションです。logging_dirオプションにログ保存先フォルダを指定してください。TensorBoard形式のログが保存されます。
505
+
506
+ たとえば--logging_dir=logsと指定すると、作業フォルダにlogsフォルダが作成され、その中の日時フォルダにログが保存されます。
507
+ また--log_prefixオプションを指定すると、日時の前に指定した文字列が追加されます。「--logging_dir=logs --log_prefix=db_style1_」などとして識別用にお使いください。
508
+
509
+ TensorBoardでログを確認するには、別のコマンドプロンプトを開き、作業フォルダで以下のように入力します。
510
+
511
+ ```
512
+ tensorboard --logdir=logs
513
+ ```
514
+
515
+ (tensorboardは環境整備時にあわせてインストールされると思いますが、もし入っていないなら `pip install tensorboard` で入れてください。)
516
+
517
+ その後ブラウザを開き、http://localhost:6006/ へアクセスすると表示されます。
518
+
519
+ - `--log_with` / `--log_tracker_name`
520
+
521
+ 学習ログの保存に関するオプションです。`tensorboard` だけでなく `wandb`への保存が可能です。詳細は [PR#428](https://github.com/kohya-ss/sd-scripts/pull/428)をご覧ください。
522
+
523
+ - `--noise_offset`
524
+
525
+ こちらの記事の実装になります: https://www.crosslabs.org//blog/diffusion-with-offset-noise
526
+
527
+ 全体的に暗い、明るい画像の生成結果が良くなる可能性があるようです。LoRA学習でも有効なようです。`0.1` 程度の値を指定するとよいようです。
528
+
529
+ - `--adaptive_noise_scale` (実験的オプション)
530
+
531
+ Noise offsetの値を、latentsの各チャネルの平均値の絶対値に応じて自動調整するオプションです。`--noise_offset` と同時に指定することで有効になります。Noise offsetの値は `noise_offset + abs(mean(latents, dim=(2,3))) * adaptive_noise_scale` で計算されます。latentは正規分布に近いためnoise_offsetの1/10~同程度の値を指定するとよいかもしれません。
532
+
533
+ 負の値も指定でき、その場合はnoise offsetは0以上にclipされます。
534
+
535
+ - `--multires_noise_iterations` / `--multires_noise_discount`
536
+
537
+ Multi resolution noise (pyramid noise)の設定です。詳細は [PR#471](https://github.com/kohya-ss/sd-scripts/pull/471) およびこちらのページ [Multi-Resolution Noise for Diffusion Model Training](https://wandb.ai/johnowhitaker/multires_noise/reports/Multi-Resolution-Noise-for-Diffusion-Model-Training--VmlldzozNjYyOTU2) を参照してください。
538
+
539
+ `--multires_noise_iterations` に数値を指定すると有効になります。6~10程度の値が良いようです。`--multires_noise_discount` に0.1~0.3 程度の値(LoRA学習等比較的データセットが小さい場合のPR作者の推奨)、ないしは0.8程度の値(元記事の推奨)を指定してください(デフォルトは 0.3)。
540
+
541
+ - `--debug_dataset`
542
+
543
+ このオプションを付けることで学習を行う前に事前にどのような画像データ、キャプションで学習されるかを確認できます。Escキーを押すと終了してコマンドラインに戻ります。`S`キーで次のステップ(バッチ)、`E`キーで次のエポックに進みます。
544
+
545
+ ※Linux環境(Colabを含む)では画像は表示されません。
546
+
547
+ - `--vae`
548
+
549
+ vaeオプションにStable Diffusionのcheckpoint、VAEのcheckpointファイル、DiffusesのモデルまたはVAE(ともにローカルまたはHugging FaceのモデルIDが指定できます)のいずれかを指定すると、そのVAEを使って学習します(latentsのキャッシュ時または学習中のlatents取得時)。
550
+
551
+ DreamBoothおよびfine tuningでは、保存されるモデルはこのVAEを組み込んだものになります。
552
+
553
+ - `--cache_latents` / `--cache_latents_to_disk`
554
+
555
+ 使用VRAMを減らすためVAEの出力をメインメモリにキャッシュします。`flip_aug` 以外のaugmentationは使えなくなります。また全体の学習速度が若干速くなります。
556
+
557
+ cache_latents_to_diskを指定するとキャッシュをディスクに保存します。スクリプトを終了し、再度起動した場合もキャッシュが有効になります。
558
+
559
+ - `--min_snr_gamma`
560
+
561
+ Min-SNR Weighting strategyを指定します。詳細は[こちら](https://github.com/kohya-ss/sd-scripts/pull/308)を参照してください。論文では`5`が推奨されています。
562
+
563
+ ## モデルの保存に関する設定
564
+
565
+ - `--save_precision`
566
+
567
+ 保存時のデータ精度を指定します。save_precisionオプションにfloat、fp16、bf16のいずれかを指定すると、その形式でモデルを保存します(DreamBooth、fine tuningでDiffusers形式でモデルを保存する場合は無効です)。モデルのサイズを削減したい場合などにお使いください。
568
+
569
+ - `--save_every_n_epochs` / `--save_state` / `--resume`
570
+
571
+ save_every_n_epochsオプションに数値を指定すると、そのエポックごとに学習途中のモデルを保存します。
572
+
573
+ save_stateオプションを同時に指定すると、optimizer等の状態も含めた学習状態を合わせて保存します(保存したモデルからも学習再開できますが、それに比べると精度の向上、学習時間の短縮が期待できます)。保存先はフォルダになります。
574
+
575
+ 学習状態は保存先フォルダに `<output_name>-??????-state`(??????はエポック数)という名前のフォルダで出力されます。長時間にわたる学習時にご利用ください。
576
+
577
+ 保存された学習状態から学習を再開するにはresumeオプションを使います。学習状態のフォルダ(`output_dir` ではなくその中のstateのフォルダ)を指定してください。
578
+
579
+ なおAcceleratorの仕様により、エポック数、global stepは保存されておらず、resumeしたときにも1からになりますがご容赦ください。
580
+
581
+ - `--save_every_n_steps`
582
+
583
+ save_every_n_stepsオプションに数値を指定すると、そのステップごとに学習途中のモデルを保存します。save_every_n_epochsと同時に指定できます。
584
+
585
+ - `--save_model_as` (DreamBooth, fine tuning のみ)
586
+
587
+ モデルの保存形式を`ckpt, safetensors, diffusers, diffusers_safetensors` から選べます。
588
+
589
+ `--save_model_as=safetensors` のように指定します。Stable Diffusion形式(ckptまたはsafetensors)を読み込み、Diffusers形式で保存する場合、不足する情報はHugging Faceからv1.5またはv2.1の情報を落としてきて補完します。
590
+
591
+ - `--huggingface_repo_id` 等
592
+
593
+ huggingface_repo_idが指定されているとモデル保存時に同時にHuggingFaceにアップロードします。アクセストークンの取り扱いに注意してください(HuggingFaceのドキュメントを参照してください)。
594
+
595
+ 他の引数をたとえば以下のように指定してください。
596
+
597
+ - `--huggingface_repo_id "your-hf-name/your-model" --huggingface_path_in_repo "path" --huggingface_repo_type model --huggingface_repo_visibility private --huggingface_token hf_YourAccessTokenHere`
598
+
599
+ huggingface_repo_visibilityに`public`を指定するとリポジトリが公開されます。省略時または`private`(などpublic以外)を指定すると非公開になります。
600
+
601
+ `--save_state`オプション指定時に`--save_state_to_huggingface`を指定するとstateもアップロードします。
602
+
603
+ `--resume`オプション指定時に`--resume_from_huggingface`を指定するとHuggingFaceからstateをダウンロードして再開します。その時の --resumeオプションは `--resume {repo_id}/{path_in_repo}:{revision}:{repo_type}`になります。
604
+
605
+ 例: `--resume_from_huggingface --resume your-hf-name/your-model/path/test-000002-state:main:model`
606
+
607
+ `--async_upload`オプションを指定するとアップロードを非同期で行います。
608
+
609
+ ## オプティマイザ関係
610
+
611
+ - `--optimizer_type`
612
+ --オプティマイザの種類を指定します。以下が指定できます。
613
+ - AdamW : [torch.optim.AdamW](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html)
614
+ - 過去のバージョンのオプション未指定時と同じ
615
+ - AdamW8bit : 引数は同上
616
+ - PagedAdamW8bit : 引数は同上
617
+ - 過去のバージョンの--use_8bit_adam指定時と同じ
618
+ - Lion : https://github.com/lucidrains/lion-pytorch
619
+ - 過去のバージョンの--use_lion_optimizer指定時と同じ
620
+ - Lion8bit : 引数は同上
621
+ - PagedLion8bit : 引数は同上
622
+ - SGDNesterov : [torch.optim.SGD](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html), nesterov=True
623
+ - SGDNesterov8bit : 引数は同上
624
+ - DAdaptation(DAdaptAdamPreprint) : https://github.com/facebookresearch/dadaptation
625
+ - DAdaptAdam : 引数は同上
626
+ - DAdaptAdaGrad : 引数は同上
627
+ - DAdaptAdan : 引数は同上
628
+ - DAdaptAdanIP : 引数は同上
629
+ - DAdaptLion : 引数は同上
630
+ - DAdaptSGD : 引数は同上
631
+ - Prodigy : https://github.com/konstmish/prodigy
632
+ - AdaFactor : [Transformers AdaFactor](https://huggingface.co/docs/transformers/main_classes/optimizer_schedules)
633
+ - 任意のオプティマイザ
634
+
635
+ - `--learning_rate`
636
+
637
+ 学習率を指定します。適切な学習率は学習スクリプトにより異なりますので、それぞれの説明を参照してください。
638
+
639
+ - `--lr_scheduler` / `--lr_warmup_steps` / `--lr_scheduler_num_cycles` / `--lr_scheduler_power`
640
+
641
+ 学習率のスケジューラ関連の指定です。
642
+
643
+ lr_schedulerオプションで学習率のスケジューラをlinear, cosine, cosine_with_restarts, polynomial, constant, constant_with_warmup, 任意のスケジューラから選べます。デフォルトはconstantです。
644
+
645
+ lr_warmup_stepsでスケジューラのウォームアップ(だんだん学習率を変えていく)ステップ数を指定できます。
646
+
647
+ lr_scheduler_num_cycles は cosine with restartsスケジューラでのリスタート回数、lr_scheduler_power は polynomialスケジューラでのpolynomial power です。
648
+
649
+ 詳細については各自お調べください。
650
+
651
+ 任意のスケジューラを使う場合、任意のオプティマイザと同様に、`--scheduler_args`でオプション引数を指定してください。
652
+
653
+ ### オプティマイザの指定について
654
+
655
+ オプティマイザのオプション引数は--optimizer_argsオプションで指定してください。key=valueの形式で、複数の値が指定できます。また、valueはカンマ区切りで複数の値が指定できます。たとえばAdamWオプティマイザに引数を指定する場合は、``--optimizer_args weight_decay=0.01 betas=.9,.999``のようになります。
656
+
657
+ オプション引数を指定する場合は、それぞれのオプティマイザの仕様をご確認ください。
658
+
659
+ 一部のオプティマイザで��必須の引数があり、省略すると自動的に追加されます(SGDNesterovのmomentumなど)。コンソールの出力を確認してください。
660
+
661
+ D-Adaptationオプティマイザは学習率を自動調整します。学習率のオプションに指定した値は学習率そのものではなくD-Adaptationが決定した学習率の適用率になりますので、通常は1.0を指定してください。Text EncoderにU-Netの半分の学習率を指定したい場合は、``--text_encoder_lr=0.5 --unet_lr=1.0``と指定します。
662
+
663
+ AdaFactorオプティマイザはrelative_step=Trueを指定すると学習率を自動調整できます(省略時はデフォルトで追加されます)。自動調整する場合は学習率のスケジューラにはadafactor_schedulerが強制的に使用されます。またscale_parameterとwarmup_initを指定するとよいようです。
664
+
665
+ 自動調整する場合のオプション指定はたとえば ``--optimizer_args "relative_step=True" "scale_parameter=True" "warmup_init=True"`` のようになります。
666
+
667
+ 学習率を自動調整しない場合はオプション引数 ``relative_step=False`` を追加してください。その場合、学習率のスケジューラにはconstant_with_warmupが、また勾配のclip normをしないことが推奨されているようです。そのため引数は ``--optimizer_type=adafactor --optimizer_args "relative_step=False" --lr_scheduler="constant_with_warmup" --max_grad_norm=0.0`` のようになります。
668
+
669
+ ### 任意のオプティマイザを使う
670
+
671
+ ``torch.optim`` のオプティマイザを使う場合にはクラス名のみを(``--optimizer_type=RMSprop``など)、他のモジュールのオプティマイザを使う時は「モジュール名.クラス名」を指定してください(``--optimizer_type=bitsandbytes.optim.lamb.LAMB``など)。
672
+
673
+ (内部でimportlibしているだけで動作は未確認です。必要ならパッケージをインストールしてください。)
674
+
675
+
676
+ <!--
677
+ ## 任意サイズの画像での学習 --resolution
678
+ 正方形以外で学習できます。resolutionに「448,640」のように「幅,高さ」で指定してください。幅と高さは64で割り切れる必要があります。学習用画像、正則化画像のサイズを合わせてください。
679
+
680
+ 個人的には縦長の画像を生成することが多いため「448,640」などで学習することもあります。
681
+
682
+ ## Aspect Ratio Bucketing --enable_bucket / --min_bucket_reso / --max_bucket_reso
683
+ enable_bucketオプションを指定すると有効になります。Stable Diffusionは512x512で学習されていますが、それに加えて256x768や384x640といった解像度でも学習します。
684
+
685
+ このオプションを指定した場合は、学習用画像、正則化画像を特定の解像度に統一する必要はありません。いくつかの解像度(アスペクト比)から最適なものを選び、その解像度で学習します。
686
+ 解像度は64ピクセル単位のため、元画像とアスペクト比が完全に一致しない場合がありますが、その場合は、はみ出した部分がわずかにトリミングされます。
687
+
688
+ 解像度の最小サイズをmin_bucket_resoオプションで、最大サイズをmax_bucket_resoで指定できます。デフォルトはそれぞれ256、1024です。
689
+ たとえば最小サイズに384を指定すると、256x1024や320x768などの解像度は使わなくなります。
690
+ 解像度を768x768のように大きくした場合、最大サイズに1280などを指定しても良いかもしれません。
691
+
692
+ なおAspect Ratio Bucketingを有効にするときには、正則化画像についても、学習用画像と似た傾向の様々な解像度を用意した方がいいかもしれません。
693
+
694
+ (ひとつのバッチ内の画像が学習用画像、正則化画像に偏らなくなるため。そこまで大きな影響はないと思いますが……。)
695
+
696
+ ## augmentation --color_aug / --flip_aug
697
+ augmentationは学習時に動的にデータを変化させることで、モデルの性能を上げる手法です。color_augで色合いを微妙に変えつつ、flip_augで左右反転をしつつ、学習します。
698
+
699
+ 動的にデータを変化させるため、cache_latentsオプションと同時に指定できません。
700
+
701
+
702
+ ## 勾配をfp16とした学習(実験的機能) --full_fp16
703
+ full_fp16オプションを指定すると勾配を通常のfloat32からfloat16(fp16)に変更して学習します(mixed precisionではなく完全なfp16学習になるようです)。
704
+ これによりSD1.xの512x512サイズでは8GB未満、SD2.xの512x512サイズで12GB未満のVRAM使用量で学習できるようです。
705
+
706
+ あらかじめaccelerate configでfp16を指定し、オプションで ``mixed_precision="fp16"`` としてください(bf16では動作しません)。
707
+
708
+ メモリ���用量を最小化するためには、xformers、use_8bit_adam、cache_latents、gradient_checkpointingの各オプションを指定し、train_batch_sizeを1としてください。
709
+
710
+ (余裕があるようならtrain_batch_sizeを段階的に増やすと若干精度が上がるはずです。)
711
+
712
+ PyTorchのソースにパッチを当てて無理やり実現しています(PyTorch 1.12.1と1.13.0で確認)。精度はかなり落ちますし、途中で学習失敗する確率も高くなります。
713
+ 学習率やステップ数の設定もシビアなようです。それらを認識したうえで自己責任でお使いください。
714
+
715
+ -->
716
+
717
+ # メタデータファイルの作成
718
+
719
+ ## 教師データの用意
720
+
721
+ 前述のように学習させたい画像データを用意し、任意のフォルダに入れてください。
722
+
723
+ たとえば以下のように画像を格納します。
724
+
725
+ ![教師データフォルダのスクショ](https://user-images.githubusercontent.com/52813779/208907739-8e89d5fa-6ca8-4b60-8927-f484d2a9ae04.png)
726
+
727
+ ## 自動キャプショニング
728
+
729
+ キャプションを使わずタグだけで学習する場合はスキップしてください。
730
+
731
+ また手動でキャプションを用意する場合、キャプションは教師データ画像と同じディレクトリに、同じファイル名、拡張子.caption等で用意してください。各ファイルは1行のみのテキストファイルとします。
732
+
733
+ ### BLIPによるキャプショニング
734
+
735
+ 最新版ではBLIPのダウンロード、重みのダウンロード、仮想環境の追加は不要になりました。そのままで動作します。
736
+
737
+ finetuneフォルダ内のmake_captions.pyを実行します。
738
+
739
+ ```
740
+ python finetune\make_captions.py --batch_size <バッチサイズ> <教師データフォルダ>
741
+ ```
742
+
743
+ バッチサイズ8、教師データを親フォルダのtrain_dataに置いた場合、以下のようになります。
744
+
745
+ ```
746
+ python finetune\make_captions.py --batch_size 8 ..\train_data
747
+ ```
748
+
749
+ キャプションファイルが教師データ画像と同じディレクトリに、同じファイル名、拡張子.captionで作成されます。
750
+
751
+ batch_sizeはGPUのVRAM容量に応じて増減してください。大きいほうが速くなります(VRAM 12GBでももう少し増やせると思います)。
752
+ max_lengthオプションでキャプションの最大長を指定できます。デフォルトは75です。モデルをトークン長225で学習する場合には長くしても良いかもしれません。
753
+ caption_extensionオプションでキャプションの拡張子を変更できます。デフォルトは.captionです(.txtにすると後述のDeepDanbooruと競合します)。
754
+
755
+ 複数の教師データフォルダがある場合には、それぞれのフォルダに対して実行してください。
756
+
757
+ なお、推論にランダム性があるため、実行するたびに結果が変わります。固定する場合には--seedオプションで `--seed 42` のように乱数seedを指定してください。
758
+
759
+ その他のオプションは `--help` でヘルプをご参照ください(パラメータの意味についてはドキュメントがまとまっていないようで、ソースを見るしかないようです)。
760
+
761
+ デフォルトでは拡張子.captionでキャプションファイルが生成されます。
762
+
763
+ ![captionが生成されたフォルダ](https://user-images.githubusercontent.com/52813779/208908845-48a9d36c-f6ee-4dae-af71-9ab462d1459e.png)
764
+
765
+ たとえば以下のようなキャプションが付きます。
766
+
767
+ ![キャプションと画像](https://user-images.githubusercontent.com/52813779/208908947-af936957-5d73-4339-b6c8-945a52857373.png)
768
+
769
+ ## DeepDanbooruによるタグ付け
770
+
771
+ danbooruタグのタグ付け自体を行わない場合は「キャプションとタグ情報の前処理」に進んでください。
772
+
773
+ タグ付けはDeepDanbooruまたはWD14Taggerで行います。WD14Taggerのほうが精度が良いようです。WD14Taggerでタグ付けする場合は、次の章へ進んでください。
774
+
775
+ ### 環境整備
776
+
777
+ DeepDanbooru https://github.com/KichangKim/DeepDanbooru を作業フォルダにcloneしてくるか、zipをダウンロードして展開します。私はzipで展開しました。
778
+ またDeepDanbooruのReleasesのページ https://github.com/KichangKim/DeepDanbooru/releases の「DeepDanbooru Pretrained Model v3-20211112-sgd-e28」のAssetsから、deepdanbooru-v3-20211112-sgd-e28.zipをダウンロードしてきてDeepDanbooruのフォルダに展開します。
779
+
780
+ 以下からダウンロードします。Assetsをクリックして開き、そこからダウンロードします。
781
+
782
+ ![DeepDanbooruダウンロードページ](https://user-images.githubusercontent.com/52813779/208909417-10e597df-7085-41ee-bd06-3e856a1339df.png)
783
+
784
+ 以下のようなこういうディレクトリ構造に��てください
785
+
786
+ ![DeepDanbooruのディレクトリ構造](https://user-images.githubusercontent.com/52813779/208909486-38935d8b-8dc6-43f1-84d3-fef99bc471aa.png)
787
+
788
+ Diffusersの環境に必要なライブラリをインストールします。DeepDanbooruのフォルダに移動してインストールします(実質的にはtensorflow-ioが追加されるだけだと思います)。
789
+
790
+ ```
791
+ pip install -r requirements.txt
792
+ ```
793
+
794
+ 続いてDeepDanbooru自体をインストールします。
795
+
796
+ ```
797
+ pip install .
798
+ ```
799
+
800
+ 以上でタグ付けの環境整備は完了です。
801
+
802
+ ### タグ付けの実施
803
+ DeepDanbooruのフォルダに移動し、deepdanbooruを実行してタグ付けを行います。
804
+
805
+ ```
806
+ deepdanbooru evaluate <教師データフォルダ> --project-path deepdanbooru-v3-20211112-sgd-e28 --allow-folder --save-txt
807
+ ```
808
+
809
+ 教師データを親フォルダのtrain_dataに置いた場合、以下のようになります。
810
+
811
+ ```
812
+ deepdanbooru evaluate ../train_data --project-path deepdanbooru-v3-20211112-sgd-e28 --allow-folder --save-txt
813
+ ```
814
+
815
+ タグファイルが教師データ画像と同じディレクトリに、同じファイル名、拡張子.txtで作成されます。1件ずつ処理されるためわりと遅いです。
816
+
817
+ 複数の教師データフォルダがある場合には、それぞれのフォルダに対して実行してください。
818
+
819
+ 以下のように生成されます。
820
+
821
+ ![DeepDanbooruの生成ファイル](https://user-images.githubusercontent.com/52813779/208909855-d21b9c98-f2d3-4283-8238-5b0e5aad6691.png)
822
+
823
+ こんな感じにタグが付きます(すごい情報量……)。
824
+
825
+ ![DeepDanbooruタグと画像](https://user-images.githubusercontent.com/52813779/208909908-a7920174-266e-48d5-aaef-940aba709519.png)
826
+
827
+ ## WD14Taggerによるタグ付け
828
+
829
+ DeepDanbooruの代わりにWD14Taggerを用いる手順です。
830
+
831
+ Automatic1111氏のWebUIで使用しているtaggerを利用します。こちらのgithubページ(https://github.com/toriato/stable-diffusion-webui-wd14-tagger#mrsmilingwolfs-model-aka-waifu-diffusion-14-tagger )の情報を参考にさせていただきました。
832
+
833
+ 最初の環境整備で必要なモジュールはインストール済みです。また重みはHugging Faceから自動的にダウンロードしてきます。
834
+
835
+ ### タグ付けの実施
836
+
837
+ スクリプトを実行してタグ付けを行います。
838
+ ```
839
+ python tag_images_by_wd14_tagger.py --batch_size <バッチサイズ> <教師データフォルダ>
840
+ ```
841
+
842
+ 教師データを親フォルダのtrain_dataに置いた場合、以下のようになります。
843
+ ```
844
+ python tag_images_by_wd14_tagger.py --batch_size 4 ..\train_data
845
+ ```
846
+
847
+ 初回起動時にはモデルファイルがwd14_tagger_modelフォルダに自動的にダウンロードされます(フォルダはオプションで変えられます)。以下のようになります。
848
+
849
+ ![ダウンロードされたファイル](https://user-images.githubusercontent.com/52813779/208910447-f7eb0582-90d6-49d3-a666-2b508c7d1842.png)
850
+
851
+ タグファイルが教師データ画像と同じディレクトリに、同じファイル名、拡張子.txtで作成されます。
852
+
853
+ ![生成されたタグファイル](https://user-images.githubusercontent.com/52813779/208910534-ea514373-1185-4b7d-9ae3-61eb50bc294e.png)
854
+
855
+ ![タグと画像](https://user-images.githubusercontent.com/52813779/208910599-29070c15-7639-474f-b3e4-06bd5a3df29e.png)
856
+
857
+ threshオプションで、判定されたタグのconfidence(確信度)がいくつ以上でタグをつけるかが指定できます。デフォルトはWD14Taggerのサンプルと同じ0.35です。値を下げるとより多くのタグが付与されますが、精度は下がります。
858
+
859
+ batch_sizeはGPUのVRAM容量に応じて増減してください。大きいほうが速くなります(VRAM 12GBでももう少し増やせると思います)。caption_extensionオプションでタグファイルの拡張子を変更できます。デフォルトは.txtです。
860
+
861
+ model_dirオプションでモデルの保存先フォルダを指定できます。
862
+
863
+ またforce_downloadオプションを指定すると保存先フォルダがあってもモデルを再ダウンロードします。
864
+
865
+ 複数の教師データフォルダがある場合には、それぞれのフォルダに対して実行してください。
866
+
867
+ ## キャプションとタグ情報の前処理
868
+
869
+ スクリプトから処理しやすいようにキャプションとタグをメタデータとしてひとつのファイルにまとめます。
870
+
871
+ ### キャプションの前処理
872
+
873
+ キャプションをメタデータに入れるには、作業フォルダ内で以下を実行してください(キャプションを学習に使わない場合は実行不要です)(実際は1行で記述します、以下同様)。`--full_path` オプションを指定してメタデータに画像ファイルの場所をフルパスで格納します。このオプションを省略すると相対パスで記録されますが、フォルダ指定が `.toml` ファイル内で別途必要になります。
874
+
875
+ ```
876
+ python merge_captions_to_metadata.py --full_path <教師データフォルダ>
877
+   --in_json <読み込むメタデータファイル名> <メタデータファイル名>
878
+ ```
879
+
880
+ メタデータファイル名は任意の名前です。
881
+ 教師データがtrain_data、読み込むメタデータファイルなし、メタデータファイルがmeta_cap.jsonの場合、以下のようになります。
882
+
883
+ ```
884
+ python merge_captions_to_metadata.py --full_path train_data meta_cap.json
885
+ ```
886
+
887
+ caption_extensionオプションでキャプションの拡張子を指定できます。
888
+
889
+ 複数の教師データフォルダがある場合には、full_path引数を指定しつつ、それぞれのフォルダに対して実行してください。
890
+
891
+ ```
892
+ python merge_captions_to_metadata.py --full_path
893
+ train_data1 meta_cap1.json
894
+ python merge_captions_to_metadata.py --full_path --in_json meta_cap1.json
895
+ train_data2 meta_cap2.json
896
+ ```
897
+
898
+ in_jsonを省略すると書き込み先メタデータファイルがあるとそこから読み込み、そこに上書きします。
899
+
900
+ __※in_jsonオプションと書き込み先を都度書き換えて、別のメタデータファイルへ書き出すようにすると安全です。__
901
+
902
+ ### タグの前処理
903
+
904
+ 同様にタグもメタデータにまとめます(タグを学習に使わない場合は実行不要です)。
905
+ ```
906
+ python merge_dd_tags_to_metadata.py --full_path <教師データフォルダ>
907
+ --in_json <読み込むメタデータファイル名> <書き込むメタデータファイル名>
908
+ ```
909
+
910
+ 先と同じディレクトリ構成で、meta_cap.jsonを読み、meta_cap_dd.jsonに書きだす場合、以下となります。
911
+ ```
912
+ python merge_dd_tags_to_metadata.py --full_path train_data --in_json meta_cap.json meta_cap_dd.json
913
+ ```
914
+
915
+ 複数の教師データフォルダがある場合には、full_path引数を指定しつつ、それぞれのフォルダに対して実行してください。
916
+
917
+ ```
918
+ python merge_dd_tags_to_metadata.py --full_path --in_json meta_cap2.json
919
+ train_data1 meta_cap_dd1.json
920
+ python merge_dd_tags_to_metadata.py --full_path --in_json meta_cap_dd1.json
921
+ train_data2 meta_cap_dd2.json
922
+ ```
923
+
924
+ in_jsonを省略すると書き込み先メタデータファイルがあるとそこから読み込み、そこに上書きします。
925
+
926
+ __※in_jsonオプションと書き込み先を都度書き換えて、別のメタデータファイルへ書き出すようにすると安全です。__
927
+
928
+ ### キャプションとタグのクリーニング
929
+
930
+ ここまででメタデータファイルにキャプションとDeepDanbooruのタグがまとめられています。ただ自動キャプショニングにしたキャプションは表記ゆれなどがあり微妙(※)ですし、タグにはアンダースコアが含まれていたりratingが付いていたりしますので(DeepDanbooruの場合)、エディタの置換機能などを用いてキャプションとタグのクリーニングをしたほうがいいでしょう。
931
+
932
+ ※たとえばアニメ絵の少女を学習する場合、キャプションにはgirl/girls/woman/womenなどのばらつきがあります。また「anime girl」なども単に「girl」としたほうが適切かもしれません。
933
+
934
+ クリーニング用のスクリプトが用意してありますので、スクリプトの内容を状況に応じて編集してお使いください。
935
+
936
+ (教師データフォルダの指定は不要になりました。メタデータ内の全データをクリーニングします。)
937
+
938
+ ```
939
+ python clean_captions_and_tags.py <読み込むメタデータファイル名> <書き込むメタデータファイル名>
940
+ ```
941
+
942
+ --in_jsonは付きませんのでご注意ください。たとえば次のようになります。
943
+
944
+ ```
945
+ python clean_captions_and_tags.py meta_cap_dd.json meta_clean.json
946
+ ```
947
+
948
+ 以上でキャプションとタグの前処理は完了です。
949
+
950
+ ## latentsの事前取得
951
+
952
+ ※ このステップは必須ではありません。省略しても学習時にlatentsを取得しながら学習できます。
953
+ また学習時に `random_crop` や `color_aug` などを行う場合にはlatentsの事前取得はできません(画像を毎回変えながら学習するため)。事前取得をしない場合、ここまでのメタデータで学習できます。
954
+
955
+ あらかじめ画像の潜在表現を取得しディスクに保存しておきます。それにより、学習を高速に進めることができます。あわせてbucketing(教師データをアスペクト比に応じて分類する)を行います。
956
+
957
+ 作業フォルダで以下のように入力してください。
958
+ ```
959
+ python prepare_buckets_latents.py --full_path <教師データフォルダ>
960
+ <読み込むメタデータファイル名> <書き込むメタデータファイル名>
961
+ <fine tuningするモデル名またはcheckpoint>
962
+ --batch_size <バッチサイズ>
963
+ --max_resolution <解像度 幅,高さ>
964
+ --mixed_precision <精度>
965
+ ```
966
+
967
+ モデルがmodel.ckpt、バッチサイズ4、学習解像度は512\*512、精度no(float32)で、meta_clean.jsonからメタデータを読み込み、meta_lat.jsonに書き込む場合、以下のようになります。
968
+
969
+ ```
970
+ python prepare_buckets_latents.py --full_path
971
+ train_data meta_clean.json meta_lat.json model.ckpt
972
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
973
+ ```
974
+
975
+ 教師データフォルダにnumpyのnpz形式でlatentsが保存されます。
976
+
977
+ 解像度の最小サイズを--min_bucket_resoオプションで、最大サイズを--max_bucket_resoで指定できます。デフォルトはそれぞれ256、1024です。たとえば最小サイズに384を指定すると、256\*1024や320\*768などの解像度は使わなくなります。
978
+ 解像度を768\*768のように大きくした場合、最大サイズに1280などを指定すると良いでしょう。
979
+
980
+ --flip_augオプションを指定すると左右反転のaugmentation(データ拡張)を行います。疑似的にデータ量を二倍に増やすことができますが、データが左右対称でない場合に指定すると(例えばキャラクタの外見、髪型など)学習がうまく行かなくなります。
981
+
982
+
983
+ (反転した画像についてもlatentsを取得し、\*\_flip.npzファイルを保存する単純な実装です。fline_tune.pyには特にオプション指定は必要ありません。\_flip付きのファイルがある場合、flip付き・なしのファイルを、ランダムに読み込みます。)
984
+
985
+ バッチサイズはVRAM 12GBでももう少し増やせるかもしれません。
986
+ 解像度は64で割り切れる数字で、"幅,高さ"で指定します。解像度はfine tuning時のメモリサイズに直結します。VRAM 12GBでは512,512が限界と思われます(※)。16GBなら512,704や512,768まで上げられるかもしれません。なお256,256等にしてもVRAM 8GBでは厳しいようです(パラメータやoptimizerなどは解像度に関係せず一定のメモリが必要なため)。
987
+
988
+ ※batch size 1の学習で12GB VRAM、640,640で動いたとの報告もありました。
989
+
990
+ 以下のようにbucketingの結果が表示されます。
991
+
992
+ ![bucketingの結果](https://user-images.githubusercontent.com/52813779/208911419-71c00fbb-2ce6-49d5-89b5-b78d7715e441.png)
993
+
994
+ 複数の教師データフォルダがある場合には、full_path引数を指定しつつ、それぞれのフォルダに対して実行してください。
995
+ ```
996
+ python prepare_buckets_latents.py --full_path
997
+ train_data1 meta_clean.json meta_lat1.json model.ckpt
998
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
999
+
1000
+ python prepare_buckets_latents.py --full_path
1001
+ train_data2 meta_lat1.json meta_lat2.json model.ckpt
1002
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
1003
+
1004
+ ```
1005
+ 読み込み元と書き込み先を同じにすることも可能ですが別々の方が安全です。
1006
+
1007
+ __※引数を都度書き換えて、別のメタデータファイルに書き込むと安全です。__
1008
+
docs/train_README-zh.md ADDED
@@ -0,0 +1,912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __由于文档正在更新中,描述可能有错误。__
2
+
3
+ # 关于训练,通用描述
4
+ 本库支持模型微调(fine tuning)、DreamBooth、训练LoRA和文本反转(Textual Inversion)(包括[XTI:P+](https://github.com/kohya-ss/sd-scripts/pull/327)
5
+
6
+ 本文档将说明它们通用的训练数据准备方法和选项等。
7
+
8
+ # 概要
9
+
10
+ 请提前参考本仓库的README,准备好环境。
11
+
12
+
13
+ 以下本节说明。
14
+
15
+ 1. 准备训练数据(使用设置文件的新格式)
16
+ 1. 训练中使用的术语的简要解释
17
+ 1. 先前的指定格式(不使用设置文件,而是从命令行指定)
18
+ 1. 生成训练过程中的示例图像
19
+ 1. 各脚本中常用的共同选项
20
+ 1. 准备 fine tuning 方法的元数据:如说明文字(打标签)等
21
+
22
+
23
+ 1. 如果只执行一次,训练就可以进行(相关内容,请参阅各个脚本的文档)。如果需要,以后可以随时参考。
24
+
25
+
26
+
27
+ # 关于准备训练数据
28
+
29
+ 在任意文件夹(也可以是多个文件夹)中准备好训练数据的图像文件。支持 `.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp` 格式的文件。通常不需要进行任何预处理,如调整大小等。
30
+
31
+ 但是请勿使用极小的图像,若其尺寸比训练分辨率(稍后将提到)还小,建议事先使用超分辨率AI等进行放大。另外,请注意不要使用过大的图像(约为3000 x 3000像素以上),因为这可能会导致错误,建议事先缩小。
32
+
33
+ 在训练时,需要整理要用于训练模型的图像数据,并将其指定给脚本。根据训练数据的数量、训练目标和说明(图像描述)是否可用等因素,可以使用几种方法指定训练数据。以下是其中的一些方法(每个名称都不是通用的,而是该存储库自定义的定义)。有关正则化图像的信息将在稍后提供。
34
+
35
+ 1. DreamBooth、class + identifier方式(可使用正则化图像)
36
+
37
+ 将训练目标与特定单词(identifier)相关联进行训练。无需准备说明。例如,当要学习特定角色时,由于无需准备说明,因此比较方便,但由于训练数据的所有元素都与identifier相关联,例如发型、服装、背景等,因此在生成时可能会出现无法更换服装的情况。
38
+
39
+ 2. DreamBooth、说明方式(可使用正则化图像)
40
+
41
+ 事先给每个图片写说明(caption),存放到文本文件中,然后进行训练。例如,通过将图像详细信息(如穿着白色衣服的角色A、穿着红色衣服的角色A等)记录在caption中,可以将角色和其他元素分离,并期望模型更准确地学习角色。
42
+
43
+ 3. 微调方式(不可使用正则化图像)
44
+
45
+ 先将说明收集到元数据文件中。支持分离标签和说明以及预先缓存latents等功能,以加速训练(这些将在另一篇文档中介绍)。(虽然名为fine tuning方式,但不仅限于fine tuning。)
46
+
47
+ 训练对象和你可以使用的规范方法的组合如下。
48
+
49
+ | 训练对象或方法 | 脚本 | DB/class+identifier | DB/caption | fine tuning |
50
+ |----------------| ----- | ----- | ----- | ----- |
51
+ | fine tuning微调模型 | `fine_tune.py`| x | x | o |
52
+ | DreamBooth训练模型 | `train_db.py`| o | o | x |
53
+ | LoRA | `train_network.py`| o | o | o |
54
+ | Textual Invesion | `train_textual_inversion.py`| o | o | o |
55
+
56
+ ## 选择哪一个
57
+
58
+ 如果您想要训练LoRA、Textual Inversion而不需要准备说明(caption)文件,则建议使用DreamBooth class+identifier。如果您能够准备caption文件,则DreamBooth Captions方法更好。如果您有大量的训练数据并且不使用正则化图像,则请考虑使用fine-tuning方法。
59
+
60
+ 对于DreamBooth也是一样的,但不能使用fine-tuning方法。若要进行微调,只能使用fine-tuning方式。
61
+
62
+ # 每种方法的指定方式
63
+
64
+ 在这里,我们只介绍每种指定方法的典型模式。有关更详细的指定方法,请参见[数据集设置](./config_README-ja.md)。
65
+
66
+ # DreamBooth,class+identifier方法(可使用正则化图像)
67
+
68
+ 在该方法中,每个图像将被视为使用与 `class identifier` 相同的标题进行训练(例如 `shs dog`)。
69
+
70
+ 这样一来,每张图片都相当于使用标题“分类标识”(例如“shs dog”)进行训练。
71
+
72
+ ## step 1.确定identifier和class
73
+
74
+ 要将训练的目标与identifier和属于该目标的class相关联。
75
+
76
+ (虽然有很多称呼,但暂时按照原始论文的说法。)
77
+
78
+ 以下是简要说明(请查阅详细信息)。
79
+
80
+ class是训练目标的一般类别。例如,如果要学习特定品种的狗,则class将是“dog”。对于动漫角色,根据模型不同,可能是“boy”或“girl”,也可能是“1boy”或“1girl”。
81
+
82
+ identifier是用于识别训练目标并进行学习的单词。可以使用任何单词,但是根据原始论文,“Tokenizer生成的3个或更少字符的罕见单词”是最好的选择。
83
+
84
+ 使用identifier和class,例如,“shs dog”可以将模型训练为从class中识别并学习所需的目标。
85
+
86
+ 在图像生成时,使用“shs dog”将生成所学习狗种的图像。
87
+
88
+ (作为identifier,我最近使用的一些参考是“shs sts scs cpc coc cic msm usu ici lvl cic dii muk ori hru rik koo yos wny”等。最好是不包含在Danbooru标签中的单词。)
89
+
90
+ ## step 2. 决定是否使用正则化图像,并在使用时生成正则化图像
91
+
92
+ 正则化图像是为防止前面提到的语言漂移,即整个类别被拉扯成为训练目标而生成的图像。如果不使用正则化图像,例如在 `shs 1girl` 中学习特定角色时,即使在简单的 `1girl` 提示下生成,也会越来越像该角色。这是因为 `1girl` 在训练时的标题中包含了该角色的信息。
93
+
94
+ 通过同时学习目标图像和正则化图像,类别仍然保持不变,仅在将标识符附加到提示中时才生成目标图像。
95
+
96
+ 如果您只想在LoRA或DreamBooth中使用特定的角色,则可以不使用正则化图像。
97
+
98
+ 在Textual Inversion中也不需要使用(如果要学习的token string不包含在标题中,则不会学习任何内容)。
99
+
100
+ 一般情况下,使用在训练目标模型时只使用类别名称生成的图像作为正则化图像是常见的做法(例如 `1girl`)。但是,如果生成的图像质量不佳,可以尝试修改提示或使用从网络上另外下载的图像。
101
+
102
+ (由于正则化图像也被训练,因此其质量会影响模型。)
103
+
104
+ 通常,准备数百张图像是理想的(图像数量太少会导致类别图像无法被归纳,特征也不会被学习)。
105
+
106
+ 如果要使用生成的图像,生成图像的大小通常应与训练分辨率(更准确地说,是bucket的分辨率,见下文)相匹配。
107
+
108
+
109
+
110
+ ## step 2. 设置文件的描述
111
+
112
+ 创建一个文本文件,并将其扩展名更改为`.toml`。例如,您可以按以下方式进行描述:
113
+
114
+ (以`#`开头的部分是注释,因此您可以直接复制粘贴,或者将其删除。)
115
+
116
+ ```toml
117
+ [general]
118
+ enable_bucket = true # 是否使用Aspect Ratio Bucketing
119
+
120
+ [[datasets]]
121
+ resolution = 512 # 训练分辨率
122
+ batch_size = 4 # 批次大小
123
+
124
+ [[datasets.subsets]]
125
+ image_dir = 'C:\hoge' # 指定包含训练图像的文件夹
126
+ class_tokens = 'hoge girl' # 指定标识符类
127
+ num_repeats = 10 # 训练图像的重复次数
128
+
129
+ # 以下仅在使用正则化图像时进行描述。不使用则删除
130
+ [[datasets.subsets]]
131
+ is_reg = true
132
+ image_dir = 'C:\reg' # 指定包含正则化图像的文件夹
133
+ class_tokens = 'girl' # 指定class
134
+ num_repeats = 1 # 正则化图像的重复次数,基本上1就可以了
135
+ ```
136
+
137
+ 基本上只需更改以下几个地方即可进行训练。
138
+
139
+ 1. 训练分辨率
140
+
141
+ 指定一个数字表示正方形(如果是 `512`,则为 512x512),如果使用方括号和逗号分隔的两个数字,则表示横向×纵向(如果是`[512,768]`,则为 512x768)。在SD1.x系列中,原始训练分辨率为512。指定较大的分辨率,如 `[512,768]` 可能会减少纵向和横向图像生成时的错误。在SD2.x 768系列中,分辨率为 `768`。
142
+
143
+ 1. 批次大小
144
+
145
+ 指定同时训练多少个数据。这取决于GPU的VRAM大小和训练分辨率。详细信息将在后面说明。此外,fine tuning/DreamBooth/LoRA等也会影响批次大小,请查看各个脚本的说明。
146
+
147
+ 1. 文件夹指定
148
+
149
+ 指定用于学习的图像和正则化图像(仅在使用时)的文件夹。指定包含图像数据的文件夹。
150
+
151
+ 1. identifier 和 class 的指定
152
+
153
+ 如前所述,与示例相同。
154
+
155
+ 1. 重复次数
156
+
157
+ 将在后面说明。
158
+
159
+ ### 关于重复次数
160
+
161
+ 重复次数用于调整正则化图像和训练用图像的数量。由于正则化图像的数量多于训练用图像,因此需要重复使用训练用图像来达到一对一的比例,从而实现训练。
162
+
163
+ 请将重复次数指定为“ __训练用图像的重复次数×训练用图像的数量≥正则化图像的重复次数×正则化图像的数量__ ”。
164
+
165
+ (1个epoch(指训练数据过完一遍)的数据量为“训练用图像的重复次数×训练用图像的数量”。如果正则化图像的数量多于这个值,则剩余的正则化图像将不会被使用。)
166
+
167
+ ## 步骤 3. 训练
168
+
169
+ 详情请参考相关文档进行训练。
170
+
171
+ # DreamBooth,文本说明(caption)方式(可使用正则化图像)
172
+
173
+ 在此方式中,每个图像都将通过caption进行训练。
174
+
175
+ ## 步骤 1. 准备文本说明文件
176
+
177
+ 请将与图像具有相同文件名且扩展名为 `.caption`(可以在设置中更改)的文件放置在用于训练图像的文件夹中。每个文件应该只有一行。编码为 `UTF-8`。
178
+
179
+ ## 步骤 2. 决定是否使用正则化图像,并在使用时生成正则化图像
180
+
181
+ 与class+identifier格式相同。可以在规范化图像上附加caption,但通常不需要。
182
+
183
+ ## 步骤 2. 编写设置文件
184
+
185
+ 创建一个文本文件并将扩展名更改为 `.toml`。例如,您可以按以下方式进行描述:
186
+
187
+ ```toml
188
+ [general]
189
+ enable_bucket = true # 是否使用Aspect Ratio Bucketing
190
+
191
+ [[datasets]]
192
+ resolution = 512 # 训练分辨率
193
+ batch_size = 4 # 批次大小
194
+
195
+ [[datasets.subsets]]
196
+ image_dir = 'C:\hoge' # 指定包含训练图像的文件夹
197
+ caption_extension = '.caption' # 若使用txt文件,更改此项
198
+ num_repeats = 10 # 训练图像的重复次数
199
+
200
+ # 以下仅在使用正则化图像时进行描述。不使用则删除
201
+ [[datasets.subsets]]
202
+ is_reg = true
203
+ image_dir = 'C:\reg' # 指定包含正则化图像的文件夹
204
+ class_tokens = 'girl' # 指定class
205
+ num_repeats = 1 # 正则化图像的重复次数,基本上1就可以了
206
+ ```
207
+
208
+ 基本上只需更改以下几个地方来训练。除非另有说明,否则与class+identifier方法相同。
209
+
210
+ 1. 训练分辨率
211
+ 2. 批次大小
212
+ 3. 文件夹指定
213
+ 4. caption文件的扩展名
214
+
215
+ 可以指定任意的扩展名。
216
+ 5. 重复次数
217
+
218
+ ## 步骤 3. 训练
219
+
220
+ 详情请参考相关文档进行训练。
221
+
222
+ # 微调方法(fine tuning)
223
+
224
+ ## 步骤 1. 准备元数据
225
+
226
+ 将caption和标签整合到管理文件中称为元数据。它的扩展名为 `.json`,格式为json。由于创建方法较长,因此在本文档的末尾进行描述。
227
+
228
+ ## 步骤 2. 编写设置文件
229
+
230
+ 创建一个文本文件,将扩展名设置为 `.toml`。例如,可以按以下方式编写:
231
+ ```toml
232
+ [general]
233
+ shuffle_caption = true
234
+ keep_tokens = 1
235
+
236
+ [[datasets]]
237
+ resolution = 512 # 图像分辨率
238
+ batch_size = 4 # 批次大小
239
+
240
+ [[datasets.subsets]]
241
+ image_dir = 'C:\piyo' # 指定包含训练图像的文件夹
242
+ metadata_file = 'C:\piyo\piyo_md.json' # 元数据文件名
243
+ ```
244
+
245
+ 基本上只需更改以下几个地方来训练。除非另有说明,否则与DreamBooth, class+identifier方法相同。
246
+
247
+ 1. 训练分辨率
248
+ 2. 批次大小
249
+ 3. 指定文件夹
250
+ 4. 元数据文件名
251
+
252
+ 指定使用后面所述方法创建的元数据文件。
253
+
254
+
255
+ ## 第三步:训练
256
+
257
+ 详情请参考相关文档进行训练。
258
+
259
+ # 训练中使用的术语简单解释
260
+
261
+ 由于省略了细节并且我自己也没有完全理解,因此请自行查阅详细信息。
262
+
263
+ ## 微调(fine tuning)
264
+
265
+ 指训练模型并微调其性能。具体含义因用法而异,但在 Stable Diffusion 中,狭义的微调是指使用图像和caption进行训练模型。DreamBooth 可视为狭义微调的一种特殊方法。广义的微调包括 LoRA、Textual Inversion、Hypernetworks 等,包括训练模型的所有内容。
266
+
267
+ ## 步骤(step)
268
+
269
+ 粗略地说,每次在训练数据上进行一次计算即为一步。具体来说,“将训练数据的caption传递给当前模型,将生成的图像与训练数据的图像进行比较,稍微更改模型,以使其更接近训练数据”即为一步。
270
+
271
+ ## 批次大小(batch size)
272
+
273
+ 批次大小指定每个步骤要计算多少数据。批次计算可以提高速度。一般来说,批次大小越大,精度也越高。
274
+
275
+ “批次大小×步数”是用于训练的数据数量。因此,建议减少步数以增加批次大小。
276
+
277
+ (但是,例如,“批次大小为 1,步数为 1600”和“批次大小为 4,步数为 400”将不会产生相同的结果。如果使用相同的学习速率,通常后者会导致模型欠拟合。请尝试增加学习率(例如 `2e-6`),将步数设置为 500 等。)
278
+
279
+ 批次大小越大,GPU 内存消耗就越大。如果内存不足,将导致错误,或者在边缘时将导致训练速度降低。建议在任务管理器或 `nvidia-smi` 命令中检查使用的内存量进行调整。
280
+
281
+ 注意,一个批次是指“一个数据单位”。
282
+
283
+ ## 学习率
284
+
285
+ 学习率指的是每个步骤中改变的程度。如果指定一个大的值,学习速度就会加快,但是可能会出现变化太大导致模型崩溃或无法达到最佳状态的情况。如果指定一个小的值,学习速度会变慢,同时可能无法达到最佳状态。
286
+
287
+ 在fine tuning、DreamBooth、LoRA等过程中,学习率会有很大的差异,并且也会受到训练数据、所需训练的模型、批次大小和步骤数等因素的影响。建议从通常值开始,观察训练状态并逐渐调整。
288
+
289
+ 默认情况下,���个训练过程中学习率是固定的。但是可以通过调度程序指定学习率如何变化,因此结果也会有所不同。
290
+
291
+ ## Epoch
292
+
293
+ Epoch指的是训练数据被完整训练一遍(即数据已经迭代一轮)。如果指定了重复次数,则在重复后的数据迭代一轮后,为1个epoch。
294
+
295
+ 1个epoch的步骤数通常为“数据量÷批次大小”,但如果使用Aspect Ratio Bucketing,则略微增加(由于不同bucket的数据不能在同一个批次中,因此步骤数会增加)。
296
+
297
+ ## 长宽比分桶(Aspect Ratio Bucketing)
298
+
299
+ Stable Diffusion 的 v1 是以 512\*512 的分辨率进行训练的,但同时也可以在其他分辨率下进行训练,例如 256\*1024 和 384\*640。这样可以减少裁剪的部分,希望更准确地学习图像和标题之间的关系。
300
+
301
+ 此外,由于可以在任意分辨率下进行训练,因此不再需要事先统一图像数据的长宽比。
302
+
303
+ 此值可以被设定,其在此之前的配置文件示例中已被启用(设置为 `true`)。
304
+
305
+ 只要不超过作为参数给出的分辨率区域(= 内存使用量),就可以按 64 像素的增量(默认值,可更改)在垂直和水平方向上调整和创建训练分辨率。
306
+
307
+ 在机器学习中,通常需要将所有输入大小统一,但实际上只要在同一批次中统一即可。 NovelAI 所说的分桶(bucketing) 指的是,预先将训练数据按照长宽比分类到每个学习分辨率下,并通过使用每个 bucket 内的图像创建批次来统一批次图像大小。
308
+
309
+ # 以前的指定格式(不使用 .toml 文件,而是使用命令行选项指定)
310
+
311
+ 这是一种通过命令行选项而不是指定 .toml 文件的方法。有 DreamBooth 类+标识符方法、DreamBooth caption方法、微调方法三种方式。
312
+
313
+ ## DreamBooth、类+标识符方式
314
+
315
+ 指定文件夹名称以指定迭代次数。还要使用 `train_data_dir` 和 `reg_data_dir` 选项。
316
+
317
+ ### 第1步。准备用于训练的图像
318
+
319
+ 创建一个用于存储训练图像的文件夹。__此外__,按以下名称创建目录。
320
+
321
+ ```
322
+ <迭代次数>_<标识符> <类别>
323
+ ```
324
+
325
+ 不要忘记下划线``_``。
326
+
327
+ 例如,如果在名为“sls frog”的提示下重复数据 20 次,则为“20_sls frog”。如下所示:
328
+
329
+ ![image](https://user-images.githubusercontent.com/52813779/210770636-1c851377-5936-4c15-90b7-8ac8ad6c2074.png)
330
+
331
+ ### 多个类别、多个标识符的训练
332
+
333
+ 该方法很简单,在用于训练的图像文件夹中,需要准备多个文件夹,每个文件夹都是以“重复次数_<标识符> <类别>”命名的,同样,在正则化图像文件夹中,也需要准备多个文件夹,每个文件夹都是以“重复次数_<类别>”命名的。
334
+
335
+ 例如,如果要同时训练“sls青蛙”和“cpc兔子”,则应按以下方式准备文件夹。
336
+
337
+ ![image](https://user-images.githubusercontent.com/52813779/210777933-a22229db-b219-4cd8-83ca-e87320fc4192.png)
338
+
339
+ 如果一个类别包含多个对象,可以只使用一个正则化图像文件夹。例如,如果在1girl类别中有角色A和角色B,则可以按照以下方式处理:
340
+
341
+ - train_girls
342
+ - 10_sls 1girl
343
+ - 10_cpc 1girl
344
+ - reg_girls
345
+ - 1_1girl
346
+
347
+ ### step 2. 准备正规化图像
348
+
349
+ 这是使用正则化图像时的过程。
350
+
351
+ 创建一个文件夹来存储正则化的图像。 __此外,__ 创建一个名为``<repeat count>_<class>`` 的目录。
352
+
353
+ 例如,使用提示“frog”并且不重复数据(仅一次):
354
+ ![image](https://user-images.githubusercontent.com/52813779/210770897-329758e5-3675-49f1-b345-c135f1725832.png)
355
+
356
+
357
+ 步骤3. 执行训练
358
+
359
+ 执行每个训练脚本。使用 `--train_data_dir` 选项指定包含训练数据文件夹的父文件夹(不是包含图像的文件夹),使用 `--reg_data_dir` 选项指定包含正则化图像的父文件夹(不是包含图像的文件夹)。
360
+
361
+ ## DreamBooth,带文本说明(caption)的方式
362
+
363
+ 在包含训练图像和正则化图像的文件夹中,将与图像具有相同文件名的文件.caption(可以使用选项进行更改)放置在该文件夹中,然后从该文件中加载caption所作为提示进行训练。
364
+
365
+ ※文件夹名称(标识符类)不再用于这些图像的训练。
366
+
367
+ 默认的caption文件扩展名为.caption。可以使用训练脚本的 `--caption_extension` 选项进行更改。 使用 `--shuffle_caption` 选项,同时对每个逗号分隔的部分进行训练时会对训练时的caption进行混洗。
368
+
369
+ ## 微调方式
370
+
371
+ 创建元数据的方式与使用配置文件相同。 使用 `in_json` 选项指定元数据文件。
372
+
373
+ # 训练过程中的样本输出
374
+
375
+ 通过在训练中使用模型生成图像,可以检查训练进度。将以下选项指定为训练脚本。
376
+
377
+ - `--sample_every_n_steps` / `--sample_every_n_epochs`
378
+
379
+ 指定要采样的步数或epoch数。为这些数字中的每一个输出样本。如果两者都��定,则 epoch 数优先。
380
+ - `--sample_prompts`
381
+
382
+ 指定示例输出的提示文件。
383
+
384
+ - `--sample_sampler`
385
+
386
+ 指定用于采样输出的采样器。
387
+ `'ddim', 'pndm', 'heun', 'dpmsolver', 'dpmsolver++', 'dpmsingle', 'k_lms', 'k_euler', 'k_euler_a', 'k_dpm_2', 'k_dpm_2_a'`が選べます。
388
+
389
+ 要输出样本,您需要提前准备一个包含提示的文本文件。每行输入一个提示。
390
+
391
+ ```txt
392
+ # prompt 1
393
+ masterpiece, best quality, 1girl, in white shirts, upper body, looking at viewer, simple background --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 768 --h 768 --d 1 --l 7.5 --s 28
394
+
395
+ # prompt 2
396
+ masterpiece, best quality, 1boy, in business suit, standing at street, looking back --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 576 --h 832 --d 2 --l 5.5 --s 40
397
+ ```
398
+
399
+ 以“#”开头的行是注释。您可以使用“`--` + 小写字母”为生成的图像指定选项,例如 `--n`。您可以使用:
400
+
401
+ - `--n` 否定提示到下一个选项。
402
+ - `--w` 指定生成图像的宽度。
403
+ - `--h` 指定生成图像的高度。
404
+ - `--d` 指定生成图像的种子。
405
+ - `--l` 指定生成图像的 CFG 比例。
406
+ - `--s` 指定生成过程中的步骤数。
407
+
408
+
409
+ # 每个脚本通用的常用选项
410
+
411
+ 文档更新可能跟不上脚本更新。在这种情况下,请使用 `--help` 选项检查可用选项。
412
+ ## 学习模型规范
413
+
414
+ - `--v2` / `--v_parameterization`
415
+
416
+ 如果使用 Hugging Face 的 stable-diffusion-2-base 或来自它的微调模型作为学习目标模型(对于在推理时指示使用 `v2-inference.yaml` 的模型),`- 当使用-v2` 选项与 stable-diffusion-2、768-v-ema.ckpt 及其微调模型(对于在推理过程中使用 `v2-inference-v.yaml` 的模型),`- 指定两个 -v2`和 `--v_parameterization` 选项。
417
+
418
+ 以下几点在 Stable Diffusion 2.0 中发生了显着变化。
419
+
420
+ 1. 使用分词器
421
+ 2. 使用哪个Text Encoder,使用哪个输出层(2.0使用倒数第二层)
422
+ 3. Text Encoder的输出维度(768->1024)
423
+ 4. U-Net的结构(CrossAttention的头数等)
424
+ 5. v-parameterization(采样方式好像变了)
425
+
426
+ 其中base使用1-4,非base使用1-5(768-v)。使用 1-4 进行 v2 选择,使用 5 进行 v_parameterization 选择。
427
+ - `--pretrained_model_name_or_path`
428
+
429
+ 指定要从中执行额外训练的模型。您可以指定Stable Diffusion检查点文件(.ckpt 或 .safetensors)、diffusers本地磁盘上的模型目录或diffusers模型 ID(例如“stabilityai/stable-diffusion-2”)。
430
+ ## 训练设置
431
+
432
+ - `--output_dir`
433
+
434
+ 指定训练后保存模型的文件夹。
435
+
436
+ - `--output_name`
437
+
438
+ 指定不带扩展名的模型文件名。
439
+
440
+ - `--dataset_config`
441
+
442
+ 指定描述数据集配置的 .toml 文件。
443
+
444
+ - `--max_train_steps` / `--max_train_epochs`
445
+
446
+ 指定要训练的步数或epoch数。如果两者都指定,则 epoch 数优先。
447
+ -
448
+ - `--mixed_precision`
449
+
450
+ 训练混合精度以节省内存。指定像`--mixed_precision = "fp16"`。与无混合精度(默认)相比,精度可能较低,但训练所需的 GPU 内存明显较少。
451
+
452
+ (在RTX30系列以后也可以指定`bf16`,请配合您在搭建环境时做的加速设置)。
453
+ - `--gradient_checkpointing`
454
+
455
+ 通过逐步计算权重而不是在训练期间一次计算所有权重来减少训练所需的 GPU 内存量。关闭它不会影响准确性,但打开它允许更大的批次大小,所以那里有影响。
456
+
457
+ 另外,打开它通常会减慢速度,但可以增加批次大小,因此总的训练时间实际上可能会更快。
458
+
459
+ - `--xformers` / `--mem_eff_attn`
460
+
461
+ 当指定 xformers 选项时,使用 xformers 的 CrossAttention。如果未安装 xformers 或发生错误(取决于环境,例如 `mixed_precision="no"`),请指定 `mem_eff_attn` 选项而不是使用 CrossAttention 的内存节省版本(xformers 比 慢)。
462
+ - `--save_precision`
463
+
464
+ 指定保存时的数据精度。为 save_precision 选项指定 float、fp16 或 bf16 将以该格式保存模型(在 DreamBooth 中保存 Diffusers 格式时无效,微调)。当您想缩小模型的尺寸时请使用它。
465
+ - `--save_every_n_epochs` / `--save_state` / `--resume`
466
+ 为 save_every_n_epochs 选项指定一个数字可以在每个时期的训练期间保存模型。
467
+
468
+ 如果同时指定save_state选项,训练状态包括优化器的状态等都会一起保存。。保存目的地将是一个文件夹。
469
+
470
+ 训练状态输出到目标文件夹中名为“<output_name>-??????-state”(??????是epoch数)的文件夹中。长时间训练时请使用。
471
+
472
+ 使用 resume 选项从保存的训练状态恢复训练。指定训练状态文件夹(其中的状态文件夹,而不是 `output_dir`)。
473
+
474
+ 请注意,由于 Accelerator 规范,epoch 数和全局步数不会保��,即使恢复时它们也从 1 开始。
475
+ - `--save_model_as` (DreamBooth, fine tuning 仅有的)
476
+
477
+ 您可以从 `ckpt, safetensors, diffusers, diffusers_safetensors` 中选择模型保存格式。
478
+
479
+ - `--save_model_as=safetensors` 指定喜欢当读取Stable Diffusion格式(ckpt 或safetensors)并以diffusers格式保存时,缺少的信息通过从 Hugging Face 中删除 v1.5 或 v2.1 信息来补充。
480
+
481
+ - `--clip_skip`
482
+
483
+ `2` 如果指定,则使用文本编码器 (CLIP) 的倒数第二层的输出。如果省略 1 或选项,则使用最后一层。
484
+
485
+ *SD2.0默认使用倒数第二层,训练SD2.0时请不要指定。
486
+
487
+ 如果被训练的模型最初被训练为使用第二层,则 2 是一个很好的值。
488
+
489
+ 如果您使用的是最后一层,那么整个模型都会根据该假设进行训练。因此,如果再次使用第二层进行训练,可能需要一定数量的teacher数据和更长时间的训练才能得到想要的训练结果。
490
+ - `--max_token_length`
491
+
492
+ 默认值为 75。您可以通过指定“150”或“225”来扩展令牌长度来训练。使用长字幕训练时指定。
493
+
494
+ 但由于训练时token展开的规范与Automatic1111的web UI(除法等规范)略有不同,如非必要建议用75训练。
495
+
496
+ 与clip_skip一样,训练与模型训练状态不同的长度可能需要一定量的teacher数据和更长的学习时间。
497
+
498
+ - `--persistent_data_loader_workers`
499
+
500
+ 在 Windows 环境中指定它可以显着减少时期之间的延迟。
501
+
502
+ - `--max_data_loader_n_workers`
503
+
504
+ 指定数据加载的进程数。大量的进程会更快地加载数据并更有效地使用 GPU,但会消耗更多的主内存。默认是"`8`或者`CPU并发执行线程数 - 1`,取小者",所以如果主存没有空间或者GPU使用率大概在90%以上,就看那些数字和 `2` 或将其降低到大约 `1`。
505
+ - `--logging_dir` / `--log_prefix`
506
+
507
+ 保存训练日志的选项。在 logging_dir 选项中指定日志保存目标文件夹。以 TensorBoard 格式保存日志。
508
+
509
+ 例如,如果您指定 --logging_dir=logs,将在您的工作文件夹中创建一个日志文件夹,并将日志保存在日期/时间文件夹中。
510
+ 此外,如果您指定 --log_prefix 选项,则指定的字符串将添加到日期和时间之前。使用“--logging_dir=logs --log_prefix=db_style1_”进行识别。
511
+
512
+ 要检查 TensorBoard 中的日志,请打开另一个命令提示符并在您的工作文件夹中键入:
513
+ ```
514
+ tensorboard --logdir=logs
515
+ ```
516
+
517
+ 我觉得tensorboard会在环境搭建的时候安装,如果没有安装,请用`pip install tensorboard`安装。)
518
+
519
+ 然后打开浏览器到http://localhost:6006/就可以看到了。
520
+ - `--noise_offset`
521
+ 本文的实现:https://www.crosslabs.org//blog/diffusion-with-offset-noise
522
+
523
+ 看起来它可能会为整体更暗和更亮的图像产生更好的结果。它似乎对 LoRA 训练也有效。指定一个大约 0.1 的值似乎很好。
524
+
525
+ - `--debug_dataset`
526
+
527
+ 通过添加此选项,您可以在训练之前检查将训练什么样的图像数据和标题。按 Esc 退出并返回命令行。按 `S` 进入下一步(批次),按 `E` 进入下一个epoch。
528
+
529
+ *图片在 Linux 环境(包括 Colab)下不显示。
530
+
531
+ - `--vae`
532
+
533
+ 如果您在 vae 选项中指定Stable Diffusion检查点、VAE 检查点文件、扩散模型或 VAE(两者都可以指定本地或拥抱面模型 ID),则该 VAE 用于训练(缓存时的潜伏)或在训练过程中获得潜伏)。
534
+
535
+ 对于 DreamBooth 和微调,保存的模型将包含此 VAE
536
+
537
+ - `--cache_latents`
538
+
539
+ 在主内存中缓存 VAE 输出以减少 VRAM 使用。除 flip_aug 之外的任何增强都将不可用。此外,整体训练速度略快。
540
+ - `--min_snr_gamma`
541
+
542
+ 指定最小 SNR 加权策略。细节是[这里](https://github.com/kohya-ss/sd-scripts/pull/308)请参阅。论文中推荐`5`。
543
+
544
+ ## 优化器相关
545
+
546
+ - `--optimizer_type`
547
+ -- 指定优化器类型。您可以指定
548
+ - AdamW : [torch.optim.AdamW](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html)
549
+ - 与过去版本中未指定选项时相同
550
+ - AdamW8bit : 参数同上
551
+ - PagedAdamW8bit : 参数同上
552
+ - 与过去版本中指定的 --use_8bit_adam 相同
553
+ - Lion : https://github.com/lucidrains/lion-pytorch
554
+ - Lion8bit : 参数同上
555
+ - PagedLion8bit : 参数同上
556
+ - 与过去版本中指定的 --use_lion_optimizer 相同
557
+ - SGDNesterov : [torch.optim.SGD](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html), nesterov=True
558
+ - SGDNesterov8bit : 参数同上
559
+ - DAdaptation(DAdaptAdamPreprint) : https://github.com/facebookresearch/dadaptation
560
+ - DAdaptAdam : 参数同上
561
+ - DAdaptAdaGrad : 参数同上
562
+ - DAdaptAdan : 参数同上
563
+ - DAdaptAdanIP : 参数同上
564
+ - DAdaptLion : 参数同上
565
+ - DAdaptSGD : 参数同上
566
+ - Prodigy : https://github.com/konstmish/prodigy
567
+ - AdaFactor : [Transformers AdaFactor](https://huggingface.co/docs/transformers/main_classes/optimizer_schedules)
568
+ - 任何优化器
569
+
570
+ - `--learning_rate`
571
+
572
+ 指定学习率。合适的学习率取决于训练脚本,所以请参考每个解释。
573
+ - `--lr_scheduler` / `--lr_warmup_steps` / `--lr_scheduler_num_cycles` / `--lr_scheduler_power`
574
+
575
+ 学习率的调度程序相关规范。
576
+
577
+ 使用 lr_scheduler 选项,您可以从线性、余弦、cosine_with_restarts、多项式、常数、constant_with_warmup 或任何调度程序中选择学习率调度程序。默认值是常量。
578
+
579
+ 使用 lr_warmup_steps,您可以指定预热调度程序的步数(逐渐改变学习率)。
580
+
581
+ lr_scheduler_num_cycles 是 cosine with restarts 调度器中的重启次数,lr_scheduler_power 是多项式调度器中的多项式幂。
582
+
583
+ 有关详细信息,请自行研究。
584
+
585
+ 要使用任何调度程序,请像使用任何优化器一样使用“--scheduler_args”指定可选参数。
586
+ ### 关于指定优化器
587
+
588
+ 使用 --optimizer_args 选项指定优化器选项参数。可以以key=value的格式指定多个值。此外,您可以指定多个值,以逗号分隔。例如,要指定 AdamW 优化器的参数,``--optimizer_args weight_decay=0.01 betas=.9,.999``。
589
+
590
+ 指定可选参数时,请检查每个优化器的规格。
591
+ 一些优化器有一个必需的参数,如果省略它会自动添加(例如 SGDNesterov 的动量)。检查控制台输出。
592
+
593
+ D-Adaptation 优化器自动调整学习率。学习率选项指定的值不是学习率本身,而是D-Adaptation决定的学习率的应用率,所以通常指定1.0。如果您希望 Text Encoder 的学习率是 U-Net 的一半,请指定 ``--text_encoder_lr=0.5 --unet_lr=1.0``。
594
+ 如果指定 relative_step=True,AdaFactor 优化器可以自动调整学习率(如果省略,将默认添加)。自动调整时,学习率调度器被迫使用 adafactor_scheduler。此外,指定 scale_parameter 和 warmup_init 似乎也不错。
595
+
596
+ 自动调整的选项类似于``--optimizer_args "relative_step=True" "scale_parameter=True" "warmup_init=True"``。
597
+
598
+ 如果您不想自动调整学习率,请添加可选参数 ``relative_step=False``。在那种情况下,似乎建议将 constant_with_warmup 用于学习率调度程序,而不要为梯度剪裁范数。所以参数就像``--optimizer_type=adafactor --optimizer_args "relative_step=False" --lr_scheduler="constant_with_warmup" --max_grad_norm=0.0``。
599
+
600
+ ### 使用任何优化器
601
+
602
+ 使用 ``torch.optim`` 优化器时,仅指定类名(例如 ``--optimizer_type=RMSprop``),使用其他模块的优化器时,指定“模块名.类名”。(例如``--optimizer_type=bitsandbytes.optim.lamb.LAMB``)。
603
+
604
+ (内部仅通过 importlib 未确认操作。如果需要,请安装包。)
605
+ <!--
606
+ ## 使用任意大小的图像进行训练 --resolution
607
+ 你可以在广场外训练。请在分辨率中指定“宽度、高度”,如“448,640”。宽度和高度必须能被 64 整除。匹配训练图像和正则化图像的大小。
608
+
609
+ 就我个人而言,我经常生成垂直长的图像,所以我有时会用“448、640”来训练。
610
+
611
+ ## 纵横比分桶 --enable_bucket / --min_bucket_reso / --max_bucket_reso
612
+ 它通过指定 enable_bucket 选项来启用。 Stable Diffusion 在 512x512 分辨率下训练,但也在 256x768 和 384x640 等分辨率下训练。
613
+
614
+ 如果指定此选项,则不需要将训练图像和正则化图像统一为特定分辨率。从多种分辨率(纵横比)中进行选择,并在该分辨率下训练。
615
+ 由于分辨率为 64 像素,纵横比可能与原始图像不完全相同。
616
+
617
+ 您可以使用 min_bucket_reso 选项指定分辨率的最小大小,使用 max_bucket_reso 指定最大大小。默认值分别为 256 和 1024。
618
+ 例如,将最小尺寸指定为 384 将不会使用 256x1024 或 320x768 等分辨率。
619
+ 如果将分辨率增加到 768x768,您可能需要将 1280 指定为最大尺寸。
620
+
621
+ 启用 Aspect Ratio Ratio Bucketing 时,最好准备具有与训练图像相似的各种分辨率的正则化图像。
622
+
623
+ (因为一批中的图像不偏向于训练图像和正则化图像。
624
+
625
+ ## 扩充 --color_aug / --flip_aug
626
+ 增强是一种通过在训练过程中动态改变数据来提高模型性能的方法。在使用 color_aug 巧妙地改变色调并使用 flip_aug 左右翻转的同时训练。
627
+
628
+ 由于数据是动态变化的,因此不能与 cache_latents 选项一起指定。
629
+
630
+ ## 使用 fp16 梯度训练(实验特征)--full_fp16
631
+ 如果指定 full_fp16 选项,梯度从普通 float32 变为 float16 (fp16) 并训练(它似乎是 full fp16 训练而不是混合精度)。
632
+ 结果,似乎 SD1.x 512x512 大小可以在 VRAM 使用量小于 8GB 的​​情况下训练,而 SD2.x 512x512 大小可以在 VRAM 使用量小于 12GB 的情况下训练。
633
+
634
+ 预先在加速配置中指定 fp16,并可选择设置 ``mixed_precision="fp16"``(bf16 不起作用)。
635
+
636
+ 为了最大限度地减少内存使用,请使用 xformers、use_8bit_adam、cache_latents、gradient_checkpointing 选项并将 train_batch_size 设置为 1。
637
+
638
+ (如果你负担得起,逐步增加 train_batch_size 应该会提高一点精度。)
639
+
640
+ 它是通过修补 PyTorch 源代码实现的(已通过 PyTorch 1.12.1 和 1.13.0 确认)。准确率会大幅下降,途中学习失败的概率也会增加。
641
+ 学习率和步数的设置似乎很严格。请注意它们并自行承担使用它们的风险。
642
+ -->
643
+
644
+ # 创建元数据文件
645
+
646
+ ## 准备训练数据
647
+
648
+ 如上所述准备好你要训练的图像数据,放在任意文件夹中。
649
+
650
+ 例如,存储这样的图像:
651
+
652
+ ![教师数据文件夹的屏幕截图](https://user-images.githubusercontent.com/52813779/208907739-8e89d5fa-6ca8-4b60-8927-f484d2a9ae04.png)
653
+
654
+ ## 自动captioning
655
+
656
+ 如果您只想训练没有标题的标签,请跳过。
657
+
658
+ 另外,手动准备caption时,请准备在与教师数据图像相同的目录下,文件名相同,扩展名.caption等。每个文件应该是只有一行的文本文件。
659
+ ### 使用 BLIP 添加caption
660
+
661
+ 最新版本不再需要 BLIP 下载、权重下载和额外的虚拟环境。按原样工作。
662
+
663
+ 运行 finetune 文件夹中的 make_captions.py。
664
+
665
+ ```
666
+ python finetune\make_captions.py --batch_size <バッチサイズ> <教師データフォルダ>
667
+ ```
668
+
669
+ 如果batch size为8,训练数据放在父文件夹train_data中,则会如下所示
670
+ ```
671
+ python finetune\make_captions.py --batch_size 8 ..\train_data
672
+ ```
673
+
674
+ caption文件创建在与教师数据图像相同的目录中,具有相同的文件名和扩展名.caption。
675
+
676
+ 根据 GPU 的 VRAM 容量增加或减少 batch_size。越大越快(我认为 12GB 的 VRAM 可以多一点)。
677
+ 您可以使用 max_length 选项指定caption的最大长度。默认值为 75。如果使用 225 的令牌长度训练模型,它可能会更长。
678
+ 您可以使用 caption_extension 选项更改caption扩展名。默认为 .caption(.txt 与稍后描述的 DeepDanbooru 冲突)。
679
+ 如果有多个教师数据文件夹,则对每个文件夹执行。
680
+
681
+ 请注意,推理是随机的,因此每次运行时结果都会发生变化。如果要修复它,请使用 --seed 选项指定一个随机数种子,例如 `--seed 42`。
682
+
683
+ 其他的选项,请参考help with `--help`(好像没有文档说明参数的含义,得看源码)。
684
+
685
+ 默认情况下,会生成扩展名为 .caption 的caption文件。
686
+
687
+ ![caption生成的文件夹](https://user-images.githubusercontent.com/52813779/208908845-48a9d36c-f6ee-4dae-af71-9ab462d1459e.png)
688
+
689
+ 例如,标题如下:
690
+
691
+ ![caption和图像](https://user-images.githubusercontent.com/52813779/208908947-af936957-5d73-4339-b6c8-945a52857373.png)
692
+
693
+ ## 由 DeepDanbooru 标记
694
+
695
+ 如果不想给danbooru标签本身打标签,请继续“标题和标签信息的预处理”。
696
+
697
+ 标记是使用 DeepDanbooru 或 WD14Tagger 完成的。 WD14Tagger 似乎更准确。如果您想使用 WD14Tagger 进行标记,请跳至下一章。
698
+ ### 环境布置
699
+
700
+ 将 DeepDanbooru https://github.com/KichangKim/DeepDanbooru 克隆到您的工作文件夹中,或下载并展开 zip。我解压缩了它。
701
+ 另外,从 DeepDanbooru 发布页面 https://github.com/KichangKim/DeepDanbooru/releases 上的“DeepDanbooru 预训练模型 v3-20211112-sgd-e28”的资产下载 deepdanbooru-v3-20211112-sgd-e28.zip 并解压到 DeepDanbooru 文件夹。
702
+
703
+ 从下面下载。单击以打开资产并从那里下载。
704
+
705
+ ![DeepDanbooru下载页面](https://user-images.githubusercontent.com/52813779/208909417-10e597df-7085-41ee-bd06-3e856a1339df.png)
706
+
707
+ 做一个这样的目录结构
708
+
709
+ ![DeepDanbooru的目录结构](https://user-images.githubusercontent.com/52813779/208909486-38935d8b-8dc6-43f1-84d3-fef99bc471aa.png)
710
+ 为diffusers环境安装必要的库。进入 DeepDanbooru 文件夹并安装它(我认为它实际上只是添加了 tensorflow-io)。
711
+ ```
712
+ pip install -r requirements.txt
713
+ ```
714
+
715
+ 接下来,安装 DeepDanbooru 本身。
716
+
717
+ ```
718
+ pip install .
719
+ ```
720
+
721
+ 这样就完成了标注环境的准备工作。
722
+
723
+ ### 实施标记
724
+ 转到 DeepDanbooru 的文件夹并运行 deepdanbooru 进行标记。
725
+ ```
726
+ deepdanbooru evaluate <教师资料夹> --project-path deepdanbooru-v3-20211112-sgd-e28 --allow-folder --save-txt
727
+ ```
728
+
729
+ 如果将训练数据放在父文件夹train_data中,则如下所示。
730
+ ```
731
+ deepdanbooru evaluate ../train_data --project-path deepdanbooru-v3-20211112-sgd-e28 --allow-folder --save-txt
732
+ ```
733
+
734
+ 在与教师数据图像相同的目录中创建具有相同文件名和扩展名.txt 的标记文件。它很慢,因为它是一个接一个地处理的。
735
+
736
+ 如果有多个教师数据文件夹,则对每个文件夹执行。
737
+
738
+ 它生成如下。
739
+
740
+ ![DeepDanbooru生成的文件](https://user-images.githubusercontent.com/52813779/208909855-d21b9c98-f2d3-4283-8238-5b0e5aad6691.png)
741
+
742
+ 它会被这样标记(信息量很大...)。
743
+
744
+ ![DeepDanbooru标签和图片](https://user-images.githubusercontent.com/52813779/208909908-a7920174-266e-48d5-aaef-940aba709519.png)
745
+
746
+ ## WD14Tagger标记为
747
+
748
+ 此过程使用 WD14Tagger 而不是 DeepDanbooru。
749
+
750
+ 使用 Mr. Automatic1111 的 WebUI 中使用的标记器。我参考了这个 github 页面上的信息 (https://github.com/toriato/stable-diffusion-webui-wd14-tagger#mrsmilingwolfs-model-aka-waifu-diffusion-14-tagger)。
751
+
752
+ 初始环境维护所需的模块已经安装。权重自动从 Hugging Face 下载。
753
+ ### 实施标记
754
+
755
+ 运行脚本以进行标记。
756
+ ```
757
+ python tag_images_by_wd14_tagger.py --batch_size <バッチサイズ> <教師データフォルダ>
758
+ ```
759
+
760
+ 如果将训练数据放在父文件夹train_data中,则如下所示
761
+ ```
762
+ python tag_images_by_wd14_tagger.py --batch_size 4 ..\train_data
763
+ ```
764
+
765
+ 模型文件将在首次启动时自动下载到 wd14_tagger_model 文件夹(文件夹可以在选项中更改)。它将如下所示。
766
+ ![下载文件](https://user-images.githubusercontent.com/52813779/208910447-f7eb0582-90d6-49d3-a666-2b508c7d1842.png)
767
+
768
+ 在与教师数据图像相同的目录中创建具有相同文件名和扩展名.txt 的标记文件。
769
+ ![生成的标签文件](https://user-images.githubusercontent.com/52813779/208910534-ea514373-1185-4b7d-9ae3-61eb50bc294e.png)
770
+
771
+ ![标签和图片](https://user-images.githubusercontent.com/52813779/208910599-29070c15-7639-474f-b3e4-06bd5a3df29e.png)
772
+
773
+ 使用 thresh 选项,您可以指定确定的标签的置信度数以附加标签。默认值为 0.35,与 WD14Tagger 示例相同。较低的值给出更多的标签,但准确性较低。
774
+
775
+ 根据 GPU 的 VRAM 容量增加或减少 batch_size。越大越快(我认为 12GB 的 VRAM 可以多一点)。您可以使用 caption_extension 选项更改标记文件扩展名。默认为 .txt。
776
+
777
+ 您可以使用 model_dir 选项指定保存模型的文件夹。
778
+
779
+ 此外,如果指定 force_download 选项,即使有保存目标文件夹,也会重新下载模型。
780
+
781
+ 如果有多个教师数据文件夹,则对每个文件夹执行。
782
+
783
+ ## 预处理caption和标签信息
784
+
785
+ 将caption和标签作为元数据合并到一个文件中,以便从脚本中轻松处理。
786
+ ### caption预处理
787
+
788
+ 要将caption放入元数据,请在您的工作文件夹中运行以下命令(如果您不使用caption进行训练,则不需要运行它)(它实际上是一行,依此类推)。指定 `--full_path` 选项以将图像文件的完整路径存储在元数据中。如果省略此选项,则会记录相对路径,但 .toml 文件中需要单独的文件夹规范。
789
+ ```
790
+ python merge_captions_to_metadata.py --full_path <教师资料夹>
791
+   --in_json <要读取的元数据文件名> <元数据文件名>
792
+ ```
793
+
794
+ 元数据文件名是任意名称。
795
+ 如果训练数据为train_data,没有读取元数据文件,元数据文件为meta_cap.json,则会如下。
796
+ ```
797
+ python merge_captions_to_metadata.py --full_path train_data meta_cap.json
798
+ ```
799
+
800
+ 您可以使用 caption_extension 选项指定标题扩展。
801
+
802
+ 如果有多个教师数据文件夹,请指定 full_path 参数并为每个文件夹执行。
803
+ ```
804
+ python merge_captions_to_metadata.py --full_path
805
+ train_data1 meta_cap1.json
806
+ python merge_captions_to_metadata.py --full_path --in_json meta_cap1.json
807
+ train_data2 meta_cap2.json
808
+ ```
809
+ 如果省略in_json,如果有写入目标元数据文件,将从那里读取并覆盖。
810
+
811
+ __* 每次重写 in_json 选项和写入目标并写入单独的元数据文件是安全的。 __
812
+ ### 标签预处理
813
+
814
+ 同样,标签也收集在元数据中(如果标签不用于训练,则无需这样做)。
815
+ ```
816
+ python merge_dd_tags_to_metadata.py --full_path <教师资料夹>
817
+ --in_json <要读取的元数据文件名> <要写入的元数据文件名>
818
+ ```
819
+
820
+ 同样的目录结构,读取meta_cap.json和写入meta_cap_dd.json时,会是这样的。
821
+ ```
822
+ python merge_dd_tags_to_metadata.py --full_path train_data --in_json meta_cap.json meta_cap_dd.json
823
+ ```
824
+
825
+ 如果有多个教师数据文件夹,请指定 full_path 参数并为每个文件夹执行。
826
+
827
+ ```
828
+ python merge_dd_tags_to_metadata.py --full_path --in_json meta_cap2.json
829
+ train_data1 meta_cap_dd1.json
830
+ python merge_dd_tags_to_metadata.py --full_path --in_json meta_cap_dd1.json
831
+ train_data2 meta_cap_dd2.json
832
+ ```
833
+
834
+ 如果省略in_json,如果有写入目标元数据文件,将从那里读取并覆盖。
835
+ __※ 通过每次重写 in_json 选项和写入目标,写入单独的元数据文件是安全的。 __
836
+ ### 标题和标签清理
837
+
838
+ 到目前为止,标题和DeepDanbooru标签已经被整理到元数据文件中。然而,自动标题生成的标题存在表达差异等微妙问题(※),而标签中可能包含下划线和评级(DeepDanbooru的情况下)。因此,最好使用编辑器的替换功能清理标题和标签。
839
+
840
+ ※例如,如果要学习动漫中的女孩,标题可能会包含girl/girls/woman/women等不同的表达方式。另外,将"anime girl"简单地替换为"girl"可能更合适。
841
+
842
+ 我们提供了用于清理的脚本,请根据情况编辑脚本并使用它。
843
+
844
+ (不需要指定教师数据文件夹。将清理元数据中的所有数据。)
845
+
846
+ ```
847
+ python clean_captions_and_tags.py <要读取的元数据文件名> <要写入的元数据文件名>
848
+ ```
849
+
850
+ --in_json 请注意,不包括在内。例如:
851
+
852
+ ```
853
+ python clean_captions_and_tags.py meta_cap_dd.json meta_clean.json
854
+ ```
855
+
856
+ 标题和标签的预处理现已完成。
857
+
858
+ ## 预先获取 latents
859
+
860
+ ※ 这一步骤并非必须。即使省略此步骤,也可以在训练过程中获取 latents。但是,如果在训练时执行 `random_crop` 或 `color_aug` 等操作,则无法预先获取 latents(因为每次图像都会改变)。如果不进行预先获取,则可以使用到目前为止的元数据进行训练。
861
+
862
+ 提前获取图像的潜在表达并保存到磁盘上。这样可以加速训练过程。同时进行 bucketing(根据宽高比对训练数据进行分类)。
863
+
864
+ 请在工作文件夹中输入以下内容。
865
+
866
+ ```
867
+ python prepare_buckets_latents.py --full_path <教师资料夹>
868
+ <要读取的元数据文件名> <要写入的元数据文件名>
869
+ <要微调的模型名称或检查点>
870
+ --batch_size <批次大小>
871
+ --max_resolution <分辨率宽、高>
872
+ --mixed_precision <准确性>
873
+ ```
874
+
875
+ 如果要从meta_clean.json中读取元数据,并将其写入meta_lat.json,使用模型model.ckpt,批处理大小为4,训练分辨率为512*512,精度为no(float32),则应如下所示。
876
+ ```
877
+ python prepare_buckets_latents.py --full_path
878
+ train_data meta_clean.json meta_lat.json model.ckpt
879
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
880
+ ```
881
+
882
+ 教师数据文件夹中,latents以numpy的npz格式保存。
883
+
884
+ 您可以使用--min_bucket_reso选项指定最小分辨率大小,--max_bucket_reso指定最大大小。默认值分别为256和1024。例如,如果指定最小大小为384,则将不再使用分辨率为256 * 1024或320 * 768等。如果将分辨率增加到768 * 768等较大的值,则最好将最大大小指定为1280等。
885
+
886
+ 如果指定--flip_aug选项,则进行左右翻转的数据增强。虽然这可以使数据量伪造一倍,但如果数据不是左右对称的(例如角色外观、发型等),则可能会导致训练不成功。
887
+
888
+ 对于翻转的图像,也会获取latents,并保存名为\ *_flip.npz的文件,这是一个简单的实现。在fline_tune.py中不需要特定的选项。如果有带有\_flip的文件,则会随机加载带有和不带有flip的文件。
889
+
890
+ 即使VRAM为12GB,批次大小也可以稍微增加。分辨率以“宽度,高度”的形式指定,必须是64的倍数。分辨率直接影响fine tuning时的内存大小。在12GB VRAM中,512,512似乎是极限(*)。如果有16GB,则可以将其提高到512,704或512,768。即使分辨率为256,256等,VRAM 8GB也很难承受(因为参数、优化器等与分辨率无关,需要一定的内存)。
891
+
892
+ *有报道称,在batch size为1的训练中,使用12GB VRAM和640,640的分辨率。
893
+
894
+ 以下是bucketing结果的显示方式。
895
+
896
+ ![bucketing的結果](https://user-images.githubusercontent.com/52813779/208911419-71c00fbb-2ce6-49d5-89b5-b78d7715e441.png)
897
+
898
+ 如果有多个教师数据文件夹,请指定 full_path 参数并为每个文件夹执行
899
+
900
+ ```
901
+ python prepare_buckets_latents.py --full_path
902
+ train_data1 meta_clean.json meta_lat1.json model.ckpt
903
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
904
+
905
+ python prepare_buckets_latents.py --full_path
906
+ train_data2 meta_lat1.json meta_lat2.json model.ckpt
907
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
908
+
909
+ ```
910
+ 可以将读取源和写入目标设为相同,但分开设定更为安全。
911
+
912
+ __※建议每次更改参数并将其写入另一个元数据文件,以确保安全性。__
docs/train_README.md ADDED
@@ -0,0 +1,1007 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > **Note:** This document is under revision, and some errors may persist. Please refer to the latest version for accurate information.
2
+
3
+ # Training, Common Section
4
+
5
+ This document facilitates training with models such as DreamBooth and LoRA, including [XTI:P+](https://github.com/kohya-ss/sd-scripts/pull/327). It details how to prepare training data and outlines common options.
6
+
7
+ # Overview
8
+
9
+ For environment setup, please refer to the README of this repository. The document covers the following topics:
10
+
11
+ 1. Preparation of training data (new format using configuration files)
12
+ 2. Simplified explanation of terms used in training
13
+ 3. Previous specification format (specify without using configuration files)
14
+ 4. Sample image generation during training
15
+ 5. Common options used in each script
16
+ 6. Preparation of metadata for fine tuning: captioning, etc.
17
+
18
+ Start training by following the initial steps; further details are available in each script's documentation.
19
+
20
+ # Training Data Preparation
21
+
22
+ Prepare your training data in any designated folder(s). Supported formats include `.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp`. Generally, preprocessing such as resizing is not required.
23
+
24
+ However, using images larger than the training resolution or upscaling them with super-resolution AI beforehand is recommended. Additionally, it's advisable to resize overly large images (around 3000x3000 pixels?) to prevent errors.
25
+
26
+ When organizing your image data for training, you can specify the training data in various ways depending on the number of data sets, the learning targets, captions (image descriptions), etc. The methods available (specific to this repository) are described below. The usage of regularization images will be discussed later.
27
+
28
+ 1. **DreamBooth, Class+Identifier Method (regularization images available):**
29
+
30
+ Learn from images associated with a specific identifier without needing captions. This method is convenient for learning a specific character but associates the character's hairstyle, clothing, and background with the identifier, potentially causing the model to generate images without changing the clothing when generating the prompt.
31
+
32
+ 2. **DreamBooth, Captioning Method (regularization images available):**
33
+
34
+ Prepare a text file with captions for each image. If you aim to learn a specific character, detailed descriptions in the captions can help differentiate the character from other elements, enabling the model to learn the character more precisely.
35
+
36
+ 3. **Fine Tuning Method (regularization images not available):**
37
+
38
+ Pre-prepare captions in a metadata file. Tags and captions can be managed separately, and caching latents can speed up learning. This method is broadly referred to as fine tuning but has various applications.
39
+
40
+ The following table illustrates the combinations of targets to be learned or methods of use:
41
+
42
+ | Target or Method | Script | DB / Class+Identifier | DB / Caption | Fine Tuning |
43
+ |----------------------------------|-----------------------------|-----------------------|--------------|-------------|
44
+ | Model Fine Tuning | `fine_tune.py` | x | x | o |
45
+ | Model DreamBooth | `train_db.py` | o | o | x |
46
+ | LoRA | `train_network.py` | o | o | o |
47
+ | Textual Inversion | `train_textual_inversion.py`| o | o | o |
48
+
49
+ ## Method Selection Guide
50
+
51
+ For those considering LoRA or Textual Inversion methods and who prefer not to prepare a caption file, the DreamBooth class+identifier method is recommended. However, if preparing a caption file is feasible, the DreamBooth captioning method may be more effective. Additionally, if you possess a substantial volume of training data and wish to incorporate regularization images, the fine tuning method should also be considered.
52
+
53
+ Note: The fine tuning method is not applicable for DreamBooth alone.
54
+
55
+ ## Configuration Guidelines
56
+
57
+ Below are the general guidelines for configuring each method. For detailed configuration instructions, please refer to [Dataset Settings](./config_README-ja.md).
58
+
59
+ # DreamBooth, Class+Identifier Method (Regularization Images Available)
60
+
61
+ This method involves training each image with a caption formatted as `class identifier` (e.g., `shs dog`).
62
+
63
+ ## Step 1. Determine Identifier and Class
64
+
65
+ Choose a unique identifier for recognizing and learning the target, and determine the class the target belongs to.
66
+
67
+ Here is a simple explanation (for further details, please conduct your own research):
68
+
69
+ - **Class**: This refers to the broad category of the learning target. For instance, to learn about a specific dog breed, the class would be "dog." For anime characters, appropriate classes might be "boy" or "girl," "1boy," "1girl," etc., based on the model.
70
+
71
+ - **Identifier**: This is a specific term used to identify and learn about the target. Any term can be used, but following the original paper's recommendations, a "rare word that can be tokenized into a single token with a maximum length of three characters" is suggested.
72
+
73
+ Using both an identifier and a class (e.g., `shs dog`) allows for precise target recognition and learning.
74
+
75
+ When generating images post-training, images of the learned dog breed can be produced by specifying `shs dog`.
76
+
77
+ (Reference: Recent identifiers I've used include `shs`, `sts`, `scs`, `cpc`, `coc`, `cic`, `msm`, `usu`, `ici`, `lvl`, `cic`, `dii`, `muk`, `ori`, `hru`, `rik`, `koo`, `yos`, `wny`. Ideally, select identifiers not listed in Danbooru Tags.)
78
+
79
+ ## Step 2. Decide Whether to Use Regularization Images and Generate Them if Necessary
80
+
81
+ Regularization images help prevent the model from biasing too heavily towards a single learning target, a phenomenon known as "language drift". For instance, training a specific character with the prompt `shs 1girl` without regularization images might cause the model to generate images that are too similar to the generic `1girl` class, even if `1girl` appears in the training caption.
82
+
83
+ Using regularization images alongside the target image ensures that the class remains broadly defined, while the identifier is specifically learned only when added to the prompt.
84
+
85
+ If the objective is to have a specific character appear distinctively, regularization images are essential.
86
+
87
+ Textual Inversion is not recommended here, as it requires the token string to be included in the caption to learn anything effectively.
88
+
89
+ Typically, regularization images are generated using only the class name (e.g., `1girl`) from the learning target model. If the quality of these generated images is subpar, consider adjusting the prompt or using downloaded images from the internet.
90
+
91
+ Note: The quality of regularization images can influence the model, so choose carefully.
92
+
93
+ It is generally advised to prepare around 100 images to ensure enough diversity to generalize the class images and effectively learn their characteristics.
94
+
95
+ For generated images, it's best to match the size of the training resolution, or more specifically, the resolution of the bucket (to be discussed later).
96
+
97
+ ## Step 2. Write the Configuration File
98
+
99
+ Create a text file and change the extension to `.toml`. Example configuration:
100
+
101
+ (Note: Lines starting with `#` are comments and can be copied as-is or omitted if preferred.)
102
+
103
+ ```toml
104
+ [general]
105
+ enable_bucket = true # Whether to use Aspect Ratio Bucketing
106
+
107
+ [[datasets]]
108
+ resolution = 512 # Training resolution
109
+ batch_size = 4 # Batch size
110
+
111
+ [[datasets.subsets]]
112
+ image_dir = 'C:\\hoge' # Specify the folder for learning target images
113
+ class_tokens = 'hoge girl' # Specify the identifier class
114
+ num_repeats = 10 # Number of repetitions for the learning target image
115
+
116
+ # Include the following only if using regularization images
117
+ [[datasets.subsets]]
118
+ is_reg = true
119
+ image_dir = 'C:\\reg' # Specify the folder for regularization images
120
+ class_tokens = 'girl' # Specify the class for regularization
121
+ num_repeats = 1 # Number of repetitions for regularization images, typically 1 is sufficient
122
+ ```
123
+
124
+ # Training Configuration Details
125
+
126
+ When setting up your training environment, consider the following parameters to optimize your model's learning effectiveness.
127
+
128
+ ## 1. Training Resolution
129
+
130
+ Specify the resolution at which the training images should be processed. Use a single number for square images (e.g., `512` produces a 512x512 image). For rectangular images, provide two numbers separated by a comma (e.g., `[512,768]` for 512x768). Standard resolutions for SD1.x models are typically 512 pixels, whereas SD2.x models are often trained at 768 pixels.
131
+
132
+ ## 2. Batch Size
133
+
134
+ This parameter defines the number of data instances processed simultaneously during training. It should be adjusted based on the GPU VRAM capacity and the desired training resolution. Further guidance is provided in later sections.
135
+
136
+ ## 3. Folder Specification
137
+
138
+ Identify the directory containing the target images for learning and, if applicable, regularization images. This should be the direct path to the folder holding the actual image files.
139
+
140
+ ## 4. Identifier and Class
141
+
142
+ Specify these as detailed in the previous guidelines.
143
+
144
+ ## 5. Number of Repetitions
145
+
146
+ For a comprehensive understanding of how many times the training images should be repeated, see the detailed explanation below.
147
+
148
+ ### About Repetitions
149
+
150
+ The number of repetitions helps synchronize the count of regularization images with the number of target images for learning. Typically, there are more regularization images than target images, so the target images are repeated to maintain a 1:1 ratio.
151
+
152
+ Configure the number of repetitions as follows: "__Number of target image repetitions * Number of target images ≥ Number of regularization image repetitions * Number of regularization images__".
153
+
154
+ (The total data count for one epoch—when the data cycles through once—is "Number of target image repetitions * Number of target images". If there are more regularization images than this total, the surplus will not be utilized.)
155
+
156
+ ## Step 3. Training Execution
157
+
158
+ Consult the specific documentation related to your training setup for detailed instructions.
159
+
160
+ # DreamBooth, Captioning Method (Regularization Images Available)
161
+
162
+ In this approach, each image is learned with an associated caption, facilitating more nuanced understanding and generation of visual content.
163
+
164
+ ## step 1. Prepare the caption file
165
+
166
+ Place a file with the same name as the image in the folder where the learning image is placed, with the extension `.caption` (which can be changed in the settings). Each file should contain only one line. The encoding is `UTF-8`.
167
+
168
+ ## step 2. Decide whether to use regularization images and generate them if necessary
169
+
170
+ Same as class+identifier. You can also add captions to regularization images, but it is usually not necessary.
171
+
172
+ ## step 2. Write the configuration file
173
+
174
+ Create a text file and change the extension to `.toml`. For example, write as follows.
175
+
176
+ ```toml
177
+ [general]
178
+ enable_bucket = true # Whether to use Aspect Ratio Bucketing
179
+
180
+ [[datasets]]
181
+ resolution = 512 # Training resolution
182
+ batch_size = 4 # Batch size
183
+
184
+ [[datasets.subsets]]
185
+ image_dir = 'C:\hoge' # Specify the folder where the learning target images are placed
186
+ caption_extension = '.caption' # Specify the extension of the caption file. If you want to use .txt, change it
187
+ num_repeats = 10 # Number of times to repeat the learning target image
188
+
189
+ # Write the following only if you are using regularization images
190
+ [[datasets.subsets]]
191
+ is_reg = true
192
+ image_dir = 'C:\reg' # Specify the folder where the regularization images are placed
193
+ class_tokens = 'girl' # Specify the class
194
+ num_repeats = 1 # Number of times to repeat the regularization image, usually 1 is enough
195
+ ```
196
+
197
+ Basically, you can change the following only.
198
+
199
+ 1. Training resolution
200
+ 1. Batch size
201
+ 1. Folder specification
202
+ 1. Caption file extension
203
+
204
+ You can specify any extension.
205
+ 1. Number of repetitions
206
+
207
+ ## step 3. Training
208
+
209
+ Please refer to each document for training.
210
+
211
+ ## step 3. Training
212
+
213
+ Please refer to each document for training.
214
+
215
+ # fine tuning method
216
+
217
+ ## step 1. Prepare the metadata
218
+
219
+ The file that collects captions and tags is called metadata. It is in json format with the extension `.json`. The method of creating it is too long to write here, so it is written at the end of this document.
220
+
221
+ ## step 2. Write the configuration file
222
+
223
+ Create a text file and change the extension to `.toml`. For example, write as follows.
224
+
225
+ ```toml
226
+ [general]
227
+ shuffle_caption = true
228
+ keep_tokens = 1
229
+
230
+ [[datasets]]
231
+ resolution = 512 # Training resolution
232
+ batch_size = 4 # Batch size
233
+
234
+ [[datasets.subsets]]
235
+ image_dir = 'C:\piyo' # Specify the folder where the learning target images are placed
236
+ metadata_file = 'C:\piyo\piyo_md.json' # Metadata file name
237
+ ```
238
+
239
+ Basically, you can change the following only. Placeholders are the same as DreamBooth, class+identifier.
240
+
241
+ 1. Training resolution
242
+ 1. Batch size
243
+ 1. Folder specification
244
+ 1. Metadata file name
245
+
246
+ Specify the metadata file created according to the method above.
247
+
248
+ ## step 3. Training
249
+
250
+ Please refer to each document for training.
251
+
252
+ # Explanation of terms used in training
253
+
254
+ I've omitted the details and I'm not fully understanding it myself, so please do your own research.
255
+
256
+ ## fine tuning
257
+
258
+ This refers to training the model and fine-tuning it. The meaning varies depending on how it's used, but in the context of Stable Diffusion, it means training the model with images and captions. DreamBooth is one of the special ways of fine tuning. Broadly speaking, fine tuning includes training the model with LoRA, Textual Inversion, Hypernetworks, etc.
259
+
260
+ ## Step
261
+
262
+ In a nutshell, 1 step is calculated with 1 piece of learning data. "Feed the caption of the learning data to the current model and see what image comes out. Compare the image with the learning data's image and make the model slightly change to get closer to the learning data." is 1 step.
263
+
264
+ ## Batch size
265
+
266
+ The batch size is a value that specifies how many pieces of data to calculate together in 1 step. By calculating together, the speed is relatively improved. Also, it is generally said that the accuracy is also improved.
267
+
268
+ `Batch size × number of steps` is the number of data used for training. Therefore, if you increase the batch size, you should also reduce the number of steps.
269
+
270
+ (However, for example, "batch size 1 with 1600 steps" and "batch size 4 with 400 steps" do not necessarily result in the same outcome. If the same learning rate is used, it is generally the latter that is underfed. Try to increase the learning rate (for example, `2e-6`) or reduce the number of steps (for example, 500 steps) to compensate for this.)
271
+
272
+ Increasing the batch size will consume more GPU memory. If the memory is insufficient, an error will occur. If the error does not occur, the learning speed will be slowed down. You can use the task manager or `nvidia-smi` command to check the memory usage and adjust accordingly.
273
+
274
+ Also, note that a batch is a unit of "a batch of data".
275
+
276
+ ## Learning Rate
277
+
278
+ In a nutshell, it refers to how much to change each step. If you specify a large value, it will progressively learn faster, but if it changes too much, the model may be damaged or may not reach the optimal state. If you specify a small value, the learning speed will be slower, and it may not reach the optimal state.
279
+
280
+ The learning rate differs greatly depending on the method used, including fine tuning, DreamBooth, and LoRA, and also depends on the learning data, the model to be trained, the batch size, and the number of steps. It is recommended to start with a general value and adjust it according to the learning state.
281
+
282
+ By default, the learning rate is fixed throughout the entire learning. The scheduler determines how the learning rate changes, so the results can vary depending on the scheduler.
283
+
284
+ ## Epoch
285
+
286
+ When the learning data is learned once (the data is cycled once), it is considered 1 epoch. If the number of repetitions is specified, it is considered 1 epoch after the repetition.
287
+
288
+ The number of steps per epoch is generally `number of dataÅbatch size`, but it increases slightly with Aspect Ratio Bucketing (since different buckets of data cannot be in the same batch, the number of steps increases).
289
+
290
+ ## Aspect Ratio Bucketing
291
+
292
+ Stable Diffusion v1 is trained at 512*512, but it also learns at 256*1024 and 384*640, etc., which reduces the amount of trimming and expects to learn more accurately about the relationship between captions and images.
293
+
294
+ This allows learning at any resolution, so you don't need to pre-uniform the aspect ratio of the image data.
295
+
296
+ It can be enabled or disabled by the settings, and in the examples of this document, it is enabled (`true` is set).
297
+
298
+ The learning resolution is created by adjusting the resolution in the parameters to be less than or equal to the area of the memory used by the parameters (default, changeable), and is created in multiples of 64 pixels.
299
+
300
+ In machine learning, it is common to standardize the input size, but there is no specific constraint, and in fact, as long as the same batch is uniformly sized, it is okay. NovelAI's bucketing seems to refer to classifying the teacher data according to the learning resolution according to the aspect ratio, and then creating a batch with each bucket's images to standardize the image size of the batch.
301
+
302
+ # Previous Specification Method (Without Using the Configuration File and Specifying Through the Command Line)
303
+
304
+ The method of specifying without using the `.toml` file and specifying through the command line option. There are three methods: DreamBooth class+identifier, DreamBooth captioning, and fine tuning.
305
+
306
+ ## DreamBooth, class+identifier Method
307
+
308
+ You specify the number of repetitions by the folder name, and also use the `train_data_dir` and `reg_data_dir` options.
309
+
310
+ ### step 1. Prepare the Learning Image
311
+
312
+ Create a folder to store the learning images. __Inside the folder, create a directory with the following name.__
313
+
314
+ ```
315
+ <Number of repetitions>_<identifier> <class>
316
+ ```
317
+
318
+ Don't forget the `_` in between.
319
+
320
+ For example, if you specify the prompt "sls frog" and repeat the data 20 times, it will be named "20_sls frog". It will look like this:
321
+
322
+ ![image](https://user-images.githubusercontent.com/52813779/210770636-1c851377-5936-4c15-90b7-8ac8ad6c2074.png)
323
+
324
+ ### Training with multiple classes and multiple targets (identifiers)
325
+
326
+ The method is simple. Prepare a folder for learning images, and create a directory with the name ``<Number of repetitions>_<identifier> <class>`` inside the folder.
327
+
328
+ For example, if you want to learn both "sls frog" and "cpc rabbit" at the same time, it will look like this:
329
+
330
+ ![image](https://user-images.githubusercontent.com/52813779/210777933-a22229db-b219-4cd8-83ca-e87320fc4192.png)
331
+
332
+ If there is only one class but multiple targets, you only need one regularization image folder. For example, if there are characters A and B in 1girl, it will look like this:
333
+
334
+ - train_girls
335
+ - 10_sls 1girl
336
+ - 10_cpc 1girl
337
+ - reg_girls
338
+ - 1_1girl
339
+
340
+ ### step 2. Prepare regularization images
341
+
342
+ The steps to use regularization images.
343
+
344
+ Create a folder to store the regularization images. __Inside the folder, create a directory with the name__ ``<Number of repetitions>_<class>``.
345
+
346
+ For example, if you specify the prompt "frog" and do not repeat the data (1 time only), it will look like this:
347
+
348
+ ![image](https://user-images.githubusercontent.com/52813779/210770897-329758e5-3675-49f1-b345-c135f1725832.png)
349
+
350
+ ### step 3. Execute training
351
+
352
+ Execute each training script. Specify the folder for learning data with the `--train_data_dir` option (__not the folder containing the images, but the parent folder__), and specify the regularization image folder with the `--reg_data_dir` option (__not the folder containing the images, but the parent folder__).
353
+
354
+ ## DreamBooth, captioning method
355
+
356
+ If you put a file with the same name as the image but with the extension .caption (optionally changeable) in the learning image and regularization image folders, it will learn the caption from the file as the prompt.
357
+
358
+ ※The folder name (identifier class) will no longer be used for the learning of those images.
359
+
360
+ The default extension for the caption file is .caption. You can change it with the `--caption_extension` option in the training script. The `--shuffle_caption` option shuffles each part of the caption when learning, separated by commas.
361
+
362
+ ## fine tuning method
363
+
364
+ The preparation of metadata is the same as when using a configuration file. Specify the metadata file with the `in_json` option.
365
+
366
+ # Sample output during training
367
+
368
+ You can check the progress of learning by generating images with the model being trained. Specify the following options in the training script.
369
+
370
+ - `--sample_every_n_steps` / `--sample_every_n_epochs`
371
+
372
+ Specify the number of steps or epochs to output a sample. Output a sample every time this number is reached. The epoch number takes precedence if both are specified.
373
+
374
+ - `--sample_at_first`
375
+
376
+ Output a sample before learning starts. You can compare before and after learning.
377
+
378
+ - `--sample_prompts`
379
+
380
+ Specify the file containing the prompts for sample output.
381
+
382
+ - `--sample_sampler`
383
+
384
+ Specify the sampler to use for sample output.
385
+ `'ddim', 'pndm', 'heun', 'dpmsolver', 'dpmsolver++', 'dpmsingle', 'k_lms', 'k_euler', 'k_euler_a', 'k_dpm_2', 'k_dpm_2_a'` can be selected.
386
+
387
+ You need to prepare a text file with the prompts for sample output in advance. Write one prompt per line.
388
+
389
+ For example:
390
+
391
+ ```txt
392
+ # prompt 1
393
+ masterpiece, best quality, 1girl, in white shirts, upper body, looking at viewer, simple background --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 768 --h 768 --d 1 --l 7.5 --s 28
394
+
395
+ # prompt 2
396
+ masterpiece, best quality, 1boy, in business suit, standing at street, looking back --n low quality, worst quality, bad anatomy,bad composition, poor, low effort --w 576 --h 832 --d 2 --l 5.5 --s 40
397
+ ```
398
+
399
+ Lines starting with `#` are comments. You can specify options for the generated image with `--` followed by a lowercase English letter. The following options are available:
400
+
401
+ - `--n` The following options are treated as negative prompts.
402
+ - `--w` Specify the width of the generated image.
403
+ - `--h` Specify the height of the generated image.
404
+ - `--d` Specify the seed for the generated image.
405
+ - `--l` Specify the CFG scale for the generated image.
406
+ - `--s` Specify the number of steps for the generation.
407
+
408
+ # Common options used by each script
409
+
410
+ If the script has been updated but the documentation has not been updated, please check the available options using the `--help` option.
411
+
412
+ ## Specifying the model to be used for training
413
+
414
+ - `--v2` / `--v_parameterization`
415
+
416
+ If you want to use Hugging Face's stable-diffusion-2-base or a fine-tuned model based on it (models that instruct you to use `v2-inference.yaml`), specify the `--v2` option. If you want to use stable-diffusion-2, 768-v-ema.ckpt, or any fine-tuned models that instruct you to use `v2-inference-v.yaml`, specify both the `--v2` and `--v_parameterization` options.
417
+
418
+ In Stable Diffusion 2.0, the following points have changed significantly:
419
+
420
+ 1. The Tokenizer used
421
+ 2. The Text Encoder used and the output layer used (Stable Diffusion 2.0 uses the second-to-last layer)
422
+ 3. The output dimension of the Text Encoder (768->1024)
423
+ 4. The structure of the U-Net (the number of heads in CrossAttention, etc.)
424
+ 5. v-parameterization (the sampling method has changed, according to what I've seen)
425
+
426
+ Of these, 1-4 are used in the base, and 1-5 are used in the non-base (768-v). The `--v2` option enables 1-4, and the `--v_parameterization` option enables 5.
427
+
428
+ - `--pretrained_model_name_or_path`
429
+
430
+ Specify the model to be used as the starting point for additional training. You can specify a Stable Diffusion checkpoint file (.ckpt or .safetensors), a local directory of a Diffusers model, or a Diffusers model ID ("stabilityai/stable-diffusion-2", etc.).
431
+
432
+ ## Training settings
433
+
434
+ - `--output_dir`
435
+
436
+ Specify the folder to save the model after training.
437
+
438
+ - `--output_name`
439
+
440
+ Specify the model file name without the extension.
441
+
442
+ - `--dataset_config`
443
+
444
+ Specify the `.toml` file that describes the dataset configuration.
445
+
446
+ - `--max_train_steps` / `--max_train_epochs`
447
+
448
+ Specify the number of steps or epochs to train. If both are specified, the number of epochs is prioritized.
449
+
450
+ - `--mixed_precision`
451
+
452
+ Train with mixed precision (mixed precision) to save memory. Specify as `--mixed_precision="fp16"`. The accuracy may be lower than without mixed precision, but the amount of GPU memory required for training is reduced.
453
+
454
+ (RTX30 series and later can also specify `bf16`. Please match the settings you made when setting up the environment with accelerate).
455
+
456
+ - `--gradient_checkpointing`
457
+
458
+ Calculate the weights in a piecemeal manner instead of all at once to reduce the amount of GPU memory required for training. It does not affect the accuracy, but it can make the batch size larger, so it may affect the overall training time.
459
+
460
+ In addition, it is generally slower than on, but it can make the batch size larger, so the total training time may be faster.
461
+
462
+ - `--xformers` / `--mem_eff_attn`
463
+
464
+ If you specify the xformers option, xformers' CrossAttention is used. If you do not have xformers installed or encounter an error (depending on the environment, such as `mixed_precision="no"`), you can specify the `mem_eff_attn` option to use the memory-efficient version of CrossAttention (which is slower than xformers).
465
+
466
+ - `--clip_skip`
467
+
468
+ Specify `2` to use the second-to-last layer's output after the Text Encoder (CLIP). Specify `1` or omit the option to use the last layer.
469
+
470
+ ※SD2.0 is set to use the second-to-last layer by default, so do not specify it when training SD2.0.
471
+
472
+ If the model was trained to use the second layer, specify `2`.
473
+
474
+ If the model was trained to use the last layer, the model is trained assuming the last layer. Therefore, re-training with the second layer may require a certain number of teacher data, and a long training time.
475
+
476
+ - `--max_token_length`
477
+
478
+ The default is `75`. Specify `150` or `225` to extend the token length for training. Specify it when training with long captions.
479
+
480
+ However, the token extension specification during training is slightly different from the Web UI of Automatic1111 (such as the specification of splitting), so it is recommended to learn with `75`.
481
+
482
+ Like clip_skip, to learn with a different length than the model's learning state, you may need a certain number of teacher data and a long training time.
483
+
484
+ - `--weighted_captions`
485
+
486
+ Specify to enable weighted captions similar to Automatic1111's Web UI. Can be used for training except for "Textual Inversion and XTI". Can also be used for DreamBooth token strings.
487
+
488
+ The notation for weighted captions is almost the same as the Web UI, and (abc), [abc], (abc:1.23), etc. can be used. Nesting is also possible. If you include a comma within the parentheses, the shuffle/dropout of the prompt will be incorrect, so do not include a comma within the parentheses.
489
+
490
+ - `--persistent_data_loader_workers`
491
+
492
+ If you specify it on a Windows environment, the waiting time between epochs is significantly shortened.
493
+
494
+ - `--max_data_loader_n_workers`
495
+
496
+ Specify the number of processes for data loading. The more processes, the faster the data loading and the GPU is used more efficiently, but it consumes main memory. The default is "`8` or `CPU concurrent thread number - 1`, whichever is smaller", so if there is no spare main memory or the GPU usage is about 90%, please reduce the number of processes to `2` or `1`.
497
+
498
+ - `--logging_dir` / `--log_prefix`
499
+
500
+ Options for saving training logs. Specify the folder to save the log with the logging_dir option. TensorBoard-formatted logs are saved.
501
+
502
+ For example, specify `--logging_dir=logs`, and a logs folder will be created in the working directory, and the log will be saved in the date-named folder within it.
503
+ Also, if you specify the `--log_prefix` option, the specified string will be added before the date. Use it to identify, such as `--logging_dir=logs --log_prefix=db_style1_`.
504
+
505
+ To check the log with TensorBoard, open another command prompt, and enter the following in the working directory.
506
+
507
+ ```
508
+ tensorboard --logdir=logs
509
+ ```
510
+
511
+ (I think tensorboard is installed together with the environment setup, but if it is not installed, please install it with `pip install tensorboard`.)
512
+
513
+ After that, open the browser and access <http://localhost:6006/> to display it.
514
+
515
+ - `--log_with` / `--log_tracker_name`
516
+
517
+ Options for saving training logs. You can save logs to `tensorboard` and `wandb`. For details, please refer to [PR#428](https://github.com/kohya-ss/sd-scripts/pull/428).
518
+
519
+ - `--noise_offset`
520
+
521
+ This implementation is based on the following article: <https://www.crosslabs.org//blog/diffusion-with-offset-noise>
522
+
523
+ It seems that overall, the results of generating dark and bright images are improved. It may be effective in LoRA training. It is recommended to specify a value of `0.1` or less.
524
+
525
+ - `--adaptive_noise_scale` (Experimental option)
526
+
527
+ This option automatically adjusts the noise offset value according to the absolute value of the mean of the latents. It is enabled when `--noise_offset` is specified. The noise offset value is calculated as `noise_offset + abs(mean(latents, dim=(2,3))) * adaptive_noise_scale`. Latents are assumed to be close to a normal distribution, so it is recommended to specify a value of `noise_offset` of 1/10~ the same or less.
528
+
529
+ Negative values can also be specified, in which case the noise offset is clipped to be 0 or above.
530
+
531
+ - `--multires_noise_iterations` / `--multires_noise_discount`
532
+
533
+ Settings for multi-resolution noise (pyramid noise). For details, please refer to [PR#471](https://github.com/kohya-ss/sd-scripts/pull/471) and the following page [Multi-Resolution Noise for Diffusion Model Training](https://wandb.ai/johnowhitaker/multires_noise/reports/Multi-Resolution-Noise-for-Diffusion-Model-Training--VmlldzozNjYyOTU2).
534
+
535
+ Specify a number value to enable. A value of 6~10 is recommended. Specify a value of `--multires_noise_discount` of 0.1~0.3 (recommended by the author of PR#471 for datasets with a smaller number of samples) or 0.8 (recommended by the author of the original article) (default is 0.3).
536
+
537
+ - `--debug_dataset`
538
+
539
+ With this option, you can check which images and captions are used for training before starting the training. Press `Esc` to exit and return to the command line. Press `S` to go to the next step (batch) and `E` to go to the next epoch.
540
+
541
+ ※Images are not displayed in Linux environments (including Colab).
542
+
543
+ - `--vae`
544
+
545
+ Specify either a Stable Diffusion checkpoint, a VAE checkpoint file, a Diffusers model, or a VAE (both local or Hugging Face model IDs) to use that VAE for training (when caching latents or retrieving latents during training).
546
+
547
+ In DreamBooth and fine tuning, the saved model will include this VAE.
548
+
549
+ - `--cache_latents` / `--cache_latents_to_disk`
550
+
551
+ Cache the output of the VAE to the main memory to reduce VRAM usage. Augmentations other than `flip_aug` are disabled. The overall training speed is also slightly faster.
552
+
553
+ Specify `--cache_latents_to_disk` to save the cache to disk. The cache will be effective even if the script is exited and restarted.
554
+
555
+ - `--min_snr_gamma`
556
+
557
+ Specify the Min-SNR Weighting strategy. For details, please refer to [this link](https://github.com/kohya-ss/sd-scripts/pull/308). The paper recommends `5`.
558
+
559
+ ## Model Saving Settings
560
+
561
+ - `--save_precision`
562
+
563
+ Specify the data precision to save. If you specify float, fp16, or bf16, the model will be saved in that format (DreamBooth and fine tuning will not be saved in Diffusers format). This is useful for reducing model size, for example.
564
+
565
+ - `--save_every_n_epochs` / `--save_state` / `--resume`
566
+
567
+ If you specify a number for save_every_n_epochs, the model will be saved every n epochs during training.
568
+
569
+ If you specify save_state at the same time, the optimizer, etc. will also be saved together with the training state (you can resume training from the saved state). This is expected to improve accuracy and shorten training time. The save destination is a folder.
570
+
571
+ The training state is output to a folder named `<output_name>-??????-state` (?????? is the epoch number) in the save destination folder. Use it for long-term training.
572
+
573
+ To resume training from a saved state, specify resume and the state folder (not `output_dir` but the state folder inside it).
574
+
575
+ Note that due to the specifications of Accelerator, the epoch number, global step are not saved and will be reset to 1 when resumed.
576
+
577
+ - `--save_every_n_steps`
578
+
579
+ If you specify a number for save_every_n_steps, the model will be saved every n steps during training. You can specify it at the same time as save_every_n_epochs.
580
+
581
+ - `--save_model_as` (DreamBooth, fine tuning only)
582
+
583
+ You can select the model saving format from `ckpt, safetensors, diffusers, diffusers_safetensors`.
584
+
585
+ Specify it like `--save_model_as=safetensors`. If you load a Stable Diffusion model (ckpt or safetensors) and save it in Diffusers format, missing information will be filled in with information from Hugging Face, such as v1.5 or v2.1.
586
+
587
+ - `--huggingface_repo_id`, etc.
588
+
589
+ If huggingface_repo_id is specified, the model will be uploaded to HuggingFace at the same time. Be careful with the handling of the access token (refer to HuggingFace's documentation).
590
+
591
+ For example, specify as follows:
592
+
593
+ - `--huggingface_repo_id "your-hf-name/your-model" --huggingface_path_in_repo "path" --huggingface_repo_type model --huggingface_repo_visibility private --huggingface_token hf_YourAccessTokenHere`
594
+
595
+ If you specify `public` for huggingface_repo_visibility, the repository will be public. If you omit it or specify anything other than `public`, it will be private.
596
+
597
+ If you specify `--save_state`, specify `--save_state_to_huggingface` to save the state.
598
+
599
+ If you specify `--resume`, specify `--resume_from_huggingface` to download the state from HuggingFace and resume. The --resume option will be `--resume {repo_id}/{path_in_repo}:{revision}:{repo_type}`.
600
+
601
+ For example: `--resume_from_huggingface --resume your-hf-name/your-model/path/test-000002-state:main:model`
602
+
603
+ Specify `--async_upload` to upload asynchronously.
604
+
605
+ ## Optimizer-related
606
+
607
+ - `--optimizer_type`
608
+ -- Specify the type of optimizer. The following can be specified.
609
+ - AdamW : [torch.optim.AdamW](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html)
610
+ - Same as when no option specified in past versions
611
+ - AdamW8bit : Same arguments as above
612
+ - PagedAdamW8bit : Same arguments as above
613
+ - Same as when `--use_8bit_adam` specified in past versions
614
+ - Lion : <https://github.com/lucidrains/lion-pytorch>
615
+ - Same as when `--use_lion_optimizer` specified in past versions
616
+ - Lion8bit : Same arguments as above
617
+ - PagedLion8bit : Same arguments as above
618
+ - SGDNesterov : [torch.optim.SGD](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html), nesterov=True
619
+ - SGDNesterov8bit : Same arguments as above
620
+ - DAdaptation(DAdaptAdamPreprint) : <https://github.com/facebookresearch/dadaptation>
621
+ - DAdaptAdam : Same arguments as above
622
+ - DAdaptAdaGrad : Same arguments as above
623
+ - DAdaptAdan : Same arguments as above
624
+ - DAdaptAdanIP : Same arguments as above
625
+ - DAdaptLion : Same arguments as above
626
+ - DAdaptSGD : Same arguments as above
627
+ - Prodigy : <https://github.com/konstmish/prodigy>
628
+ - AdaFactor : [Transformers AdaFactor](https://huggingface.co/docs/transformers/main_classes/optimizer_schedules)
629
+ - Any optimizer
630
+
631
+ - `--learning_rate`
632
+
633
+ Specify the learning rate. The appropriate learning rate varies depending on the learning script, so please refer to the descriptions for each.
634
+
635
+ - `--lr_scheduler` / `--lr_warmup_steps` / `--lr_scheduler_num_cycles` / `--lr_scheduler_power`
636
+
637
+ Specifications related to the learning rate scheduler.
638
+
639
+ With the lr_scheduler option, you can select a learning rate scheduler from linear, cosine, cosine_with_restarts, polynomial, constant, constant_with_warmup, or any scheduler. The default is constant.
640
+
641
+ With lr_warmup_steps, you can specify the number of steps for the scheduler's warmup (gradually changing the learning rate).
642
+
643
+ lr_scheduler_num_cycles is the number of restarts for the cosine with restarts scheduler, and lr_scheduler_power is the polynomial power for the polynomial scheduler.
644
+
645
+ For more details, please refer to the scheduler's documentation.
646
+
647
+ If you use any scheduler, specify the options as arguments with `--scheduler_args` in the same way as for any optimizer.
648
+
649
+ ### Specifying the Optimizer
650
+
651
+ To specify the arguments for the optimizer, use the `--optimizer_args` option. Specify the arguments in the format of `key=value`, and multiple values can be specified by separating them with commas. For example, to specify arguments for the AdamW optimizer, you would use `--optimizer_args weight_decay=0.01 betas=.9,.999`.
652
+
653
+ When specifying the arguments, please refer to the specifications of each optimizer.
654
+
655
+ Some optimizers require certain arguments, and if they are omitted, they will be automatically added (e.g., SGDNesterov's momentum). Check the console output for details.
656
+
657
+ The D-Adaptation optimizer adjusts the learning rate automatically. The value specified for the learning rate option is the rate of application of the learning rate determined by D-Adaptation, not the actual learning rate itself, so it is usually recommended to specify 1.0. If you want to specify half the learning rate for the text encoder and the full learning rate for the U-Net, you can specify `--text_encoder_lr=0.5 --unet_lr=1.0`.
658
+
659
+ The AdaFactor optimizer can adjust the learning rate automatically by specifying `relative_step=True` (which is added by default if omitted). To adjust the learning rate, the learning rate scheduler should be set to `adafactor_scheduler`. It is also recommended to specify `scale_parameter` and `warmup_init`.
660
+
661
+ The options for adjusting the learning rate are specified as `--optimizer_args "relative_step=True" "scale_parameter=True" "warmup_init=True"`.
662
+
663
+ If you do not want to adjust the learning rate, specify the argument `relative_step=False`. In this case, the learning rate scheduler should be set to `constant_with_warmup`, and it is recommended not to clip the gradient norm. The arguments would be `--optimizer_type=adafactor --optimizer_args "relative_step=False" --lr_scheduler="constant_with_warmup" --max_grad_norm=0.0`.
664
+
665
+ ### Using Any Optimizer
666
+
667
+ To use an optimizer from `torch.optim`, specify only the class name (e.g., `--optimizer_type=RMSprop`). For other optimizers from other modules, specify the module name and class name separated by a period (e.g., `--optimizer_type=bitsandbytes.optim.lamb.LAMB`).
668
+
669
+ (Note: This is implemented using `importlib` internally, and the actual behavior is not confirmed. If necessary, please install the necessary package.)
670
+
671
+ <!--
672
+ ## Training with arbitrary image size --resolution
673
+ You can train with non-square images. Specify the resolution as "448,640" for example, where "width,height". The width and height must be divisible by 64. Make sure the size of the training image and regularization image are the same.
674
+
675
+ Personally, I often generate vertical images, so I train with "448,640" and so on.
676
+
677
+ ## Aspect Ratio Bucketing --enable_bucket / --min_bucket_reso / --max_bucket_reso
678
+ When you specify the enable_bucket option, it will be enabled. Stable Diffusion is trained at 512x512, but also learns at resolutions such as 256x768 and 384x640.
679
+
680
+ In this case, you do not need to unify the training image and regularization image to a specific resolution. You can select the optimal resolution from several resolutions (aspect ratios) and learn with that resolution.
681
+ The resolution is in units of 64 pixels, so the original image and aspect ratio may not match exactly, in which case the trimmed part is slightly trimmed.
682
+
683
+ You can specify the minimum size with the min_bucket_reso option and the maximum size with the max_bucket_reso option. The default is 256 and 1024 respectively.
684
+ For example, if you specify a minimum size of 384, resolutions such as 256x1024 or 320x768 will not be used.
685
+ If you increase the resolution to 768x768 or more, you may want to specify a maximum size of 1280 or so.
686
+
687
+ It may be beneficial to prepare various resolutions with similar trends to the training image for regularization images when enabling Aspect Ratio Bucketing.
688
+
689
+ (The images in a batch do not deviate significantly from the training image and regularization image, so it may not have a significant impact, but...)
690
+
691
+ ## augmentation --color_aug / --flip_aug
692
+ Augmentation is a method to improve the model's performance by dynamically changing the data during training. It changes the color slightly with color_aug and flips left and right with flip_aug during training.
693
+
694
+ Since the data is dynamically changed, it cannot be specified with the cache_latents option at the same time.
695
+
696
+ ## Training with fp16 gradients (experimental feature) --full_fp16
697
+ If you specify the full_fp16 option, the gradient will be changed from the usual float32 to float16 (fp16) during training (not mixed precision, but full fp16 training).
698
+ This allows you to train at 512x512 size with less than 8GB VRAM for SD1.x and less than 12GB VRAM for SD2.x.
699
+
700
+ Please specify fp16 in advance with accelerate config and specify ``mixed_precision="fp16"`` option (bf16 does not work).
701
+
702
+ To minimize memory usage, specify the xformers, use_8bit_adam, cache_latents, and gradient_checkpointing options, and set train_batch_size to 1.
703
+
704
+ (If you have the time, you can gradually increase the train_batch_size to slightly improve accuracy.)
705
+
706
+ I'm patching the PyTorch source to force it (confirmed with PyTorch 1.12.1 and 1.13.0). The accuracy will drop significantly, and the likelihood of training failure will also increase.
707
+ The learning rate and number of steps are also sensitive. Please be aware of these and use them at your own risk.
708
+ -->
709
+
710
+ # Creating Metadata Files
711
+
712
+ ## Preparing Teacher Data
713
+
714
+ As described above, prepare the image data you want to learn and put it in any folder.
715
+
716
+ For example, you can store the images as follows:
717
+
718
+ ![Screenshot of Teacher Data Folder](https://user-images.githubusercontent.com/52813779/208907739-8e89d5fa-6ca8-4b60-8927-f484d2a9ae04.png)
719
+
720
+ ## Automatic Captioning
721
+
722
+ If you want to learn only with tags without captions, skip this section.
723
+
724
+ If you want to prepare captions manually, prepare the captions in the same directory as the teacher data images, with the same file name, but with the extension .caption, for example. Each file should be a single-line text file.
725
+
726
+ ### Captioning with BLIP
727
+
728
+ With the latest version, you no longer need to download BLIP, download weights, or add a virtual environment. It should work as is.
729
+
730
+ Run make_captions.py in the finetune folder.
731
+
732
+ ```
733
+ python finetune\make_captions.py --batch_size <batch_size> <teacher_data_folder>
734
+ ```
735
+
736
+ If you put the teacher data in the parent folder's train_data, it would look like this:
737
+
738
+ ```
739
+ python finetune\make_captions.py --batch_size 8 ..\train_data
740
+ ```
741
+
742
+ Caption files are created in the same directory as the teacher data images, with the same file name, but with the extension .caption.
743
+
744
+ You can adjust the batch_size according to the capacity of your GPU's VRAM. Larger is faster (I think it can be increased even with VRAM 12GB).
745
+ You can specify the maximum length of the caption with the max_length option. The default is 75. If you want to increase it for models trained with token length 225, you can increase it.
746
+ You can change the extension of the caption with the caption_extension option. The default is .caption (if you change it to .txt, it will conflict with DeepDanbooru in the next section).
747
+
748
+ If there are multiple teacher data folders, run for each folder.
749
+
750
+ Note that inference has randomness, so the results will vary each time you run. To fix it, specify the random seed with the `--seed` option, such as `--seed 42`.
751
+
752
+ For other options, refer to the help with `--help` (the meanings of parameters are not well documented, so you need to refer to the source).
753
+
754
+ By default, caption files are generated with the extension .caption.
755
+
756
+ ![Folder with Generated Captions](https://user-images.githubusercontent.com/52813779/208908845-48a9d36c-f6ee-4dae-af71-9ab462d1459e.png)
757
+
758
+ For example, the captions might look like this:
759
+
760
+ ![Caption and Image](https://user-images.githubusercontent.com/52813779/208908947-af936957-5d73-4339-b6c8-945a52857373.png)
761
+
762
+ ## Tagging with DeepDanbooru
763
+
764
+ If you do not want to tag with danbooru tags yourself, proceed to "Preprocessing Captions and Tag Information".
765
+
766
+ Tagging is done with DeepDanbooru or WD14Tagger. WD14Tagger seems to have higher accuracy. If you want to tag with WD14Tagger, proceed to the next section.
767
+
768
+ ### Setting up the Environment
769
+
770
+ Clone DeepDanbooru <https://github.com/KichangKim/DeepDanbooru> into your working directory or download the zip and extract it. I extracted it.
771
+ Also, download deepdanbooru-v3-20211112-sgd-e28.zip from the Releases page <https://github.com/KichangKim/DeepDanbooru/releases> and extract it into the DeepDanbooru folder.
772
+
773
+ Download from the following page:
774
+
775
+ ![DeepDanbooru Download Page](https://user-images.githubusercontent.com/52813779/208909417-10e597df-7085-41ee-bd06-3e856a1339df.png)
776
+
777
+ Set up the directory structure as follows:
778
+
779
+ ![DeepDanbooru Directory Structure](https://user-images.githubusercontent.com/52813779/208909486-38935d8b-8dc6-43f1-84d3-fef99bc471aa.png)
780
+
781
+ Install the necessary libraries for the Diffusers environment. Move to the DeepDanbooru folder and install (I think it just adds tensorflow-io).
782
+
783
+ ```
784
+ pip install -r requirements.txt
785
+ ```
786
+
787
+ Next, install DeepDanbooru itself.
788
+
789
+ ```
790
+ pip install .
791
+ ```
792
+
793
+ With these steps, the tagging environment setup is complete.
794
+
795
+ ### Tagging
796
+
797
+ Move to the DeepDanbooru folder and run deepdanbooru to tag.
798
+
799
+ ```
800
+ deepdanbooru evaluate <teacher_data_folder> --project-path deepdanbooru-v3-20211112-sgd-e28 --allow-folder --save-txt
801
+ ```
802
+
803
+ If you put the teacher data in the parent folder's train_data, it will look like this:
804
+
805
+ ```
806
+ deepdanbooru evaluate ../train_data --project-path deepdanbooru-v3-20211112-sgd-e28 --allow-folder --save-txt
807
+ ```
808
+
809
+ The tag file is created in the same directory as the teacher data image, with the same file name and extension .txt. It is processed one by one, so it is quite slow.
810
+
811
+ If there are multiple teacher data folders, please run for each folder.
812
+
813
+ The following will be generated:
814
+
815
+ ![DeepDanbooru Generated Files](https://user-images.githubusercontent.com/52813779/208909855-d21b9c98-f2d3-4283-8238-5b0e5aad6691.png)
816
+
817
+ The tags look like this (a lot of information...).
818
+
819
+ ![DeepDanbooru Tags and Images](https://user-images.githubusercontent.com/52813779/208909908-a7920174-266e-48d5-aaef-940aba709519.png)
820
+
821
+ ## Tagging with WD14Tagger
822
+
823
+ Steps to use WD14Tagger instead of DeepDanbooru.
824
+
825
+ We use the tagger used in Automatic1111's WebUI. Please refer to the information on the following github page (<https://github.com/toriato/stable-diffusion-webui-wd14-tagger#mrsmilingwolfs-model-aka-waifu-diffusion-14-tagger>).
826
+
827
+ The necessary modules for the initial setup are already installed. The weights are automatically downloaded from Hugging Face.
828
+
829
+ ### Tagging
830
+
831
+ Run the script to tag.
832
+
833
+ ```
834
+ python tag_images_by_wd14_tagger.py --batch_size <batch_size> <teacher_data_folder>
835
+ ```
836
+
837
+ If you put the teacher data in the parent folder's train_data, it will look like this:
838
+
839
+ ```
840
+ python tag_images_by_wd14_tagger.py --batch_size 4 ..\train_data
841
+ ```
842
+
843
+ The model file is automatically downloaded to the wd14_tagger_model folder on the first run (you can specify the folder with the model_dir option).
844
+
845
+ ![Downloaded Files](https://user-images.githubusercontent.com/52813779/208910447-f7eb0582-90d6-49d3-a666-2b508c7d1842.png)
846
+
847
+ The tag file is created in the same directory as the teacher data image, with the same file name and extension .txt.
848
+
849
+ ![Generated Tag File](https://user-images.githubusercontent.com/52813779/208910534-ea514373-1185-4b7d-9ae3-61eb50bc294e.png)
850
+
851
+ ![Tags and Images](https://user-images.githubusercontent.com/52813779/208910599-29070c15-7639-474f-b3e4-06bd5a3df29e.png)
852
+
853
+ The thresh option specifies the minimum confidence (probability) for a tag to be assigned. The default is the same as the WD14Tagger sample, 0.35. Lowering the value will increase the number of tags, but the accuracy will decrease.
854
+
855
+ The batch_size depends on the VRAM capacity of the GPU. Larger is faster (even if you can increase it a bit with a VRAM of 12GB). The caption_extension option allows you to change the extension of the tag file. The default is .txt.
856
+
857
+ The model_dir option allows you to specify the destination folder for the model.
858
+
859
+ The force_download option forces the model to be re-downloaded even if the destination folder already exists.
860
+
861
+ If there are multiple teacher data folders, please run for each folder.
862
+
863
+ ## Preprocessing of captions and tag information
864
+
865
+ To make it easier to process from the script, we aggregate the captions and tags into one metadata file.
866
+
867
+ ### Preprocessing of captions
868
+
869
+ To put the captions into the metadata, run the following in the working directory (if you don't use captions for learning, you don't need to run it) (actually, it's written in one line, as follows). The `--full_path` option stores the location of the image file in the metadata as a full path. If this option is omitted, the relative path is recorded, but the folder specification is required in the `.toml` file separately.
870
+
871
+ ```
872
+ python merge_captions_to_metadata.py --full_path <teacher_data_folder>
873
+   --in_json <metadata_file_to_read> <metadata_file_to_write>
874
+ ```
875
+
876
+ The metadata file name is arbitrary.
877
+ If the teacher data is train_data, there is no metadata file to read, and the metadata file to write is meta_cap.json, it will look like this:
878
+
879
+ ```
880
+ python merge_captions_to_metadata.py --full_path train_data meta_cap.json
881
+ ```
882
+
883
+ The caption_extension option allows you to specify the extension of the caption.
884
+
885
+ If there are multiple teacher data folders, specify the full_path argument and run for each folder.
886
+
887
+ ```
888
+ python merge_captions_to_metadata.py --full_path
889
+ train_data1 meta_cap1.json
890
+ python merge_captions_to_metadata.py --full_path --in_json meta_cap1.json
891
+ train_data2 meta_cap2.json
892
+ ```
893
+
894
+ If in_json is omitted, it will read from the existing metadata file and overwrite it.
895
+
896
+ __※If you specify in_json and write to a different metadata file each time, it is safer.__
897
+
898
+ ### Preprocessing of tags
899
+
900
+ Similarly, we can also put the tags into the metadata (if you don't use tags for learning, you don't need to run it).
901
+
902
+ ```
903
+ python merge_dd_tags_to_metadata.py --full_path <teacher_data_folder>
904
+ --in_json <metadata_file_to_read> <metadata_file_to_write>
905
+ ```
906
+
907
+ If the same directory structure as before, read meta_cap.json and write to meta_cap_dd.json, it will look like this:
908
+
909
+ ```
910
+ python merge_dd_tags_to_metadata.py --full_path train_data --in_json meta_cap.json meta_cap_dd.json
911
+ ```
912
+
913
+ If there are multiple teacher data folders, specify the full_path argument and run for each folder.
914
+
915
+ ```
916
+ python merge_dd_tags_to_metadata.py --full_path --in_json meta_cap2.json
917
+ train_data1 meta_cap_dd1.json
918
+ python merge_dd_tags_to_metadata.py --full_path --in_json meta_cap_dd1.json
919
+ train_data2 meta_cap_dd2.json
920
+ ```
921
+
922
+ If in_json is omitted, it will read from the existing metadata file and overwrite it.
923
+
924
+ __※If you specify in_json and write to a different metadata file each time, it is safer.__
925
+
926
+ ### Cleaning of captions and tags
927
+
928
+ So far, the metadata file has been assembled with captions and DeepDanbooru tags. However, the automatically captioned captions are slightly awkward (※), and the tags contain underscores and ratings, so (for DeepDanbooru) it is better to clean up the captions and tags using the editor's replace function.
929
+
930
+ ※For example, if you are learning about anime girls, the captions may contain variations such as girl/girls/woman/women. Also, "anime girl" could be simply "girl".
931
+
932
+ A script is prepared for cleaning, so please edit the script contents according to the situation.
933
+
934
+ (No need to specify the teacher data folder. Clean all data in the metadata.)
935
+
936
+ ```
937
+ python clean_captions_and_tags.py <metadata_file_to_read> <metadata_file_to_write>
938
+ ```
939
+
940
+ --in_json is not specified, so please be careful. For example, it will look like this:
941
+
942
+ ```
943
+ python clean_captions_and_tags.py meta_cap_dd.json meta_clean.json
944
+ ```
945
+
946
+ So far, the preprocessing of captions and tags is complete.
947
+
948
+ ## Pre-acquisition of latents
949
+
950
+ ※ This step is not required. You can omit it and learn while acquiring latents.
951
+ Also, if you perform `random_crop` or `color_aug` during learning, latents cannot be acquired in advance (because the image is changed every time). If you do not acquire it in advance, you can learn with the metadata up to this point.
952
+
953
+ Pre-acquire the latent representations of the images and save them to the disk. This allows you to speed up the learning process. Also, perform bucketing (classify teacher data according to aspect ratio).
954
+
955
+ Enter the following in the working directory:
956
+
957
+ ```
958
+ python prepare_buckets_latents.py --full_path <teacher_data_folder>
959
+ <metadata_file_to_read> <metadata_file_to_write>
960
+ <model_name_or_checkpoint>
961
+ --batch_size <batch_size>
962
+ --max_resolution <resolution width,height>
963
+ --mixed_precision <precision>
964
+ ```
965
+
966
+ If the model is model.ckpt, the batch size is 4, the learning resolution is 512*512, the precision is no (float32), read the metadata from meta_clean.json and write to meta_lat.json, it will look like this:
967
+
968
+ ```
969
+ python prepare_buckets_latents.py --full_path
970
+ train_data meta_clean.json meta_lat.json model.ckpt
971
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
972
+ ```
973
+
974
+ The teacher data folder will save the latents in numpy's npz format.
975
+
976
+ You can specify the minimum resolution with the --min_bucket_reso option and the maximum resolution with the --max_bucket_reso option. The default is 256 and 1024, respectively. For example, if you specify a minimum resolution of 384, resolutions such as 256*1024 or 320*768 will not be used.
977
+ If you increase the resolution to 768*768 or larger, it is recommended to specify a maximum resolution of 1280 or higher.
978
+
979
+ Specify the --flip_aug option to perform augmentation (data expansion) of left-right flips. This can artificially double the amount of data, but if the data is not symmetrical on the left and right (for example, character appearance, hair type, etc.), it may not learn well.
980
+
981
+ (A simple implementation is to acquire latents for flipped images and save them to a file named *_flip.npz. There is no need to specify any options in fine_tune.py. If there is a file with _flip, it will randomly read either the flipped or non-flipped file.)
982
+
983
+ The batch size can be increased a little with VRAM 12GB.
984
+ The resolution must be a multiple of 64, specified as "width,height". The resolution is directly related to the memory size during fine tuning. With VRAM 12GB, 512,512 seems to be the limit (※). With 16GB, you can increase it to 512,704 or 512,768. However, with 256,256, it is said to be difficult with VRAM 8GB (parameters, optimizer, etc. require a certain amount of memory regardless of resolution).
985
+
986
+ ※It has been reported that a batch size of 1 can run with 12GB VRAM at 640,640.
987
+
988
+ The following shows the results of bucketing.
989
+
990
+ ![bucketing results](https://user-images.githubusercontent.com/52813779/208911419-71c00fbb-2ce6-49d5-89b5-b78d7715e441.png)
991
+
992
+ If there are multiple teacher data folders, specify the full_path argument and run for each folder.
993
+
994
+ ```
995
+ python prepare_buckets_latents.py --full_path
996
+ train_data1 meta_clean.json meta_lat1.json model.ckpt
997
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
998
+
999
+ python prepare_buckets_latents.py --full_path
1000
+ train_data2 meta_lat1.json meta_lat2.json model.ckpt
1001
+ --batch_size 4 --max_resolution 512,512 --mixed_precision no
1002
+
1003
+ ```
1004
+
1005
+ It is also possible to read and write to the same file, but it is safer to use different files.
1006
+
1007
+ __※If you specify in_json and write to a different metadata file each time, it is safer.__
docs/train_db_README-ja.md ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DreamBoothのガイドです。
2
+
3
+ [学習についての共通ドキュメント](./train_README-ja.md) もあわせてご覧ください。
4
+
5
+ # 概要
6
+
7
+ DreamBoothとは、画像生成モデルに特定の主題を追加学習し、それを特定の識別子で生成する技術です。[論文はこちら](https://arxiv.org/abs/2208.12242)。
8
+
9
+ 具体的には、Stable Diffusionのモデルにキャラや画風などを学ばせ、それを `shs` のような特定の単語で呼び出せる(生成画像に出現させる)ことができます。
10
+
11
+ スクリプトは[DiffusersのDreamBooth](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth)を元にしていますが、以下のような機能追加を行っています(いくつかの機能は元のスクリプト側もその後対応しています)。
12
+
13
+ スクリプトの主な機能は以下の通りです。
14
+
15
+ - 8bit Adam optimizerおよびlatentのキャッシュによる省メモリ化([Shivam Shrirao氏版](https://github.com/ShivamShrirao/diffusers/tree/main/examples/dreambooth)と同様)。
16
+ - xformersによる省メモリ化。
17
+ - 512x512だけではなく任意サイズでの学習。
18
+ - augmentationによる品質の向上。
19
+ - DreamBoothだけではなくText Encoder+U-Netのfine tuningに対応。
20
+ - Stable Diffusion形式でのモデルの読み書き。
21
+ - Aspect Ratio Bucketing。
22
+ - Stable Diffusion v2.0対応。
23
+
24
+ # 学習の手順
25
+
26
+ あらかじめこのリポジトリのREADMEを参照し、環境整備を行ってください。
27
+
28
+ ## データの準備
29
+
30
+ [学習データの準備について](./train_README-ja.md) を参照してください。
31
+
32
+ ## 学習の実行
33
+
34
+ スクリプトを実行します。最大限、メモリを節約したコマンドは以下のようになります(実際には1行で入力します)。それぞれの行を必要に応じて書き換えてください。12GB程度のVRAMで動作するようです。
35
+
36
+ ```
37
+ accelerate launch --num_cpu_threads_per_process 1 train_db.py
38
+ --pretrained_model_name_or_path=<.ckptまたは.safetensordまたはDiffusers版モデルのディレクトリ>
39
+ --dataset_config=<データ準備で作成した.tomlファイル>
40
+ --output_dir=<学習したモデルの出力先フォルダ>
41
+ --output_name=<学習したモデル出力時のファイル名>
42
+ --save_model_as=safetensors
43
+ --prior_loss_weight=1.0
44
+ --max_train_steps=1600
45
+ --learning_rate=1e-6
46
+ --optimizer_type="AdamW8bit"
47
+ --xformers
48
+ --mixed_precision="fp16"
49
+ --cache_latents
50
+ --gradient_checkpointing
51
+ ```
52
+
53
+ `num_cpu_threads_per_process` には通常は1を指定するとよいようです。
54
+
55
+ `pretrained_model_name_or_path` に追加学習を行う元となるモデルを指定します。Stable Diffusionのcheckpointファイル(.ckptまたは.safetensors)、Diffusersのローカルディスクにあるモデルディレクトリ、DiffusersのモデルID("stabilityai/stable-diffusion-2"など)が指定できます。
56
+
57
+ `output_dir` に学習後のモデルを保存するフォルダを指定します。`output_name` にモデルのファイル名を拡張子を除いて指定します。`save_model_as` でsafetensors形式での保存を指定しています。
58
+
59
+ `dataset_config` に `.toml` ファイルを指定します。ファイル内でのバッチサイズ指定は、当初はメモリ消費を抑えるために `1` としてください。
60
+
61
+ `prior_loss_weight` は正則化画像のlossの重みです。通常は1.0を指定します。
62
+
63
+ 学習させるステップ数 `max_train_steps` を1600とします。学習率 `learning_rate` はここでは1e-6を指定しています。
64
+
65
+ 省メモリ化のため `mixed_precision="fp16"` を指定します(RTX30 シリーズ以降では `bf16` も指定できます。環境整備時にaccelerateに行った設定と合わせてください)。また `gradient_checkpointing` を指定します。
66
+
67
+ オプティマイザ(モデルを学習データにあうように最適化=学習させるクラス)にメモリ消費の少ない 8bit AdamW を使うため、 `optimizer_type="AdamW8bit"` を指定します。
68
+
69
+ `xformers` オプションを指定し、xformersのCrossAttentionを用います。xformersをインストールしていない場合やエラーとなる場合(環境にもよりますが `mixed_precision="no"` の場合など)、代わりに `mem_eff_attn` オプションを指定すると省メモリ版CrossAttentionを使用します(速度は遅くなります)。
70
+
71
+ 省メモリ化のため `cache_latents` オプションを指定してVAEの出力をキャッシュします。
72
+
73
+ ある程度メモリがある場合は、`.toml` ファイルを編集してバッチサイズをたとえば `4` くらいに増やしてください(高速化と精度向上の可能性があります)。また `cache_latents` を外すことで augmentation が可能になります。
74
+
75
+ ### よく使われるオプションについて
76
+
77
+ 以下の場合には [学習の共通ドキュメント](./train_README-ja.md) の「よく使われるオプション」を参照してください。
78
+
79
+ - Stable Diffusion 2.xまたはそこからの派生モデルを学習する
80
+ - clip skipを2以上を前提としたモデルを学習する
81
+ - 75トークンを超えたキャプションで学習する
82
+
83
+ ### DreamBoothでのステップ数について
84
+
85
+ 当スクリプトでは省メモリ化のため、ステップ当たりの学習回数が元のスクリプトの半分になっています(対象の画像と正則化画像を同一のバッチではなく別のバッチに分割して学習するため)。
86
+
87
+ 元のDiffusers版やXavierXiao氏のStable Diffusion版とほぼ同じ学習を行うには、ステップ数を倍にしてください。
88
+
89
+ (学習画像と正則化画像をまとめてから shuffle するため厳密にはデータの順番が変わってしまいますが、学習には大きな影響はないと思います。)
90
+
91
+ ### DreamBoothでのバッチサイズについて
92
+
93
+ モデル全体を学習するためLoRA等の学習に比べるとメモリ消費量は多くなります(fine tuningと同じ)。
94
+
95
+ ### 学習率について
96
+
97
+ Diffusers版では5e-6ですがStable Diffusion版は1e-6ですので、上のサンプルでは1e-6を指定しています。
98
+
99
+ ### 以前の形式のデータセット指定をした場合のコマンドライン
100
+
101
+ 解像度やバッチサイズをオプションで指定します。コマンドラインの例は以下の通りです。
102
+
103
+ ```
104
+ accelerate launch --num_cpu_threads_per_process 1 train_db.py
105
+ --pretrained_model_name_or_path=<.ckptまたは.safetensordまたはDiffusers版モデルのディレクトリ>
106
+ --train_data_dir=<学習用データのディレクトリ>
107
+ --reg_data_dir=<正則化画像のディレクトリ>
108
+ --output_dir=<学習したモデルの出力先ディレクトリ>
109
+ --output_name=<学習したモデル出力時のファイル名>
110
+ --prior_loss_weight=1.0
111
+ --resolution=512
112
+ --train_batch_size=1
113
+ --learning_rate=1e-6
114
+ --max_train_steps=1600
115
+ --use_8bit_adam
116
+ --xformers
117
+ --mixed_precision="bf16"
118
+ --cache_latents
119
+ --gradient_checkpointing
120
+ ```
121
+
122
+ ## 学習したモデルで画像生成する
123
+
124
+ 学習が終わると指定したフォルダに指定した名前でsafetensorsファイルが出力されます。
125
+
126
+ v1.4/1.5およびその他の派生モデルの場合、このモデルでAutomatic1111氏のWebUIなどで推論できます。models\Stable-diffusionフォルダに置いてください。
127
+
128
+ v2.xモデルでWebUIで画像生成する場合、モデルの仕様が記述された.yamlファイルが別途必要になります。v2.x baseの場合はv2-inference.yamlを、768/vの場合はv2-inference-v.yamlを、同じフォルダに置き、拡張子の前の部分をモデルと同じ名前にしてください。
129
+
130
+ ![image](https://user-images.githubusercontent.com/52813779/210776915-061d79c3-6582-42c2-8884-8b91d2f07313.png)
131
+
132
+ 各yamlファイルは[Stability AIのSD2.0のリポジトリ](https://github.com/Stability-AI/stablediffusion/tree/main/configs/stable-diffusion)にあります。
133
+
134
+ # DreamBooth特有のその他の主なオプション
135
+
136
+ すべてのオプションについては別文書を参照してください。
137
+
138
+ ## Text Encoderの学習を途中から行わない --stop_text_encoder_training
139
+
140
+ stop_text_encoder_trainingオプションに数値を指定すると、そのステップ数以降はText Encoderの学習を行わずU-Netだけ学習します。場合によっては精度の向上が期待できるかもしれません。
141
+
142
+ (恐らくText Encoderだけ先に過学習することがあり、それを防げるのではないかと推測していますが、詳細な影響は不明です。)
143
+
144
+ ## Tokenizerのパディングをしない --no_token_padding
145
+ no_token_paddingオプションを指定するとTokenizerの出力をpaddingしません(Diffusers版の旧DreamBoothと同じ動きになります)。
146
+
147
+
148
+ <!--
149
+ bucketing(後述)を利用しかつaugmentation(後述)を使う場合の例は以下のようになります。
150
+
151
+ ```
152
+ accelerate launch --num_cpu_threads_per_process 8 train_db.py
153
+ --pretrained_model_name_or_path=<.ckptまたは.safetensordまたはDiffusers版モデルのディレクトリ>
154
+ --train_data_dir=<学習用データのディレクトリ>
155
+ --reg_data_dir=<正則化画像のディレクトリ>
156
+ --output_dir=<学習したモデルの出力先ディレクトリ>
157
+ --resolution=768,512
158
+ --train_batch_size=20 --learning_rate=5e-6 --max_train_steps=800
159
+ --use_8bit_adam --xformers --mixed_precision="bf16"
160
+ --save_every_n_epochs=1 --save_state --save_precision="bf16"
161
+ --logging_dir=logs
162
+ --enable_bucket --min_bucket_reso=384 --max_bucket_reso=1280
163
+ --color_aug --flip_aug --gradient_checkpointing --seed 42
164
+ ```
165
+
166
+
167
+ -->
docs/train_db_README-zh.md ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 这是DreamBooth的指南。
2
+
3
+ 请同时查看[关于学习的通用文档](./train_README-zh.md)。
4
+
5
+ # 概要
6
+
7
+ DreamBooth是一种将特定主题添加到图像生成模型中进行学习,并使用特定识别子生成它的技术。论文链接。
8
+
9
+ 具体来说,它可以将角色和绘画风格等添加到Stable Diffusion模型中进行学习,并使用特定的单词(例如`shs`)来调用(呈现在生成的图像中)。
10
+
11
+ 脚本基于Diffusers的DreamBooth,但添加了以下功能(一些功能已在原始脚本中得到支持)。
12
+
13
+ 脚本的主要功能如下:
14
+
15
+ - 使用8位Adam优化器和潜在变量的缓存来节省内存(与Shivam Shrirao版相似)。
16
+ - 使用xformers来节省内存。
17
+ - 不仅支持512x512,还支持任意尺寸的训练。
18
+ - 通过数据增强来提高质量。
19
+ - 支持DreamBooth和Text Encoder + U-Net的微调。
20
+ - 支持以Stable Diffusion格式读写模型。
21
+ - 支持Aspect Ratio Bucketing。
22
+ - 支持Stable Diffusion v2.0。
23
+
24
+ # 训练步骤
25
+
26
+ 请先参阅此存储库的README以进行环境设置。
27
+
28
+ ## 准备数据
29
+
30
+ 请参阅[有关准备训练数据的说明](./train_README-zh.md)。
31
+
32
+ ## 运行训练
33
+
34
+ 运行脚本。以下是最大程度地节省内存的命令(实际上,这将在一行中输入)。请根据需要修改每行。它似乎需要约12GB的VRAM才能运行。
35
+ ```
36
+ accelerate launch --num_cpu_threads_per_process 1 train_db.py
37
+ --pretrained_model_name_or_path=<.ckpt或.safetensord或Diffusers版模型的目录>
38
+ --dataset_config=<数据准备时创建的.toml文件>
39
+ --output_dir=<训练模型的输出目录>
40
+ --output_name=<训练模型输出时的文件名>
41
+ --save_model_as=safetensors
42
+ --prior_loss_weight=1.0
43
+ --max_train_steps=1600
44
+ --learning_rate=1e-6
45
+ --optimizer_type="AdamW8bit"
46
+ --xformers
47
+ --mixed_precision="fp16"
48
+ --cache_latents
49
+ --gradient_checkpointing
50
+ ```
51
+ `num_cpu_threads_per_process` 通常应该设置为1。
52
+
53
+ `pretrained_model_name_or_path` 指定要进行追加训练的基础模型。可以指定 Stable Diffusion 的 checkpoint 文件(.ckpt 或 .safetensors)、Diffusers 的本地模型目录或模型 ID(如 "stabilityai/stable-diffusion-2")。
54
+
55
+ `output_dir` 指定保存训练后模型的文件夹。在 `output_name` 中指定模型文件名,不包括扩展名。使用 `save_model_as` 指定以 safetensors 格式保存。
56
+
57
+ 在 `dataset_config` 中指定 `.toml` 文件。初始批处理大小应为 `1`,以减少内存消耗。
58
+
59
+ `prior_loss_weight` 是正则化图像损失的权重。通常设为1.0。
60
+
61
+ 将要训练的步数 `max_train_steps` 设置为1600。在这里,学习率 `learning_rate` 被设置为1e-6。
62
+
63
+ 为了节省内存,设置 `mixed_precision="fp16"`(在 RTX30 系列及更高版本中也可以设置为 `bf16`)。同时指定 `gradient_checkpointing`。
64
+
65
+ 为了使用内存消耗较少的 8bit AdamW 优化器(将模型优化为适合于训练数据的状态),指定 `optimizer_type="AdamW8bit"`。
66
+
67
+ 指定 `xformers` 选项,并使用 xformers 的 CrossAttention。如果未安装 xformers 或出现错误(具体情况取决于环境,例如使用 `mixed_precision="no"`),则可以指定 `mem_eff_attn` 选项以使用省内存版的 CrossAttention(速度会变慢)。
68
+
69
+ 为了节省内存,指定 `cache_latents` 选项以缓存 VAE 的输出。
70
+
71
+ 如果有足够的内存,请编辑 `.toml` 文件将批处理大小增加到大约 `4`(可能会提高速度和精度)。此外,取消 `cache_latents` 选项可以进行数据增强。
72
+
73
+ ### 常用选项
74
+
75
+ 对于以下情况,请参阅“常用选项”部分。
76
+
77
+ - 学习 Stable Diffusion 2.x 或其衍生模型。
78
+ - 学习基于 clip skip 大于等于2的模型。
79
+ - 学习超过75个令牌的标题。
80
+
81
+ ### 关于DreamBooth中的步数
82
+
83
+ 为了实现省内存化,该脚本中每个步骤的学习次数减半(因为学习和正则化的图像在训练时被分为不同的批次)。
84
+
85
+ 要进行与原始Diffusers版或XavierXiao的Stable Diffusion版几乎相同的学习,请将步骤数加倍。
86
+
87
+ (虽然在将学习图像和正则化图像整合后再打乱顺序,但我认为对学习没有太大影响。)
88
+
89
+ 关于DreamBooth的批量大小
90
+
91
+ 与像LoRA这样的学习相比,为了训练整个模型,内存消耗量会更大(与微调相同)。
92
+
93
+ 关于学习率
94
+
95
+ 在Diffusers版中,学习率为5e-6,而在Stable Diffusion版中为1e-6,因此在上面的示例中指定了1e-6。
96
+
97
+ 当使用旧格式的数据集指定命令行时
98
+
99
+ 使用选项指定分辨率和批量大小。命令行示例如下。
100
+ ```
101
+ accelerate launch --num_cpu_threads_per_process 1 train_db.py
102
+ --pretrained_model_name_or_path=<.ckpt或.safetensord或Diffusers版模型的目录>
103
+ --train_data_dir=<训练数据的目录>
104
+ --reg_data_dir=<正则化图像的目录>
105
+ --output_dir=<训练��模型的输出目录>
106
+ --output_name=<训练后模型输出文件的名称>
107
+ --prior_loss_weight=1.0
108
+ --resolution=512
109
+ --train_batch_size=1
110
+ --learning_rate=1e-6
111
+ --max_train_steps=1600
112
+ --use_8bit_adam
113
+ --xformers
114
+ --mixed_precision="bf16"
115
+ --cache_latents
116
+ --gradient_checkpointing
117
+ ```
118
+
119
+ ## 使用训练好的模型生成图像
120
+
121
+ 训练完成后,将在指定的文件夹中以指定的名称输出safetensors文件。
122
+
123
+ 对于v1.4/1.5和其他派生模型,可以在此模型中使用Automatic1111先生的WebUI进行推断。请将其放置在models\Stable-diffusion文件夹中。
124
+
125
+ 对于使用v2.x模型在WebUI中生成图像的情况,需要单独的.yaml文件来描述模型的规格。对于v2.x base,需要v2-inference.yaml,对于768/v,则需要v2-inference-v.yaml。请将它们放置在相同的文件夹中,并将文件扩展名之前的部分命名为与模型相同的名称。
126
+ ![image](https://user-images.githubusercontent.com/52813779/210776915-061d79c3-6582-42c2-8884-8b91d2f07313.png)
127
+
128
+ 每个yaml文件都在[Stability AI的SD2.0存储库](https://github.com/Stability-AI/stablediffusion/tree/main/configs/stable-diffusion)……之中。
129
+
130
+ # DreamBooth的其他主要选项
131
+
132
+ 有关所有选项的详细信息,请参阅另一份文档。
133
+
134
+ ## 不在中途开始对文本编码器进行训练 --stop_text_encoder_training
135
+
136
+ 如果在stop_text_encoder_training选项中指定一个数字,则在该步骤之后,将不再对文本编码器进行训练,只会对U-Net进行训练。在某些情况下,可能会期望提高精度。
137
+
138
+ (我们推测可能会有时候仅仅文本编码器会过度学习,而这样做可以避免这种情况,但详细影响尚不清楚。)
139
+
140
+ ## 不进行分词器的填充 --no_token_padding
141
+
142
+ 如果指定no_token_padding选项,则不会对分词器的输出进行填充(与Diffusers版本的旧DreamBooth相同)。
143
+
144
+ <!--
145
+ 如果使用分桶(bucketing)和数据增强(augmentation),则使用示例如下:
146
+ ```
147
+ accelerate launch --num_cpu_threads_per_process 8 train_db.py
148
+ --pretrained_model_name_or_path=<.ckpt或.safetensord或Diffusers版模型的目录>
149
+ --train_data_dir=<训练数据的目录>
150
+ --reg_data_dir=<正则化图像的目录>
151
+ --output_dir=<训练后模型的输出目录>
152
+ --resolution=768,512
153
+ --train_batch_size=20 --learning_rate=5e-6 --max_train_steps=800
154
+ --use_8bit_adam --xformers --mixed_precision="bf16"
155
+ --save_every_n_epochs=1 --save_state --save_precision="bf16"
156
+ --logging_dir=logs
157
+ --enable_bucket --min_bucket_reso=384 --max_bucket_reso=1280
158
+ --color_aug --flip_aug --gradient_checkpointing --seed 42
159
+ ```
160
+
161
+
162
+ -->
docs/train_lllite_README-ja.md ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ControlNet-LLLite について
2
+
3
+ __きわめて実験的な実装のため、将来的に大きく変更される可能性があります。__
4
+
5
+ ## 概要
6
+ ControlNet-LLLite は、[ControlNet](https://github.com/lllyasviel/ControlNet) の軽量版です。LoRA Like Lite という意味で、LoRAからインスピレーションを得た構造を持つ、軽量なControlNetです。現在はSDXLにのみ対応しています。
7
+
8
+ ## サンプルの重みファイルと推論
9
+
10
+ こちらにあります: https://huggingface.co/kohya-ss/controlnet-lllite
11
+
12
+ ComfyUIのカスタムノードを用意しています。: https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
13
+
14
+ 生成サンプルはこのページの末尾にあります。
15
+
16
+ ## モデル構造
17
+ ひとつのLLLiteモジュールは、制御用画像(以下conditioning image)を潜在空間に写像するconditioning image embeddingと、LoRAにちょっと似た構造を持つ小型のネットワークからなります。LLLiteモジュールを、LoRAと同様にU-NetのLinearやConvに追加します。詳しくはソースコードを参照してください。
18
+
19
+ 推論環境の制限で、現在はCrossAttentionのみ(attn1のq/k/v、attn2のq)に追加されます。
20
+
21
+ ## モデルの学習
22
+
23
+ ### データセットの準備
24
+ 通常のdatasetに加え、`conditioning_data_dir` で指定したディレクトリにconditioning imageを格納してください。conditioning imageは学習用画像と同じbasenameを持つ必要があります。また、conditioning imageは学習用画像と同じサイズに自動的にリサイズされます。conditioning imageにはキャプションファイルは不要です。
25
+
26
+ たとえば DreamBooth 方式でキャプションファイルを用いる場合の設定ファイルは以下のようになります。
27
+
28
+ ```toml
29
+ [[datasets.subsets]]
30
+ image_dir = "path/to/image/dir"
31
+ caption_extension = ".txt"
32
+ conditioning_data_dir = "path/to/conditioning/image/dir"
33
+ ```
34
+
35
+ 現時点の制約として、random_cropは使用できません。
36
+
37
+ 学習データとしては、元のモデルで生成した画像を学習用画像として、そこから加工した画像をconditioning imageとした、合成によるデータセットを用いるのがもっとも簡単です(データセットの品質的には問題があるかもしれません)。具体的なデータセットの合成方法については後述します。
38
+
39
+ なお、元モデルと異なる画風の画像を学習用画像とすると、制御に加えて、その画風についても学ぶ必要が生じます。ControlNet-LLLiteは容量が少ないため、画風学習には不向きです。このような場合には、後述の次元数を多めにしてください。
40
+
41
+ ### 学習
42
+ スクリプトで生成する場合は、`sdxl_train_control_net_lllite.py` を実行してください。`--cond_emb_dim` でconditioning image embeddingの次元数を指定できます。`--network_dim` でLoRA的モジュールのrankを指定できます。その他のオプションは`sdxl_train_network.py`に準じますが、`--network_module`の指定は不要です。
43
+
44
+ 学習時にはメモリを大量に使用しますので、キャッシュやgradient checkpointingなどの省メモリ化のオプションを有効にしてください。また`--full_bf16` オプションで、BFloat16を使用するのも有効です(RTX 30シリーズ以降のGPUが必要です)。24GB VRAMで動作確認しています。
45
+
46
+ conditioning image embeddingの次元数は、サンプルのCannyでは32を指定しています。LoRA的モジュールのrankは同じく64です。対象とするconditioning imageの特徴に合わせて調整してください。
47
+
48
+ (サンプルのCannyは恐らくかなり難しいと思われます。depthなどでは半分程度にしてもいいかもしれません。)
49
+
50
+ 以下は .toml の設定例です。
51
+
52
+ ```toml
53
+ pretrained_model_name_or_path = "/path/to/model_trained_on.safetensors"
54
+ max_train_epochs = 12
55
+ max_data_loader_n_workers = 4
56
+ persistent_data_loader_workers = true
57
+ seed = 42
58
+ gradient_checkpointing = true
59
+ mixed_precision = "bf16"
60
+ save_precision = "bf16"
61
+ full_bf16 = true
62
+ optimizer_type = "adamw8bit"
63
+ learning_rate = 2e-4
64
+ xformers = true
65
+ output_dir = "/path/to/output/dir"
66
+ output_name = "output_name"
67
+ save_every_n_epochs = 1
68
+ save_model_as = "safetensors"
69
+ vae_batch_size = 4
70
+ cache_latents = true
71
+ cache_latents_to_disk = true
72
+ cache_text_encoder_outputs = true
73
+ cache_text_encoder_outputs_to_disk = true
74
+ network_dim = 64
75
+ cond_emb_dim = 32
76
+ dataset_config = "/path/to/dataset.toml"
77
+ ```
78
+
79
+ ### 推論
80
+
81
+ スクリプトで生成する場合は、`sdxl_gen_img.py` を実行してください。`--control_net_lllite_models` でLLLiteのモデルファイルを指定できます。次元数はモデルファイルから自動取得します。
82
+
83
+ `--guide_image_path`で推論に��いるconditioning imageを指定してください。なおpreprocessは行われないため、たとえばCannyならCanny処理を行った画像を指定してください(背景黒に白線)。`--control_net_preps`, `--control_net_weights`, `--control_net_ratios` には未対応です。
84
+
85
+ ## データセットの合成方法
86
+
87
+ ### 学習用画像の生成
88
+
89
+ 学習のベースとなるモデルで画像生成を行います。Web UIやComfyUIなどで生成してください。画像サイズはモデルのデフォルトサイズで良いと思われます(1024x1024など)。bucketingを用いることもできます。その場合は適宜適切な解像度で生成してください。
90
+
91
+ 生成時のキャプション等は、ControlNet-LLLiteの利用時に生成したい画像にあわせるのが良いと思われます。
92
+
93
+ 生成した画像を任意のディレクトリに保存してください。このディレクトリをデータセットの設定ファイルで指定します。
94
+
95
+ 当リポジトリ内の `sdxl_gen_img.py` でも生成できます。例えば以下のように実行します。
96
+
97
+ ```dos
98
+ python sdxl_gen_img.py --ckpt path/to/model.safetensors --n_iter 1 --scale 10 --steps 36 --outdir path/to/output/dir --xformers --W 1024 --H 1024 --original_width 2048 --original_height 2048 --bf16 --sampler ddim --batch_size 4 --vae_batch_size 2 --images_per_prompt 512 --max_embeddings_multiples 1 --prompt "{portrait|digital art|anime screen cap|detailed illustration} of 1girl, {standing|sitting|walking|running|dancing} on {classroom|street|town|beach|indoors|outdoors}, {looking at viewer|looking away|looking at another}, {in|wearing} {shirt and skirt|school uniform|casual wear} { |, dynamic pose}, (solo), teen age, {0-1$$smile,|blush,|kind smile,|expression less,|happy,|sadness,} {0-1$$upper body,|full body,|cowboy shot,|face focus,} trending on pixiv, {0-2$$depth of fields,|8k wallpaper,|highly detailed,|pov,} {0-1$$summer, |winter, |spring, |autumn, } beautiful face { |, from below|, from above|, from side|, from behind|, from back} --n nsfw, bad face, lowres, low quality, worst quality, low effort, watermark, signature, ugly, poorly drawn"
99
+ ```
100
+
101
+ VRAM 24GBの設定です。VRAMサイズにより`--batch_size` `--vae_batch_size`を調整してください。
102
+
103
+ `--prompt`でワイルドカードを利用してランダムに生成しています。適宜調整してください。
104
+
105
+ ### 画像の加工
106
+
107
+ 外部のプログラムを用いて、生成した画像を加工します。加工した画像を任意のディレクトリに保存してください。これらがconditioning imageになります。
108
+
109
+ 加工にはたとえばCannyなら以下のようなスクリプトが使えます。
110
+
111
+ ```python
112
+ import glob
113
+ import os
114
+ import random
115
+ import cv2
116
+ import numpy as np
117
+
118
+ IMAGES_DIR = "path/to/generated/images"
119
+ CANNY_DIR = "path/to/canny/images"
120
+
121
+ os.makedirs(CANNY_DIR, exist_ok=True)
122
+ img_files = glob.glob(IMAGES_DIR + "/*.png")
123
+ for img_file in img_files:
124
+ can_file = CANNY_DIR + "/" + os.path.basename(img_file)
125
+ if os.path.exists(can_file):
126
+ print("Skip: " + img_file)
127
+ continue
128
+
129
+ print(img_file)
130
+
131
+ img = cv2.imread(img_file)
132
+
133
+ # random threshold
134
+ # while True:
135
+ # threshold1 = random.randint(0, 127)
136
+ # threshold2 = random.randint(128, 255)
137
+ # if threshold2 - threshold1 > 80:
138
+ # break
139
+
140
+ # fixed threshold
141
+ threshold1 = 100
142
+ threshold2 = 200
143
+
144
+ img = cv2.Canny(img, threshold1, threshold2)
145
+
146
+ cv2.imwrite(can_file, img)
147
+ ```
148
+
149
+ ### キャプションファイルの作成
150
+
151
+ 学習用画像のbasenameと同じ名前で、それぞれの画像に対応したキャプションファイルを作成してください。生成時のプロンプトをそのまま利用すれば良いと思われます。
152
+
153
+ `sdxl_gen_img.py` で生成した場合は、画像内のメタデータに生成時のプロンプトが記録されていますので、以下のようなスクリプトで学習用画像と同じディレクトリにキャプションファイルを作成できます(拡張子 `.txt`)。
154
+
155
+ ```python
156
+ import glob
157
+ import os
158
+ from PIL import Image
159
+
160
+ IMAGES_DIR = "path/to/generated/images"
161
+
162
+ img_files = glob.glob(IMAGES_DIR + "/*.png")
163
+ for img_file in img_files:
164
+ cap_file = img_file.replace(".png", ".txt")
165
+ if os.path.exists(cap_file):
166
+ print(f"Skip: {img_file}")
167
+ continue
168
+ print(img_file)
169
+
170
+ img = Image.open(img_file)
171
+ prompt = img.text["prompt"] if "prompt" in img.text else ""
172
+ if prompt == "":
173
+ print(f"Prompt not found in {img_file}")
174
+
175
+ with open(cap_file, "w") as f:
176
+ f.write(prompt + "\n")
177
+ ```
178
+
179
+ ### データセットの設定ファイルの作成
180
+
181
+ コマンドラインオプションからの指定も可能ですが、`.toml`ファイルを作成する場合は `conditioning_data_dir` に加工した画像を��存したディレクトリを指定します。
182
+
183
+ 以下は設定ファイルの例です。
184
+
185
+ ```toml
186
+ [general]
187
+ flip_aug = false
188
+ color_aug = false
189
+ resolution = [1024,1024]
190
+
191
+ [[datasets]]
192
+ batch_size = 8
193
+ enable_bucket = false
194
+
195
+ [[datasets.subsets]]
196
+ image_dir = "path/to/generated/image/dir"
197
+ caption_extension = ".txt"
198
+ conditioning_data_dir = "path/to/canny/image/dir"
199
+ ```
200
+
201
+ ## 謝辞
202
+
203
+ ControlNetの作者である lllyasviel 氏、実装上のアドバイスとトラブル解決へのご尽力をいただいた furusu 氏、ControlNetデータセットを実装していただいた ddPn08 氏に感謝いたします。
204
+
205
+ ## サンプル
206
+ Canny
207
+ ![kohya_ss_girl_standing_at_classroom_smiling_to_the_viewer_class_78976b3e-0d4d-4ea0-b8e3-053ae493abbc](https://github.com/kohya-ss/sd-scripts/assets/52813779/37e9a736-649b-4c0f-ab26-880a1bf319b5)
208
+
209
+ ![im_20230820104253_000_1](https://github.com/kohya-ss/sd-scripts/assets/52813779/c8896900-ab86-4120-932f-6e2ae17b77c0)
210
+
211
+ ![im_20230820104302_000_1](https://github.com/kohya-ss/sd-scripts/assets/52813779/b12457a0-ee3c-450e-ba9a-b712d0fe86bb)
212
+
213
+ ![im_20230820104310_000_1](https://github.com/kohya-ss/sd-scripts/assets/52813779/8845b8d9-804a-44ac-9618-113a28eac8a1)
214
+
docs/train_lllite_README.md ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # About ControlNet-LLLite
2
+
3
+ __This is an extremely experimental implementation and may change significantly in the future.__
4
+
5
+ 日本語版は[こちら](./train_lllite_README-ja.md)
6
+
7
+ ## Overview
8
+
9
+ ControlNet-LLLite is a lightweight version of [ControlNet](https://github.com/lllyasviel/ControlNet). It is a "LoRA Like Lite" that is inspired by LoRA and has a lightweight structure. Currently, only SDXL is supported.
10
+
11
+ ## Sample weight file and inference
12
+
13
+ Sample weight file is available here: https://huggingface.co/kohya-ss/controlnet-lllite
14
+
15
+ A custom node for ComfyUI is available: https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
16
+
17
+ Sample images are at the end of this page.
18
+
19
+ ## Model structure
20
+
21
+ A single LLLite module consists of a conditioning image embedding that maps a conditioning image to a latent space and a small network with a structure similar to LoRA. The LLLite module is added to U-Net's Linear and Conv in the same way as LoRA. Please refer to the source code for details.
22
+
23
+ Due to the limitations of the inference environment, only CrossAttention (attn1 q/k/v, attn2 q) is currently added.
24
+
25
+ ## Model training
26
+
27
+ ### Preparing the dataset
28
+
29
+ In addition to the normal dataset, please store the conditioning image in the directory specified by `conditioning_data_dir`. The conditioning image must have the same basename as the training image. The conditioning image will be automatically resized to the same size as the training image. The conditioning image does not require a caption file.
30
+
31
+ ```toml
32
+ [[datasets.subsets]]
33
+ image_dir = "path/to/image/dir"
34
+ caption_extension = ".txt"
35
+ conditioning_data_dir = "path/to/conditioning/image/dir"
36
+ ```
37
+
38
+ At the moment, random_crop cannot be used.
39
+
40
+ For training data, it is easiest to use a synthetic dataset with the original model-generated images as training images and processed images as conditioning images (the quality of the dataset may be problematic). See below for specific methods of synthesizing datasets.
41
+
42
+ Note that if you use an image with a different art style than the original model as a training image, the model will have to learn not only the control but also the art style. ControlNet-LLLite has a small capacity, so it is not suitable for learning art styles. In such cases, increase the number of dimensions as described below.
43
+
44
+ ### Training
45
+
46
+ Run `sdxl_train_control_net_lllite.py`. You can specify the dimension of the conditioning image embedding with `--cond_emb_dim`. You can specify the rank of the LoRA-like module with `--network_dim`. Other options are the same as `sdxl_train_network.py`, but `--network_module` is not required.
47
+
48
+ Since a large amount of memory is used during training, please enable memory-saving options such as cache and gradient checkpointing. It is also effective to use BFloat16 with the `--full_bf16` option (requires RTX 30 series or later GPU). It has been confirmed to work with 24GB VRAM.
49
+
50
+ For the sample Canny, the dimension of the conditioning image embedding is 32. The rank of the LoRA-like module is also 64. Adjust according to the features of the conditioning image you are targeting.
51
+
52
+ (The sample Canny is probably quite difficult. It may be better to reduce it to about half for depth, etc.)
53
+
54
+ The following is an example of a .toml configuration.
55
+
56
+ ```toml
57
+ pretrained_model_name_or_path = "/path/to/model_trained_on.safetensors"
58
+ max_train_epochs = 12
59
+ max_data_loader_n_workers = 4
60
+ persistent_data_loader_workers = true
61
+ seed = 42
62
+ gradient_checkpointing = true
63
+ mixed_precision = "bf16"
64
+ save_precision = "bf16"
65
+ full_bf16 = true
66
+ optimizer_type = "adamw8bit"
67
+ learning_rate = 2e-4
68
+ xformers = true
69
+ output_dir = "/path/to/output/dir"
70
+ output_name = "output_name"
71
+ save_every_n_epochs = 1
72
+ save_model_as = "safetensors"
73
+ vae_batch_size = 4
74
+ cache_latents = true
75
+ cache_latents_to_disk = true
76
+ cache_text_encoder_outputs = true
77
+ cache_text_encoder_outputs_to_disk = true
78
+ network_dim = 64
79
+ cond_emb_dim = 32
80
+ dataset_config = "/path/to/dataset.toml"
81
+ ```
82
+
83
+ ### Inference
84
+
85
+ If you want to generate images with a script, run `sdxl_gen_img.py`. You can specify the LLLite model file with `--control_net_lllite_models`. The dimension is automatically obtained from the model file.
86
+
87
+ Specify the conditioning image to be used for inference with `--guide_image_path`. Since preprocess is not performed, if it is Canny, specify an image processed with Canny (white line on black background). `--control_net_preps`, `--control_net_weights`, and `--control_net_ratios` are not supported.
88
+
89
+ ## How to synthesize a dataset
90
+
91
+ ### Generating training images
92
+
93
+ Generate images with the base model for training. Please generate them with Web UI or ComfyUI etc. The image size should be the default size of the model (1024x1024, etc.). You can also use bucketing. In that case, please generate it at an arbitrary resolution.
94
+
95
+ The captions and other settings when generating the images should be the same as when generating the images with the trained ControlNet-LLLite model.
96
+
97
+ Save the generated images in an arbitrary directory. Specify this directory in the dataset configuration file.
98
+
99
+
100
+ You can also generate them with `sdxl_gen_img.py` in this repository. For example, run as follows:
101
+
102
+ ```dos
103
+ python sdxl_gen_img.py --ckpt path/to/model.safetensors --n_iter 1 --scale 10 --steps 36 --outdir path/to/output/dir --xformers --W 1024 --H 1024 --original_width 2048 --original_height 2048 --bf16 --sampler ddim --batch_size 4 --vae_batch_size 2 --images_per_prompt 512 --max_embeddings_multiples 1 --prompt "{portrait|digital art|anime screen cap|detailed illustration} of 1girl, {standing|sitting|walking|running|dancing} on {classroom|street|town|beach|indoors|outdoors}, {looking at viewer|looking away|looking at another}, {in|wearing} {shirt and skirt|school uniform|casual wear} { |, dynamic pose}, (solo), teen age, {0-1$$smile,|blush,|kind smile,|expression less,|happy,|sadness,} {0-1$$upper body,|full body,|cowboy shot,|face focus,} trending on pixiv, {0-2$$depth of fields,|8k wallpaper,|highly detailed,|pov,} {0-1$$summer, |winter, |spring, |autumn, } beautiful face { |, from below|, from above|, from side|, from behind|, from back} --n nsfw, bad face, lowres, low quality, worst quality, low effort, watermark, signature, ugly, poorly drawn"
104
+ ```
105
+
106
+ This is a setting for VRAM 24GB. Adjust `--batch_size` and `--vae_batch_size` according to the VRAM size.
107
+
108
+ The images are generated randomly using wildcards in `--prompt`. Adjust as necessary.
109
+
110
+ ### Processing images
111
+
112
+ Use an external program to process the generated images. Save the processed images in an arbitrary directory. These will be the conditioning images.
113
+
114
+ For example, you can use the following script to process the images with Canny.
115
+
116
+ ```python
117
+ import glob
118
+ import os
119
+ import random
120
+ import cv2
121
+ import numpy as np
122
+
123
+ IMAGES_DIR = "path/to/generated/images"
124
+ CANNY_DIR = "path/to/canny/images"
125
+
126
+ os.makedirs(CANNY_DIR, exist_ok=True)
127
+ img_files = glob.glob(IMAGES_DIR + "/*.png")
128
+ for img_file in img_files:
129
+ can_file = CANNY_DIR + "/" + os.path.basename(img_file)
130
+ if os.path.exists(can_file):
131
+ print("Skip: " + img_file)
132
+ continue
133
+
134
+ print(img_file)
135
+
136
+ img = cv2.imread(img_file)
137
+
138
+ # random threshold
139
+ # while True:
140
+ # threshold1 = random.randint(0, 127)
141
+ # threshold2 = random.randint(128, 255)
142
+ # if threshold2 - threshold1 > 80:
143
+ # break
144
+
145
+ # fixed threshold
146
+ threshold1 = 100
147
+ threshold2 = 200
148
+
149
+ img = cv2.Canny(img, threshold1, threshold2)
150
+
151
+ cv2.imwrite(can_file, img)
152
+ ```
153
+
154
+ ### Creating caption files
155
+
156
+ Create a caption file for each image with the same basename as the training image. It is fine to use the same caption as the one used when generating the image.
157
+
158
+ If you generated the images with `sdxl_gen_img.py`, you can use the following script to create the caption files (`*.txt`) from the metadata in the generated images.
159
+
160
+ ```python
161
+ import glob
162
+ import os
163
+ from PIL import Image
164
+
165
+ IMAGES_DIR = "path/to/generated/images"
166
+
167
+ img_files = glob.glob(IMAGES_DIR + "/*.png")
168
+ for img_file in img_files:
169
+ cap_file = img_file.replace(".png", ".txt")
170
+ if os.path.exists(cap_file):
171
+ print(f"Skip: {img_file}")
172
+ continue
173
+ print(img_file)
174
+
175
+ img = Image.open(img_file)
176
+ prompt = img.text["prompt"] if "prompt" in img.text else ""
177
+ if prompt == "":
178
+ print(f"Prompt not found in {img_file}")
179
+
180
+ with open(cap_file, "w") as f:
181
+ f.write(prompt + "\n")
182
+ ```
183
+
184
+ ### Creating a dataset configuration file
185
+
186
+ You can use the command line arguments of `sdxl_train_control_net_lllite.py` to specify the conditioning image directory. However, if you want to use a `.toml` file, specify the conditioning image directory in `conditioning_data_dir`.
187
+
188
+ ```toml
189
+ [general]
190
+ flip_aug = false
191
+ color_aug = false
192
+ resolution = [1024,1024]
193
+
194
+ [[datasets]]
195
+ batch_size = 8
196
+ enable_bucket = false
197
+
198
+ [[datasets.subsets]]
199
+ image_dir = "path/to/generated/image/dir"
200
+ caption_extension = ".txt"
201
+ conditioning_data_dir = "path/to/canny/image/dir"
202
+ ```
203
+
204
+ ## Credit
205
+
206
+ I would like to thank lllyasviel, the author of ControlNet, furusu, who provided me with advice on implementation and helped me solve problems, and ddPn08, who implemented the ControlNet dataset.
207
+
208
+ ## Sample
209
+
210
+ Canny
211
+ ![kohya_ss_girl_standing_at_classroom_smiling_to_the_viewer_class_78976b3e-0d4d-4ea0-b8e3-053ae493abbc](https://github.com/kohya-ss/sd-scripts/assets/52813779/37e9a736-649b-4c0f-ab26-880a1bf319b5)
212
+
213
+ ![im_20230820104253_000_1](https://github.com/kohya-ss/sd-scripts/assets/52813779/c8896900-ab86-4120-932f-6e2ae17b77c0)
214
+
215
+ ![im_20230820104302_000_1](https://github.com/kohya-ss/sd-scripts/assets/52813779/b12457a0-ee3c-450e-ba9a-b712d0fe86bb)
216
+
217
+ ![im_20230820104310_000_1](https://github.com/kohya-ss/sd-scripts/assets/52813779/8845b8d9-804a-44ac-9618-113a28eac8a1)
docs/train_network_README-ja.md ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRAの学習について
2
+
3
+ [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685)(arxiv)、[LoRA](https://github.com/microsoft/LoRA)(github)をStable Diffusionに適用したものです。
4
+
5
+ [cloneofsimo氏のリポジトリ](https://github.com/cloneofsimo/lora)を大いに参考にさせていただきました。ありがとうございます。
6
+
7
+ 通常のLoRAは Linear およぴカーネルサイズ 1x1 の Conv2d にのみ適用されますが、カーネルサイズ 3x3 のConv2dに適用を拡大することもできます。
8
+
9
+ Conv2d 3x3への拡大は [cloneofsimo氏](https://github.com/cloneofsimo/lora) が最初にリリースし、KohakuBlueleaf氏が [LoCon](https://github.com/KohakuBlueleaf/LoCon) でその有効性を明らかにしたものです。KohakuBlueleaf氏に深く感謝します。
10
+
11
+ 8GB VRAMでもぎりぎり動作するようです。
12
+
13
+ [学習についての共通ドキュメント](./train_README-ja.md) もあわせてご覧ください。
14
+
15
+ # 学習できるLoRAの種類
16
+
17
+ 以下の二種類をサポートします。以下は当リポジトリ内の独自の名称です。
18
+
19
+ 1. __LoRA-LierLa__ : (LoRA for __Li__ n __e__ a __r__ __La__ yers、リエラと読みます)
20
+
21
+ Linear およびカーネルサイズ 1x1 の Conv2d に適用されるLoRA
22
+
23
+ 2. __LoRA-C3Lier__ : (LoRA for __C__ olutional layers with __3__ x3 Kernel and __Li__ n __e__ a __r__ layers、セリアと読みます)
24
+
25
+ 1.に加え、カーネルサイズ 3x3 の Conv2d に適用されるLoRA
26
+
27
+ LoRA-LierLaに比べ、LoRA-C3Liarは適用される層が増える分、高い精度が期待できるかもしれません。
28
+
29
+ また学習時は __DyLoRA__ を使用することもできます(後述します)。
30
+
31
+ ## 学習したモデルに関する注意
32
+
33
+ LoRA-LierLa は、AUTOMATIC1111氏のWeb UIのLoRA機能で使用することができます。
34
+
35
+ LoRA-C3Liarを使いWeb UIで生成するには、こちらの[WebUI用extension](https://github.com/kohya-ss/sd-webui-additional-networks)を使ってください。
36
+
37
+ いずれも学習したLoRAのモデルを、Stable Diffusionのモデルにこのリポジトリ内のスクリプトであらかじめマージすることもできます。
38
+
39
+ cloneofsimo氏のリポジトリ、およびd8ahazard氏の[Dreambooth Extension for Stable-Diffusion-WebUI](https://github.com/d8ahazard/sd_dreambooth_extension)とは、現時点では互換性がありません。いくつかの機能拡張を行っているためです(後述)。
40
+
41
+ # 学習の手順
42
+
43
+ あらかじめこのリポジトリのREADMEを参照し、環境整備を行ってください。
44
+
45
+ ## データの準備
46
+
47
+ [学習データの準備について](./train_README-ja.md) を参照してください。
48
+
49
+
50
+ ## 学習の実行
51
+
52
+ `train_network.py`を用います。
53
+
54
+ `train_network.py`では `--network_module` オプションに、学習対象のモジュール名を指定します。LoRAに対応するのは`network.lora`となりますので、それを指定してください。
55
+
56
+ なお学習率は通常のDreamBoothやfine tuningよりも高めの、`1e-4`~`1e-3`程度を指定するとよいようです。
57
+
58
+ 以下はコマンドラインの例です。
59
+
60
+ ```
61
+ accelerate launch --num_cpu_threads_per_process 1 train_network.py
62
+ --pretrained_model_name_or_path=<.ckptまたは.safetensordまたはDiffusers版モデルのディレクトリ>
63
+ --dataset_config=<データ準備で作成した.tomlファイル>
64
+ --output_dir=<学習したモデルの出力先フォルダ>
65
+ --output_name=<学習したモデル出力時のファイル名>
66
+ --save_model_as=safetensors
67
+ --prior_loss_weight=1.0
68
+ --max_train_steps=400
69
+ --learning_rate=1e-4
70
+ --optimizer_type="AdamW8bit"
71
+ --xformers
72
+ --mixed_precision="fp16"
73
+ --cache_latents
74
+ --gradient_checkpointing
75
+ --save_every_n_epochs=1
76
+ --network_module=networks.lora
77
+ ```
78
+
79
+ このコマンドラインでは LoRA-LierLa が学習されます。
80
+
81
+ `--output_dir` オプションで指定したフォルダに、LoRAのモデルが保存されます。他のオプション、オプティマイザ等については [学習の共通ドキュメント](./train_README-ja.md) の「よく使われるオプション」も参照してください。
82
+
83
+ その他、以下のオプションが指定できます。
84
+
85
+ * `--network_dim`
86
+ * LoRAのRANKを指定します(``--networkdim=4``など)。省略時は4になります。数が多いほど表現力は増しますが、学習に必要なメモリ、時間は増えます。また闇雲に増やしても良くないようです。
87
+ * `--network_alpha`
88
+ * アンダーフローを防ぎ安定して学習するための ``alpha`` 値を指定します。デフォルトは1です。``network_dim``と同じ値を指定すると以前のバージョンと同じ動作になります。
89
+ * `--persistent_data_loader_workers`
90
+ * Windows環境で指定するとエポック間の待ち時間が大幅に短縮されます。
91
+ * `--max_data_loader_n_workers`
92
+ * データ読み込みのプロセス数を指定します。プロセス数が多いとデータ読み込みが速くなりGPUを効率的に利用できますが、メインメモリを消費します。デフォルトは「`8` または `CPU同時実行スレッド数-1` の小さいほう」なので、メインメモリに余裕がない場合や、GPU使用率が90%程度以上なら、それらの数値を見ながら `2` または `1` 程度まで下げてください。
93
+ * `--network_weights`
94
+ * 学習前に学習済みのLoRAの重みを読み込み、そこから追加で学習します。
95
+ * `--network_train_unet_only`
96
+ * U-Netに関連するLoRAモジュールのみ有効とします。fine tuning的な学習で指定するとよいかもしれません。
97
+ * `--network_train_text_encoder_only`
98
+ * Text Encoderに関連するLoRAモジュールのみ有効とします。Textual Inversion的な効果が期待できるかもしれません。
99
+ * `--unet_lr`
100
+ * U-Netに関連するLoRAモジュールに、通常の学習率(--learning_rateオプションで指定)とは異なる学習率を使う時に指定します。
101
+ * `--text_encoder_lr`
102
+ * Text Encoderに関連するLoRAモジュールに、通常の学習率(--learning_rateオプションで指定)とは異なる学習率を使う時に指定します。Text Encoderのほうを若干低めの学習率(5e-5など)にしたほうが良い、という話もあるようです。
103
+ * `--network_args`
104
+ * 複数の引数を指定できます。後述します。
105
+
106
+ `--network_train_unet_only` と `--network_train_text_encoder_only` の両方とも未指定時(デフォルト)はText EncoderとU-Netの両方のLoRAモジュールを有効にします。
107
+
108
+ # その他の学習方法
109
+
110
+ ## LoRA-C3Lier を学習する
111
+
112
+ `--network_args` に以下のように指定してください。`conv_dim` で Conv2d (3x3) の rank を、`conv_alpha` で alpha を指定してください。
113
+
114
+ ```
115
+ --network_args "conv_dim=4" "conv_alpha=1"
116
+ ```
117
+
118
+ 以下のように alpha 省略時は1になります。
119
+
120
+ ```
121
+ --network_args "conv_dim=4"
122
+ ```
123
+
124
+ ## DyLoRA
125
+
126
+ DyLoRAはこちらの論文で提案されたものです。[DyLoRA: Parameter Efficient Tuning of Pre-trained Models using Dynamic Search-Free Low-Rank Adaptation](https://arxiv.org/abs/2210.07558) 公式実装は[こちら](https://github.com/huawei-noah/KD-NLP/tree/main/DyLoRA)です。
127
+
128
+ 論文によると、LoRAのrankは必ずしも高いほうが良いわけではなく、対象のモデル、データセット、タスクなどにより適切なrankを探す必要があるようです。DyLoRAを使うと、指定したdim(rank)以下のさまざまなrankで同時にLoRAを学習します。これにより最適なrankをそれぞれ学習して探す手間を省くことができます。
129
+
130
+ 当リポジトリの実装は公式実装をベースに独自の拡張を加えています(そのため不具合などあるかもしれません)。
131
+
132
+ ### 当リポジトリのDyLoRAの特徴
133
+
134
+ 学習後のDyLoRAのモデルファイルはLoRAと互換性があります。また、モデルファイルから指定したdim(rank)以下の複数のdimのLoRAを抽出できます。
135
+
136
+ DyLoRA-LierLa、DyLoRA-C3Lierのどちらも学習できます。
137
+
138
+ ### DyLoRAで学習する
139
+
140
+ `--network_module=networks.dylora` のように、DyLoRAに対応する`network.dylora`を指定してください。
141
+
142
+ また `--network_args` に、たとえば`--network_args "unit=4"`のように`unit`を指定します。`unit`はrankを分割する単位です。たとえば`--network_dim=16 --network_args "unit=4"` のように指定します。`unit`は`network_dim`を割り切れる値(`network_dim`は`unit`の倍数)としてください。
143
+
144
+ `unit`を指定しない場合は、`unit=1`として扱われます。
145
+
146
+ 記述例は以下です。
147
+
148
+ ```
149
+ --network_module=networks.dylora --network_dim=16 --network_args "unit=4"
150
+
151
+ --network_module=networks.dylora --network_dim=32 --network_alpha=16 --network_args "unit=4"
152
+ ```
153
+
154
+ DyLoRA-C3Lierの場合は、`--network_args` に`"conv_dim=4"`のように`conv_dim`を指定します。通常のLoRAと異なり、`conv_dim`は`network_dim`と同じ値である必要があります。記述例は以下です。
155
+
156
+ ```
157
+ --network_module=networks.dylora --network_dim=16 --network_args "conv_dim=16" "unit=4"
158
+
159
+ --network_module=networks.dylora --network_dim=32 --network_alpha=16 --network_args "conv_dim=32" "conv_alpha=16" "unit=8"
160
+ ```
161
+
162
+ たとえばdim=16、unit=4(後述)で学習すると、4、8、12、16の4つのrankのLoRAを学習、抽出できます。抽出した各モデルで画像を生成し、比較することで、最適なrankのLoRAを選択できます。
163
+
164
+ その他のオプションは��常のLoRAと同じです。
165
+
166
+ ※ `unit`は当リポジトリの独自拡張で、DyLoRAでは同dim(rank)の通常LoRAに比べると学習時間が長くなることが予想されるため、分割単位を大きくしたものです。
167
+
168
+ ### DyLoRAのモデルからLoRAモデルを抽出する
169
+
170
+ `networks`フォルダ内の `extract_lora_from_dylora.py`を使用します。指定した`unit`単位で、DyLoRAのモデルからLoRAのモデルを抽出します。
171
+
172
+ コマンドラインはたとえば以下のようになります。
173
+
174
+ ```powershell
175
+ python networks\extract_lora_from_dylora.py --model "foldername/dylora-model.safetensors" --save_to "foldername/dylora-model-split.safetensors" --unit 4
176
+ ```
177
+
178
+ `--model` にはDyLoRAのモデルファイルを指定します。`--save_to` には抽出したモデルを保存するファイル名を指定します(rankの数値がファイル名に付加されます)。`--unit` にはDyLoRAの学習時の`unit`を指定します。
179
+
180
+ ## 階層別学習率
181
+
182
+ 詳細は[PR #355](https://github.com/kohya-ss/sd-scripts/pull/355) をご覧ください。
183
+
184
+ SDXLは現在サポートしていません。
185
+
186
+ フルモデルの25個のブロックの重みを指定できます。最初のブロックに該当するLoRAは存在しませんが、階層別LoRA適用等との互換性のために25個としています。またconv2d3x3に拡張しない場合も一部のブロックにはLoRAが存在しませんが、記述を統一するため常に25個の値を指定してください。
187
+
188
+ `--network_args` で以下の引数を指定してください。
189
+
190
+ - `down_lr_weight` : U-Netのdown blocksの学習率の重みを指定します。以下が指定可能です。
191
+ - ブロックごとの重み : `"down_lr_weight=0,0,0,0,0,0,1,1,1,1,1,1"` のように12個の数値を指定します。
192
+ - プリセットからの指定 : `"down_lr_weight=sine"` のように指定します(サインカーブで重みを指定します)。sine, cosine, linear, reverse_linear, zeros が指定可能です。また `"down_lr_weight=cosine+.25"` のように `+数値` を追加すると、指定した数値を加算します(0.25~1.25になります)。
193
+ - `mid_lr_weight` : U-Netのmid blockの学習率の重みを指定します。`"down_lr_weight=0.5"` のように数値を一つだけ指定します。
194
+ - `up_lr_weight` : U-Netのup blocksの学習率の重みを指定します。down_lr_weightと同様です。
195
+ - 指定を省略した部分は1.0として扱われます。また重みを0にするとそのブロックのLoRAモジュールは作成されません。
196
+ - `block_lr_zero_threshold` : 重みがこの値以下の場合、LoRAモジュールを作成しません。デフォルトは0です。
197
+
198
+ ### 階層別学習率コマンドライン指定例:
199
+
200
+ ```powershell
201
+ --network_args "down_lr_weight=0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0,1.5,1.5,1.5,1.5" "mid_lr_weight=2.0" "up_lr_weight=1.5,1.5,1.5,1.5,1.0,1.0,1.0,1.0,0.5,0.5,0.5,0.5"
202
+
203
+ --network_args "block_lr_zero_threshold=0.1" "down_lr_weight=sine+.5" "mid_lr_weight=1.5" "up_lr_weight=cosine+.5"
204
+ ```
205
+
206
+ ### 階層別学習率tomlファイル指定例:
207
+
208
+ ```toml
209
+ network_args = [ "down_lr_weight=0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0,1.5,1.5,1.5,1.5", "mid_lr_weight=2.0", "up_lr_weight=1.5,1.5,1.5,1.5,1.0,1.0,1.0,1.0,0.5,0.5,0.5,0.5",]
210
+
211
+ network_args = [ "block_lr_zero_threshold=0.1", "down_lr_weight=sine+.5", "mid_lr_weight=1.5", "up_lr_weight=cosine+.5", ]
212
+ ```
213
+
214
+ ## 階層別dim (rank)
215
+
216
+ フルモデルの25個のブロックのdim (rank)を指定できます。階層別学習率と同様に一部のブロックにはLoRAが存在しない場合がありますが、常に25個の値を指定してください。
217
+
218
+ `--network_args` で以下の引数を指定してください。
219
+
220
+ - `block_dims` : 各ブロックのdim (rank)を指定します。`"block_dims=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2"` のように25個の数値を指定します。
221
+ - `block_alphas` : 各ブロックのalphaを指定します。block_dimsと同様に25個の数値を指定します。省略時はnetwork_alphaの値が使用されます。
222
+ - `conv_block_dims` : LoRAをConv2d 3x3に拡張し、各ブロックのdim (rank)を指定します。
223
+ - `conv_block_alphas` : LoRAをConv2d 3x3に拡張したときの各ブロックのalphaを指定します。省略時はconv_alphaの値が使用されます。
224
+
225
+ ### 階層別dim (rank)コマンドライン指定例:
226
+
227
+ ```powershell
228
+ --network_args "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2"
229
+
230
+ --network_args "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2" "conv_block_dims=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2"
231
+
232
+ --network_args "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2" "block_alphas=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2"
233
+ ```
234
+
235
+ ### 階層別dim (rank)tomlファイル指定例:
236
+
237
+ ```toml
238
+ network_args = [ "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2",]
239
+
240
+ network_args = [ "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2", "block_alphas=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2",]
241
+ ```
242
+
243
+ # その他のスクリプト
244
+
245
+ マージ等LoRAに関連するスクリプト群です。
246
+
247
+ ## マージスクリプトについて
248
+
249
+ merge_lora.pyでStable DiffusionのモデルにLoRAの学習結果をマージしたり、複数のLoRAモデルをマージしたりできます。
250
+
251
+ SDXL向けにはsdxl_merge_lora.pyを用意しています。オプション等は同一ですので、以下のmerge_lora.pyを読み替えてください。
252
+
253
+ ### Stable DiffusionのモデルにLoRAのモデルをマージする
254
+
255
+ マージ後のモデルは通常のStable Diffusionのckptと同様に扱えます。たとえば以下のようなコマンドラインになります。
256
+
257
+ ```
258
+ python networks\merge_lora.py --sd_model ..\model\model.ckpt
259
+ --save_to ..\lora_train1\model-char1-merged.safetensors
260
+ --models ..\lora_train1\last.safetensors --ratios 0.8
261
+ ```
262
+
263
+ Stable Diffusion v2.xのモデルで学習し、それにマージする場合は、--v2オプションを指定してください。
264
+
265
+ --sd_modelオプションにマージの元となるStable Diffusionのモデルファイルを指定します(.ckptまたは.safetensorsのみ対応で、Diffusersは今のところ対応していません)。
266
+
267
+ --save_toオプションにマージ後のモデルの保存先を指定します(.ckptまたは.safetensors、拡張子で自動判定)。
268
+
269
+ --modelsに学習したLoRAのモデルファイルを指定します。複数指定も可能で、その時は順にマージします。
270
+
271
+ --ratiosにそれぞれのモデルの適用率(どのくらい重みを元モデルに反映するか)を0~1.0の数値で指定します。例えば過学習に近いような場合は、適用率を下げるとマシになるかもしれません。モデルの数と同じだけ指定してください。
272
+
273
+ 複数指定時は以下のようになります。
274
+
275
+ ```
276
+ python networks\merge_lora.py --sd_model ..\model\model.ckpt
277
+ --save_to ..\lora_train1\model-char1-merged.safetensors
278
+ --models ..\lora_train1\last.safetensors ..\lora_train2\last.safetensors --ratios 0.8 0.5
279
+ ```
280
+
281
+ ### 複数のLoRAのモデルをマージする
282
+
283
+ --concatオプションを指定すると、複数のLoRAを単純に結合して新しいLoRAモデルを作成できます。ファイルサイズ(およびdim/rank)は指定したLoRAの合計サイズになります(マージ時にdim (rank)を変更する場合は `svd_merge_lora.py` を使用してください)。
284
+
285
+ たとえば以下のようなコマンドラインになります。
286
+
287
+ ```
288
+ python networks\merge_lora.py --save_precision bf16
289
+ --save_to ..\lora_train1\model-char1-style1-merged.safetensors
290
+ --models ..\lora_train1\last.safetensors ..\lora_train2\last.safetensors
291
+ --ratios 1.0 -1.0 --concat --shuffle
292
+ ```
293
+
294
+ --concatオプションを指定します。
295
+
296
+ また--shuffleオプションを追加し、重みをシャッフルします。シャッフルしないとマージ後のLoRAから元のLoRAを取り出せるため、コピー機学習などの場合には学習元データが明らかになります。ご注意ください。
297
+
298
+ --save_toオプションにマージ後のLoRAモデルの保存先を指定します(.ckptまたは.safetensors、拡張子で自動判定)。
299
+
300
+ --modelsに学習したLoRAのモデルファイルを指定します。三つ以上も指定可能です。
301
+
302
+ --ratiosにそれぞれのモデルの比率(どのくらい重みを元モデルに反映するか)を0~1.0の数値で指定します。二つのモデルを一対一でマージする場合は、「0.5 0.5」になります。「1.0 1.0」では合計の重みが大きくなりすぎて、恐らく結果はあまり望ましくないものになると思われます。
303
+
304
+ v1で学習したLoRAとv2で学習したLoRA、rank(次元数)の異なるLoRAはマージできません。U-NetだけのLoRAとU-Net+Text EncoderのLoRAはマージできるはずですが、結果は未知数です。
305
+
306
+ ### その他のオプション
307
+
308
+ * precision
309
+ * マージ計算時の精度をfloat、fp16、bf16から指定できます。省略時は精度を確保するためfloatになります。メモリ使用量を減らしたい場合はfp16/bf16を指定してください。
310
+ * save_precision
311
+ * モデル保存時の精度をfloat、fp16、bf16から指定できます。省略時はprecisionと同じ精度になります。
312
+
313
+ 他にもいくつかのオプションがありますので、--helpで確認してください。
314
+
315
+ ## 複数のrankが異なるLoRAのモデルをマージする
316
+
317
+ 複数のLoRAをひとつのLoRAで近似します(完全な再現はできません)。`svd_merge_lora.py`を用います。たとえば以下のようなコマンドラインになります。
318
+
319
+ ```
320
+ python networks\svd_merge_lora.py
321
+ --save_to ..\lora_train1\model-char1-style1-merged.safetensors
322
+ --models ..\lora_train1\last.safetensors ..\lora_train2\last.safetensors
323
+ --ratios 0.6 0.4 --new_rank 32 --device cuda
324
+ ```
325
+
326
+ `merge_lora.py` と主なオプションは同一です。以下のオプションが追加されています。
327
+
328
+ - `--new_rank`
329
+ - 作成するLoRAのrankを指定します。
330
+ - `--new_conv_rank`
331
+ - 作成する Conv2d 3x3 LoRA の rank を指定します。省略時は `new_rank` と同じになります。
332
+ - `--device`
333
+ - `--device cuda`としてcudaを指定すると計算をGPU上で行います。処理が速くなります。
334
+
335
+ ## 当リポジトリ内の画像生成スクリプトで生成する
336
+
337
+ gen_img_diffusers.pyに、--network_module、--network_weightsの各オプションを追加してください。意味は学習時と同様です。
338
+
339
+ --network_mulオプションで0~1.0の数値を指定すると、LoRAの適用率を変えられます。
340
+
341
+ ## Diffusersのpipelineで生成する
342
+
343
+ 以下の例を参考にしてください。必要なファイルはnetworks/lora.pyのみです。Diffusersのバージョンは0.10.2以外では動作しない可能性があります。
344
+
345
+ ```python
346
+ import torch
347
+ from diffusers import StableDiffusionPipeline
348
+ from networks.lora import LoRAModule, create_network_from_weights
349
+ from safetensors.torch import load_file
350
+
351
+ # if the ckpt is CompVis based, convert it to Diffusers beforehand with tools/convert_diffusers20_original_sd.py. See --help for more details.
352
+
353
+ model_id_or_dir = r"model_id_on_hugging_face_or_dir"
354
+ device = "cuda"
355
+
356
+ # create pipe
357
+ print(f"creating pipe from {model_id_or_dir}...")
358
+ pipe = StableDiffusionPipeline.from_pretrained(model_id_or_dir, revision="fp16", torch_dtype=torch.float16)
359
+ pipe = pipe.to(device)
360
+ vae = pipe.vae
361
+ text_encoder = pipe.text_encoder
362
+ unet = pipe.unet
363
+
364
+ # load lora networks
365
+ print(f"loading lora networks...")
366
+
367
+ lora_path1 = r"lora1.safetensors"
368
+ sd = load_file(lora_path1) # If the file is .ckpt, use torch.load instead.
369
+ network1, sd = create_network_from_weights(0.5, None, vae, text_encoder,unet, sd)
370
+ network1.apply_to(text_encoder, unet)
371
+ network1.load_state_dict(sd)
372
+ network1.to(device, dtype=torch.float16)
373
+
374
+ # # You can merge weights instead of apply_to+load_state_dict. network.set_multiplier does not work
375
+ # network.merge_to(text_encoder, unet, sd)
376
+
377
+ lora_path2 = r"lora2.safetensors"
378
+ sd = load_file(lora_path2)
379
+ network2, sd = create_network_from_weights(0.7, None, vae, text_encoder,unet, sd)
380
+ network2.apply_to(text_encoder, unet)
381
+ network2.load_state_dict(sd)
382
+ network2.to(device, dtype=torch.float16)
383
+
384
+ lora_path3 = r"lora3.safetensors"
385
+ sd = load_file(lora_path3)
386
+ network3, sd = create_network_from_weights(0.5, None, vae, text_encoder,unet, sd)
387
+ network3.apply_to(text_encoder, unet)
388
+ network3.load_state_dict(sd)
389
+ network3.to(device, dtype=torch.float16)
390
+
391
+ # prompts
392
+ prompt = "masterpiece, best quality, 1girl, in white shirt, looking at viewer"
393
+ negative_prompt = "bad quality, worst quality, bad anatomy, bad hands"
394
+
395
+ # exec pipe
396
+ print("generating image...")
397
+ with torch.autocast("cuda"):
398
+ image = pipe(prompt, guidance_scale=7.5, negative_prompt=negative_prompt).images[0]
399
+
400
+ # if not merged, you can use set_multiplier
401
+ # network1.set_multiplier(0.8)
402
+ # and generate image again...
403
+
404
+ # save image
405
+ image.save(r"by_diffusers..png")
406
+ ```
407
+
408
+ ## 二つのモデルの差分からLoRAモデルを作成する
409
+
410
+ [こちらのディスカッション](https://github.com/cloneofsimo/lora/discussions/56)を参考に実装したものです。数式はそのまま使わせていただきました(よく理解していませんが近似には特異値分解を用いるようです)。
411
+
412
+ 二つのモデル(たとえばfine tuningの元モデルとfine tuning後のモデル)の差分を、LoRAで近似します。
413
+
414
+ ### スクリプトの実行方法
415
+
416
+ 以下のように指定してください。
417
+ ```
418
+ python networks\extract_lora_from_models.py --model_org base-model.ckpt
419
+ --model_tuned fine-tuned-model.ckpt
420
+ --save_to lora-weights.safetensors --dim 4
421
+ ```
422
+
423
+ --model_orgオプションに元のStable Diffusionモデルを指定します。作成したLoRAモデルを適用する場合は、このモデルを指定して適用することになります。.ckptまたは.safetensorsが指定できます。
424
+
425
+ --model_tunedオプションに差分を抽出する対象のStable Diffusionモデルを指定します。たとえばfine tuningやDreamBooth後のモデルを指定します。.ckptまたは.safetensorsが指定できます。
426
+
427
+ --save_toにLoRAモデルの保存先を指定します。--dimにLoRAの次元数を指定します。
428
+
429
+ 生成されたLoRAモデルは、学習したLoRAモデルと同様に使用できます。
430
+
431
+ Text Encoderが二つのモデルで同じ場���にはLoRAはU-NetのみのLoRAとなります。
432
+
433
+ ### その他のオプション
434
+
435
+ - `--v2`
436
+ - v2.xのStable Diffusionモデルを使う場合に指定してください。
437
+ - `--device`
438
+ - ``--device cuda``としてcudaを指定すると計算をGPU上で行います。処理が速くなります(CPUでもそこまで遅くないため、せいぜい倍~数倍程度のようです)。
439
+ - `--save_precision`
440
+ - LoRAの保存形式を"float", "fp16", "bf16"から指定します。省略時はfloatになります。
441
+ - `--conv_dim`
442
+ - 指定するとLoRAの適用範囲を Conv2d 3x3 へ拡大します。Conv2d 3x3 の rank を指定します。
443
+
444
+ ## 画像リサイズスクリプト
445
+
446
+ (のちほどドキュメントを整理しますがとりあえずここに説明を書いておきます。)
447
+
448
+ Aspect Ratio Bucketingの機能拡張で、小さな画像については拡大しないでそのまま教師データとすることが可能になりました。元の教師画像を縮小した画像を、教師データに加えると精度が向上したという報告とともに前処理用のスクリプトをいただきましたので整備して追加しました。bmaltais氏に感謝します。
449
+
450
+ ### スクリプトの実行方法
451
+
452
+ 以下のように指定してください。元の画像そのまま、およびリサイズ後の画像が変換先フォルダに保存されます。リサイズ後の画像には、ファイル名に ``+512x512`` のようにリサイズ先の解像度が付け加えられます(画像サイズとは異なります)。リサイズ先の解像度より小さい画像は拡大されることはありません。
453
+
454
+ ```
455
+ python tools\resize_images_to_resolution.py --max_resolution 512x512,384x384,256x256 --save_as_png
456
+ --copy_associated_files 元画像フォルダ 変換先フォルダ
457
+ ```
458
+
459
+ 元画像フォルダ内の画像ファイルが、指定した解像度(複数指定可)と同じ面積になるようにリサイズされ、変換先フォルダに保存されます。画像以外のファイルはそのままコピーされます。
460
+
461
+ ``--max_resolution`` オプションにリサイズ先のサイズを例のように指定してください。面積がそのサイズになるようにリサイズします。複数指定すると、それぞれの解像度でリサイズされます。``512x512,384x384,256x256``なら、変換先フォルダの画像は、元サイズとリサイズ後サイズ×3の計4枚になります。
462
+
463
+ ``--save_as_png`` オプションを指定するとpng形式で保存します。省略するとjpeg形式(quality=100)で保存されます。
464
+
465
+ ``--copy_associated_files`` オプションを指定すると、拡張子を除き画像と同じファイル名(たとえばキャプションなど)のファイルが、リサイズ後の画像のファイル名と同じ名前でコピーされます。
466
+
467
+
468
+ ### その他のオプション
469
+
470
+ - divisible_by
471
+ - リサイズ後の画像のサイズ(縦、横のそれぞれ)がこの値で割り切れるように、画像中心を切り出します。
472
+ - interpolation
473
+ - 縮小時の補完方法を指定します。``area, cubic, lanczos4``から選択可能で、デフォルトは``area``です。
474
+
475
+
476
+ # 追加情報
477
+
478
+ ## cloneofsimo氏のリポジトリとの違い
479
+
480
+ 2022/12/25時点では、当リポジトリはLoRAの適用個所をText EncoderのMLP、U-NetのFFN、Transformerのin/out projectionに拡大し、表現力が増しています。ただその代わりメモリ使用量は増え、8GBぎりぎりになりました。
481
+
482
+ またモジュール入れ替え機構は全く異なります。
483
+
484
+ ## 将来拡張について
485
+
486
+ LoRAだけでなく他の拡張にも対応可能ですので、それらも追加予定です。
docs/train_network_README-zh.md ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 关于LoRA的学习。
2
+
3
+ [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685)(arxiv)、[LoRA](https://github.com/microsoft/LoRA)(github)这是应用于Stable Diffusion“稳定扩散”的内容。
4
+
5
+ [cloneofsimo先生的代码仓库](https://github.com/cloneofsimo/lora) 我们非常感謝您提供的参考。非常感謝。
6
+
7
+ 通常情況下,LoRA只适用于Linear和Kernel大小为1x1的Conv2d,但也可以將其擴展到Kernel大小为3x3的Conv2d。
8
+
9
+ Conv2d 3x3的扩展最初是由 [cloneofsimo先生的代码仓库](https://github.com/cloneofsimo/lora)
10
+ 而KohakuBlueleaf先生在[LoCon](https://github.com/KohakuBlueleaf/LoCon)中揭示了其有效性。我们深深地感谢KohakuBlueleaf先生。
11
+
12
+ 看起来即使在8GB VRAM上也可以勉强运行。
13
+
14
+ 请同时查看关于[学习的通用文档](./train_README-zh.md)。
15
+ # 可学习的LoRA 类型
16
+
17
+ 支持以下两种类型。以下是本仓库中自定义的名称。
18
+
19
+ 1. __LoRA-LierLa__:(用于 __Li__ n __e__ a __r__ __La__ yers 的 LoRA,读作 "Liela")
20
+
21
+ 适用于 Linear 和卷积层 Conv2d 的 1x1 Kernel 的 LoRA
22
+
23
+ 2. __LoRA-C3Lier__:(用于具有 3x3 Kernel 的卷积层和 __Li__ n __e__ a __r__ 层的 LoRA,读作 "Seria")
24
+
25
+ 除了第一种类型外,还适用于 3x3 Kernel 的 Conv2d 的 LoRA
26
+
27
+ 与 LoRA-LierLa 相比,LoRA-C3Lier 可能会获得更高的准确性,因为它适用于更多的层。
28
+
29
+ 在训练时,也可以使用 __DyLoRA__(将在后面介绍)。
30
+
31
+ ## 请注意与所学模型相关的事项。
32
+
33
+ LoRA-LierLa可以用于AUTOMATIC1111先生的Web UI LoRA功能。
34
+
35
+ 要使用LoRA-C3Liar并在Web UI中生成,请使用此处的[WebUI用extension](https://github.com/kohya-ss/sd-webui-additional-networks)。
36
+
37
+ 在此存储库的脚本中,您还可以预先将经过训练的LoRA模型合并到Stable Diffusion模型中。
38
+
39
+ 请注意,与cloneofsimo先生的存储库以及d8ahazard先生的[Stable-Diffusion-WebUI的Dreambooth扩展](https://github.com/d8ahazard/sd_dreambooth_extension)不兼容,因为它们进行了一些功能扩展(如下文所述)。
40
+
41
+ # 学习步骤
42
+
43
+ 请先参考此存储库的README文件并进行环境设置。
44
+
45
+ ## 准备数据
46
+
47
+ 请参考 [关于准备学习数据](./train_README-zh.md)。
48
+
49
+ ## 网络训练
50
+
51
+ 使用`train_network.py`。
52
+
53
+ 在`train_network.py`中,使用`--network_module`选项指定要训练的模块名称。对于LoRA模块,它应该是`network.lora`,请指定它。
54
+
55
+ 请注意,学习率应该比通常的DreamBooth或fine tuning要高,建议指定为`1e-4`至`1e-3`左右。
56
+
57
+ 以下是命令行示例。
58
+
59
+ ```
60
+ accelerate launch --num_cpu_threads_per_process 1 train_network.py
61
+ --pretrained_model_name_or_path=<.ckpt或.safetensord或Diffusers版模型目录>
62
+ --dataset_config=<数据集配置的.toml文件>
63
+ --output_dir=<训练过程中的模型输出文件夹>
64
+ --output_name=<训练模型输出时的文件名>
65
+ --save_model_as=safetensors
66
+ --prior_loss_weight=1.0
67
+ --max_train_steps=400
68
+ --learning_rate=1e-4
69
+ --optimizer_type="AdamW8bit"
70
+ --xformers
71
+ --mixed_precision="fp16"
72
+ --cache_latents
73
+ --gradient_checkpointing
74
+ --save_every_n_epochs=1
75
+ --network_module=networks.lora
76
+ ```
77
+
78
+ 在这个命令行中,LoRA-LierLa将会被训练。
79
+
80
+ LoRA的模型将会被保存在通过`--output_dir`选项指定的文件夹中。关于其他选项和优化器等,请参阅[学习的通用文档](./train_README-zh.md)中的“常用选项”。
81
+
82
+ 此外,还可以指定以下选项:
83
+
84
+ * `--network_dim`
85
+ * 指定LoRA的RANK(例如:`--network_dim=4`)。默认值为4。数值越大表示表现力越强,但需要更多的内存和时间来训练。而且不要盲目增加此数值。
86
+ * `--network_alpha`
87
+ * 指定用于防止下溢并稳定训练的alpha值。默认值为1。如果与`network_dim`指定相同的值,则将获得与以前版本相同的行为。
88
+ * `--persistent_data_loader_workers`
89
+ * 在Windows环境中指定可大幅缩短epoch之间的等待时间。
90
+ * `--max_data_loader_n_workers`
91
+ * 指定数据读取进程的数量。进程数越多,数据读取速度越快,可以更有效地利用GPU,但会占用主存。默认值为“`8`或`CPU同步执行线程数-1`的最小值”,因此如果主存不足或GPU使用率超过90%,则应将这些数字降低到约`2`或`1`。
92
+ * `--network_weights`
93
+ * 在训练之前读取预训练的LoRA权重,并在此基础上进行进一步的训练。
94
+ * `--network_train_unet_only`
95
+ * 仅启用与U-Net相关的LoRA模块。在类似fine tuning的学习中指定此选项可能会很有用。
96
+ * `--network_train_text_encoder_only`
97
+ * 仅启用与Text Encoder相关的LoRA模块。可能会期望Textual Inversion效果。
98
+ * `--unet_lr`
99
+ * 当在U-Net相关的LoRA模块中使用与常规学习率(由`--learning_rate`选项指定)不同的学习率时,应指定此选项。
100
+ * `--text_encoder_lr`
101
+ * 当在Text Encoder相关的LoRA模块中使用与常规学习率(由`--learning_rate`选项指定)不同的学习率时,应指定此选项。可能最好将Text Encoder的学习率稍微降低(例如5e-5)。
102
+ * `--network_args`
103
+ * 可以指定多个参数。将在下面详细说明。
104
+
105
+ 当未指定`--network_train_unet_only`和`--network_train_text_encoder_only`时(默认情况),将启用Text Encoder和U-Net的两个LoRA模块。
106
+
107
+ # 其他的学习方法
108
+
109
+ ## 学习 LoRA-C3Lier
110
+
111
+ 请使用以下方式
112
+
113
+ ```
114
+ --network_args "conv_dim=4"
115
+ ```
116
+
117
+ DyLoRA是在这篇论文中提出的[DyLoRA: Parameter Efficient Tuning of Pre-trained Models using Dynamic Search-Free Low-Rank Adaptation](​https://arxiv.org/abs/2210.07558),
118
+ [其官方实现可在这里找到](​https://github.com/huawei-noah/KD-NLP/tree/main/DyLoRA)。
119
+
120
+ 根据论文,LoRA的rank并不是越高越好,而是需要根据模型、数据集、任务等因素来寻找合适的rank。使用DyLoRA,可以同时在指定的维度(rank)下学习多种rank的LoRA,从而省去了寻找最佳rank的麻烦。
121
+
122
+ 本存储库的实现基于官方实现进行了自定义扩展(因此可能存在缺陷)。
123
+
124
+ ### 本存储库DyLoRA的特点
125
+
126
+ DyLoRA训练后的模型文件与LoRA兼容。此外,可以从模型文件中提取多个低于指定维度(rank)的LoRA。
127
+
128
+ DyLoRA-LierLa和DyLoRA-C3Lier均可训练。
129
+
130
+ ### 使用DyLoRA进行训练
131
+
132
+ 请指定与DyLoRA相对应的`network.dylora`,例如 `--network_module=networks.dylora`。
133
+
134
+ 此外,通过 `--network_args` 指定例如`--network_args "unit=4"`的参数。`unit`是划分rank的单位。例如,可以指定为`--network_dim=16 --network_args "unit=4"`。请将`unit`视为可以被`network_dim`整除的值(`network_dim`是`unit`的倍数)。
135
+
136
+ 如果未指定`unit`,则默认为`unit=1`。
137
+
138
+ 以下是示例说明。
139
+
140
+ ```
141
+ --network_module=networks.dylora --network_dim=16 --network_args "unit=4"
142
+
143
+ --network_module=networks.dylora --network_dim=32 --network_alpha=16 --network_args "unit=4"
144
+ ```
145
+
146
+ 对于DyLoRA-C3Lier,需要在 `--network_args` 中指定 `conv_dim`,例如 `conv_dim=4`。与普通的LoRA不同,`conv_dim`必须与`network_dim`具有相同的值。以下是一个示例描述:
147
+
148
+ ```
149
+ --network_module=networks.dylora --network_dim=16 --network_args "conv_dim=16" "unit=4"
150
+
151
+ --network_module=networks.dylora --network_dim=32 --network_alpha=16 --network_args "conv_dim=32" "conv_alpha=16" "unit=8"
152
+ ```
153
+
154
+ 例如,当使用dim=16、unit=4(如下所述)进行学习时,可以学习和提取4个rank的LoRA,即4、8、12和16。通过在每个提取的模型中生成图像并进行比较,可以选择最佳rank的LoRA。
155
+
156
+ 其他选项与普通的LoRA相同。
157
+
158
+ *`unit`是本存储库的独有扩展,在DyLoRA中,由于预计相比同维度(rank)的普通LoRA,学习时间更长,因此将分割单位增加。
159
+
160
+ ### 从DyLoRA模型中提取LoRA模型
161
+
162
+ 请使用`networks`文件夹中的`extract_lora_from_dylora.py`。指定`unit`单位后,从DyLoRA模型中提取LoRA模型。
163
+
164
+ 例如,命令行如下:
165
+
166
+ ```powershell
167
+ python networks\extract_lora_from_dylora.py --model "foldername/dylora-model.safetensors" --save_to "foldername/dylora-model-split.safetensors" --unit 4
168
+ ```
169
+
170
+ `--model` 参数用于指定DyLoRA模型文件。`--save_to` 参数用于指定要保存提取的模型的文件名(rank值将附加到文件名中)。`--unit` 参数用于指定DyLoRA训练时的`unit`。
171
+
172
+ ## 分层学习率
173
+
174
+ 请参阅PR#355了解详细信息。
175
+
176
+ 您可以指定完整模型的25个块的权重。虽然第一个块没有对应的LoRA,但为了与分层LoRA应用等的兼容性,将其设为25个。此外,如果不扩展到conv2d3x3,则某些块中可能不存在LoRA,但为了统一描述,请始终指定25个值。
177
+
178
+ 请在 `--network_args` 中指定以下参数。
179
+
180
+ - `down_lr_weight`:指定U-Net down blocks的学习率权重。可以指定以下内容:
181
+ - 每个块的权重:指定12个数字,例如`"down_lr_weight=0,0,0,0,0,0,1,1,1,1,1,1"`
182
+ - 从预设中指定:例如`"down_lr_weight=sine"`(使用正弦曲线指定权重)。可以指定sine、cosine、linear、reverse_linear、zeros。另外,添加 `+数字` 时,可以将指定的数字加上(变为0.25〜1.25)。
183
+ - `mid_lr_weight`:指定U-Net mid block的学习率权重。只需指定一个数字,例如 `"mid_lr_weight=0.5"`。
184
+ - `up_lr_weight`:指定U-Net up blocks的学习率权重。与down_lr_weight相同。
185
+ - 省略指定的部分将被视为1.0。另外,如果将权重设为0,则不会创建该块的LoRA模块。
186
+ - `block_lr_zero_threshold`:如果权重小于此值,则不会创建LoRA模块。默认值为0。
187
+
188
+ ### 分层学习率命令行指定示例:
189
+
190
+
191
+ ```powershell
192
+ --network_args "down_lr_weight=0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0,1.5,1.5,1.5,1.5" "mid_lr_weight=2.0" "up_lr_weight=1.5,1.5,1.5,1.5,1.0,1.0,1.0,1.0,0.5,0.5,0.5,0.5"
193
+
194
+ --network_args "block_lr_zero_threshold=0.1" "down_lr_weight=sine+.5" "mid_lr_weight=1.5" "up_lr_weight=cosine+.5"
195
+ ```
196
+
197
+ ### Hierarchical Learning Rate指定的toml文件示例:
198
+
199
+ ```toml
200
+ network_args = [ "down_lr_weight=0.5,0.5,0.5,0.5,1.0,1.0,1.0,1.0,1.5,1.5,1.5,1.5", "mid_lr_weight=2.0", "up_lr_weight=1.5,1.5,1.5,1.5,1.0,1.0,1.0,1.0,0.5,0.5,0.5,0.5",]
201
+
202
+ network_args = [ "block_lr_zero_threshold=0.1", "down_lr_weight=sine+.5", "mid_lr_weight=1.5", "up_lr_weight=cosine+.5", ]
203
+ ```
204
+
205
+ ## 层次结构维度(rank)
206
+
207
+ 您可以指定完整模型的25个块的维度(rank)。与分层学习率一样,某些块可能不存在LoRA,但请始终指定25个值。
208
+
209
+ 请在 `--network_args` 中指定以下参数:
210
+
211
+ - `block_dims`:指定每个块的维度(rank)。指定25个数字,例如 `"block_dims=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2"`。
212
+ - `block_alphas`:指定每个块的alpha。与block_dims一样,指定25个数字。如果省略,将使用network_alpha的值。
213
+ - `conv_block_dims`:将LoRA扩展到Conv2d 3x3,并指定每个块的维度(rank)。
214
+ - `conv_block_alphas`:在将LoRA扩展到Conv2d 3x3时指定每个块的alpha。如果省略,将使用conv_alpha的值。
215
+
216
+ ### 层次结构维度(rank)命令行指定示例:
217
+
218
+
219
+ ```powershell
220
+ --network_args "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2"
221
+
222
+ --network_args "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2" "conv_block_dims=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2"
223
+
224
+ --network_args "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2" "block_alphas=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2"
225
+ ```
226
+
227
+ ### 层级别dim(rank) toml文件指定示例:
228
+
229
+ ```toml
230
+ network_args = [ "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2",]
231
+
232
+ network_args = [ "block_dims=2,4,4,4,8,8,8,8,12,12,12,12,16,12,12,12,12,8,8,8,8,4,4,4,2", "block_alphas=2,2,2,2,4,4,4,4,6,6,6,6,8,6,6,6,6,4,4,4,4,2,2,2,2",]
233
+ ```
234
+
235
+ # Other scripts
236
+ 这些是与LoRA相关的脚本,如合并脚本等。
237
+
238
+ 关于合并脚本
239
+ 您可以使用merge_lora.py脚本将LoRA的训练结果合并到稳定扩散模型中,也可以将多个LoRA模型合并。
240
+
241
+ 合并到稳定扩散模型中的LoRA模型
242
+ 合并后的模型可以像常规的稳定扩散ckpt一样使用。例如,以下是一个命令行示例:
243
+
244
+ ```
245
+ python networks\merge_lora.py --sd_model ..\model\model.ckpt
246
+ --save_to ..\lora_train1\model-char1-merged.safetensors
247
+ --models ..\lora_train1\last.safetensors --ratios 0.8
248
+ ```
249
+
250
+ 请使用 Stable Diffusion v2.x 模型进行训练并进行合并时,需要指定--v2选项。
251
+
252
+ 使用--sd_model选项指定要合并的 Stable Diffusion 模型文件(仅支持 .ckpt 或 .safetensors 格式,目前不支持 Diffusers)。
253
+
254
+ 使用--save_to选项指定合并后模型的保存路径(根据扩展名自动判断为 .ckpt 或 .safetensors)。
255
+
256
+ 使用--models选项指定已训练的 LoRA 模型文件,也可以指定多个,然后按顺序进行合并。
257
+
258
+ 使用--ratios选项以0~1.0的数字指定每个模型的应用率(将多大比例的权重反映到原始模型中)。例如,在接近过度拟合的情况下,降低应用率可能会使结果更好。请指定与模型数量相同的比率。
259
+
260
+ 当指定多个模型时,格式如下:
261
+
262
+
263
+ ```
264
+ python networks\merge_lora.py --sd_model ..\model\model.ckpt
265
+ --save_to ..\lora_train1\model-char1-merged.safetensors
266
+ --models ..\lora_train1\last.safetensors ..\lora_train2\last.safetensors --ratios 0.8 0.5
267
+ ```
268
+
269
+ ### 将多个LoRA模型合并
270
+
271
+ 将多个LoRA模型逐个应用于SD模型与将多个LoRA模型合并后再应用于SD模型之间,由于计算顺序的不同,会得到微妙不同的结果。
272
+
273
+ 例如,下面是一个命令行示例:
274
+
275
+ ```
276
+ python networks\merge_lora.py
277
+ --save_to ..\lora_train1\model-char1-style1-merged.safetensors
278
+ --models ..\lora_train1\last.safetensors ..\lora_train2\last.safetensors --ratios 0.6 0.4
279
+ ```
280
+
281
+ --sd_model选项不需要指定。
282
+
283
+ 通过--save_to选项指定合并后的LoRA模型的保存位置(.ckpt或.safetensors,根据扩展名自动识别)。
284
+
285
+ 通过--models选项指定学习的LoRA模型文件。可以指定三个或更多。
286
+
287
+ 通过--ratios选项以0~1.0的数字指定每个模型的比率(反映多少权重来自原始模型)。如果将两个模型一对一合并,则比率将是“0.5 0.5”。如果比率为“1.0 1.0”,则总重量将过大,可能会产生不理想的结果。
288
+
289
+ 在v1和v2中学习的LoRA,以及rank(维数)或“alpha”不同的LoRA不能合并。仅包含U-Net的LoRA和包含U-Net+文本编码器的LoRA可以合并,但结果未知。
290
+
291
+ ### 其他选项
292
+
293
+ * 精度
294
+ * 可以从float、fp16或bf16中选择合并计算时的精度。默认为float以保证精度。如果想减少内存使用量,请指定fp16/bf16。
295
+ * save_precision
296
+ * 可以从float、fp16或bf16中选择在保存模型时的精度。默认与精度相同。
297
+
298
+ ## 合并多个维度不同的LoRA模型
299
+
300
+ 将多个LoRA近似为一个LoRA(无法完全复制)。使用'svd_merge_lora.py'。例如,以下是命令行的示例。
301
+ ```
302
+ python networks\svd_merge_lora.py
303
+ --save_to ..\lora_train1\model-char1-style1-merged.safetensors
304
+ --models ..\lora_train1\last.safetensors ..\lora_train2\last.safetensors
305
+ --ratios 0.6 0.4 --new_rank 32 --device cuda
306
+ ```
307
+ `merge_lora.py`和主要选项相同。以下选项已添加:
308
+
309
+ - `--new_rank`
310
+ - 指定要创建的LoRA rank。
311
+ - `--new_conv_rank`
312
+ - 指定要创建的Conv2d 3x3 LoRA的rank。如果省略,则与`new_rank`相同。
313
+ - `--device`
314
+ - 如果指定为`--device cuda`,则在GPU上执行计算。处理速度将更快。
315
+
316
+ ## 在此存储库中生成图像的脚本中
317
+
318
+ 请在`gen_img_diffusers.py`中添加`--network_module`和`--network_weights`选项。其含义与训练时相同。
319
+
320
+ 通过`--network_mul`选项,可以指定0~1.0的数字来改变LoRA的应用率。
321
+
322
+ ## 请参考以下示例,在Diffusers的pipeline中生成。
323
+
324
+ 所需文件仅为networks/lora.py。请注意,该示例只能在Diffusers版本0.10.2中正常运行。
325
+
326
+ ```python
327
+ import torch
328
+ from diffusers import StableDiffusionPipeline
329
+ from networks.lora import LoRAModule, create_network_from_weights
330
+ from safetensors.torch import load_file
331
+
332
+ # if the ckpt is CompVis based, convert it to Diffusers beforehand with tools/convert_diffusers20_original_sd.py. See --help for more details.
333
+
334
+ model_id_or_dir = r"model_id_on_hugging_face_or_dir"
335
+ device = "cuda"
336
+
337
+ # create pipe
338
+ print(f"creating pipe from {model_id_or_dir}...")
339
+ pipe = StableDiffusionPipeline.from_pretrained(model_id_or_dir, revision="fp16", torch_dtype=torch.float16)
340
+ pipe = pipe.to(device)
341
+ vae = pipe.vae
342
+ text_encoder = pipe.text_encoder
343
+ unet = pipe.unet
344
+
345
+ # load lora networks
346
+ print(f"loading lora networks...")
347
+
348
+ lora_path1 = r"lora1.safetensors"
349
+ sd = load_file(lora_path1) # If the file is .ckpt, use torch.load instead.
350
+ network1, sd = create_network_from_weights(0.5, None, vae, text_encoder,unet, sd)
351
+ network1.apply_to(text_encoder, unet)
352
+ network1.load_state_dict(sd)
353
+ network1.to(device, dtype=torch.float16)
354
+
355
+ # # You can merge weights instead of apply_to+load_state_dict. network.set_multiplier does not work
356
+ # network.merge_to(text_encoder, unet, sd)
357
+
358
+ lora_path2 = r"lora2.safetensors"
359
+ sd = load_file(lora_path2)
360
+ network2, sd = create_network_from_weights(0.7, None, vae, text_encoder,unet, sd)
361
+ network2.apply_to(text_encoder, unet)
362
+ network2.load_state_dict(sd)
363
+ network2.to(device, dtype=torch.float16)
364
+
365
+ lora_path3 = r"lora3.safetensors"
366
+ sd = load_file(lora_path3)
367
+ network3, sd = create_network_from_weights(0.5, None, vae, text_encoder,unet, sd)
368
+ network3.apply_to(text_encoder, unet)
369
+ network3.load_state_dict(sd)
370
+ network3.to(device, dtype=torch.float16)
371
+
372
+ # prompts
373
+ prompt = "masterpiece, best quality, 1girl, in white shirt, looking at viewer"
374
+ negative_prompt = "bad quality, worst quality, bad anatomy, bad hands"
375
+
376
+ # exec pipe
377
+ print("generating image...")
378
+ with torch.autocast("cuda"):
379
+ image = pipe(prompt, guidance_scale=7.5, negative_prompt=negative_prompt).images[0]
380
+
381
+ # if not merged, you can use set_multiplier
382
+ # network1.set_multiplier(0.8)
383
+ # and generate image again...
384
+
385
+ # save image
386
+ image.save(r"by_diffusers..png")
387
+ ```
388
+
389
+ ## 从两个模型的差异中创建LoRA模型。
390
+
391
+ [参考讨论链接](https://github.com/cloneofsimo/lora/discussions/56)這是參考實現的結果。數學公式沒有改變(我並不完全理解,但似乎使用奇異值分解進行了近似)。
392
+
393
+ 将两个模型(例如微调原始模型和微调后的模型)的差异近似为LoRA。
394
+
395
+ ### 脚本执行方法
396
+
397
+ 请按以下方式指定。
398
+
399
+ ```
400
+ python networks\extract_lora_from_models.py --model_org base-model.ckpt
401
+ --model_tuned fine-tuned-model.ckpt
402
+ --save_to lora-weights.safetensors --dim 4
403
+ ```
404
+
405
+ --model_org 选项指定原始的Stable Diffusion模型。如果要应用创建的LoRA模型,则需要指定该模型并将其应用。可以指定.ckpt或.safetensors文件。
406
+
407
+ --model_tuned 选项指定要提取差分的目标Stable Diffusion模型。例如,可以指定经过Fine Tuning或DreamBooth后的模型。可以指定.ckpt或.safetensors文件。
408
+
409
+ --save_to 指定LoRA模型的保存路径。--dim指定LoRA的维数。
410
+
411
+ 生成的LoRA模型可以像已训练的LoRA模型一样使用。
412
+
413
+ 当两个模型的文本编码器相同时,LoRA将成为仅包含U-Net的LoRA。
414
+
415
+ ### 其他选项
416
+
417
+ - `--v2`
418
+ - 如果使用v2.x的稳定扩散模型,请指定此选项。
419
+ - `--device`
420
+ - 指定为 ``--device cuda`` 可在GPU上执行计算。这会使处理速度更快(即使在CPU上��不会太慢,大约快几倍)。
421
+ - `--save_precision`
422
+ - 指定LoRA的保存格式为“float”、“fp16”、“bf16”。如果省略,将使用float。
423
+ - `--conv_dim`
424
+ - 指定后,将扩展LoRA的应用范围到Conv2d 3x3。指定Conv2d 3x3的rank。
425
+ -
426
+ ## 图像大小调整脚本
427
+
428
+ (稍后将整理文件,但现在先在这里写下说明。)
429
+
430
+ 在 Aspect Ratio Bucketing 的功能扩展中,现在可以将小图像直接用作教师数据,而无需进行放大。我收到了一个用于前处理的脚本,其中包括将原始教师图像缩小的图像添加到教师数据中可以提高准确性的报告。我整理了这个脚本并加入了感谢 bmaltais 先生。
431
+
432
+ ### 执行脚本的方法如下。
433
+ 原始图像以及调整大小后的图像将保存到转换目标文件夹中。调整大小后的图像将在文件名中添加“+512x512”之类的调整后的分辨率(与图像大小不同)。小于调整大小后分辨率的图像将不会被放大。
434
+
435
+ ```
436
+ python tools\resize_images_to_resolution.py --max_resolution 512x512,384x384,256x256 --save_as_png
437
+ --copy_associated_files 源图像文件夹目标文件夹
438
+ ```
439
+
440
+ 在元画像文件夹中的图像文件将被调整大小以达到指定的分辨率(可以指定多个),并保存到目标文件夹中。除图像外的文件将被保留为原样。
441
+
442
+ 请使用“--max_resolution”选项指定调整大小后的大小,使其达到指定的面积大小。如果指定多个,则会在每个分辨率上进行调整大小。例如,“512x512,384x384,256x256”将使目标文件夹中的图像变为原始大小和调整大小后的大小×3共计4张图像。
443
+
444
+ 如果使用“--save_as_png”选项,则会以PNG格式保存。如果省略,则默认以JPEG格式(quality=100)保存。
445
+
446
+ 如果使用“--copy_associated_files”选项,则会将与图像相同的文件名(例如标题等)的文件复制到调整大小后的图像文件的文件名相同的位置,但不包括扩展名。
447
+
448
+ ### 其他选项
449
+
450
+ - divisible_by
451
+ - 将图像中心裁剪到能够被该值整除的大小(分别是垂直和水平的大小),以便调整大小后的图像大小可以被该值整除。
452
+ - interpolation
453
+ - 指定缩小时的插值方法。可从``area、cubic、lanczos4``中选择,默认为``area``。
454
+
455
+
456
+ # 追加信息
457
+
458
+ ## 与cloneofsimo的代码库的区别
459
+
460
+ 截至2022年12月25日,本代码库将LoRA应用扩展到了Text Encoder的MLP、U-Net的FFN以及Transformer的输入/输出投影中,从而增强了表现力。但是,内存使用量增加了,接近了8GB的限制。
461
+
462
+ 此外,模块交换机制也完全不同。
463
+
464
+ ## 关于未来的扩展
465
+
466
+ 除了LoRA之外,我们还计划添加其他扩展,以支持更多的功能。
docs/train_ti_README-ja.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Textual Inversion](https://textual-inversion.github.io/) の学習についての説明です。
2
+
3
+ [学習についての共通ドキュメント](./train_README-ja.md) もあわせてご覧ください。
4
+
5
+ 実装に当たっては https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion を大いに参考にしました。
6
+
7
+ 学習したモデルはWeb UIでもそのまま使えます。
8
+
9
+ # 学習の手順
10
+
11
+ あらかじめこのリポジトリのREADMEを参照し、環境整備を行ってください。
12
+
13
+ ## データの準備
14
+
15
+ [学習データの準備について](./train_README-ja.md) を参照してください。
16
+
17
+ ## 学習の実行
18
+
19
+ ``train_textual_inversion.py`` を用います。以下はコマンドラインの例です(DreamBooth手法)。
20
+
21
+ ```
22
+ accelerate launch --num_cpu_threads_per_process 1 train_textual_inversion.py
23
+ --dataset_config=<データ準備で作成した.tomlファイル>
24
+ --output_dir=<学習したモデルの出力先フォルダ>
25
+ --output_name=<学習したモデル出力時のファイル名>
26
+ --save_model_as=safetensors
27
+ --prior_loss_weight=1.0
28
+ --max_train_steps=1600
29
+ --learning_rate=1e-6
30
+ --optimizer_type="AdamW8bit"
31
+ --xformers
32
+ --mixed_precision="fp16"
33
+ --cache_latents
34
+ --gradient_checkpointing
35
+ --token_string=mychar4 --init_word=cute --num_vectors_per_token=4
36
+ ```
37
+
38
+ ``--token_string`` に学習時のトークン文字列を指定します。__学習時のプロンプトは、この文字列を含むようにしてください(token_stringがmychar4なら、``mychar4 1girl`` など)__。プロンプトのこの文字列の部分が、Textual Inversionの新しいtokenに置換されて学習されます。DreamBooth, class+identifier形式のデータセットとして、`token_string` をトークン文字列にするのが最も簡単で確実です。
39
+
40
+ プロンプトにトークン文字列が含まれているかどうかは、``--debug_dataset`` で置換後のtoken idが表示されますので、以下のように ``49408`` 以降のtokenが存在するかどうかで確認できます。
41
+
42
+ ```
43
+ input ids: tensor([[49406, 49408, 49409, 49410, 49411, 49412, 49413, 49414, 49415, 49407,
44
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
45
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
46
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
47
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
48
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
50
+ 49407, 49407, 49407, 49407, 49407, 49407, 49407]])
51
+ ```
52
+
53
+ tokenizerがすでに持っている単語(一般的な単語)は使用できません。
54
+
55
+ ``--init_word`` にembeddingsを初期化するときのコピー元トークンの文字列を指定します。学ばせたい概念が近いものを選ぶとよいようです。二つ以上のトークンになる文字列は指定できません。
56
+
57
+ ``--num_vectors_per_token`` にいくつのトークンをこの学習で使うかを指定します。多いほうが表現力が増しますが、その分多くのトークンを消費します。たとえばnum_vectors_per_token=8の場合、指定したトークン文字列は(一般的なプロンプトの77トークン制限のうち)8トークンを消費します。
58
+
59
+ 以上がTextual Inversionのための主なオプションです。以降は他の学習スクリプトと同様です。
60
+
61
+ `num_cpu_threads_per_process` には通常は1を指定するとよいようです。
62
+
63
+ `pretrained_model_name_or_path` に追加学習を行う元となるモデルを指定します。Stable Diffusionのcheckpointファイル(.ckptまたは.safetensors)、Diffusersのローカルディスクにあるモデルディレクトリ、DiffusersのモデルID("stabilityai/stable-diffusion-2"など)が指定できます。
64
+
65
+ `output_dir` に学習後のモデルを保存するフォルダを指定します。`output_name` にモデルのファイル名を拡張子を除いて指定します。`save_model_as` でsafetensors形式での保存を指定しています。
66
+
67
+ `dataset_config` に `.toml` ファイルを指定します。ファイル内でのバッチサイズ指定は、当初はメモリ消費を抑えるために `1` としてください。
68
+
69
+ 学習させるステップ数 `max_train_steps` を10000とします。学習率 `learning_rate` はここでは5e-6を指定しています。
70
+
71
+ 省メモリ化のため `mixed_precision="fp16"` を指定します(RTX30 シリーズ以降では `bf16` も指定できます。環境整備時にaccelerateに行った設定と合わせてください)。また `gradient_checkpointing` を指定します。
72
+
73
+ オプティマイザ(モデルを学習データにあうように最適化=学習させるクラス)にメモリ消費の少ない 8bit AdamW を使うため、 `optimizer_type="AdamW8bit"` を指定します。
74
+
75
+ `xformers` オプションを指定し、xformersのCrossAttentionを用います。xformersをインストールしていない場合やエラーとなる場合(環境にもよりますが `mixed_precision="no"` の場合など)、代わりに `mem_eff_attn` オプションを指定すると省メモリ版CrossAttentionを使用します(速度は遅くなります)。
76
+
77
+ ある程度メモリがある場合は、`.toml` ファイルを編集してバッチサイズをたとえば `8` くらいに増やしてください(高速化と精度向上の可能性があります)。
78
+
79
+ ### よく使われるオプションについて
80
+
81
+ 以下の場合にはオプションに関するドキュメントを参照してください。
82
+
83
+ - Stable Diffusion 2.xまたはそこからの派生モデルを学習する
84
+ - clip skipを2以上を前提としたモデルを学習する
85
+ - 75トークンを超えたキャプションで学習する
86
+
87
+ ### Textual Inversionでのバッチサイズについて
88
+
89
+ モデル全体を学習するDreamBoothやfine tuningに比べてメモリ使用量が少ないため、バッチサイズは大きめにできます。
90
+
91
+ # Textual Inversionのその他の主なオプション
92
+
93
+ すべてのオプションについては別文書を参照してください。
94
+
95
+ * `--weights`
96
+ * 学習前に学習済みのembeddingsを読み込み、そこから追加で学習します。
97
+ * `--use_object_template`
98
+ * キャプションではなく既定の物体用テンプレート文字列(``a photo of a {}``など)で学習します。公式実装と同じになります。キャプションは無視されます。
99
+ * `--use_style_template`
100
+ * キャプションではなく既定のスタイル用テンプレート文字列で学習します(``a painting in the style of {}``など)。公式実装と同じになります。キャプションは無視されます。
101
+
102
+ ## 当リポジトリ内の画像生成スクリプトで生成する
103
+
104
+ gen_img_diffusers.pyに、``--textual_inversion_embeddings`` オプションで学習したembeddingsファイルを指定してください(複数可)。プロンプトでembeddingsファイルのファイル名(拡張子を除く)を使うと、そのembeddingsが適用されます。
105
+