Fine-Tuning MedGemma-27B with Fully Sharded Data Parallelism (FSDP)
1 Introduction
Fine-tuning large language models (LLMs) like MedGemma-27B presents a significant challenge due to the massive memory requirements. A 27-billion parameter model, even with mixed-precision (FP16) training, requires a substantial amount of memory. The model parameters alone would consume 54GB (27B * 2 bytes), and the AdamW optimizer states would require an additional 108GB (27B * 4 bytes). With gradients, the total memory requirement would be around 216GB, which is well beyond the capacity of a single GPU. By using LoRA, we only need to train a small fraction of the parameters, which drastically reduces the memory required for the optimizer states and gradients. This is where Fully Sharded Data Parallelism (FSDP) comes in. FSDP is a technique that shards the model’s parameters, gradients, and optimizer states across multiple GPUs, allowing you to train massive models.
In this blog post, we’ll dive into a real-world example of fine-tuning the google/medgemma-27b-text-it model using FSDP and Parameter-Efficient Fine-Tuning (PEFT) with LoRA. We’ll explore the entire process, from the configuration and infrastructure to the training script and the underlying NCCL collectives that make it all possible.
2 The Base Model: MedGemma-27B
We start with the google/medgemma-27b-text-it model, a powerful, instruction-tuned LLM from Google, specialized for the medical domain. Our goal is to fine-tune this model on a custom dataset to further enhance its capabilities for specific medical text generation tasks.
3 The Fine-Tuning Strategy
To make the fine-tuning process feasible, we employ a combination of FSDP and PEFT with LoRA.
3.1 Fully Sharded Data Parallelism (FSDP)
FSDP is a data parallelism strategy that shards the model across multiple GPUs. Unlike traditional data parallelism where the entire model is replicated on each GPU, FSDP shards the model’s parameters, gradients, and optimizer states. This dramatically reduces the memory footprint on each GPU, allowing us to train much larger models.
Our FSDP configuration is defined in configs/fsdp.py:
import torch
from dataclasses import dataclass
from torch.distributed.fsdp import ShardingStrategy, MixedPrecision, CPUOffload
from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
class fsdp_config:
def __init__(self,
mixed_precision=False,
use_fp16=False,
sharding_strategy=ShardingStrategy.FULL_SHARD,
hsdp=False,
sharding_group_size=0,
replica_group_size=0,
checkpoint_type=StateDictType.FULL_STATE_DICT,
fsdp_activation_checkpointing=True,
fsdp_cpu_offload=False,
pure_bf16=True):
self.mixed_precision = mixed_precision
self.use_fp16 = use_fp16
self.sharding_strategy = sharding_strategy
self.hsdp = hsdp
self.sharding_group_size = sharding_group_size
self.replica_group_size = replica_group_size
self.checkpoint_type = checkpoint_type
self.fsdp_activation_checkpointing = fsdp_activation_checkpointing
self.fsdp_cpu_offload = CPUOffload(offload_params=True) if fsdp_cpu_offload else CPUOffload(offload_params=False)
if pure_bf16:
self.mixed_precision = MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16, buffer_dtype=torch.bfloat16)
elif mixed_precision:
self.mixed_precision = MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16, buffer_dtype=torch.bfloat16)
else:
self.mixed_precision = NoneKey FSDP settings: - sharding_strategy=ShardingStrategy.FULL_SHARD: This is the most memory-efficient strategy, sharding everything: parameters, gradients, and optimizer states. - pure_bf16=True: We use bfloat16 for mixed-precision training, which is ideal for modern GPUs like A100s and H100s. - fsdp_activation_checkpointing=True: This further reduces memory by recomputing activations during the backward pass instead of storing them.
3.2 Parameter-Efficient Fine-Tuning (PEFT) with LoRA
PEFT methods fine-tune only a small number of model parameters, which significantly reduces the computational and memory costs of fine-tuning. We use Low-Rank Adaptation (LoRA), which injects trainable rank decomposition matrices into the layers of the Transformer model.
Our LoRA configuration is defined in configs/peft.py:
from dataclasses import dataclass
@dataclass
class peft_config:
use_peft: bool = True
peft_type: str = "lora"
lora_r: int = 8
lora_alpha: int = 16
lora_dropout: float = 0.05
target_modules: tuple = ("q_proj", "k_proj", "v_proj", "o_proj")Key PEFT settings: - use_peft: True: We enable PEFT with LoRA. - lora_r: 8: The rank of the LoRA matrices. A smaller rank means fewer trainable parameters. - target_modules: We apply LoRA to the query, key, value, and output projections in the attention layers.
4 The Dataset
We use the miriad/miriad-5.8M dataset for fine-tuning. To make the training more manageable for this example, we sample the dataset.
The training configuration in configs/training.py specifies the dataset and other training parameters:
from dataclasses import dataclass
@dataclass
class train_config:
model_name: str="google/medgemma-27b-text-it"
batch_size: int=8
epochs: int=1
lr: float=2e-5
warmup_steps: int = 50
use_fp16: bool=True
mixed_precision: bool=True
seed: int=42
save_model: bool=True
dataset_path: str = "miriad/miriad-5.8M"
dataset_sample_percentage: float = 0.0054
gradient_accumulation_steps: int = 8
max_seq_length: int = 512
validation_freq: int = 1
resume_from_checkpoint: bool=True
debug_mode: bool=False5 The Infrastructure
The training is performed on a single node with 2 A100 GPUs on Lambda Cloud instance.
6 The Training Process
The training is launched using the run_training.sh script, which uses torchrun to start the distributed training on 2 GPUs.
6.1 NCCL Collectives in Action
NCCL (NVIDIA Collective Communications Library) is a library of multi-GPU collective communication primitives that are performance-optimized for NVIDIA GPUs. PyTorch’s torch.distributed package uses NCCL as a backend for distributed training.
In our trainer.py script, we use the dist.all_reduce collective operation during the evaluation phase to aggregate the loss from all GPUs.
def evaluate(model, test_dataloader, local_rank, world_size, current_epoch):
# ... (evaluation loop) ...
# Aggregate results using all_reduce
loss_tensor = torch.tensor(total_loss, dtype=torch.float32).cuda(local_rank)
samples_tensor = torch.tensor(total_samples, dtype=torch.float32).cuda(local_rank)
dist.all_reduce(loss_tensor, op=dist.ReduceOp.SUM)
dist.all_reduce(samples_tensor, op=dist.ReduceOp.SUM)
# ... (calculate and print global average loss) ...6.1.1 How all_reduce Works
The all_reduce operation performs a reduction on the tensor data from all processes and then distributes the result back to all processes. In our case, we are summing the total_loss and total_samples from each GPU.
Here’s a simplified illustration of how all_reduce with a SUM operation works with 2 GPUs:
- Initial State: Each GPU has its own
loss_tensor.- GPU 0:
loss_tensor_0 - GPU 1:
loss_tensor_1
- GPU 0:
- Reduction: The
all_reduceoperation performs a reduction (in this case, summation) of the tensors from all GPUs. This is often done in a ring-like fashion to maximize bandwidth.- GPU 0: sends its
loss_tensor_0to GPU 1. - GPU 1: receives
loss_tensor_0, adds it to its ownloss_tensor_1, resulting inloss_tensor_0 + loss_tensor_1.
- GPU 0: sends its
- Broadcast: The result of the reduction is then broadcasted back to all GPUs.
- GPU 1: sends the result
loss_tensor_0 + loss_tensor_1to GPU 0.
- GPU 1: sends the result
- Final State: Both GPUs now have the same final tensor, which is the sum of the initial tensors from all GPUs.
- GPU 0:
loss_tensor_0 + loss_tensor_1 - GPU 1:
loss_tensor_0 + loss_tensor_1
- GPU 0:
This ensures that each process has the global sum of the losses and samples, allowing us to calculate the global average validation loss on rank 0.
7 Model Performance
The model’s performance was evaluated on the test split of the cais/mmlu dataset, specifically the clinical_knowledge subset. The primary metric used for evaluation was accuracy.
After fine-tuning, the model achieved an accuracy of 0.834 with a standard error of 0.0229.
7.1 Evaluation Process
The evaluate function in trainer.py is responsible for calculating the validation loss after each epoch. The losses from all GPUs are aggregated using the dist.all_reduce collective operation, and the global average validation loss is calculated and logged.
8 Training Observability
We use Weights & Biases (wandb) to monitor the training process in real-time. This allows us to visualize key metrics, identify potential issues, and ensure that our training is running efficiently.
8.1 Training Loss Curve
The training loss curve shows the model’s loss over time. A decreasing loss indicates that the model is learning from the training data.
Observations: The training loss curve shows a steady decrease over time, which is a good sign that the model is learning and converging. The curve starts to flatten towards the end, which suggests that the model is approaching its optimal performance on the training data.
8.2 SM Utilization
Streaming Multiprocessor (SM) utilization is a measure of how effectively the GPU’s computing resources are being used. High SM utilization is desirable as it indicates that the GPU is not being bottlenecked by other factors like data loading or CPU processing.
Observations: The SM utilization graph shows a consistently high utilization throughout the training process. This indicates that our FSDP setup is efficient and that the GPUs are being used to their full potential. This is a good sign that our training is not being held back by data loading or other bottlenecks.
9 Hugging Face Model Release
The fine-tuned model is available on the Hugging Face Hub at the following repository: