A pipeline parallel training script for diffusion models.
Currently supports Flux, LTX-Video, and HunyuanVideo.
Work in progress and highly experimental. It is unstable and not well tested. Things might not work right.
Features
Pipeline parallelism, for training models larger than can fit on a single GPU
Full fine tune support for:
Flux
LoRA support for:
Flux, LTX-Video, HunyuanVideo
Useful metrics logged to Tensorboard
Compute metrics on a held-out eval set, for measuring generalization
Training state checkpointing and resuming from checkpoint
Efficient multi-process, multi-GPU pre-caching of latents and text embeddings
Easily add support for new models by implementing a single subclass
Windows support
There are reports that it doesn't work on Windows. This is because Deepspeed only has partial Windows support. However, at least one user was able to get it running and training successfully on Windows Subsystem for Linux, specifically WSL 2. If you must use Windows I recommend trying WSL 2.
Almost everything is commented, explaining what each setting does.
Assistant
Start by reading through the config files in the examples directory.
Once you've familiarized yourself with the config file format, go ahead and make a copy and edit to your liking. At minimum, change all the paths to conform to your setup, including the paths in the dataset config file.
RTX 4000 series needs those 2 environment variables set. Other GPUs may not need them. You can try without them, Deepspeed will complain if it's wrong.
If you enabled checkpointing, you can resume training from the latest checkpoint by simply re-running the exact same command but with the --resume_from_checkpoint flag.
Output files
A new directory will be created in output_dir for each training run. This contains the checkpoints, saved models, and Tensorboard metrics. Saved models/LoRAs will be in directories named like epoch1, epoch2, etc. Deepspeed checkpoints are in directories named like global_step1234. These checkpoints contain all training state, including weights, optimizer, and dataloader state, but can't be used directly for inference. The saved model directory will have the safetensors weights, PEFT adapter config JSON, as well as the diffusion-pipe config file for easier tracking of training run settings.
VRAM requirements
Flux
Flux doesn't currently support training a LoRA on a fp8 base model (if you want this, PRs are welcome :) ). So you need to use a >24GB GPU, or use pipeline_stages=2 or higher with multiple 24GB cards. With four 24GB GPUs, you can even full finetune Flux with the right techniques (see the train.py code about gradient release and the custom AdamW8bitKahan optimizer).
HunyuanVideo
HunyuanVideo supports fp8 transformer. The example config file will train a HunyuanVideo LoRA, on images only, in well under 24GB of VRAM. You can probably bump the resolution to 1024x1024 or higher.
Video uses A LOT more memory. I was able to train a rank 32 LoRA on 512x512x33 sized videos in just under 23GB VRAM usage. Pipeline parallelism will help a bit if you have multiple GPUs, since the model weights will be further divided among them (but it doesn't help with the huge activation memory use of videos). Long term I want to eventually implement ring attention and/or Deepspeed Ulysses for parallelizing the sequence dimension across GPUs, which should greatly help for training on videos.
LTX-Video
I've barely done any training on LTX-Video. The model is much lighter than Hunyuan, and the latent space more compressed, so it uses less memory. You can train loras even on video at a reasonable length (I forgot exactly what it was) on 24GB.
Parallelism
This code uses hybrid data- and pipeline-parallelism. Set the --num_gpus flag appropriately for your setup. Set pipeline_stages in the config file to control the degree of pipeline parallelism. Then the data parallelism degree will automatically be set to use all GPUs (number of GPUs must be divisible by pipeline_stages). For example, with 4 GPUs and pipeline_stages=2, you will run two instances of the model, each divided across two GPUs. Note that due to a weird bug I'm still investigating, pipeline_stages>1 doesn't work with HunyuanVideo.
Pre-caching
Latents and text embeddings are cached to disk before training happens. This way, the VAE and text encoders don't need to be kept loaded during training. The Huggingface Datasets library is used for all the caching. Cache files are reused between training runs if they exist. All cache files are written into a directory named "cache" inside each dataset directory.
This caching also means that training LoRAs for text encoders is not currently supported.
Two flags are relevant for caching. --cache_only does the caching flow, then exits without training anything. --regenerate_cache forces cache regeneration. If you edit the dataset in-place (like changing a caption), you need to force regenerate the cache (or delete the cache dir) for the changes to be picked up.
HunyuanVideo LoRAs
HunyuanVideo doesn't have an official Diffusers integration yet, and as such it doesn't have an official LoRA format. This script outputs the LoRA using the typical Diffusers convention, i.e. the state_dict keys are all prefixed with "transformer.". This will work with the latest version of the ComfyUI HunyuanVideoWrapper extension, and is likely to work with Diffusers whenever HunyuanVideo is officially integrated. Make sure the HunyuanVideoWrapper extension is fully updated, and use the "HunyuanVideo Lora Select" node.
Extra
You can check out my qlora-pipe project, which is basically the same thing as this but for LLMs.
how to run this on Modal with a h100?
To run the diffusion-pipe training script on Modal with an H100 GPU, you'll need to set up an environment that replicates your local setup within Modal's infrastructure. Below are step-by-step instructions to help you achieve this:
Overview
Understand Modal's Capabilities
Set Up a Modal Function
Configure the Environment and Dependencies
Handle Data and Outputs
Run the Training Job
Monitor and Retrieve Results
1. Understand Modal's Capabilities
Modal is a cloud platform that allows you to run Python code and functions in the cloud with minimal setup. It provides support for GPUs, including NVIDIA H100 GPUs, which are powerful for training large-scale deep learning models.
Key Features:
GPU Support: Access to various GPU types, including A100 and H100.
Custom Environments: Ability to define custom images with specific dependencies.
Data Management: Persistent storage options for datasets and outputs.
Scalability: Easily scale up resources as needed.
Note: As of my knowledge cutoff in September 2021, I don't have information on the availability of H100 GPUs in Modal. Please check Modal's latest documentation or contact their support to confirm H100 GPU availability.
2. Set Up a Modal Function
You'll need to create a Python script that defines a Modal function responsible for setting up the environment and running your training script.
Example Modal Script: modal_train.py
python
import modal
# Create a Modal stub
stub = modal.Stub(name="diffusion-pipe-training")
# Define the image with Base OS and dependencies
# We'll define the image in the next section
3. Configure the Environment and Dependencies
A. Define the Custom Image
Since diffusion-pipe has several dependencies, including specific versions of PyTorch and CUDA, you'll need to create a custom Docker image that includes all necessary libraries and tools.
Option 1: Use an Existing Image and Install Dependencies
CUDA Compatibility: Ensure that the versions of PyTorch and CUDA are compatible with the H100 GPU. H100 GPUs require CUDA 12.x. As of PyTorch 2.0, CUDA 12 support might be experimental. You may need to build PyTorch from source or use nightly builds that support CUDA 12.
Dependencies: Include all dependencies from requirements.txt.
Conda Environment: Using Conda helps manage dependencies and avoid conflicts.
Option 2: Build a Docker Image Locally and Use It in Modal
Create a Dockerfile with all necessary dependencies and push it to a container registry.
# If you built and pushed a Docker image
image = modal.Image.from_dockerhub("yourusername/diffusion-pipe:latest")
C. Define the Training Function
python
@stub.function(
image=image,
gpu="H100", # Use "H100" if available; otherwise, check the Modal documentation
secret=Secret.from_dict({"HF_TOKEN": "your_huggingface_token"}),
timeout=60 * 60 * 24, # Adjust based on expected training time
)
def train():
pass # Entry point is defined in the Dockerfile; nothing else to do here
If you didn't specify an entry point in the Dockerfile or are using the first option, you can define the train function as:
python
import os
@stub.function(
image=image,
gpu="H100",
secret=Secret.from_dict({"HF_TOKEN": "your_huggingface_token"}),
timeout=60 * 60 * 24,
)
def train():
os.environ["NCCL_P2P_DISABLE"] = "1"
os.environ["NCCL_IB_DISABLE"] = "1"
# Navigate to the diffusion-pipe directory
os.chdir("/diffusion-pipe")
# Run the training command
os.system("deepspeed --num_gpus=1 train.py --deepspeed --config examples/hunyuan_video.toml")
4. Handle Data and Outputs
A. Mount Datasets and Configurations
If your training relies on local datasets or specific configuration files, you need to make them accessible inside the Modal environment.
Mounting Local Directories:
python
from modal import Mount
# Mount your local data directory to /data in the container
data_mount = Mount.from_local_dir("/path/to/your/data", remote_path="/data")
@stub.function(
image=image,
gpu="H100",
mounts=[data_mount],
# Other parameters...
)
def train():
# Your training code
B. Use Modal's Persistent Storage
If your datasets are large or you need persistent storage, consider using modal.NetworkFileSystem.
python
volume = modal.NetworkFileSystem.persisted("diffusion-pipe-data")
@stub.function(
image=image,
gpu="H100",
network_file_systems={"/data": volume},
# Other parameters...
)
def train():
# Ensure datasets are in /data
if not os.path.exists("/data/dataset_name"):
# Code to download or copy your dataset to /data
pass
# Proceed with training
C. Save Outputs
Ensure that model checkpoints, logs, and other outputs are saved to a persistent storage location.
5. Run the Training Job
A. Execute the Modal Script
bash
modal run modal_train.py
This command will:
Upload your code and dependencies to Modal.
Schedule a function execution with the specified resources.
Run your training script on an H100 GPU.
B. Monitor the Job
You can monitor the progress of your job using Modal's dashboard or CLI tools. Logs will be streamed to your console or can be accessed through Modal's interface.
6. Monitor and Retrieve Results
A. Access Logs
Use Modal's logging to debug and monitor your training process.
B. Retrieve Checkpoints and Outputs
Ensure that your training script saves model checkpoints and outputs to a location accessible after the job completes.
If using modal.NetworkFileSystem, you can access the files from subsequent jobs or download them locally.
C. TensorBoard Monitoring
If you use TensorBoard for monitoring, you can set it up to record logs to a mounted directory and access it as needed.
Additional Considerations
Check GPU Availability
Confirm that Modal supports H100 GPUs.
If H100 GPUs are not available, you may use an A100 GPU by setting gpu="A100".
CUDA and PyTorch Compatibility
Ensure that the CUDA version in your Docker image matches the requirements of the H100 GPU.
As H100 GPUs require CUDA 12.x, make sure you're using a version of PyTorch that supports CUDA 12.
Deepspeed Configuration
Configure Deepspeed properly within the Modal environment.
Set any necessary environment variables.
Environment Variables
Set NCCL_P2P_DISABLE and NCCL_IB_DISABLE as needed.
Confirm other environment variables required for your training.
Testing
Before running a full training job, consider running a short test to ensure everything is set up correctly.
Summary
By following the steps above, you can run the diffusion-pipe training script on Modal with an H100 GPU:
Set Up the Modal Function: Define a Modal function that includes your custom image and specifies GPU resources.
Configure the Environment: Ensure all dependencies are installed and compatible with the H100 GPU.
Handle Data and Outputs: Use Modal's features to mount data and save outputs persistently.
Run the Training Job: Execute your Modal script to start training.
Monitor and Retrieve Results: Access logs and outputs to monitor progress and retrieve trained models.
Dependency Conflicts: If you encounter conflicts, carefully check version compatibility between CUDA, PyTorch, and Deepspeed.
GPU Errors: Ensure that your environment is correctly configured for the H100 GPU.
Data Access Issues: Verify that datasets are properly mounted and accessible within the container.
Permissions: Check file permissions, especially when writing outputs to mounted directories or network file systems.
By carefully setting up your environment and leveraging Modal's features, you can scale your diffusion model training using powerful H100 GPUs in the cloud.