Click to expand
This repository contains training, generation and utility scripts for Stable Diffusion and other image generation models.
We are grateful to the following companies for their generous sponsorship:
If you find this project helpful, please consider supporting its development via GitHub Sponsors. Your support is greatly appreciated!
-
Version 0.13.1 (2026-11-23):
- Added
networks/lora_post_hoc_ema.py, which merges several LoRA checkpoints of one training run into a single LoRA with an exponential moving average (Post-Hoc EMA), ported from Musubi Tuner. Averaging the checkpoints saved near the end of a training reduces the fluctuation of the weights, and the result may be more stable than the last checkpoint. For details, please refer to the documentation. PR #2510 - Fixed a bug in single-process multi-GPU training (
--replica_devices): when the number of batches per epoch was not a multiple of the number of GPUs, the GPUs did not run at the same time in some epochs (every other epoch with 2 GPUs), and those epochs were up to about two times slower. Only the speed was affected; the training results are not. PR #2508
- Added
-
Version 0.13.0 (2026-11-21):
- Added
--run_control(experimental) to the LoRA training scripts. A running training can be observed and operated from outside, by scripts and AI agents. See the documentation for details. PR #2494 PR #2495 PR #2496 PR #2497 PR #2498 PR #2499 PR #2500 PR #2501- The state of the running training is written to plain JSON files in
<output_dir>/<output_name>_run, so scripts and AI agents can observe the training without parsing the TensorBoard event files.manifest.json: resolved arguments, dataset summary, environment.status.json: current step, loss, learning rate, speed, ETA, VRAM, last outputs.events.jsonl: checkpoints, states, sample images, anomalies, end of the run with the error if it failed.loss.jsonl: the loss of each training sample with its image, timestep and resolution.
tools/analyze_run_loss.pysummarizes the per-sample loss by timestep, resolution and image, which helps to find images that are not learned well (e.g. a mismatch between the image and its caption).- The running training also accepts commands, without waiting for the scheduled timing. They are sent with
tools/run_control_cli.py(or any program which writes a JSON file).sample: generates sample images with the current weights (prompts of the prompt file, or new prompts if the text encoder is in memory).save/save_state: saves the model or the state.stop: stops the training after saving them.pause/resume: pauses the training to free the VRAM for a while (the base models are moved to CPU and back, the process stays). In replica training (--replica_devices),pauseonly stops the training: the models stay on the devices and the VRAM is not freed.
- A prompt with
--s 0(0 steps) in the prompt file is a reserved prompt: it is skipped by the scheduled sampling, but its text encoder outputs are cached at the start, so it can be generated on demand (sample --index) even when the text encoder is not kept in memory. - For Anima and MOSS-Image,
tools/run_control_sample_prompt.pygenerates a sample image of a new prompt even when the text encoder is not kept in memory: it encodes the prompt with the text encoder in its own process (on CPU by default, so an error there does not affect the training) and sends the outputs to the training. - For AI coding agents which start and watch a training for you, there is a short guide with the procedure and the pitfalls; let your agent read it.
- The state of the running training is written to plain JSON files in
- Added
--gradient_checkpointing_skip_blocks(partial gradient checkpointing) to MOSS-Image and Anima training. The last N transformer blocks keep their activations instead of recomputing them in the backward pass, so spare VRAM can be converted into speed; the VRAM usage and the step time change linearly with N (0, the default, is the previous behavior). With the recent large models a larger batch size gives little throughput gain, so this is usually the better use of the VRAM left over on 24GB to 48GB GPUs. Measured with MOSS-Image LoRA training (about 1MP, batch size 1, bf16): 13.5GB / 1.29 s/step with0to 55GB / 0.93 s/step with42(all blocks), about 1GB and 8.6 ms per block; with--compile(ConvRot INT8) the cost per block drops to about 0.6GB. Anima: 6.5GB / 0.85 s/step with0to 19.9GB / 0.53 s/step with28. See the documentation of MOSS-Image and Anima for the tables. PR #2485 - Added experimental single-process multi-GPU training (
--replica_devices) for Anima and MOSS-Image LoRA training. One Python process drives a master and one replica per additional GPU without DDP, so noaccelerate launch --multi_gpu,torchrunor NCCL / gloo is needed, and multi-GPU LoRA training also works on Windows. Requires--cache_latents,--cache_text_encoder_outputsand--network_train_unet_only;train_batch_sizeis per device as with DDP. For details, please refer to the documentation.- For developers:
NetworkTrainer.create_network(network creation from the arguments) andNetworkTrainer.forward_backward(one micro-step) are new overridable methods oftrain_network.py; the replica trainer (library/replica_trainer.py) is a mixin composed in front of the per-model trainer class. - Fixed: a single-process training started with plain
python(withoutaccelerate launch) on a machine with several GPUs failed in the accelerator initialization (Default process group has not been initialized).
- For developers:
- Added
--text_encoder_blocks_to_swapfor MOSS-Image: streams the given number of the 32 text encoder layers from the CPU instead of keeping them on the GPU, so the text encoder outputs can be cached on GPUs with 8GB of VRAM (peak about 5GB with28and 3.5GB with32in bf16, 2.2GB with32and ConvRot INT8). Available in the training script andtools/cache_text_encoder_outputs.py. PR #2478 Thanks to dskjal. PR #2483- The text encoder layers are streamed with the same H2D-only offloader as
--block_swap_h2d_only(it does not need to be specified; the weights stay on the CPU, the next layer is prefetched while the current one runs), which now supports blocks of different shapes, such as the linear / full attention layers of Qwen3.5-9B.
- The text encoder layers are streamed with the same H2D-only offloader as
- Added
--svd_method qrtonetworks/resize_lora.py. It computes the exact SVD of the LoRA weights via QR decomposition without merginglora_up @ lora_down, which is much faster (more than 100 times on an SDXL LoRA) and has no randomness ofsvd_lowrank. If--new_rankis larger than the original rank, the output is padded to--new_rank. The defaultmergedkeeps the previous behavior. PR #2482 Thanks to woct0rdho. PR #2484 - Anima: the number of DiT blocks is now inferred from the checkpoint, so variants which differ from Anima-Preview only in the number of blocks, such as the community Anima-2.9B (40 blocks), can be used for LoRA training and inference. Please note that these variants are not tested regularly. PR #2418 Thanks to gazingstars123. PR #2486 Thanks to davrens101. PR #2502
- Added
-
Version 0.12.3 (2026-10-26):
- Added
--timestep_sampling truncated_logit_normalfor FLUX.1, Anima, HunyuanImage-2.1 and MOSS-Image training: the logit-normal distribution (--logit_mean/--logit_std) on the discrete training grid, truncated at--timestep_cutoff(default 0.95) and rescaled, with a--timestep_uniform_ratio(default 0.01) share of uniform samples. With--logit_mean -1.09 --logit_std 0.95 --discrete_flow_shift 1.0, this reproduces the timestep schedule of the MOSS-Image pre-training exactly (previously the truncation and the uniform samples were not reproduced). PR #2471- The per-subset
timestep_sampling.offsetnow also applies totruncated_logit_normaland tosigmawith--weighting_scheme logit_normal(a positive offset biases toward higher noise, as in the other modes). See the documentation.
- The per-subset
- MOSS-Image: the ConvRot INT8 Linear layers are now included in
--compile. The fused Triton kernels are registered astorch.librarycustom ops, so the compiled blocks no longer break at every quantized Linear layer and--compilespeeds up--convrot_int8training too. PR #2473- The backward of the INT8 Linear layers is also faster: the weight is dequantized and rotated back in one kernel instead of rotating the activations after the GEMM. PR #2474
- The autotune configs of the INT8 GEMM now include tiles for Ampere (RTX 30xx) GPUs, where the upstream configs reached only ~40% of the hardware INT8 throughput, and a Blackwell (RTX 50xx / RTX PRO) config. PR #2475
- Added
-
Version 0.12.2 (2026-10-20):
- Added H2D-only block swap (
--block_swap_h2d_only) for LoRA training, ported from Musubi Tuner. The frozen base weights are kept on the CPU and only copied HostβDevice, which removes the DeviceβHost transfer of the classic block swap and improves the training speed. Supported for FLUX.1 / Chroma, Lumina Image 2.0, HunyuanImage-2.1, Anima and MOSS-Image (not for SD3).--gradient_checkpointingis required. For details, please refer to the documentation. PR #2467--block_swap_ring_size(default 2) sets the number of GPU buffers for the streamed blocks, and--use_pinned_memory_for_block_swapkeeps the CPU copies in pinned memory for faster transfers.- For developers:
enable_block_swapof the models now takes aBlockSwapConfiginstead of a device, andsubmit_move_blocksof the offloader is renamed tosubmit_move_blocks_forward, the same as Musubi Tuner.
- The Text Encoder outputs of multiple caption candidates (
enable_multiline_captionwith separator lines) can now be cached for MOSS-Image. All candidates are encoded and stored in one cache file, and one of them is chosen randomly at each step. PR #2466- The processed caption texts are stored in the cache files, so the cache is rebuilt automatically when captions (or
caption_prefix/caption_suffix) are changed. The cache files created with version 0.12.1 are still valid for images with a single caption. - The cache size and the caching time are multiplied by the number of candidates. Other models still cannot cache the Text Encoder outputs when some captions have multiple candidates.
tools/cache_text_encoder_outputs.pynow stops with an error for multiple caption candidates with models that do not support them (previously only the first candidate was cached silently).
- The processed caption texts are stored in the cache files, so the cache is rebuilt automatically when captions (or
- Added H2D-only block swap (
-
Version 0.12.1 (2026-10-18):
- Added support for LoRA training of MOSS-Image (OpenMOSS), a 5B DiT with the Qwen3.5-9B text encoder and the FLUX.2 VAE. PR #2458, PR #2459, PR #2460, PR #2461
moss_image_train_network.pytrains LoRA (and LoHa / LoKr) for the DiT and optionally for the text encoder. The official diffusers-format shards and the ComfyUI single-file checkpoints can be loaded. For details, please refer to the documentation.- ConvRot INT8 quantization of the base weights (
--convrot_int8for the DiT,--convrot_int8_text_encoderfor the text encoder, ported from Musubi Tuner) is available as an alternative to fp8. The ComfyUI pre-quantized*_int8_convrot.safetensorsfiles are detected automatically. The fused int8 kernels requiretriton(triton-windowson Windows). - The DiT LoRA can be used in ComfyUI without conversion.
moss_image_minimal_inference.pyis also available for inference with LoRA. tools/cache_latents.pyandtools/cache_text_encoder_outputs.pysupport MOSS-Image with--moss_image.- The LoRA module is the new generic
networks.lora_generic(regex-based module selection,network_reg_dims/network_reg_lrs, the same asnetworks.lora_anima). It is expected to be the base for other architectures in the future.
- Added
enable_multiline_captionsubset option (--enable_multiline_caption) to use captions containing line breaks as they are, for models with LLM-based text encoders (Anima, Lumina, HunyuanImage, etc.).- Lines starting with
multiline_caption_separator(default---===---) separate multiple caption candidates for one image, and one candidate is chosen randomly at each step. In metadata files for fine tuning,captioncan also be a list of strings. For details, please refer to the dataset config documentation. - In
.txtsample prompt files,\n(backslash + n) is now converted to a line break. - Fixed
caption_prefix/caption_suffixbeing added only to the first / last line of multi-line captions (withenable_wildcard, the prefix was attached only to the first line and the suffix only to the last line; without it, the suffix was lost).
- Lines starting with
- Fixed
caption_prefix/caption_suffix,secondary_separatorand the first-line truncation of multi-line captions not being applied when caching Text Encoder outputs (--cache_text_encoder_outputs); the raw caption was encoded. Issue #2453- If you use these options with
--cache_text_encoder_outputs_to_disk, delete the existing cache files (*_te.npzetc.) so that they are re-created with the processed captions. enable_wildcardcannot be applied to cached outputs (the caption is encoded as is); a warning is now shown in that case.- For custom caching strategies:
TextEncoderOutputsCachingStrategy.cache_batch_outputsnow receives the processed captions as an additionalcaptionsargument.
- If you use these options with
- When a custom LR scheduler is specified with
--lr_scheduler_type, the total number of training steps and the number of warmup steps computed by sd-scripts are now passed to the scheduler asnum_training_stepsandnum_warmup_steps. Issue #2444- They are passed only when the scheduler's constructor has arguments with these exact names, and values given explicitly with
--lr_scheduler_argstake priority. Schedulers with differently named arguments (e.g.total_steps) are not affected; specify them with--lr_scheduler_argsas before. - Note that a custom scheduler that has
num_training_stepsbut was used without specifying it in--lr_scheduler_argspreviously ran with its default value, and now uses the actual number of training steps. Similarly,--lr_warmup_stepsis now passed to a scheduler that hasnum_warmup_steps(previously it caused an error).
- They are passed only when the scheduler's constructor has arguments with these exact names, and values given explicitly with
- Added support for LoRA training of MOSS-Image (OpenMOSS), a 5B DiT with the Qwen3.5-9B text encoder and the FLUX.2 VAE. PR #2458, PR #2459, PR #2460, PR #2461
-
Version 0.12.0 (2026-09-24):
- Added support for Windows on ARM64 (e.g. NVIDIA RTX Spark PCs). PR #2430, PR #2431, PR #2433
opencv-pythonis now optional (a Pillow/NumPy fallback is used when it is missing), andrequirements.txtselects the packages that have Windows ARM64 wheels automatically. For details, please refer to Installing without OpenCV / Windows on ARM64.transformers,schedulefreeandsafetensorsinrequirements.txthave been updated to versions that provide Windows ARM64 wheels.
- Updated the dependencies in
requirements.txt:transformers4.57.6 -> 5.5.4,diffusers0.32.1 -> 0.40.0,accelerate1.6.0 -> 1.15.0,huggingface-hub0.34.3 -> 1.32.0. PR #2436- This is mainly a security maintenance update (the 4.x line of
transformersanddiffusers< 0.38 no longer receive fixes). The previous versions of the libraries still work with this release, so you do not have to update them immediately, but it is recommended to runpip install --upgrade -r requirements.txtat your earliest convenience. diffusers0.40 requires PyTorch 2.6 or later (PyTorch 2.6.0 or later has been the requirement of sd-scripts already). CI now tests with PyTorch 2.6.0 and 2.8.0.- In
transformers5.x,CLIPTokenizerno longer applies theftfytext normalization of the original CLIP tokenizer (straightening curly quotes, converting full-width characters, etc.). sd-scripts now applies it itself, so tokenization is unchanged from previous versions. - Text encoder outputs, VAE outputs and the noise schedulers were verified to be identical to the previous versions with the local regression tests in
tests/local. diffusers0.40 prints a spurious warning "There are modules in AutoencoderKL that should be kept in float32: [] ..." on every.to(dtype)call (a bug in diffusers: the check fires even when the list is empty). sd-scripts suppresses this warning when the list is empty.
- This is mainly a security maintenance update (the 4.x line of
- Added support for
transformers5.6 and later, and updatedtransformersinrequirements.txtto 5.17.0. PR #2437transformers5.6 changed the internal structure ofCLIPTextModel(thetext_modelsubmodule was removed). sd-scripts now wraps the model so that the checkpoint keys, the LoRA weight names of the text encoders (lora_te_text_model_...) andtext_encoder.text_model.*access stay the same as before. Nothing changes fortransformers< 5.6, where the wrapper is not applied.transformers5.6 also switched the attention implementation of T5 (T5-XXL of FLUX.1 / SD3, byT5 of HunyuanImage) to SDPA, which should be faster and use less memory. The bf16/fp16 outputs of T5 differ very slightly from previous versions (cosine similarity β 0.998 for T5-XXL, the accuracy against fp32 is the same). This may change generated images or trained weights in minor details, and cached text encoder outputs from previous versions are still usable. The outputs of the other text encoders are identical.- As above, the previous versions of
transformersstill work, but updating withpip install --upgrade -r requirements.txtis recommended.
- Added OFTv2 and BOFT network modules (
networks.oft_v2,networks.boft) for SD1.x / SD2.x / SDXL training. PR #2357- Orthogonal fine-tuning adapters following the PEFT implementation. Weights in PEFT format can also be loaded. Thanks to umisetokikaze.
- Note that
--network_dimmeans the block size for these modules. For details, please refer to the documentation.
- Added per-subset timestep sampling offset (
custom_attributes.timestep_sampling.offset) for FLUX.1 and Anima LoRA training. PR #2401 Thanks to okdsf.- Shifts the timestep sampling distribution of each dataset subset toward lower- or higher-noise timesteps. For details, please refer to the documentation.
- Added
--show_timesteps_offsetto preview the timestep distribution with the offset applied when using--show_timesteps. PR #2410- The documentation also describes how the offset behaves with
shift/flux_shifttimestep sampling.
- The documentation also describes how the offset behaves with
- Removed
gen_img_diffusers.py, the old image generation script for SD1.x / SD2.x. It had not worked for a while (it depended on a function removed by the refactoring) andgen_img.pysupports everything it did except the experimental CLIP / VGG16 guidance. Please usegen_img.pyinstead (see gen_img_README.md). The file is still available in the previous releases. PR #2439 - Fixed the
dpmsolveranddpmsinglesamplers of--sample_sampler(sample image generation during training) and--samplerofgen_img.py/sdxl_gen_img.py, which failed with an error on recent versions ofdiffusers. PR #2438- The
lms/k_lmssamplers require thescipypackage, which is not included inrequirements.txt. A clear error message is now shown at startup (instead of at the first sample generation) whenscipyis missing. Please runpip install scipyto use them.
- The
- Added support for Windows on ARM64 (e.g. NVIDIA RTX Spark PCs). PR #2430, PR #2431, PR #2433
- Stable Diffusion 1.x/2.x
- SDXL
- SD3/SD3.5
- FLUX.1
- LUMINA
- HunyuanImage-2.1
- Anima
- MOSS-Image
- LoRA training
- Fine-tuning (native training, DreamBooth): except for HunyuanImage-2.1
- Textual Inversion training: SD/SDXL
- Inpainting model training: SD1.5 and SDXL
- Image generation
- Other utilities such as model conversion, image tagging, LoRA merging, etc.
- LoRA Training Overview
- Dataset config / Japanese version
- Advanced Training
- OFTv2 / BOFT Training
- SDXL Training
- SD3 Training
- FLUX.1 Training
- LUMINA Training
- HunyuanImage-2.1 Training
- Anima Training
- MOSS-Image Training
- Fine-tuning
- Textual Inversion Training
- ControlNet-LLLite Training / Japanese version
- Anima ControlNet-LLLite Training Guide
- Validation
- Masked Loss Training / Japanese version
- Inpainting Training
- Block Swap (CPU Offloading)
- Single-Process Multi-GPU Training (Replica Training)
- LoRA Post-Hoc EMA Merging
- Observing and Controlling a Running Training (Run Control)
- Guide for AI Agents Operating a Training (give this to your AI coding agent when it starts and watches a training)
This repository provides recommended instructions to help AI agents like Claude and Gemini understand our project context and coding standards.
To use them, you need to opt-in by creating your own configuration file in the project root.
Quick Setup:
-
Create a
CLAUDE.mdand/orGEMINI.mdfile in the project root. -
Add the following line to your
CLAUDE.mdto import the repository's recommended prompt:@./.ai/claude.prompt.md
or for Gemini:
@./.ai/gemini.prompt.md
-
You can now add your own personal instructions below the import line (e.g.,
Always respond in Japanese.).
This approach ensures that you have full control over the instructions given to your agent while benefiting from the shared project context. Your CLAUDE.md and GEMINI.md are already listed in .gitignore, so they won't be committed to the repository.
Python 3.10.x and Git:
- Python 3.10.x: Download Windows installer (64-bit) from https://www.python.org/downloads/windows/
- git: Download latest installer from https://git-scm.com/download/win
Python 3.11.x, and 3.12.x will work but not tested.
Give unrestricted script access to powershell so venv can work:
- Open an administrator powershell window
- Type
Set-ExecutionPolicy Unrestrictedand answer A - Close admin powershell window
Open a regular Powershell terminal and type the following inside:
git clone https://github.com/kohya-ss/sd-scripts.git
cd sd-scripts
python -m venv venv
.\venv\Scripts\activate
pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cu124
pip install --upgrade -r requirements.txt
accelerate configIf python -m venv shows only python, change python to py.
Note: bitsandbytes, prodigyopt and lion-pytorch are included in the requirements.txt. If you'd like to use another version, please install it manually.
This installation is for CUDA 12.4. If you use a different version of CUDA, please install the appropriate version of PyTorch. For example, if you use CUDA 12.1, please install pip install torch==2.6.0 torchvision==0.21.0 --index-url https://download.pytorch.org/whl/cu121.
Answers to accelerate config:
- This machine
- No distributed training
- NO
- NO
- NO
- all
- fp16If you'd like to use bf16, please answer bf16 to the last question.
Note: Some user reports ValueError: fp16 mixed precision requires a GPU is occurred in training. In this case, answer 0 for the 6th question:
What GPU(s) (by id) should be used for training on this machine as a comma-separated list? [all]:
(Single GPU with id 0 will be used.)
The file does not contain requirements for PyTorch. Because the version of PyTorch depends on the environment, it is not included in the file. Please install PyTorch first according to the environment. See installation instructions below.
The scripts are tested with PyTorch 2.6.0. PyTorch 2.6.0 or later is required.
For RTX 50 series GPUs, PyTorch 2.8.0 with CUDA 12.8/12.9 should be used. requirements.txt will work with this version.
opencv-python is listed in requirements.txt, but the core training / dataset pipeline only uses a small subset of OpenCV (mainly cv2.resize, cv2.cvtColor, and a debug-only cv2.imshow). When opencv-python is not available, a lightweight Pillow/NumPy fallback under library/_cv2_stub is automatically registered as cv2, so existing scripts continue to work. If you would rather avoid the large OpenCV install, simply uninstall it after installing the requirements:
pip uninstall opencv-pythonOn Windows on ARM64 (e.g. NVIDIA RTX Spark PCs), opencv-python has no prebuilt wheel, so requirements.txt skips it automatically through an environment marker and the usual pip install --upgrade -r requirements.txt works as is. For the same reason tensorboardX is installed instead of tensorboard on that platform (TensorBoard 2.x depends on grpcio, which has no Windows ARM64 wheel). Logging with --log_with tensorboard works unchanged through tensorboardX; view the logs with TensorBoard on another machine.
Note that:
- The default install with OpenCV remains the recommended path. The fallback reproduces OpenCV's
INTER_AREAandINTER_LINEARresizing (the modes the dataset pipeline uses by default) in NumPy, so training results match up to rounding, but it is slower than OpenCV (roughly 0.1 s per 24-megapixel image).INTER_CUBIC/INTER_LANCZOS4go through Pillow and differ slightly. - The following tools still require real
opencv-pythonand will exit with a clear message when it is missing:tools/canny.py,tools/detect_face_rotate.py, and the ControlNetcannypreprocessor used bygen_img.py/sdxl_gen_img.py. - Debug-only features such as
cv2.imshowduring dataset inspection fall back to Pillow's default image viewer (PIL.Image.show), andcv2.waitKeyblocks oninput()in the terminal so you can page through images one at a time.
To install xformers, run the following command in your activated virtual environment:
pip install xformers --index-url https://download.pytorch.org/whl/cu124Please change the CUDA version in the URL according to your environment if necessary. xformers may not be available for some GPU architectures.
Linux or WSL2 installation steps are almost the same as Windows. Just change venv\Scripts\activate to source venv/bin/activate.
Note: Please make sure that NVIDIA driver and CUDA toolkit are installed in advance.
To install DeepSpeed, run the following command in your activated virtual environment:
pip install deepspeed==0.16.7 When a new release comes out you can upgrade your repo with the following command:
cd sd-scripts
git pull
.\venv\Scripts\activate
pip install --use-pep517 --upgrade -r requirements.txtOnce the commands have completed successfully you should be ready to use the new version.
If you want to upgrade PyTorch, you can upgrade it with pip install command in Windows Installation section.
The implementation for LoRA is based on cloneofsimo's repo. Thank you for great work!
The LoRA expansion to Conv2d 3x3 was initially released by cloneofsimo and its effectiveness was demonstrated at LoCon by KohakuBlueleaf. Thank you so much KohakuBlueleaf!
The majority of scripts is licensed under ASL 2.0 (including codes from Diffusers, cloneofsimo's and LoCon), however portions of the project are available under separate license terms:
Memory Efficient Attention Pytorch: MIT
bitsandbytes: MIT
BLIP: BSD-3-Clause