LoRA (Low-Rank Adaptation)#
NeMo RL supports LoRA for parameter-efficient fine-tuning. LoRA reduces the number of trainable parameters by learning low-rank update matrices for selected linear layers while keeping the base model frozen. This lowers memory usage and checkpoint size, and enables serving many task-specific adapters on top of a single shared base model.
This page is the single reference for LoRA in NeMo RL. It covers backend support, a side-by-side schema comparison, backend-specific config examples, and links to the algorithm guides and checkpoint-export tooling.
For the theory behind the method, see LoRA: Low-Rank Adaptation of Large Language Models.
Backend Support#
LoRA is implemented on two training backends, each with its own config schema:
Training backend |
Config path |
Rollout representation |
Notes |
|---|---|---|---|
Automodel |
|
Native A/B with synchronous vLLM by default; merged is opt-in. |
This is the default training backend. |
Megatron Core |
|
Merged full weights. |
Requires |
LoRA is supported across the SFT, GRPO, and DPO algorithms on both backends.
Note
Automodel does not support Triton kernels when tensor_parallel_size > 1, so set use_triton: false in that case (see the parameter details below).
Schema Comparison#
The two backends share most of their fields but differ in a few backend-specific options. The table below maps equivalent fields and highlights the differences.
Concept |
Automodel ( |
Megatron ( |
|---|---|---|
Enable LoRA |
|
|
Modules to adapt |
|
|
Modules to skip |
|
|
Adapt all linear layers |
|
(implicit: empty |
Rank (r) |
|
|
Scaling factor |
|
|
Dropout probability |
|
|
Dropout position |
|
|
A-matrix init |
|
|
B-matrix init |
(always zero) |
|
Optimized kernels |
|
— |
Adapter dtype |
(follows base layer) |
|
Experimental A2A comm |
— |
|
Share adapters across grouped MoE experts |
— |
|
Warm start from a donor adapter |
|
|
The effective learning-rate multiplier for the adapter is alpha / dim on both backends.
Automodel Configuration#
LoRA settings live under policy.automodel_cfg.lora_cfg:
policy:
automodel_cfg:
lora_cfg:
enabled: False # Set to True to enable LoRA fine-tuning
target_modules: [] # List of module names to apply LoRA
exclude_modules: [] # List of module names to exclude from LoRA
match_all_linear: true # Apply LoRA to all linear layers
dim: 8 # LoRA rank (r): controls adaptation capacity
alpha: 32 # LoRA scaling factor (effective lr = alpha/dim)
dropout: 0.0 # Dropout probability for LoRA layers
dropout_position: "post" # Dropout position: "pre" or "post"
lora_A_init: "xavier" # Initialization method: "xavier" or "uniform"
use_triton: true # Use Triton-optimized kernels
restore_from: null # Warm start from a donor adapter checkpoint (see below)
Automodel Parameter Details#
enabled(bool): Whether to enable LoRA training.target_modules(list): Specific module names to apply LoRA. Empty withmatch_all_linear=trueapplies to all linear layers.exclude_modules(list): Module names to exclude from LoRA.match_all_linear(bool): Whentrue, applies LoRA to all linear layers (overridestarget_modules).dim(int): LoRA rank (r). Lower values = fewer parameters but less capacity. Typical: 4, 8, 16, 32, 64.alpha(int): LoRA scaling factor. Effective learning rate multiplier =alpha/dim. Typical: 16, 32, 64.dropout(float): Dropout probability for regularization.dropout_position(str): Apply dropout before ("pre") or after ("post") LoRA.lora_A_init(str): Initialization method for the LoRA A matrix ("xavier"or"uniform"). The B matrix is always initialized to zero.use_triton(bool): Use Triton-optimized kernels for better performance. Note: Automodel does not support Triton for TP > 1. Set tofalsewhentensor_parallel_size > 1to avoid compatibility issues.restore_from(str, optional): Path to a donor PEFT adapter checkpoint (a directory containingadapter_model.safetensors+adapter_config.json, e.g. a previous run’sstep_*/policy/weights) whose adapter weights initialize this run’s LoRA modules. See Warm-Starting from a LoRA Checkpoint.
Grouped MoE Experts#
match_all_linear: true matches linear modules and skips Automodel’s grouped expert modules. To adapt grouped experts, set match_all_linear: false and include their module names in target_modules, for example:
policy:
automodel_cfg:
lora_cfg:
enabled: true
match_all_linear: false
target_modules: ['*_proj', '*experts']
dim: 8
alpha: 32
generation:
lora_refit_mode: merged
With merged refitting, the grouped expert adapters are merged into gate_and_up_projs and down_projs before conversion to the inference engine’s weight format. The adapter tensors themselves are excluded from the refit.
The example explicitly selects merged refitting; synchronous vLLM otherwise defaults to native adapter refitting.
Megatron Configuration#
LoRA settings live under policy.megatron_cfg.peft:
policy:
megatron_cfg:
peft:
enabled: false # Set to True to enable LoRA fine-tuning
target_modules: [] # List of module names to apply LoRA, defaults to all linear layers
exclude_modules: [] # List of module names not to apply LoRA
dim: 32 # LoRA rank (r): controls adaptation capacity
alpha: 32 # LoRA scaling factor (effective lr = alpha/dim)
dropout: 0.0 # Dropout probability for LoRA layers
dropout_position: "pre" # Dropout position: "pre" or "post"
lora_A_init_method: "xavier" # Initialization method for lora A: "xavier" or "uniform"
lora_B_init_method: "zero" # Initialization method for lora B: "zero"
a2a_experimental: false # Enables the experimental All-to-All (A2A) communication strategy
lora_dtype: None # Adapter weights dtype
share_expert_adapters: true # Share one adapter across grouped MoE experts on each EP rank
restore_from: null # Warm start from a donor PEFT checkpoint (see below)
generation:
# Megatron LoRA does not yet export native vLLM adapter tensors.
lora_refit_mode: merged
Megatron Parameter Details#
enabled(bool): Whether to enable LoRA training.target_modules(list): Specific module names to apply LoRA. Defaults to all linear layers if the list is left empty. Example:['linear_qkv', 'linear_proj', 'linear_fc1', 'linear_fc2'].linear_qkv: Apply LoRA to the fused linear layer used for query, key, and value projections in self-attention.linear_proj: Apply LoRA to the linear layer used for projecting the output of self-attention.linear_fc1: Apply LoRA to the first fully-connected layer in MLP.linear_fc2: Apply LoRA to the second fully-connected layer in MLP.
Target modules can also contain wildcards. For example, you can specify
target_modules=['*.layers.0.*.linear_qkv', '*.layers.1.*.linear_qkv']to add LoRA to onlylinear_qkvon the first two layers.exclude_modules(list, optional): A list of module names not to apply LoRA. It will match allnn.Linear&nn.Linear-adjacent modules whose name does not match any string inexclude_modules. If used, it requirestarget_modulesto be an empty list orNone.dim(int): LoRA rank (r). Lower values = fewer parameters but less capacity. Typical: 4, 8, 16, 32, 64.alpha(int): LoRA scaling factor. Effective learning rate multiplier =alpha/dim. Typical: 16, 32, 64.dropout(float): Dropout probability for regularization, defaults to 0.0.dropout_position(str): Apply dropout before ("pre") or after ("post") LoRA.lora_A_init_method(str): Initialization method forlora_A(choices:['xavier', 'uniform']), defaults toxavier.lora_B_init_method(str): Initialization method for the low-rank matrix B. Defaults to"zero".a2a_experimental(bool): Enables the experimental All-to-All (A2A) communication strategy. Defaults toFalse.lora_dtype(torch.dtype): Adapter weights dtype. By default it followsorig_linear’s dtype, but for quantized weights (e.g. 4-bit) it must be specified explicitly.share_expert_adapters(bool): Share one adapter across all grouped MoE experts on each expert-parallel rank. Set tofalseto create one adapter per local expert. Defaults totruefor backward compatibility.restore_from(str, optional): Path to a donor Megatron-Bridge PEFT checkpoint (aniter_XXXXXXXdirectory, or a checkpoint root resolving to one) whose adapter weights initialize this run’s LoRA modules. See Warm-Starting from a LoRA Checkpoint.
Warm-Starting from a LoRA Checkpoint#
restore_from initializes this run’s adapters from a donor PEFT checkpoint, e.g. to carry an SFT LoRA into GRPO. The accepted path format differs by backend:
Automodel:
policy.automodel_cfg.lora_cfg.restore_from— a directory containingadapter_model.safetensors+adapter_config.json(a previous run’sstep_*/policy/weightsor itsmodel/subdirectory).Megatron Core:
policy.megatron_cfg.peft.restore_from— a native Megatroniter_XXXXXXXdirectory, or a checkpoint root containing one.
The donor’s dim/alpha must match this run’s. On Automodel, a donor’s recorded base_model_name_or_path (unless absent, empty, or N/A) must also equal this run’s policy.model_name as an exact string: an HF repo ID and a local path for the same model will not match, nor will a model moved to a different path. Setup fails loudly otherwise. Optimizer, RNG, and train state always start fresh. restore_from requires enabled: true. When resuming from a NeMo RL training checkpoint, the resumed weights take precedence for the policy; the KL reference policy still anchors to the warm-started (donor) adapters, not to the bare base model.
Usage by Algorithm#
SFT#
The config uses the Automodel backend by default, so Automodel LoRA only requires enabling the flag:
uv run examples/run_sft.py policy.automodel_cfg.lora_cfg.enabled=true
To use the Megatron backend, switch backends and enable the PEFT block:
uv run examples/run_sft.py \
--config examples/configs/sft.yaml \
policy.automodel_cfg.enabled=false \
policy.megatron_cfg.enabled=true \
policy.megatron_cfg.peft.enabled=true
See the SFT guide for the full SFT workflow.
GRPO#
GRPO supports LoRA on both backends. Enable the Automodel adapter with:
uv run examples/run_grpo.py policy.automodel_cfg.lora_cfg.enabled=true
For Automodel training with synchronous vLLM generation, native LoRA refit is the default: NeMo RL sends only the factorized A/B tensors, replaces an in-memory vLLM adapter, and selects it on every generation request. The base model is loaded once and is not overwritten during adapter updates.
Native refit currently supports the topology-default transport (colocated CUDA IPC or non-colocated NCCL) and matching BF16/FP16 trainer and rollout precision. It exports the trainer’s LoRA tensors through the model’s Automodel state-dict adapter when one is present, so custom model layouts such as grouped MoE are converted to conventional per-expert HF/PEFT factors with the orientation consumed by vLLM. It fails at setup for unsupported combinations such as asynchronous vLLM, vLLM’s exposed HTTP server (NeMo Gym), speculative decoding, quantized rollout models, custom refit transports, DoRA, moe_rank_scaling, or Megatron LoRA. Models with dynamically updated MoE router bias fail before their first native refit rather than silently omitting that mutable state.
Native refit also fails rather than silently dropping a trained module that the selected vLLM model implementation cannot apply. For example, Qwen2 does not expose lm_head as a native-LoRA module; configure its Automodel LoRA policy with match_all_linear=false and exclude_modules=["*lm_head*"], or use merged refit.
Individual recipes may still set policy.automodel_cfg.automodel_kwargs.force_hf=true for model-specific training or parallelization compatibility. That setting is independent of native refit; native refit itself accepts either HF-native LoRA names or names converted by a custom Automodel state-dict adapter.
Native refit requires policy.generation.backend: vllm. Other rollout backends use the merged representation and must set policy.generation.lora_refit_mode: merged.
The previous full-weight behavior remains available as an explicit compatibility or performance opt-in:
policy:
generation:
lora_refit_mode: merged
Merged refit materializes W + scale * B @ A in the rollout dtype. In reduced precision, this can discard LoRA updates that are smaller than the BF16/FP16 spacing of the base weight and therefore can increase the trainer/generation logprob mismatch.
See the GRPO guide for the full GRPO workflow.
DPO#
DPO fully supports LoRA on both the Automodel and Megatron backends, using the same lora_cfg / peft config blocks as SFT and GRPO. There is no dedicated DPO LoRA recipe; enable it on an existing DPO config via an override. For the Automodel backend:
uv run examples/run_dpo.py policy.automodel_cfg.lora_cfg.enabled=true
For the Megatron backend:
uv run examples/run_dpo.py \
--config examples/configs/dpo.yaml \
policy.automodel_cfg.enabled=false \
policy.megatron_cfg.enabled=true \
policy.megatron_cfg.peft.enabled=true
See the DPO guide for the full DPO workflow.
Example Recipes#
Ready-to-run LoRA recipes live under examples/configs/recipes/llm/:
Recipe |
Algorithm |
Backend |
|---|---|---|
SFT |
Automodel |
|
SFT |
Megatron |
|
SFT |
Automodel |
|
GRPO |
Automodel |
|
GRPO |
Megatron |
|
GRPO |
Automodel |
|
GRPO |
Megatron |
DPO LoRA is supported on both backends but ships no dedicated recipe — enable it on an existing DPO config with the overrides shown in Usage by Algorithm → DPO.
Exporting a LoRA Checkpoint to Hugging Face Format#
After training with LoRA on the Megatron backend, the convert_lora_to_hf.py script supports two export modes:
Merged: fold the adapter into the base model and export a single standalone Hugging Face checkpoint for inference or evaluation.
Adapter-only: export only the adapter weights in Hugging Face PEFT format, keeping the base model separate (e.g. for use with vLLM’s LoRA support).
See the Checkpointing documentation for full usage details and examples.