pull/3451/merge
Sungjoon Kim 2025-11-01 10:16:28 +00:00 committed by GitHub
commit 24296f0d4f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
33 changed files with 1184 additions and 705 deletions

View File

@ -3,7 +3,6 @@ cudnn_windows/
bitsandbytes_windows/
bitsandbytes_windows_deprecated/
dataset/
models/
__pycache__/
venv/
**/.hadolint.yml
@ -14,3 +13,11 @@ venv/
**/.github
**/.vscode
**/*.ps1
.idea/
.vscode/
docs/
examples/
logs/
outputs/
sd-scripts/venv
models/sd_xl_base_1.0.safetensors

3
.github/FUNDING.yml vendored
View File

@ -1,3 +0,0 @@
# These are supported funding model platforms
github: [bmaltais]

View File

@ -1,7 +0,0 @@
---
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"

View File

@ -1,91 +0,0 @@
# Check this guide for more information about publishing to ghcr.io with GitHub Actions:
# 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
# Build the Docker image and push it to the registry
name: docker_publish
on:
# Trigger the workflow on tags push that match the pattern v*, for example v1.0.0
push:
tags:
- "v*"
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
# Only run this job on tags
docker-tag:
runs-on: ubuntu-latest
if: startsWith(github.ref, 'refs/tags/')
# Sets the permissions granted to the GITHUB_TOKEN for the actions in this job.
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: true
# We require additional space due to the large size of our image. (~10GB)
- name: Free Disk Space (Ubuntu)
uses: jlumbroso/free-disk-space@main
with:
tool-cache: true
android: true
dotnet: true
haskell: true
large-packages: true
docker-images: true
swap-storage: true
- name: Docker meta:${{ github.ref_name }}
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository_owner }}/kohya-ss-gui
flavor: |
latest=auto
prefix=
suffix=
# https://github.com/docker/metadata-action/tree/v5/?tab=readme-ov-file#tags-input
tags: |
type=semver,pattern=v{{major}}
type=semver,pattern={{raw}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# You may need to manage write and read access of GitHub Actions for repositories in the container settings.
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v6
id: publish
with:
context: .
file: ./Dockerfile
push: true
target: final
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ github.ref_name }}
RELEASE=${{ github.run_number }}
platforms: linux/amd64
# Cache to regietry instead of gha to avoid the capacity limit.
cache-from: type=registry,ref=ghcr.io/${{ github.repository_owner }}/kohya-ss-gui:cache
cache-to: type=registry,ref=ghcr.io/${{ github.repository_owner }}/kohya-ss-gui:cache,mode=max
sbom: true
provenance: true

View File

@ -1,21 +0,0 @@
---
# yamllint disable rule:line-length
name: Typos
on: # yamllint disable-line rule:truthy
push:
pull_request:
types:
- opened
- synchronize
- reopened
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: typos-action
uses: crate-ci/typos@v1.32.0

7
.gitignore vendored
View File

@ -1,3 +1,4 @@
.idea
# Python
.venv
venv
@ -52,7 +53,9 @@ dataset/**
models
data
config.toml
sd-scripts
venv
venv*
.python-version
.python-version
output_models
output_models/
output_models/**

View File

@ -1,179 +1,45 @@
# syntax=docker/dockerfile:1
ARG UID=1000
ARG VERSION=EDGE
ARG RELEASE=0
# Python 3.11 + PyTorch 2.7.1 + CUDA 12.8 + CuDNN 9.5
FROM pytorch/pytorch:2.7.1-cuda12.8-cudnn9-devel
########################################
# Base stage
########################################
FROM docker.io/library/python:3.11-slim-bookworm AS base
# 기본 작업 경로 설정
WORKDIR /app
# RUN mount cache for multi-arch: https://github.com/docker/buildx/issues/549#issuecomment-1788297892
ARG TARGETARCH
ARG TARGETVARIANT
WORKDIR /tmp
ENV NVIDIA_VISIBLE_DEVICES=all
ENV NVIDIA_DRIVER_CAPABILITIES=compute,utility
# Install CUDA partially
# https://docs.nvidia.com/cuda/cuda-installation-guide-linux/#debian
# Installing the complete CUDA Toolkit system-wide usually adds around 8GB to the image size.
# Since most CUDA packages already installed through pip, there's no need to download the entire toolkit.
# Therefore, we opt to install only the essential libraries.
# Here is the package list for your reference: https://developer.download.nvidia.com/compute/cuda/repos/debian12/x86_64
ADD https://developer.download.nvidia.com/compute/cuda/repos/debian12/x86_64/cuda-keyring_1.1-1_all.deb /tmp/cuda-keyring_x86_64.deb
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
--mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
dpkg -i cuda-keyring_x86_64.deb && \
rm -f cuda-keyring_x86_64.deb && \
# 필수 패키지 설치
RUN sed -i 's|archive.ubuntu.com|mirror.kakao.com|g' /etc/apt/sources.list && \
apt-get update && \
apt-get install -y --no-install-recommends \
# !If you experience any related issues, replace the following line with `cuda-12-8` to obtain the complete CUDA package.
cuda-nvcc-12-8
apt-get install -y apt-utils libgl1 libglib2.0-0 && \
apt-get install -y --no-install-recommends git wget curl && \
rm -rf /var/lib/apt/lists/*
ENV PATH="/usr/local/cuda/bin${PATH:+:${PATH}}"
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64
ENV CUDA_VERSION=12.8
ENV NVIDIA_REQUIRE_CUDA=cuda>=12.8
ENV CUDA_HOME=/usr/local/cuda
# Python 패키지 캐싱 방지
ENV PIP_NO_CACHE_DIR=1
########################################
# Build stage
########################################
FROM base AS build
# pip 업그레이드 및 공통 유틸 설치
RUN pip install --upgrade pip setuptools wheel
# RUN mount cache for multi-arch: https://github.com/docker/buildx/issues/549#issuecomment-1788297892
ARG TARGETARCH
ARG TARGETVARIANT
# kohya_ss 전체 복사 (모델 포함)
COPY . /app/sdxl_train_captioner
# requirements.txt 설치
WORKDIR /app/sdxl_train_captioner
WORKDIR /app
# 2. xformers
RUN pip install xformers==0.0.31
# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
RUN pip install --no-cache-dir -r requirements.txt
# 문제 발생 시 버전 고정: ====2.8.0
RUN pip install flash-attn==2.8.0.post2 --no-build-isolation
ENV UV_PROJECT_ENVIRONMENT=/venv
ENV VIRTUAL_ENV=/venv
ENV UV_LINK_MODE=copy
ENV UV_PYTHON_DOWNLOADS=0
ENV UV_INDEX=https://download.pytorch.org/whl/cu128
RUN mkdir -p /app/sdxl_train_captioner/dataset
RUN mkdir -p /app/sdxl_train_captioner/models
# Install build dependencies
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
--mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
apt-get update && apt-get upgrade -y && \
apt-get install -y --no-install-recommends python3-launchpadlib git curl
# 모델 파일 복사 (미리 포함시킬 가중치)
COPY ./models /app/sdxl_train_captioner/models
# Install big dependencies separately for layer caching
# !Please note that the version restrictions should be the same as pyproject.toml
# No packages listed should be removed in the next `uv sync` command
# If this happens, please update the version restrictions or update the uv.lock file
RUN --mount=type=cache,id=uv-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/root/.cache/uv \
uv venv --system-site-packages /venv && \
uv pip install --no-deps \
# torch (1.0GiB)
torch==2.7.0+cu128 \
# triton (149.3MiB)
triton>=3.1.0 \
# tensorflow (615.0MiB)
tensorflow>=2.16.1 \
# onnxruntime-gpu (215.7MiB)
onnxruntime-gpu==1.19.2
WORKDIR /app/sdxl_train_captioner/sd-scripts
# Install dependencies
RUN --mount=type=cache,id=uv-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/root/.cache/uv \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=sd-scripts,target=sd-scripts,rw \
uv sync --frozen --no-dev --no-install-project --no-editable
RUN chmod +x ./entrypoint.sh
RUN chmod +x ./run-tensorboard.sh
RUN chmod +x ./run-train-auto.sh
RUN chmod +x ./run-train-single.sh
# Replace pillow with pillow-simd (Only for x86)
ARG TARGETPLATFORM
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
--mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
apt-get update && apt-get install -y --no-install-recommends zlib1g-dev libjpeg62-turbo-dev build-essential && \
uv pip uninstall pillow && \
CC="cc -mavx2" uv pip install pillow-simd; \
fi
########################################
# Final stage
########################################
FROM base AS final
ARG TARGETARCH
ARG TARGETVARIANT
WORKDIR /tmp
# Install runtime dependencies
RUN --mount=type=cache,id=apt-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/cache/apt \
--mount=type=cache,id=aptlists-$TARGETARCH$TARGETVARIANT,sharing=locked,target=/var/lib/apt/lists \
apt-get update && apt-get upgrade -y && \
apt-get install -y --no-install-recommends libgl1 libglib2.0-0 libjpeg62 libtcl8.6 libtk8.6 libgoogle-perftools-dev dumb-init
# Fix missing libnvinfer7
RUN ln -s /usr/lib/x86_64-linux-gnu/libnvinfer.so /usr/lib/x86_64-linux-gnu/libnvinfer.so.7 && \
ln -s /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so /usr/lib/x86_64-linux-gnu/libnvinfer_plugin.so.7
# Create user
ARG UID
RUN groupadd -g $UID $UID && \
useradd -l -u $UID -g $UID -m -s /bin/sh -N $UID
# Create directories with correct permissions
RUN install -d -m 775 -o $UID -g 0 /dataset && \
install -d -m 775 -o $UID -g 0 /licenses && \
install -d -m 775 -o $UID -g 0 /app && \
install -d -m 775 -o $UID -g 0 /venv
# Copy licenses (OpenShift Policy)
COPY --link --chmod=775 LICENSE.md /licenses/LICENSE.md
# Copy dependencies and code (and support arbitrary uid for OpenShift best practice)
COPY --link --chown=$UID:0 --chmod=775 --from=build /venv /venv
COPY --link --chown=$UID:0 --chmod=775 . /app
ENV PATH="/venv/bin${PATH:+:${PATH}}"
ENV PYTHONPATH="/venv/lib/python3.11/site-packages"
ENV LD_LIBRARY_PATH="/venv/lib/python3.11/site-packages/nvidia/cudnn/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
ENV LD_PRELOAD=libtcmalloc.so
ENV PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
# Rich logging
# https://rich.readthedocs.io/en/stable/console.html#interactive-mode
ENV FORCE_COLOR="true"
ENV COLUMNS="100"
WORKDIR /app
VOLUME [ "/dataset" ]
# 7860: Kohya GUI
EXPOSE 7860
USER $UID
STOPSIGNAL SIGINT
# Use dumb-init as PID 1 to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
CMD ["python3", "kohya_gui.py", "--listen", "0.0.0.0", "--server_port", "7860", "--headless", "--noverify"]
ARG VERSION
ARG RELEASE
LABEL name="bmaltais/kohya_ss" \
vendor="bmaltais" \
maintainer="bmaltais" \
# Dockerfile source repository
url="https://github.com/bmaltais/kohya_ss" \
version=${VERSION} \
# This should be a number, incremented with each change
release=${RELEASE} \
io.k8s.display-name="kohya_ss" \
summary="Kohya's GUI: This repository provides a Gradio GUI for Kohya's Stable Diffusion trainers(https://github.com/kohya-ss/sd-scripts)." \
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."
ENTRYPOINT ["bash", "entrypoint.sh"]

246
MANUAL_TRAIN.md Normal file
View File

@ -0,0 +1,246 @@
# I. 단일폴더 수동 학습 사용 예시
## 1. 기본 사용 (자동 계산)
```cmd
run-train-single --folder ../dataset/training/01_alice
```
## 2. Epochs만 수동 지정
```cmd
run-train-single --folder ../dataset/training/01_alice --epochs 25
또는
run-train-single --folder ../training/mainchar/01_alic3 --epochs 17 --resume alic3-000009.safetensors
```
## 3. 세밀한 조정
```cmd
run-train-single ^
--folder ../dataset/training/01_alice ^
--epochs 30 ^
--repeats 50 ^
--lr 0.00015 ^
--dim 64 ^
--alpha 32
```
## 4. 고해상도 학습
```cmd
run-train-single ^
--folder ../dataset/training/01_alice ^
--resolution 1024,1024 ^
--batch-size 1
```
## 5. 빠른 테스트
```cmd
run-train-single ^
--folder ../dataset/training/01_alice ^
--epochs 5 ^
--repeats 10 ^
--save-every 1
```
## 6. 완전 수동 모드
```cmd
run-train-single ^
--folder ../dataset/training/01_alice ^
--no-auto ^
--epochs 20 ^
--repeats 30 ^
--lr 0.0001 ^
--optimizer AdamW8bit ^
--scheduler cosine
```
## 주요 기능
✨ 자동 + 수동 하이브리드
- 기본값은 자동 계산
- 원하는 파라미터만 오버라이드
- --no-auto 플래그로 완전 수동 제어
## 🎯 주요 파라미터
| 파라미터 | 설명 | 예시 |
|---------|------|------|
| --folder | 학습 폴더 (필수) | ../dataset/training/01_alice |
| --output | 출력 이름 | alice_v2 |
| --epochs | Epoch 수 | 20 |
| --repeats | 반복 횟수 | 30 |
| --lr | Learning rate | 0.0001 |
| --dim | Network dimension | 64 |
| --alpha | Network alpha | 32 |
| --resolution | 해상도 | 1024,1024 |
| --batch-size | 배치 크기 | 2 |
| --optimizer | Optimizer | AdamW8bit, Lion, Prodigy |
| --scheduler | LR Scheduler | cosine, constant |
| --save-every | 저장 주기 | 5 |
## 비교
### train_batch.py (일괄 자동)
```cmd
# 여러 폴더 자동 학습
python train_batch.py
→ 01_alice, 02_bob, 03_background 모두 학습
```
### train_single.py (단일 수동)
```cmd
# 특정 폴더만 세밀 조정
run-train-single --folder ../dataset/training/mainchar/01_alice --epochs 30 --lr 0.00015
→ alice만 커스텀 파라미터로 학습
```
## 워크플로우 추천
### 초보자
```cmd
# 1. 먼저 일괄 자동으로 테스트
python train_batch.py
# 2. 결과가 좋지 않은 캐릭터만 재학습
run-train-single --folder ../dataset/training/mainchar/01_alice --epochs 25
```
### 고급 사용자
```cmd
# 처음부터 세밀하게 조정
run-train-single ^
--folder ../dataset/training/mainchar/01_alice ^
--epochs 30 ^
--repeats 50 ^
--lr 0.00012 ^
--dim 64 ^
--alpha 32 ^
--optimizer Prodigy ^
--resolution 1024,1024
```
# II. 단일폴더 학습재개(resume) 방법
## 1. 기본 Resume
```cmd
run-train-single --folder ../dataset/training/mainchar/01_alice --resume ../output_models/alice-epoch-010.safetensors
```
## 2. Resume + Learning Rate 조정 (Fine-tuning)
```cmd
run-train-single --folder ../dataset/training/mainchar/01_alice ^
--folder ../dataset/training/01_alice ^
--resume ../output_models/alice-epoch-010.safetensors ^
--epochs 20 ^
--lr 0.00005
```
## 3. Resume + 더 많은 데이터
```cmd
run-train-single --folder ../dataset/training/mainchar/01_alice ^
--folder ../dataset/training/01_alice_more ^
--resume ../output_models/alice-epoch-015.safetensors ^
--epochs 10
```
## 주의사항
✅ Resume 시 동일하게 유지해야 할 것
- --dim (network_dim)
- --alpha (network_alpha)
- 네트워크 구조 관련 설정
## ⚠️ Resume 시 변경 가능한 것
- --epochs (더 학습)
- --lr (learning rate 조정)
- --repeats (데이터 반복)
- --optimizer (optimizer 변경)
- --scheduler (스케줄러 변경)
## ❌ Resume 시 변경하면 안되는 것
```cmd
# 잘못된 예
run-train-single \
--folder ../dataset/training/01_alice \
--resume ../output_models/alice-epoch-010.safetensors \
--dim 64 # ❌ 원래 32였으면 에러!
```
## 실전 예시
### 시나리오 1: 학습이 중단됨
```cmd
# 10 epoch에서 중단
# → 10 epoch부터 이어서 15 epoch까지
run-train-single ^
--folder ../dataset/training/01_alice ^
--resume ../output_models/alice-epoch-010.safetensors ^
--epochs 15
```
### 시나리오 2: Overfitting 방지 (LR 감소)
```cmd
# 학습률 낮춰서 Fine-tuning
run-train-single ^
--folder ../dataset/training/01_alice ^
--resume ../output_models/alice-epoch-015.safetensors ^
--epochs 25 ^
--lr 0.00005
```
### 시나리오 3: 데이터 추가 후 재학습
```cmd
# 이미지 20장 → 50장으로 증가
run-train-single ^
--folder ../dataset/training/01_alice_extended ^
--resume ../output_models/alice-epoch-015.safetensors ^
--epochs 10 ^
--repeats 20
```
## 출력 예시
```
======================================================================
🎯 SDXL LoRA Training - Single Mode
======================================================================
📁 Folder: ../dataset/training/01_alice
💾 Output: alice.safetensors
📋 Config: config-24g.json
🖥️ GPU: 0 (24GB VRAM)
⚡ Precision: bf16
🔄 Resume from: ../output_models/alice-epoch-010.safetensors
----------------------------------------------------------------------
📊 Training Parameters
----------------------------------------------------------------------
Images: 25
Repeats: 48 (auto)
Epochs: 20 (manual)
Batch size: 1
Images/epoch: 1200
Steps/epoch: 1200
Total steps: 24000
======================================================================
학습을 시작하시겠습니까? (y/N): y
🔄 Resuming from: ../output_models/alice-epoch-010.safetensors
🚀 Starting training...
```
## 💡 선택 가이드
### State Resume을 써야 할 때
✅ 학습이 중단됨 (컴퓨터 꺼짐, 에러 등)
✅ Epoch 수를 늘리고 싶음 (10 → 20)
✅ 데이터는 그대로, 학습만 더
✅ Optimizer momentum 유지가 중요
## Network Weights를 써야 할 때
✅ 새로운 데이터 추가
✅ 다른 스타일/컨셉 학습
✅ Fine-tuning (특정 부분만 강화)
✅ 기존 모델 기반으로 파생 모델 생성
✅ State 폴더가 없음

582
README.md
View File

@ -1,307 +1,275 @@
# Kohya's GUI
[![GitHub stars](https://img.shields.io/github/stars/bmaltais/kohya_ss?style=social)](https://github.com/bmaltais/kohya_ss/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/bmaltais/kohya_ss?style=social)](https://github.com/bmaltais/kohya_ss/network/members)
[![License](https://img.shields.io/github/license/bmaltais/kohya_ss)](LICENSE.md)
[![GitHub issues](https://img.shields.io/github/issues/bmaltais/kohya_ss)](https://github.com/bmaltais/kohya_ss/issues)
This is a GUI and CLI for training diffusion models.
This project provides a user-friendly Gradio-based Graphical User Interface (GUI) for [Kohya's Stable Diffusion training scripts](https://github.com/kohya-ss/sd-scripts).
Stable Diffusion training empowers users to customize image generation models by fine-tuning existing models, creating unique artistic styles,
and training specialized models like LoRA (Low-Rank Adaptation).
Key features of this GUI include:
* Easy-to-use interface for setting a wide range of training parameters.
* Automatic generation of the command-line interface (CLI) commands required to run the training scripts.
* Support for various training methods, including LoRA, Dreambooth, fine-tuning, and SDXL training.
Support for Linux and macOS is also available. While Linux support is actively maintained through community contributions, macOS compatibility may vary.
## Table of Contents
- [Installation Options](#installation-options)
- [Local Installation Overview](#local-installation-overview)
- [`uv` vs `pip` What's the Difference?](#uv-vs-pip--whats-the-difference)
- [Cloud Installation Overview](#cloud-installation-overview)
- [Colab](#-colab)
- [Runpod, Novita, Docker](#runpod-novita-docker)
- [Custom Path Defaults](#custom-path-defaults)
- [LoRA](#lora)
- [Sample image generation during training](#sample-image-generation-during-training)
- [Troubleshooting](#troubleshooting)
- [Page File Limit](#page-file-limit)
- [No module called tkinter](#no-module-called-tkinter)
- [LORA Training on TESLA V100 - GPU Utilization Issue](#lora-training-on-tesla-v100---gpu-utilization-issue)
- [SDXL training](#sdxl-training)
- [Masked loss](#masked-loss)
- [Guides](#guides)
- [Using Accelerate Lora Tab to Select GPU ID](#using-accelerate-lora-tab-to-select-gpu-id)
- [Starting Accelerate in GUI](#starting-accelerate-in-gui)
- [Running Multiple Instances (linux)](#running-multiple-instances-linux)
- [Monitoring Processes](#monitoring-processes)
- [Interesting Forks](#interesting-forks)
- [Contributing](#contributing)
- [License](#license)
- [Change History](#change-history)
- [v25.0.3](#v2503)
- [v25.0.2](#v2502)
- [v25.0.1](#v2501)
- [v25.0.0](#v2500)
## Installation Options
You can run `kohya_ss` either **locally on your machine** or via **cloud-based solutions** like Colab or Runpod.
- If you have a GPU-equipped PC and want full control: install it locally using `uv` or `pip`.
- If your system doesnt meet requirements or you prefer a browser-based setup: use Colab or a paid GPU provider like Runpod or Novita.
- If you are a developer or DevOps user, Docker is also supported.
---
### Local Installation Overview
You can install `kohya_ss` locally using either the `uv` or `pip` method. Choose one depending on your platform and preferences:
| Platform | Recommended Method | Instructions |
|--------------|----------------|---------------------------------------------|
| Linux | `uv` | [uv_linux.md](./docs/Installation/uv_linux.md) |
| Linux or Mac | `pip` | [pip_linux.md](./docs/Installation/pip_linux.md) |
| Windows | `uv` | [uv_windows.md](./docs/Installation/uv_windows.md) |
| Windows | `pip` | [pip_windows.md](./docs/Installation/pip_windows.md) |
#### `uv` vs `pip` What's the Difference?
- `uv` is faster and isolates dependencies more cleanly, ideal if you want minimal setup hassle.
- `pip` is more traditional, easier to debug if issues arise, and works better with some IDEs or Python tooling.
- If unsure: try `uv`. If it doesn't work for you, fall back to `pip`.
### Cloud Installation Overview
#### 🦒 Colab
For browser-based training without local setup, use this Colab notebook:
<https://github.com/camenduru/kohya_ss-colab>
- No installation required
- Free to use (GPU availability may vary)
- Maintained by **camenduru**, not the original author
| Colab | Info |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ |
| [![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 |
> 💡 If you encounter issues, please report them on camendurus repo.
**Special thanks**
I would like to express my gratitude to camenduru for their valuable contribution.
#### Runpod, Novita, Docker
These options are for users running training on hosted GPU infrastructure or containers.
- **[Runpod setup](docs/runpod_setup.md)** Ready-made GPU background training via templates.
- **[Novita setup](docs/novita_setup.md)** Similar to Runpod, but integrated into the Novita UI.
- **[Docker setup](docs/docker.md)** For developers/sysadmins using containerized environments.
## Custom Path Defaults with `config.toml`
The GUI supports a configuration file named `config.toml` that allows you to set default paths for many of the input fields. This is useful for avoiding repetitive manual selection of directories every time you start the GUI.
**Purpose of `config.toml`:**
* Pre-fill default directory paths for pretrained models, datasets, output folders, LoRA models, etc.
* Streamline your workflow by having the GUI remember your preferred locations.
**How to Use and Customize:**
1. **Create your configuration file:**
* In the root directory of the `kohya_ss` repository, you'll find a file named `config example.toml`.
* Copy this file and rename the copy to `config.toml`. This `config.toml` file will be automatically loaded when the GUI starts.
2. **Edit `config.toml`:**
* Open `config.toml` with a text editor.
* The file uses TOML (Tom's Obvious, Minimal Language) format, which consists of `key = "value"` pairs.
* Modify the paths for the keys according to your local directory structure.
* **Important:**
* Use absolute paths (e.g., `C:/Users/YourName/StableDiffusion/Models` or `/home/yourname/sd-models`).
* Alternatively, you can use paths relative to the `kohya_ss` root directory.
* Ensure you use forward slashes (`/`) for paths, even on Windows, as this is generally more compatible with TOML and Python.
* Make sure the specified directories exist on your system.
**Structure of `config.toml`:**
The `config.toml` file can have several sections, typically corresponding to different training modes or general settings. Common keys you might want to set include:
* `model_dir`: Default directory for loading base Stable Diffusion models.
* `lora_model_dir`: Default directory for saving and loading LoRA models.
* `output_dir`: Default base directory for training outputs (images, logs, model checkpoints).
* `dataset_dir`: A general default if you store all your datasets in one place.
* Specific input paths for different training tabs like Dreambooth, Finetune, LoRA, etc. (e.g., `db_model_dir`, `ft_source_model_name_or_path`).
**Example Configurations:**
Here's an example snippet of what your `config.toml` might look like:
```toml
# General settings
model_dir = "C:/ai_stuff/stable-diffusion-webui/models/Stable-diffusion"
lora_model_dir = "C:/ai_stuff/stable-diffusion-webui/models/Lora"
vae_dir = "C:/ai_stuff/stable-diffusion-webui/models/VAE"
output_dir = "C:/ai_stuff/kohya_ss_outputs"
logging_dir = "C:/ai_stuff/kohya_ss_outputs/logs"
# Dreambooth specific paths
db_model_dir = "C:/ai_stuff/stable-diffusion-webui/models/Stable-diffusion"
db_reg_image_dir = "C:/ai_stuff/datasets/dreambooth_regularization_images"
# Add other db_... paths as needed
# Finetune specific paths
ft_model_dir = "C:/ai_stuff/stable-diffusion-webui/models/Stable-diffusion"
# Add other ft_... paths as needed
# LoRA / LoCon specific paths
lc_model_dir = "C:/ai_stuff/stable-diffusion-webui/models/Stable-diffusion" # Base model for LoRA training
lc_output_dir = "C:/ai_stuff/kohya_ss_outputs/lora"
lc_dataset_dir = "C:/ai_stuff/datasets/my_lora_project"
# Add other lc_... paths as needed
# You can find a comprehensive list of all available keys in the `config example.toml` file.
# Refer to it to customize paths for all supported options in the GUI.
```
**Using a Custom Config File Path:**
If you prefer to name your configuration file differently or store it in another location, you can specify its path using the `--config` command-line argument when launching the GUI:
* On Windows: `gui.bat --config D:/my_configs/kohya_settings.toml`
* On Linux/macOS: `./gui.sh --config /home/user/my_configs/kohya_settings.toml`
By effectively using `config.toml`, you can significantly speed up your training setup process. Always refer to the `config example.toml` for the most up-to-date list of configurable paths.
## LoRA
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.
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).
For more detailed information on LoRA training options and advanced configurations, please refer to our LoRA documentation:
- [LoRA Training Guide](docs/LoRA/top_level.md)
- [LoRA Training Options](docs/LoRA/options.md)
## Sample image generation during training
A prompt file might look like this, for example:
```txt
# prompt 1
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
# prompt 2
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
```
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:
- `--n`: Negative prompt up to the next option.
- `--w`: Specifies the width of the generated image.
- `--h`: Specifies the height of the generated image.
- `--d`: Specifies the seed of the generated image.
- `--l`: Specifies the CFG scale of the generated image.
- `--s`: Specifies the number of steps in the generation.
The prompt weighting such as `( )` and `[ ]` is working.
## Troubleshooting
If you encounter any issues, refer to the troubleshooting steps below.
### Page File Limit
If you encounter an X error related to the page file, you may need to increase the page file size limit in Windows.
### No module called tkinter
If you encounter an error indicating that the module `tkinter` is not found, try reinstalling Python 3.10 on your system.
### LORA Training on TESLA V100 - GPU Utilization Issue
See [Troubleshooting LORA Training on TESLA V100](docs/troubleshooting_tesla_v100.md) for details.
## SDXL training
For detailed guidance on SDXL training, please refer to the [official sd-scripts documentation](https://github.com/kohya-ss/sd-scripts/blob/main/README.md#sdxl-training) and relevant sections in our [LoRA Training Guide](docs/LoRA/top_level.md).
## Masked loss
The masked loss is supported in each training script. To enable the masked loss, specify the `--masked_loss` option.
> [!WARNING]
> The feature is not fully tested, so there may be bugs. If you find any issues, please open an Issue.
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).
## Guides
The following are guides extracted from issues discussions
### Using Accelerate Lora Tab to Select GPU ID
#### Starting Accelerate in GUI
- Open the kohya GUI on your desired port.
- Open the `Accelerate launch` tab
- Ensure the Multi-GPU checkbox is unchecked.
- Set GPU IDs to the desired GPU (like 1).
#### Running Multiple Instances (linux)
- For tracking multiple processes, use separate kohya GUI instances on different ports (e.g., 7860, 7861).
- Start instances using `nohup ./gui.sh --listen 0.0.0.0 --server_port <port> --headless > log.log 2>&1 &`.
#### Monitoring Processes
- Open each GUI in a separate browser tab.
- For terminal access, use SSH and tools like `tmux` or `screen`.
For more details, visit the [GitHub issue](https://github.com/bmaltais/kohya_ss/issues/2577).
## Interesting Forks
To finetune HunyuanDiT models or create LoRAs, visit this [fork](https://github.com/Tencent/HunyuanDiT/tree/main/kohya_ss-hydit)
## Contributing
Contributions are welcome! If you'd like to contribute to this project, please consider the following:
- For bug reports or feature requests, please open an issue on the [GitHub Issues page](https://github.com/bmaltais/kohya_ss/issues).
- If you'd like to submit code changes, please open a pull request. Ensure your changes are well-tested and follow the existing code style.
- For security-related concerns, please refer to our `SECURITY.md` file.
## License
This project is licensed under the Apache License 2.0. See the [LICENSE.md](LICENSE.md) file for details.
## Change History
### v25.0.3
- Upgrade Gradio, diffusers and huggingface-hub to latest release to fix issue with ASGI.
- Add a new method to setup and run the GUI. You will find two new script for both Windows (gui-uv.bat) and Linux (gui-uv.sh). With those scripts there is no need to run setup.bat or setup.sh anymore.
### v25.0.2
- Force gradio to 5.14.0 or greater so it is updated.
### v25.0.1
- Fix issue with requirements version causing huggingface download issues
### v25.0.0
- Major update: Introduced support for flux.1 and sd3, moving the GUI to align with more recent script functionalities.
- Users preferring the pre-flux.1/sd3 version can check out tag `v24.1.7`.
```shell
git checkout v24.1.7
```
- For details on new flux.1 and sd3 parameters, refer to the [sd-scripts README](https://github.com/kohya-ss/sd-scripts/blob/sd3/README.md).
NVIDIA Studio Driver(SDR) : Windows 10/11 → 531.79 / 536.67 등 :
아래서 기종 선택하고 Studio Driver 선택하고 검색 버튼
https://www.nvidia.com/ko-kr/geforce/drivers/
제일 낮은 버전이 아마 괜찮을 듯 함.
## 1. 호환 버전
CUDA 12.4 : https://developer.nvidia.com/cuda-12-4-0-download-archive
CcuDNN v9.5.0 : https://developer.nvidia.com/cudnn-9-5-0-download-archive
## 2. CuDNN 설치
cuDNN (예) C:\Program Files\NVIDIA\CUDNN\v9.5\bin 폴더 안에는 Cuda Major 버전에 대응되는 라이브러리들이 있습니다.
해당폴더 하위의 파일들을 CUDA Toolkit이 설치된 경로 내의 해당 폴더에 복사합니다.
예시:
C:\Program Files\NVIDIA\CUDNN\v9.5\bin\12.6 아래의 모든 dll 파일을
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\bin으로 복사합니다.
[README.md](../sdxl_train_captioner_runtime/README.md)
## 3. SDXL 모델 다운로드
- 도커 컨테이너가 실행될 때 models 하위에 StableDiffusion XL 1.0 모델이 다운로드 됩니다.
- 만약에 해당 URL 지원이 종료 된 경우, 허깅페이지 또는 CIVITAI에서 다운로드 하세요.
- 현재 사용가능한 다운로드 주소는 아래와 같습니다.
- https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors
## 학습방법 1: 폴더명 규칙 사용 (자동)
./train.sh config.json 0
# 방법 2: 강제로 15번 반복
./train.sh config.json 0 15
# 방법 3: 강제로 20번 반복
./train.sh config.json 0 20
3가지 요소 비교
1⃣ 폴더 식별자 (예: 15_alice)
목적: Kohya 학습 시스템이 이미지를 분류하고 관리하는 용도
training/
├── 15_alice/ ← "alice"는 내부 식별용
│ ├── img1.jpg
│ └── img1.txt
└── 10_background/ ← "background"는 내부 식별용
├── bg1.jpg
└── bg1.txt
특징:
학습 시 로그에만 표시됨
LoRA 모델이나 trigger word와 무관
단순히 폴더 구분용
2⃣ --output_name (예: karina)
목적: 저장되는 LoRA 파일명
3⃣ LoRA 태그명
- 학습에 사용되는 캡션 tag + 문장에서 가장 많이 발견되는 Unique Word가 태그명이 됩니다.
- 일반적으로 캡션의 제일 앞에 배치하고 그 뒤에 콤마를 찍고 나머지를 서술합니다.
이 저장소에는 Stable Diffusion용 훈련, 생성 및 유틸리티 스크립트가 포함되어 있습니다.
변경 내역은 페이지 하단으로 이동했습니다.
최신 업데이트: 2025-03-21 (버전 0.9.1)
일본어판 README는 여기
개발 버전은 dev 브랜치에 있습니다. 최신 변경 사항은 dev 브랜치를 확인해 주세요.
FLUX.1 및 SD3/SD3.5 지원은 sd3 브랜치에서 이루어집니다. 해당 모델을 훈련하려면 sd3 브랜치를 사용해 주세요.
더 쉬운 사용법(GUI 및 PowerShell 스크립트 등)을 원하시면 bmaltais가 관리하는 저장소를 방문해 주세요. @bmaltais 님께 감사드립니다!
이 저장소에는 다음 스크립트가 포함되어 있습니다:
- DreamBooth 훈련 (U-Net 및 텍스트 인코더 포함)
- 미세 조정 (네이티브 훈련) (U-Net 및 텍스트 인코더 포함)
- LoRA 훈련
- 텍스트 역전 훈련
- 이미지 생성
- 모델 변환 (1.x 및 2.x, Stable Diffusion ckpt/safetensors 및 Diffusers 지원)
## requirements.txt 파일 안내
이 파일에는 PyTorch 요구 사항이 포함되어 있지 않습니다. PyTorch 버전은 환경에 따라 달라지므로 별도로 관리됩니다. 먼저 환경에 맞는 PyTorch를 설치해 주세요. 설치 방법은 아래를 참고하세요.
스크립트는 PyTorch 2.1.2로 테스트되었습니다. PyTorch 2.2 이상도 작동합니다. 적절한 버전의 PyTorch와 xformers를 설치해 주세요.
## 사용법 문서 링크
대부분의 문서는 일본어로 작성되었습니다.
[darkstorm2150님의 영어 번역본은 여기](https://github.com/darkstorm2150/sd-scripts#links-to-usage-documentation)에서 확인하실 수 있습니다. darkstorm2150님께 감사드립니다!
* [훈련 가이드 - 공통](sd-scripts/docs/train_README-ja.md) : 데이터 준비, 옵션 등...
* [중국어 버전](sd-scripts/docs/train_README-zh.md)
* [SDXL 훈련](sd-scripts/docs/train_SDXL-en.md) (영어 버전)
* [데이터셋 구성](sd-scripts/docs/config_README-ja.md)
* [영어 버전](sd-scripts/docs/config_README-en.md)
* [DreamBooth 훈련 가이드](sd-scripts/docs/train_db_README-ja.md)
* [단계별 미세 조정 가이드](sd-scripts/docs/fine_tune_README_ja.md):
* [LoRA 훈련](sd-scripts/docs/train_network_README-ja.md)
* [텍스트 역전 훈련](sd-scripts/docs/train_ti_README-ja.md)
* [이미지 생성](sd-scripts/docs/gen_img_README-ja.md)
* note.com [모델 변환](https://note.com/kohya_ss/n/n374f316fe4ad)
## Windows Required Dependencies
## Windows 필수 종속성
Python 3.10.6 및 Git:
- Python 3.10.6: https://www.python.org/ftp/python/3.10.6/python-3.10.6-amd64.exe
- git: https://git-scm.com/download/win
Python 3.10.x, 3.11.x, 3.12.x도 작동하지만 테스트되지 않았습니다.
venv가 작동하도록 PowerShell에 제한 없는 스크립트 실행 권한 부여:
- 관리자 권한 PowerShell 창 열기
- `Set-ExecutionPolicy Unrestricted` 입력 후 A 선택
- 관리자 권한 PowerShell 창 닫기
## Windows 설치
일반 PowerShell 터미널을 열고 다음 명령어를 입력하세요:
```powershell
git clone https://github.com/kohya-ss/sd-scripts.git
cd sd-scripts
python -m venv venv
.\venv\Scripts\activate
pip install torch==2.1.2 torchvision==0.16.2 --index-url https://download.pytorch.org/whl/cu118
pip install --upgrade -r requirements.txt
pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu118
accelerate config
```
`python -m venv` 명령어 실행 시 `python`만 표시된다면, `python``py`로 변경하십시오.
참고: 현재 `bitsandbytes==0.44.0`, `prodigyopt==1.0``lion-pytorch==0.0.6`이 requirements.txt에 포함되어 있습니다. 다른 버전을 사용하려면 수동으로 설치하십시오.
이 설치는 CUDA 11.8용입니다. 다른 버전의 CUDA를 사용하는 경우, 해당 버전의 PyTorch와 xformers를 설치하십시오. 예를 들어, CUDA 12를 사용하는 경우 `pip install torch==2.1.2 torchvision==0.16.2 --index-url https://download.pytorch.org/whl/cu121``pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu121`를 실행하십시오.
PyTorch 2.2 이상을 사용하는 경우 `torch==2.1.2`, `torchvision==0.16.2`, `xformers==0.0.23.post1`을 적절한 버전으로 변경하십시오.
<!--
cp .\bitsandbytes_windows\*.dll .\venv\Lib\site-packages\bitsandbytes\
cp .\bitsandbytes_windows\cextension.py .\venv\Lib\site-packages\bitsandbytes\cextension.py
cp .\bitsandbytes_windows\main.py .\venv\Lib\site-packages\bitsandbytes\cuda_setup\main.py
-->
accelerate config에 대한 답변:
```txt
- This machine
- No distributed training
- NO
- NO
- NO
- all
- fp16
```
bf16을 사용하려면 마지막 질문에 `bf16`이라고 답변해 주세요.
참고: 일부 사용자가 훈련 중 ``ValueError: fp16 혼합 정밀도는 GPU가 필요합니다`` 오류가 발생한다고 보고했습니다. 이 경우, 여섯 번째 질문에 `0`을 입력하세요:
``이 머신에서 훈련에 사용할 GPU(ID 기준)를 쉼표로 구분된 목록으로 입력하세요? [all]:``
(ID `0`의 단일 GPU가 사용됩니다.)
## 업그레이드
새 버전이 출시되면 다음 명령어로 저장소를 업그레이드할 수 있습니다:
```powershell
cd sd-scripts
git pull
.\venv\Scripts\activate
pip install --use-pep517 --upgrade -r requirements.txt
```
명령어가 성공적으로 완료되면 새 버전을 사용할 준비가 된 것입니다.
### PyTorch 업그레이드
PyTorch를 업그레이드하려면 [Windows 설치](#windows-installation) 섹션의 `pip install` 명령어로 업그레이드할 수 있습니다. PyTorch를 업그레이드할 때 `xformers`도 함께 업그레이드해야 합니다.
## 크레딧
LoRA 구현은 [cloneofsimo의 저장소](https://github.com/cloneofsimo/lora)를 기반으로 합니다. 훌륭한 작업에 감사드립니다!
Conv2d 3x3에 대한 LoRA 확장은 cloneofsimo에 의해 처음 공개되었으며, 그 효과는 KohakuBlueleaf에 의해 [LoCon](https://github.com/KohakuBlueleaf/LoCon)에서 입증되었습니다. KohakuBlueleaf님께 진심으로 감사드립니다!
## 라이선스
대부분의 스크립트는 ASL 2.0 라이선스 하에 배포됩니다(Diffusers, cloneofsimo 및 LoCon의 코드 포함). 다만 프로젝트의 일부 구성 요소는 별도의 라이선스 조건이 적용됩니다:
[Memory Efficient Attention Pytorch](https://github.com/lucidrains/memory-efficient-attention-pytorch): MIT
[bitsandbytes](https://github.com/TimDettmers/bitsandbytes): MIT
[BLIP](https://github.com/salesforce/BLIP): BSD-3-Clause
## Change History
### Mar 21, 2025 / 2025-03-21 Version 0.9.1
- Fixed a bug where some of LoRA modules for CLIP Text Encoder were not trained. Thank you Nekotekina for PR [#1964](https://github.com/kohya-ss/sd-scripts/pull/1964)
- The LoRA modules for CLIP Text Encoder are now 264 modules, which is the same as before. Only 88 modules were trained in the previous version.
### Jan 17, 2025 / 2025-01-17 Version 0.9.0
- __important__ The dependent libraries are updated. Please see [Upgrade](#upgrade) and update the libraries.
- bitsandbytes, transformers, accelerate and huggingface_hub are updated.
- If you encounter any issues, please report them.
- The dev branch is merged into main. The documentation is delayed, and I apologize for that. I will gradually improve it.
- The state just before the merge is released as Version 0.8.8, so please use it if you encounter any issues.
- The following changes are included.
#### 변경 사항
## 추가 정보
### LoRA 명명 규칙
`train_network.py`에서 지원하는 LoRA의 명칭을 혼동을 피하기 위해 변경하였습니다. 관련 문서도 업데이트되었습니다. 본 저장소에서 사용하는 LoRA 유형의 명칭은 다음과 같습니다.
1. __LoRA-LierLa__ : (LoRA for __Li__ n __e__ a __r__ __La__ yers)
LoRA for Linear layers and Conv2d layers with 1x1 kernel
2. __LoRA-C3Lier__ : (LoRA for __C__ olutional layers with __3__ x3 Kernel and __Li__ n __e__ a __r__ layers)
In addition to 1., LoRA for Conv2d layers with 3x3 kernel
LoRA-LierLa는 `train_network.py`의 기본 LoRA 유형입니다(네트워크 인자 `conv_dim` 제외).
<!--
LoRA-LierLa can be used with [our extension](https://github.com/kohya-ss/sd-webui-additional-networks) for AUTOMATIC1111's Web UI, or with the built-in LoRA feature of the Web UI.
To use LoRA-C3Lier with Web UI, please use our extension.
-->
### 훈련 중 샘플 이미지 생성
예를 들어 프롬프트 파일은 다음과 같을 수 있습니다
```
# prompt 1
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
# prompt 2
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
```
`#`로 시작하는 줄은 주석입니다. 프롬프트 뒤에 `--n`과 같은 옵션을 사용하여 생성된 이미지의 옵션을 지정할 수 있습니다. 다음을 사용할 수 있습니다.
* `--n` 다음 옵션까지 프롬프트를 음수로 지정합니다.
* `--w` 생성된 이미지의 너비를 지정합니다.
* `--h` 생성된 이미지의 높이를 지정합니다.
* `--d` 생성된 이미지의 시드(seed)를 지정합니다.
* `--l` 생성된 이미지의 CFG 스케일을 지정합니다.
* `--s` 생성 과정의 단계 수를 지정합니다.
`( )``[ ]`와 같은 프롬프트 가중치 기능이 작동합니다.

View File

@ -1,14 +0,0 @@
# Security Policy
## Supported Versions
Versions that are currently being supported with security updates.
| Version | Supported |
| ------- | ------------------ |
| 23.2.x | :white_check_mark: |
| < 23.1.x | :x: |
## Reporting a Vulnerability
Please open an issue if you discover a security issue.

82
TRAINING.md Normal file
View File

@ -0,0 +1,82 @@
🎨 폴더 명명 예시:
```cmd
01_alice_woman (3단어와 언더스코어 2개: 클래스 포함)
- name=alice, class=woman -> --class_tokens=woman 적용.
02_style (2단어와 언더스코어 1개: 클래스 미포함)
- name=style, class=None -> --class_tokens 미적용.
```
🎨 클래스 키워드 선정 기준 및 분류 예시
#### 클래스 키워드를 선정할 때는 **"이 대상이 없었을 때, 모델이 원래 무엇을 생성해야 하는가?"**를 생각하면 쉽습니다.
### 1. 인물/캐릭터 학습 시
사람이나 캐릭터를 학습시킬 때는 성별, 연령대, 종족 등 가장 넓은 카테고리를 사용합니다.
| 학습 대상 (ID 토큰) | 클래스 키워드 | 설명 |
|---------------------|---------------------------|-------|
| 특정 인물 (alice) | woman 또는 man | 성별을 나타내는 가장 일반적인 단어. |
| 특정 어린이 (child_A) | child 또는 kid | 연령대를 나타내는 일반적인 단어. |
| 특정 동물 캐릭터 (pet_dragon) | dragon 또는 monster | 해당 대상의 종족 또는 종류. |
| 만화체 캐릭터 (manga_hero) | person 또는 character | 스타일이 강한 경우 일반적인 '사람'이나 '캐릭터'로 정의. |
### 2. 스타일/화풍 학습 시
스타일을 학습시킬 때는 그 스타일이 적용될 가장 일반적인 대상을 클래스로 지정합니다.
| 학습 대상 (ID 토큰) | 클래스 키워드 | 설명 |
|---------------------|---------------------------|--------|
| 특정 작가 화풍 (artstyle_A) | style 또는 art | '스타일' 자체를 클래스로 지정하는 것이 일반적입니다. |
| 특정 조명 효과 (cinema_light) | lighting 또는 effect | 모델이 **'조명'**의 개념을 잃지 않도록 합니다. |
| 특정 의상 (maid_dress_v2) | clothing 또는 dress | 의류의 일반적인 카테고리. |
### 3. 사물/배경 학습 시
특정 사물이나 배경을 학습시킬 때는 그 사물의 가장 넓은 범주를 사용합니다.
| 학습 대상 (ID 토큰) | 클래스 키워드 | 설명 |
|---------------------|---------------------------|--------|
| 특정 자동차 모델 (car_v1) | car 또는 vehicle | 해당 사물의 일반적인 명칭. |
| 특정 건물 (my_house) | house 또는 building | 해당 배경의 일반적인 명칭. |
| 특정 음식 (korean_dish) | food 또는 dish | 해당 카테고리의 일반적인 명칭. |
### 🛑 클래스 키워드를 넣는 경우 (정규화의 중요성)
클래스 키워드를 01_alice_woman처럼 넣는다는 것은 다음과 같은 의미가 있습니다.
ID 토큰 정의: alice는 **woman**이다.
정규화 활성화: Kohya_SS에게 **woman**이라는 클래스에 대한 **정규화 이미지(Regularization Images)**를 찾아서 함께 학습하라고 지시합니다.
정규화 이미지가 없다면 클래스 키워드를 넣어도 효과가 없거나 미미합니다. 따라서 클래스 키워드를 정했다면, 해당 키워드(예: woman)로 생성된 수백~수천 장의 이미지를 정규화 폴더 (일반적으로 reg_woman 등)에 넣어 함께 학습해야 가장 좋은 품질을 얻을 수 있습니다.
### 🎯 SDXL Base 모델 학습 시 정규화 이미지의 역할
#### SDXL Base 1.0 모델을 기반으로 학습할 때, woman과 같은 일반적인 클래스 이미지(정규화 이미지)를 추가로 넣어줄 필요는 없습니다.
### 1. SDXL의 강점: 이미 "알고 있음"
- SDXL Base 1.0은 수많은 이미지로 학습된 **대규모 모델(Foundation Model)**입니다.
- 이미 **woman (여성), car (자동차), house (집)**과 같은 일반적인 개념과 해당 개념의 다양한 형태를 매우 잘 이해하고 표현할 수 있습니다.
- LoRA 학습의 목표는 SDXL이 이미 알고 있는 **일반적인 지식(클래스 지식)**을 잊어버리지 않게 하면서, **새로운 고유 개념(ID 토큰)**만 추가로 학습시키는 것입니다.
### 2. 정규화 이미지의 필요성
- 일반 LoRA/Dreambooth 학습: SD 1.5 같은 구형 모델이나 미세 조정되지 않은 모델로 학습할 때는 정규화 이미지가 필수였습니다. 이는 모델이 일반적인 개념을 잊어버리는 **재앙적 망각(Catastrophic Forgetting)**을 방지하기 위함이었습니다.
- SDXL LoRA 학습: SDXL은 기본적으로 이 지식을 매우 잘 보존합니다. 따라서 **woman**이라는 클래스에 대해 수백, 수천 장의 정규화 이미지를 직접 수집하고 넣어주는 노동은 대부분의 경우 불필요합니다.
### 3. Kohya_SS 설정 (SDXL에 특화된 방식)
- Kohya_SS를 포함한 최신 학습 툴들은 SDXL 학습 시 정규화 이미지 폴더를 비워두거나, 아예 지정하지 않는 방식을 지원합니다.
- 이 방식은 SDXL이 이미 방대한 내부 지식을 가지고 있기 때문에, 따로 외부 이미지를 가져와 정규화하지 않아도 충분히 안정적인 결과를 얻을 수 있다는 전제에 기반합니다.
### ⚠️ 예외적인 경우: 정규화가 필요한 경우
- 대부분의 경우 woman에 대한 정규화는 불필요하지만, 매우 특수한 형태의 클래스를 학습시킬 때는 고려해 볼 수 있습니다.
| 경우 | 예시 | 설명 |
|---------------------|---------------------------|--------|
| 강력한 스타일 학습 | artstyle_A (극도로 만화적인 스타일) | "스타일 자체가 SDXL이 '인간'으로 인식하는 방식을 크게 왜곡할 때, 일반적인 woman 이미지를 정규화하여 모델의 지식을 보호할 수 있습니다." |
| 특정 자세/배경에 과적합 우려 | 특정 포즈만 있는 pose_v1 |"pose 클래스에 대해 다양한 일반 포즈 이미지를 정규화하여, 모델이 모든 사람의 포즈를 해당 포즈로 고정시키지 않도록 방지합니다." |
#### - 일반적으로 사람이나 평범한 사물을 학습할 때는 클래스 명만 지정(01_alice_woman)하고 정규화 이미지는 넣지 않는 것이 시간과 자원(디스크 공간)을 아끼는 가장 효율적인 방법입니다.

View File

@ -0,0 +1,2 @@
python -c "import torch; print(torch.__version__)"
python -c "import transformers; print(transformers.__version__)"

3
docker-build.cmd Normal file
View File

@ -0,0 +1,3 @@
docker build --no-cache -t aicompanion/sdxl_train_captioner:1.0.4 .
docker tag aicompanion/sdxl_train_captioner:1.0.4 aicompanion/sdxl_train_captioner:latest

View File

@ -1,59 +0,0 @@
services:
kohya-ss-gui:
container_name: kohya-ss-gui
image: ghcr.io/bmaltais/kohya-ss-gui:latest
user: 1000:0
build:
context: .
args:
- UID=1000
cache_from:
- ghcr.io/bmaltais/kohya-ss-gui:cache
cache_to:
- type=inline
ports:
- 7860:7860
environment:
SAFETENSORS_FAST_GPU: 1
TENSORBOARD_PORT: ${TENSORBOARD_PORT:-6006}
tmpfs:
- /tmp
volumes:
- /tmp/.X11-unix:/tmp/.X11-unix
- ./models:/app/models
- ./dataset:/dataset
- ./dataset/images:/app/data
- ./dataset/logs:/app/logs
- ./dataset/outputs:/app/outputs
- ./dataset/regularization:/app/regularization
- ./models:/app/models
- ./.cache/config:/app/config
- ./.cache/user:/home/1000/.cache
- ./.cache/triton:/home/1000/.triton
- ./.cache/nv:/home/1000/.nv
- ./.cache/keras:/home/1000/.keras
- ./.cache/config:/home/1000/.config # For backward compatibility
deploy:
resources:
reservations:
devices:
- driver: nvidia
capabilities: [gpu]
device_ids: ["all"]
tensorboard:
container_name: tensorboard
image: tensorflow/tensorflow:latest-gpu
ports:
# !Please change the port in .env file
- ${TENSORBOARD_PORT:-6006}:6006
volumes:
- ./dataset/logs:/app/logs
command: tensorboard --logdir=/app/logs --bind_all
deploy:
resources:
reservations:
devices:
- driver: nvidia
capabilities: [gpu]
device_ids: ["all"]

49
docker-compose.yml Normal file
View File

@ -0,0 +1,49 @@
services:
sdxl_train_captioner:
build:
context: .
dockerfile: Dockerfile
image: aicompanion/sdxl_train_captioner:latest
container_name: sdxl_train_captioner
runtime: nvidia
# GPU 설정
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
# 볼륨 마운트 (호스트 ↔ 컨테이너)
volumes:
- ./models:/app/sdxl_train_captioner/models
- ./dataset:/app/sdxl_train_captioner/dataset
- ./output_models:/app/sdxl_train_captioner/output_models
- ./logs:/app/sdxl_train_captioner/logs
ports:
- "6006:6006"
environment:
# GPU 선택 (필요 시 GPU ID 지정)
- NVIDIA_VISIBLE_DEVICES=all
- CUDA_VISIBLE_DEVICES=0
- HF_HOME=/app/sdxl_train_captioner/models
- HF_HUB_CACHE=/app/sdxl_train_captioner/models
- PYTHONUNBUFFERED=1
- TZ=Asia/Seoul
- OMP_NUM_THREADS=8
- MKL_NUM_THREADS=8
- TMPDIR=/dev/shm
stdin_open: true
tty: true
restart: unless-stopped
shm_size: "16gb"
working_dir: /app/sdxl_train_captioner/sd-scripts
# GPU 자동 탐색, 기본 0번 GPU
# command: ["python", "cap-watcher.py"] # "--device", "3", "--overwrite"

3
docker-down.cmd Normal file
View File

@ -0,0 +1,3 @@
docker-compose down --volumes --remove-orphans sdxl_train_captioner
pause

3
docker-pull.cmd Normal file
View File

@ -0,0 +1,3 @@
docker pull aicompanion/sdxl_train_captioner:latest
pause

1
docker-push.cmd Normal file
View File

@ -0,0 +1 @@
docker push aicompanion/sdxl_train_captioner:latest

3
docker-start.cmd Normal file
View File

@ -0,0 +1,3 @@
docker-compose start sdxl_train_captioner
pause

3
docker-stop.cmd Normal file
View File

@ -0,0 +1,3 @@
docker-compose stop sdxl_train_captioner
pause

3
docker-up.cmd Normal file
View File

@ -0,0 +1,3 @@
docker-compose up -d
pause

180
epoch와-steps설정.md Normal file
View File

@ -0,0 +1,180 @@
Max train epoch
training epochs (overrides max_train_steps). 0 = no override
```
### **해석:**
- **"Max train epoch"**: 최대 학습 에포크 수
- **"overrides max_train_steps"**: 이 값을 설정하면 max_train_steps를 **무시함**
- **"0 = no override"**: `0`으로 설정하면 max_train_steps를 **따름**
---
## 🎯 사용 방법
### **케이스 1: Epoch 기준으로 학습** ⭐ 일반적
```
Max train epoch: 10
Max train steps: 0 (또는 비워둠)
```
**결과:** 10 에포크 학습
---
### **케이스 2: Steps 기준으로 학습**
```
Max train epoch: 0
Max train steps: 2000
```
**결과:** 2000 스텝 학습
---
### **케이스 3: 둘 다 설정 (Epoch 우선!)**
```
Max train epoch: 10
Max train steps: 5000
```
**결과:** 10 에포크만 학습 (max_train_steps **무시됨**)
---
## 🔍 우선순위 정리
```
Max train epoch > 0 → 이것만 사용 (steps 무시)
Max train epoch = 0 → max_train_steps 사용
```
---
## 💡 실전 설정
### **일반적인 LoRA 학습:**
```
Max train epoch: 10 ← 여기만 설정
Max train steps: 0 ← 0 또는 비워둠
Save every N epochs: 1
```
### **정밀한 스텝 컨트롤이 필요할 때:**
```
Max train epoch: 0 ← 0으로 설정
Max train steps: 2500 ← 여기 설정
Save every N steps: 500
```
---
## 📊 예시 계산
### **50장, 4회 반복 기준:**
#### **설정 A: Epoch 우선**
```
Max train epoch: 10
Max train steps: 999999 ← 아무리 커도 무시됨
```
**실제 학습:** 50 × 4 × 10 = **2000 스텝**
#### **설정 B: Steps 우선**
```
Max train epoch: 0
Max train steps: 1500
```
**실제 학습:** **1500 스텝** (7.5 에포크)
---
## ⚠️ 흔한 실수
### ❌ **틀린 설정:**
```
Max train epoch: 10
Max train steps: 2000
```
→ Steps 값이 **무시됨!** (Epoch만 적용)
### ✅ **올바른 설정:**
**Epoch 쓰고 싶으면:**
```
Max train epoch: 10
Max train steps: 0
```
**Steps 쓰고 싶으면:**
```
Max train epoch: 0
Max train steps: 2000
```
---
## 🎯 **최종 답변**
### **같은 값 넣으면 되나요?**
**아니요!**
### **어떻게 설정해야 하나요?**
#### **대부분의 경우 (권장):**
```
Max train epoch: 10 ← 원하는 에포크 수
Max train steps: 0 ← 0으로!
```
#### **스텝 수를 정확히 지정하고 싶으면:**
```
Max train epoch: 0 ← 0으로!
Max train steps: 2500 ← 원하는 스텝 수
----------------
총 스텝 = 이미지 수 × 반복 횟수 × 에포크 수
3000 = 100 × 2 × 에포크
3000 = 200 × 에포크
에포크 = 3000 ÷ 200
에포크 = 15
```
---
## ✅ 답: **15 에포크**
### **설정:**
```
폴더명: 2_character_name
이미지: 100장
Max train epoch: 15
Max train steps: 0
```
### **결과:**
```
1 에포크 = 100 × 2 = 200 스텝
15 에포크 = 200 × 15 = 3000 스텝 ✅
✅ 고정 Seed (추천!)
시드: Seed: 42 (또는 1234, 777 등 아무 숫자)
**이유:**
### ✅ **고정 Seed (추천!)**
```
Seed: 42
```
**장점:**
- **재현성** - 똑같은 결과 재생산 가능
- **실험 비교** - 다른 하이퍼파라미터 테스트 시 공정한 비교
- **디버깅** - 문제 발생 시 재현 가능
- **협업** - 다른 사람도 같은 결과 얻을 수 있음
**사용 케이스:**
- 대부분의 경우 ✅
- 하이퍼파라미터 튜닝
- 안정적인 학습 원함
---

37
requirements-org-bak.txt Normal file
View File

@ -0,0 +1,37 @@
accelerate>=1.7.0
aiofiles==23.2.1
altair==4.2.2
dadaptation==3.2
diffusers[torch]==0.32.2
easygui==0.98.3
einops==0.7.0
fairscale==0.4.13
ftfy==6.1.1
gradio>=5.34.1
huggingface-hub==0.29.3
imagesize==1.4.1
invisible-watermark==0.2.0
lion-pytorch==0.0.6
lycoris_lora==3.2.0.post2
omegaconf==2.3.0
prodigyopt==1.1.2
protobuf==3.20.3
open-clip-torch==2.20.0
opencv-python==4.10.0.84
prodigy-plus-schedule-free==1.8.0
pytorch-lightning==1.9.0
pytorch-optimizer==3.5.0
rich>=13.7.1
safetensors==0.4.4
schedulefree==1.4
scipy==1.11.4
# for T5XXL tokenizer (SD3/FLUX)
sentencepiece==0.2.0
timm==1.0.15
tk==0.1.0
toml==0.10.2
transformers==4.44.2
voluptuous==0.13.1
wandb==0.18.0
# for kohya_ss sd-scripts library
-e ./sd-scripts

View File

@ -1,38 +1,53 @@
accelerate>=1.7.0
aiofiles==23.2.1
altair==4.2.2
dadaptation==3.2
diffusers[torch]==0.32.2
easygui==0.98.3
einops==0.7.0
fairscale==0.4.13
# Core packages
torch==2.7.1+cu128 --index-url https://download.pytorch.org/whl/cu128
torchvision==0.22.1+cu128 --index-url https://download.pytorch.org/whl/cu128
torchaudio==2.7.1 --index-url https://download.pytorch.org/whl/cu128
accelerate==0.34.2
transformers==4.45.2 # ✅ 업데이트
diffusers[torch]==0.34.0 # ✅ 업데이트
ftfy==6.1.1
gradio>=5.34.1
huggingface-hub==0.29.3
imagesize==1.4.1
invisible-watermark==0.2.0
einops==0.7.0
# pytorch-lightning==1.9.0 # ❌ 제거! (범인)
lightning==2.5.5 # ✅ 최신 버전
lion-pytorch==0.0.6
lycoris_lora==3.2.0.post2
omegaconf==2.3.0
onnx==1.16.1
prodigyopt==1.1.2
protobuf==3.20.3
open-clip-torch==2.20.0
opencv-python==4.10.0.84
prodigy-plus-schedule-free==1.8.0
pytorch-lightning==1.9.0
pytorch-optimizer==3.5.0
rich>=13.7.1
safetensors==0.4.4
schedulefree==1.4
scipy==1.11.4
# for T5XXL tokenizer (SD3/FLUX)
sentencepiece==0.2.0
timm==1.0.15
tk==0.1.0
pytorch-optimizer==3.5.0
prodigy-plus-schedule-free==1.9.0
prodigyopt==1.1.2
tensorboard
safetensors==0.4.5 # ✅ 업데이트
altair==4.2.2
easygui==0.98.3
toml==0.10.2
transformers==4.44.2
voluptuous==0.13.1
wandb==0.18.0
# for kohya_ss sd-scripts library
-e ./sd-scripts
huggingface-hub>=0.27.0 # ✅ 업데이트
bitsandbytes>=0.45.0
imagesize==1.4.1
numpy==1.26.4 # ✅ 구체적 버전
requests==2.31.0 # ✅ 업데이트
timm==1.0.21 # ✅ 업데이트 (2번째 범인)
fairscale==0.4.13 # ✅ 업데이트 (3번째 범인)
opencv-python==4.7.0.72
opencv-python-headless==4.7.0.72
numpy==1.26.4
# WD14 captioning
onnx==1.16.0 # ✅ 업데이트
onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/
# BLIP captioning
# blip==0.1.0 # ❌ 주석처리 (구버전, 문제 가능)
Pillow>=10.0.0 # ✅ BLIP 대신 필요하면
# NLP utils
nltk==3.9.2
sentencepiece==0.2.0
# OpenCLIP for SDXL
open-clip-torch==2.26.1 # ✅ 업데이트
# Logging
rich==13.9.4 # ✅ 업데이트
# Kohya_ss library
triton==3.3.1

1
resume-train-example.cmd Normal file
View File

@ -0,0 +1 @@
run-train-single --resume ../output_models/01_alic3_woman-000009.safetensors --epochs 17 --folder ../dataset/training/mainchar/01_alic3_woman

3
run-tensorboard.cmd Normal file
View File

@ -0,0 +1,3 @@
docker exec -it sdxl_train_captioner bash -c "/app/sdxl_train_captioner/sd-scripts/run-tensorboard.sh 1"
pause

1
run-train-auto.cmd Normal file
View File

@ -0,0 +1 @@
docker exec -it sdxl_train_captioner bash -c "/app/sdxl_train_captioner/sd-scripts/run-train-auto.sh 1"

4
run-train-single.cmd Normal file
View File

@ -0,0 +1,4 @@
@echo off
REM 단순히 CMD에서 인자 전달만
docker exec -it sdxl_train_captioner bash -c "/app/sdxl_train_captioner/sd-scripts/run-train-single.sh %*"
pause

@ -1 +1 @@
Subproject commit 3e6935a07edcb944407840ef74fcaf6fcad352f7
Subproject commit 7443d0806a05bea1c7fbcadddaa4cd8595703bb7

1
tail-logs.cmd Normal file
View File

@ -0,0 +1 @@
docker logs -f sdxl_train_captioner

190
로컬-설치가이드.md Normal file
View File

@ -0,0 +1,190 @@
CUDA 12.4
CUDNN 9.1.0
# 1. 클론
git clone https://github.com/kohya-ss/sd-scripts.git
cd sd-scripts
# 2. 가상환경 생성
python -m venv venv
.\venv\Scripts\activate # Windows
# 또는
source venv/bin/activate # Linux/Mac
# 3. PyTorch 설치 (CUDA 11.8 기준)
pip install torch==2.1.2 torchvision==0.16.2 --index-url https://download.pytorch.org/whl/cu118
# 4. 의존성 설치
pip install --upgrade -r requirements.txt
pip install xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu118
# 5. Accelerate 설정
accelerate config
질문에 답변:
컴퓨팅 환경: This machine
머신 타입: No distributed training
CPU only?: NO
torch dynamo?: NO
DeepSpeed?: NO
GPU ids: all (또는 0)
Mixed precision: 8GB VRAM의 경우 fp16, 12GB 이상의 경우 bf16
SDXL(Stable Diffusion XL) 모델 아키텍처는 여러 개의 대용량 파일로 구성되며 두 가지 주요 구성 요소는 기본 모델과 선택적 정제 모델입니다..safetensors. 모델 파일 크기는 사용된 파일 형식(예: 또는 .ckpt) 에 따라 달라질 수 있습니다 .
공식 SDXL 1.0 파일
공식 SDXL 1.0 릴리스의 일반적인 파일 크기는 다음과 같습니다.
기본 모델: 약 6.94GB. 이 모델은 텍스트 프롬프트에서 초기 이미지를 생성하는 데 사용됩니다.
리파이너 모델: 약 6.08GB. 리파이너는 기본 모델에서 생성된 이미지에 세부적인 정보를 추가하고 품질을 개선하는 두 번째 단계로 사용됩니다.
전체 파이프라인의 총 크기: 기본 모델과 정제 모델의 결합된 크기는 약 13GB이지만, 많은 사용자는 이제 더 빠른 워크플로를 위해 기본 모델을 주로 사용합니다.
3. 이미지 크기 조정 및 버킷화
최적 해상도: 훈련하려는 기본 모델에 따라 권장 해상도가 다릅니다.
Stable Diffusion 1.5: 512x512, 512x768, 768x512 등
SDXL: 1024x1024
버킷화 (Bucketing): Kohya_ss는 여러 다른 해상도의 이미지를 효율적으로 처리하는 '버킷' 기능을 제공합니다.
GUI에서 사전 처리 탭 선택: Kohya GUI의 Utilities 탭에서 Prepare training data를 선택합니다.
폴더 설정: Source directory에 원본 이미지 폴더를, Destination directory에 처리된 이미지를 저장할 폴더를 지정합니다.
최소/최대 해상도 설정: Min resolution과 Max resolution을 설정하고, Use buckets를 활성화합니다.
자동 크기 조정: Process images를 실행하면 이미지가 지정된 버킷 해상도에 맞게 자동으로 리사이즈되고 크롭됩니다.
💡 추가 팁
최대 3000 스텝 또는 30 에포크 권장 GitHub
50장의 학습 이미지와 4회 반복 권장 GitHub
VRAM별 배치 크기:
8GB: batch_size 1-2 GitHub
12GB: batch_size 2-3 GitHub
더 높은 VRAM: batch_size 5+ GitHub
## 💡 반복 횟수 선택 가이드
| 이미지 수 | 권장 반복 | 폴더명 예시 | 10 에포크 시 총 스텝 |
|----------|---------|------------|-------------------|
| 10장 | 10회 | `10_character` | 1000 스텝 |
| 20장 | 5회 | `5_character` | 1000 스텝 |
| 50장 | 4회 | `4_character` | 2000 스텝 |
| 100장 | 2회 | `2_character` | 2000 스텝 |
| 200장 | 1회 | `1_character` | 2000 스텝 |
**목표:** 총 스텝이 **1500~3000** 정도가 되도록 조절
고품질 (일관된 스타일/포즈/의상):
→ 4회 반복으로 충분
저품질 (다양한 각도/의상/배경):
→ 10~20회 필요할 수도
```
### **2. 목표가 다름**
```
Gemini 기준: 캐릭터 얼굴/특징 확실히 학습
Kohya 문서: 과적합(overfitting) 방지
```
### **3. 총 스텝 수 계산 방식**
```
50장 × 4회 × 10 에포크 = 2000 스텝
50장 × 10회 × 5 에포크 = 2500 스텝
50장 × 20회 × 2 에포크 = 2000 스텝
```
결국 **총 스텝이 비슷**하면 결과도 비슷해요!
---
## 📊 실전 테스트 결과 (커뮤니티 경험)
| 반복 횟수 | 이미지 수 | 에포크 | 총 스텝 | 결과 |
|----------|----------|-------|---------|------|
| 4회 | 50장 | 10 | 2000 | ⭐⭐⭐⭐ 균형 잡힘 |
| 10회 | 50장 | 5 | 2500 | ⭐⭐⭐⭐⭐ 강한 학습 |
| 20회 | 50장 | 3 | 3000 | ⚠️ 과적합 위험 |
| 2회 | 100장 | 10 | 2000 | ⭐⭐⭐⭐ 자연스러움 |
---
## 🎯 실전 가이드
### **상황별 권장 설정**
#### **📷 고품질 데이터셋 (일관된 캐릭터/스타일)**
```
이미지: 50장
반복: 4~6회
에포크: 8~10
총 스텝: 1600~3000
예: 4_character_name
```
#### **🎨 다양한 데이터셋 (여러 포즈/의상/배경)**
```
이미지: 50장
반복: 8~12회
에포크: 5~8
총 스텝: 2000~4800
예: 10_character_name
```
#### **⚡ 빠른 테스트 (품질 확인용)**
```
이미지: 30장
반복: 5회
에포크: 5
총 스텝: 750
예: 5_test_character
```
#### **🏆 프로덕션 품질 (상업용/고품질)**
```
이미지: 100장+
반복: 3~5회
에포크: 10~15
총 스텝: 3000~7500
예: 3_character_name
```
---
## 💡 **내 추천: 점진적 테스트**
### **1단계: 낮게 시작**
```
폴더: 4_character
에포크: 5
→ 1000 스텝에서 결과 확인
```
### **2단계: 필요시 증가**
```
만족스럽지 않으면:
폴더: 8_character
에포크: 5
→ 2000 스텝에서 재확인
```
### **3단계: 최적점 찾기**
```
과적합 보이면: 반복 횟수 줄이기
언더피팅이면: 반복 횟수 늘리기
```
---
## 🔬 과학적(?) 접근
### **총 스텝 기준 가이드:**
```
1000~1500 스텝: 가벼운 스타일 LoRA
2000~3000 스텝: 캐릭터 LoRA (일반)
3000~5000 스텝: 디테일한 캐릭터
5000+ 스텝: 복잡한 컨셉/다중 캐릭터