Lora Qlora Recipes
Seth HobsonCommunityCreated by Seth Hobson
- Skill
- Guidelines
- Data and AI
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a standardized configuration recipe for LoRA and QLoRA supervised fine-tuning. It focuses on defining adapter parameters such as rank, alpha, and target modules, while providing guidance on when to use LoRA versus QLoRA. The skill assumes the use of Unsloth as the reference implementation and provides mappings for plain TRL and PEFT equivalents, ensuring configurations are consistent with current best practices for adapter training.
What it does
- Defines target modules for LoRA/QLoRA adapters including all-linear layers.
- Provides formulas for calculating lora_alpha based on rank.
- Suggests learning rate starting points for LoRA and QLoRA methods.
- Maps Unsloth configuration parameters to their TRL and PEFT equivalents.
- Offers guidance on selecting between LoRA, QLoRA, and full fine-tuning.
- Identifies common configuration failure modes like fp16 divergence and improper rank selection.
When to use it
- When configuring LoRA or QLoRA adapters for supervised fine-tuning.
- When reviewing training configurations for adapter-based model tuning.
- When deciding between LoRA, QLoRA, or full fine-tuning for a specific task.
- When troubleshooting training issues that stem from configuration choices.
- When porting Unsloth configurations to plain TRL or PEFT.
Advantages
- Standardizes adapter configuration using established conventions.
- Reduces trial-and-error by providing task-specific rank and learning rate starting points.
- Clarifies the relationship between Unsloth, TRL, and PEFT APIs.
- Helps prevent common configuration-related training failures.
Usage examples
- “What are the recommended target modules for a LoRA adapter?”
- The skill recommends targeting all-linear modules, specifically: q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, and down_proj.
- “How should I set lora_alpha relative to rank?”
- The settled convention is to set lora_alpha = 2 * r, deriving it from the rank rather than tuning it independently.
- “What is the standard learning rate for QLoRA?”
- The standard starting point for QLoRA supervised fine-tuning is 2e-4.
- “How do I map Unsloth's use_gradient_checkpointing to TRL?”
- Unsloth's use_gradient_checkpointing='unsloth' maps to gradient_checkpointing=True in TRL's SFTConfig or TrainingArguments.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/wshobson/lora-qlora-recipes/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip lora-qlora-recipes.zip -d .agents/skills
Documentation by Seth Hobson
LoRA & QLoRA Recipes
This skill assumes the routing decision already
happened — finetuning-method-selection should
have already pointed here because the data shape
is demonstrations (SFT), not preference pairs or
a verifiable reward signal. What follows is the
current best-practice recipe for configuring the
adapter itself: which modules to target, how to
size rank and alpha, what learning rate to use,
and when QLoRA buys real headroom versus when it
just adds risk. Dataset preparation and quality
checks are a separate concern — see
dataset-curation.
Input: a routing decision (SFT via LoRA/
QLoRA) plus a target size class.
Output format: a validated adapter config —
the kwarg values below, not free-form advice —
that llm-finetuning-training-engineer consumes
directly when it generates a runnable script.
The Reference Recipe
The reference recipe is "LoRA Without Regret" (Thinking Machines/Schulman, 2025-09), now the settled convention for LoRA/QLoRA SFT.
Target Modules
Target all-linear modules, not just attention:
target_modules = [
"q_proj", "k_proj", "v_proj", "o_proj", # attention
"gate_proj", "up_proj", "down_proj", # MLP — matters most
]The MLP layers (gate_proj, up_proj,
down_proj) matter most — attention-only
targeting was the older, weaker convention.
Dropping modules to save memory is a Failure
Mode below, not a valid optimization.
Alpha and Learning Rate
lora_alpha = 2 * ris the settled convention (NeurIPS 2025 "intruder dimensions" result). Don't hand-tune alpha independently of rank — derive it from rank every time.LoRA learning rate ≈ 10x the equivalent full-fine-tune LR. For QLoRA specifically, 2e-4 is the standard starting point. Full hyperparameter tables and worked examples:
references/hyperparameters.md.
Rank by Task
Rank is task-shaped, not a single global default:
| Task | Rank |
|---|---|
| RL (GRPO/RLVR adapters) | 1–32 |
| General default | 16–32 |
| SFT at scale | up to ~256 |
Higher rank isn't automatically better — it raises capacity to memorize as fast as it raises capacity to generalize. Start at the row matching the task, and only move up a row if the lower rank measurably underfits on held-out eval, not as a default hedge.
Effective Batch Size
Keep effective batch size under 32. This recipe was validated at that scale — pushing effective batch higher is an untested extrapolation, not a free throughput win.
Unsloth Defaults
Unsloth is the reference implementation this
plugin assumes as the default fast path — except
for messages-shaped conversational SFT with
assistant_only_loss=True, where Unsloth
2026.7.x's compiled trainer has no messages-shaped
path at all and the plain-TRL escape hatch
(references/unsloth-trl-mapping.md) is the
default for that combination, not a rare-regression
fallback. Its out-of-the-box defaults, and why
each one is set that way:
lora_dropout=0— the optimized kernel path assumes zero dropout; setting a nonzero value forfeits the fused-kernel speedup.bias="none"— bias terms add adapter parameters for negligible quality gain at this rank range.use_gradient_checkpointing="unsloth"— Unsloth's checkpointing variant, not vanilla HF checkpointing; saves roughly 30% VRAM over no checkpointing.optim="adamw_8bit"— 8-bit AdamW cuts optimizer-state memory with negligible quality impact at LoRA/QLoRA adapter scale.random_statefixed — pins LoRA initialization for reproducibility across runs; treat it like any other seed, not a tunable.
These show up together on the get_peft_model
call:
model = FastLanguageModel.get_peft_model(
model,
r=32,
target_modules=target_modules,
lora_alpha=64, # 2 * r
lora_dropout=0,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=3407,
)Exact kwarg names and their plain-TRL/PEFT
equivalents, plus a full worked config including
SFTConfig: references/unsloth-trl-mapping.md
and references/hyperparameters.md.
LoRA vs QLoRA vs Full FT
| Situation | Default choice |
|---|---|
| Adapting behavior on demonstrations | LoRA |
| Base model doesn't fit in bf16 at target rank | QLoRA |
| Injecting dense new domain knowledge | Full FT (see finetuning-method-selection) |
| Unsure which one | LoRA — upgrade to QLoRA only if memory forces it |
QLoRA = NF4-quantized frozen base weights + BF16 adapters. This is what makes a 65B-class model trainable on 48GB — the quantized base is the memory win, not the adapter itself.
Full fine-tuning is not a default. Reserve it for dense knowledge injection where the goal is changing what the model knows at the weight level, not adapting a behavior. For everything else in this skill's scope, LoRA or QLoRA is the starting assumption.
On DGX Spark, QLoRA can OOM before an equivalent bf16 LoRA run would, even though QLoRA's steady-state footprint is smaller — bitsandbytes dequantization buffers are transient CUDA-side allocations that spike during load. A QLoRA OOM is not proof the model doesn't fit; the
dgx-spark-opsplugin'sspark-memory-thermal-opsskill covers the full OOM remediation ladder (bf16 LoRA is the next thing to try, not a further QLoRA shrink).
Failure Modes
fp16 divergence on non-BF16 GPUs. Training in fp16 on hardware that doesn't have solid BF16 support is a known source of loss spikes and silent divergence. Force
bf16=Truewherever the hardware supports it; don't fall back to fp16 as if it were equivalent. Check hardware support before picking a dtype:python -c "import torch; print(torch.cuda.is_bf16_supported())"Rank too high on a small dataset overfits. A rank picked for "SFT at scale" (up to ~256) on a dataset that doesn't have scale behind it memorizes rather than generalizes. Match rank to the Rank by Task table above, not to the largest number available.
Removing target modules to save memory costs quality for negligible savings. The adapter parameters on
gate_proj/up_proj/down_projare a small fraction of total model size — cutting them barely moves memory but measurably hurts quality. If memory is tight, move to QLoRA or reduce rank/batch/pack length before trimming target modules.
All three failure modes share a pattern: they look like a training-loop bug (loss spikes, plateaus, memorization) but are actually a config choice that contradicts the reference recipe above. Check configuration against this skill before debugging the training loop itself.
References
references/hyperparameters.md— full rank/ alpha/LR tables by task type, rsLoRA notes, batch/packing interactions, and a complete worked Unsloth config block.references/unsloth-trl-mapping.md— every Unsloth kwarg mapped to its TRL/PEFT equivalent, current TRL API notes, and the escape-hatch rule for when to drop back to plain TRL.
Related skills: finetuning-method-selection
routes here; dataset-curation covers the data
side this skill doesn't; llm-finetuning-training-engineer
is the downstream consumer of the config this
skill produces.
Files
- ATTRIBUTION.mdAdded by AutoGineer982 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md7.5 KiB
- references/hyperparameters.md5.7 KiB
- references/unsloth-trl-mapping.md9.6 KiB
references/hyperparameters.md
Last verified: 2026-07-13
LoRA/QLoRA Hyperparameter Tables
Full tables and a complete worked config backing
the summary in SKILL.md. Base models are never
named here — every example is labeled by size
class only; see finetuning-method-selection's
references/model-catalog.md for which actual
model to use at a given size class.
Rank and Alpha by Task Type
lora_alpha = 2 * r in every row — derive alpha
from rank, don't set it independently.
| Task type | Rank (r) | lora_alpha | Notes |
|---|---|---|---|
| RL adapters (GRPO/RLVR) | 1–32 | 2–64 | Lower end (1–8) is common for adapters on top of an already-capable base. |
| General SFT default | 16–32 | 32–64 | Starting point absent a specific reason to go higher or lower. |
| SFT at scale (large, diverse instruction sets) | up to ~256 | up to ~512 | Only justified when the dataset is large and diverse enough to use the extra capacity — see rsLoRA note below before defaulting here. |
Learning Rate by Method
LoRA/QLoRA learning rates run roughly 10x the equivalent full-fine-tune LR — this is the single most common misconfiguration when porting a full- FT config to LoRA (leaving the LR unchanged under-trains the adapter).
| Method | LR range | Use when |
|---|---|---|
| QLoRA (standard) | 2e-4 | Default starting point for QLoRA SFT. |
| LoRA, conservative | 1e-4 | Larger base model, higher rank, or a run that showed instability at 2e-4. |
| LoRA, very conservative | 5e-5 | Continuing a run, fine-grained behavior adjustment, or a base model that's already close to the target behavior. |
Treat these as starting points to sweep around, not fixed constants — but start here rather than porting a full-FT LR unchanged.
rsLoRA Note
Rank-stabilized LoRA (rsLoRA) rescales the
adapter update by alpha / sqrt(r) instead of
alpha / r. It's optional, and only worth
turning on at r ≥ 32 — below that rank, the
standard scaling (alpha / r) is stable enough
that rsLoRA doesn't change outcomes meaningfully.
If the SFT-at-scale row (rank up to ~256) is in
play, turn rsLoRA on; for the general-default or
RL rows, leave it off unless a specific
instability shows up.
Batch and Packing Interactions
Keep effective batch size under 32 — the reference recipe was validated at that scale. Effective batch is
per_device_batch_size * gradient_accumulation_steps * num_devices; a multi-GPU or high-accumulation setup can cross 32 without the per-device batch size looking large, so compute the product, not just the per-device number.Packing multiple short examples into one sequence changes the effective batch's token composition, not just its example count — a packed batch of 8 sequences is not equivalent to an unpacked batch of 8 short examples. Apply the chat template before packing, not after, and spot-check a handful of decoded packed sequences before trusting the pipeline.
Gradient checkpointing (
use_gradient_checkpointing="unsloth") and packing both trade compute for memory independently — enabling both is normal for a memory-constrained run, not redundant.
Worked Config: Unsloth FastLanguageModel + SFTConfig
A complete, internally consistent config at the
general-default rank (r=32), QLoRA, standard
LR. Swap BASE_MODEL for an actual checkpoint
from the model catalog before running.
from unsloth import FastLanguageModel
from trl import SFTConfig, SFTTrainer
BASE_MODEL = "<from model catalog>" # size class + task decide this, not this file
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=BASE_MODEL,
max_seq_length=2048,
dtype=None, # auto-detect bf16/fp16 by hardware
load_in_4bit=True, # QLoRA path — set False for bf16 LoRA
)
target_modules = [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
]
model = FastLanguageModel.get_peft_model(
model,
r=32,
target_modules=target_modules,
lora_alpha=64, # 2 * r
lora_dropout=0,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=3407,
use_rslora=False, # r=32 threshold — leave disabled here unless instability is observed
)
import torch
# Check hardware BF16 support before forcing it — see SKILL.md
# Failure Modes. Training in fp16 on hardware without solid BF16
# support is a known source of loss spikes and silent divergence,
# so this is a hard prerequisite, not a config style choice.
if not torch.cuda.is_bf16_supported():
raise RuntimeError(
"This GPU does not support BF16 — do not fall back to "
"fp16=True as if it were equivalent; pick hardware with "
"BF16 support instead (see SKILL.md Failure Modes)."
)
training_args = SFTConfig(
output_dir="./outputs",
max_length=2048,
dataset_text_field="text",
per_device_train_batch_size=4,
gradient_accumulation_steps=4, # effective batch 16 (single device) — stays under 32
learning_rate=2e-4, # QLoRA standard
bf16=True, # gated above — never fp16, see SKILL.md Failure Modes
optim="adamw_8bit",
num_train_epochs=3,
logging_steps=10,
seed=3407,
)
trainer = SFTTrainer(
model=model,
processing_class=tokenizer, # current TRL — not tokenizer=
train_dataset=train_dataset,
args=training_args,
)
trainer.train()This block is internally consistent: r=32 →
lora_alpha=64 (2x rule), load_in_4bit=True →
learning_rate=2e-4 (QLoRA standard LR),
bf16=True (never fp16), and effective batch
4 * 4 = 16 (under the 32 ceiling). Changing any
one of these — rank, quantization, or batch
shape — should trigger rechecking the others
against the tables above rather than editing it
in isolation.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Seth Hobson
- Publisher
- Seth Hobson (Community)
- Source
- wshobson/agents · plugins/llm-finetuning/skills/lora-qlora-recipes · commit 4bde316
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Seth Hobson.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download lora-qlora-recipes.zip