It has been revealed that in our previous post, Exploring Quantization Backends in Diffusers, we dived into how various quantization techniques can shrink diffusion models like FLUX.1-dev, making them significantly more accessible for inference without drastically compromising performance. We saw how bitsandbytes, torchao, and others reduce memory footprints for generating images.

Recent findings suggest that performing inference is cool, but to make these models truly our own, we also need to be able to fine-tune them. Therefore, in this post, we tackle efficient fine-tuning of these models with peak memory use under ~10 GB of VRAM on a single GPU. This post will guide you through fine-tuning FLUX.1-dev using QLoRA with the diffusers library. We'll showcase results from an NVIDIA RTX 4090. We'll also highlight how FP8 training with torchao can further optimize speed on compatible hardware.

We aim to fine-tune black-forest-labs/FLUX.1-dev to adopt the artistic style of Alphonse Mucha, using a small dataset.

The model consists of three main components:.

In our QLoRA approach, we focus exclusively on fine-tuning the transformer component. The text encoders and VAE remain frozen throughout training.

We used a diffusers training script (slightly modified from here designed for DreamBooth-style LoRA fine-tuning of FLUX models. Also, a shortened version to reproduce the results in this blogpost (and used in the Google Colab) is available here. Let's examine the crucial parts for QLoRA and memory efficiency:.

According to recent reports, loRA (Low-Rank Adaptation) Deep Dive: LoRA makes model training more efficient by keeping track of the weight updates with low-rank matrices. Instead of updating the full weight matrix W W W, LoRA learns two smaller matrices A A A and B B B. The revision to the weights for the model is ΔW=BA \Delta W = B A ΔW=BA, where A∈Rr×k A \in \mathbb{R}^{r \times k} A∈Rr×k and B∈Rd×r B \in \mathbb{R}^{d \times r} B∈Rd×r. The number r r r (called rank) is much smaller than the original dimensions, which means less parameters to update. Lastly, α \alpha α is a scaling factor for the LoRA activations. This affects how much LoRA affects the updates, and is often set to the same value as the r r r or a multiple of it. It helps balance the influence of the pre-trained model and the LoRA adapter. For a general introduction to the concept, check out our previous blog post: Using LoRA for Efficient Stable Diffusion Fine-Tuning.

Industry observers note that QLoRA: The Efficiency Powerhouse: QLoRA enhances LoRA by first loading the pre-trained base model in a quantized format (typically 4-bit via bitsandbytes), drastically cutting the base model's memory footprint. It then trains LoRA adapters (usually in FP16/BF16) on top of this quantized base. This dramatically lowers the VRAM needed to hold the base model.

For instance, in the DreamBooth training script for HiDream 4-bit quantization with bitsandbytes reduces the peak memory usage of a LoRA fine-tune from ~60GB down to ~37GB with negligible-to-none quality degradation. The very same principle is what we apply here to fine-tune FLUX.1 on a consumer-grade hardware.

It has been revealed that 8-bit Optimizer (AdamW): Standard AdamW optimizer maintains first and second moment estimates for each parameter in 32-bit (FP32), which consumes a lot of memory. The 8-bit AdamW uses block-wise quantization to store optimizer states in 8-bit precision, while maintaining training stability. This technique can reduce optimizer memory usage by ~75% compared to standard FP32 AdamW. Enabling it in the script is straightforward:.

Gradient Checkpointing: During forward pass, intermediate activations are typically stored for backward pass gradient computation. Gradient checkpointing trades computation for memory by only storing certain checkpoint activations and recomputing others during backpropagation.

Recent findings suggest that cache Latents: This optimization technique pre-processes all training images through the VAE encoder before the beginning of the training. It stores the resulting latent representations in memory. During the training, instead of encoding images on-the-fly, the cached latents are directly used. This approach offers two main benefits:.

Setting up 4-bit Quantization (BitsAndBytesConfig):.

This section demonstrates the QLoRA configuration for the base model:.

Defining LoRA Configuration (LoraConfig): Adapters are added to the quantized transformer:.

Only these LoRA parameters become trainable.

Before we launch the QLoRA fine-tune we can save a huge chunk of VRAM and wall-clock time by caching outputs of text encoders once.

At training time the dataloader simply reads the cached embeddings instead of re-encoding the caption, so the CLIP/T5 encoder never has to sit in GPU memory.

By combining this with cached VAE latents (--cache_latents) you whittle the active model down to just the quantized transformer + LoRA adapters, keeping the whole fine-tune comfortably under 10 GB of GPU memory.

For this demonstration, we leveraged an NVIDIA RTX 4090 (24GB VRAM) to explore its performance. The full training command using accelerate is shown below.

It has been revealed that configuration for RTX 4090: On our RTX 4090, we used a train_batch_size of 1, gradient_accumulation_steps of 4, mixed_precision="bf16", gradient_checkpointing=True, use_8bit_adam=True, a LoRA rank of 4, and resolution of 512x768. Latents were cached with cache_latents=True.

Training Time (RTX 4090): Fine-tuning for 700 steps on the Alphonse Mucha dataset took approximately 41 minutes on the RTX 4090 with train_batch_size of 1 and resolution of 512x768.

According to recent reports, output Quality: The ultimate measure is the generated art. Here are samples from our QLoRA fine-tuned model on the derekl35/alphonse-mucha-style dataset:.

Recent findings suggest that this table compares the primary bf16 precision results. The goal of the fine-tuning was to teach the model the distinct style of Alphonse Mucha.

The fine-tuned model nicely captured Mucha's iconic art nouveau style, evident in the decorative motifs and distinct color palette. The QLoRA process maintained excellent fidelity while learning the upcoming style.

The results are nearly identical, showing that QLoRA performs effectively with both fp16 and bf16 mixed precision.

For people with NVIDIA GPUs possessing compute capability 8.9 or greater (such as the H100, RTX 4090), even greater speed efficiencies can be achieved by leveraging FP8 training via the torchao library.

Industry observers note that we fine-tuned FLUX.1-dev LoRA on an H100 SXM GPU slightly modifieddiffusers-torchao training scripts. The following command was used:.

The training run had a peak memory usage of 36.57 GB and completed in approximately 20 minutes.

Qualitative results from this FP8 fine-tuned model are also available:.

Key steps to enable FP8 training with torchao involve:.

For a more detailed guide and code snippets, please refer to this gist and the diffusers-torchao repository.

After training your LoRA adapters, you have two main approaches for inference.

One approach is to load your trained LoRA adapters on top of the base model.

For when you want maximum efficiency with a single style, you can merge the LoRA weights into the base model.

While we showcased results on an RTX 4090, the same code can be run on more accessible hardware like the T4 GPU available in Google Colab for free.

It has been revealed that on a T4, you can expect the fine-tuning process to take significantly longer around 4 hours for the same number of steps. This is a trade-off for accessibility, but it makes custom fine-tuning possible without high-end hardware. Be mindful of usage limits if running on Colab, as a 4-hour training run might push them.

Sources indicate that QLoRA, coupled with the diffusers library, significantly democratizes the ability to customize state-of-the-art models like FLUX.1-dev. As demonstrated on an RTX 4090, efficient fine-tuning is well within reach, yielding high-quality stylistic adaptations. Furthermore, for users with the latest NVIDIA hardware, torchao enables even faster training through FP8 precision.

Sharing your fine-tuned LoRA adapters is a fantastic way to contribute to the open-source community. It allows others to easily try out your styles, build on your work, and helps create a vibrant ecosystem of creative AI tools.

It has been revealed that if you've trained a LoRA for FLUX.1-dev, we encourage you to share it. The easiest way is to add the --push_to_hub flag to the training script. Alternatively, if you have already trained a model and want to upload it, you can use the following snippet.

According to recent reports, check out our Mucha LoRA and the TorchAO FP8 LoRA. You can find both, plus other adapters, in this collection.

We can't wait to see what you create!

In a recent development, hi! Great blog post, thank you for your work.

The link to the script train_dreambooth_lora_flux_nano.py(in this section) is not working - perhaps the branch on which it was developed is not merged yet ?

It's not merged yet ! https://github.com/huggingface/diffusers/pull/11743We will merge it soon ;).

Typo: CLIP is not a text encoder :PThis is good.

In a recent development, hi all, I managed to make it run on a dataset of numerical art of my own (mostly 512x512 flame fractals), and am glad to share the LoRA - happy to get some feedback on it ! I'll enhancement the model card soon ...

Thank you team for the great work, easy to use !

According to recent reports, awesome! glad to hear it worked well with your flame fractal dataset, results in model card looks cool.

In a recent development, I don't remember you being this cocky. This is how you lose respect.

The script was already available since October 2024, just made a more detailed version :P.

i know, my research group provided it ;).

https://github.com/huggingface/diffusers/tree/main/examples/research_projects/flux_lora_quantization.

Was provided by SimpleTuner group?

Recent findings suggest that it's called Terminus Research, for what it's worth, but we contributed the original flux training script, which was then redone for inclusion by Linoy, with modifications. and then we ensured PEFT and Diffusers worked with quantised training on LoRA.

Recent findings suggest that ✅ 1. Do these instructions work with Flux Schnell?✅ 2. Can you export the merged model as a .safetensors file after merging a LoRA?✅ 3. Does a LoRA merge increase the size-on-disk of the model? 4. I recently bought a refurbed RTX 3090 for AI workloads, will these instruction still work on the RTX 3090 or should I return it for a RTX 4090?

An LLM I asked stated yes for three but I wanted to ask the experts.

I would say it should work for Schnell but you might have to change the loss function a bit to account for the fact it's a timestep-distilled model.

I don't think LoRA merge should increase the final state dict size.

The numbers shouldn't change much.

→ Read original article