feat: Enable QLoRA and FSDP compatibility#974
Conversation
Deleting comment
mreso
left a comment
There was a problem hiding this comment.
That looks great @jscaldwell55, thanks for figuring this out!
Could you post the logs of your test runs and if you have the loss curves of both?
|
@mreso Thanks for the review! Below are the loss curves and training logs: Test Configuration
Loss Curves
Testing: Baseline (FP16) Testing: QLoRA only (4-bit) Testing: QLoRA + FSDP (PR fix) Summary of Results
ValidationThe logs demonstrate that the fix successfully:
|
IgorKasianenko
left a comment
There was a problem hiding this comment.
Thanks for the feature, approved!

Fixes #945
Problem
When attempting to use QLoRA (e.g., --quantization 4bit) with FSDP (--enable_fsdp), training fails due to two consecutive ValueErrors:
Dtype mismatch between bfloat16 (LoRA adapters) and uint8/float16 (quantized base model weights).
requires_grad mismatch between the frozen base model parameters and the trainable LoRA adapters.
This PR implements the modern, recommended solution to enable seamless QLoRA + FSDP integration — without introducing new user-facing flags.
Solution
The fix includes two key updates, applied automatically when both quantization and enable_fsdp are enabled:
Sets bnb_4bit_quant_storage=torch.bfloat16 in BitsAndBytesConfig.
This feature from bitsandbytes ensures quantized parameters appear as bfloat16 to PyTorch/FSDP.
Crucially, it preserves the 4-bit storage internally, maintaining QLoRA's memory efficiency while resolving the dtype error.
FSDP is now instantiated with use_orig_params=True whenever PEFT is active (train_config.use_peft).
This is the documented best practice for FSDP + PEFT.
It ensures FSDP respects each parameter’s requires_grad state, resolving the second ValueError.
Usage
No additional CLI arguments or config changes are required. When both --quantization 4bit and --enable_fsdp are set, the framework applies the necessary fixes automatically.
Example Command:
python -m llama_cookbook.finetuning
--model_name "meta-llama/Llama-2-7b-hf"
--quantization "4bit"
--enable_fsdp
--dataset "samsum_dataset"
Testing
Verified on a Google Colab A100 GPU that fine-tuning a 4-bit quantized model (Llama-2-7b-hf) with FSDP now runs without errors.
Memory Verification: Confirmed that GPU memory usage with this fix is consistent with a 4-bit quantized model. Peak training memory was ~4.7GB, compared to ~13GB for a full-precision model—proving that no dequantization occurs and memory benefits are fully maintained.
End-to-End Validation: The model successfully completed several training steps using the SFTTrainer, confirming full compatibility.
cc @mreso - This implements the proper solution as discussed, maintaining quantization benefits while ensuring FSDP compatibility.