LoRA fine tuning almost never fails because the GPU is too slow. It fails at 2 a.m. with a CUDA out-of-memory error, forty minutes after you started a run that looked fine on paper. The gap between the two is huge. A 7B model needs about 3.5 GB for its 4-bit weights, against about 112 GB for full fine-tuning once gradients and optimizer states are counted, according to CloudMinister’s November 23, 2026 fine-tuning guide. Everything that decides whether your run survives sits in that gap.
Most people close it by trial and error: halve the batch size, shorten the sequence length, rerun, and wait through another model load. You can replace that loop with a budget. A 60-line estimator predicts peak VRAM from the model config alone, a probe measures what the card really uses, and a sweep picks the largest configuration that fits with headroom to spare.
The method itself is old news. In 2023 the QLoRA authors (Tim Dettmers, Artidoro Pagnoni, Ari Holtzman and Luke Zettlemoyer) wrote: “We present QLoRA, an efficient finetuning approach that reduces memory usage enough to finetune a 65B parameter model on a single 48GB GPU while preserving full 16-bit finetuning task performance.” That abstract is on arXiv. What changed since is the tooling and the models, and the tutorials that predate Transformers 5 mostly skip the memory accounting that keeps a run alive. If you want the plain dataset-to-adapter run first, start with the site’s tutorial on how to fine-tune an LLM with QLoRA, then come back here to size it properly.
Don't miss new tech stories on Google
Add Shattered once in the Google app and our stories show up in your news suggestions.
Why LoRA Fine-Tuning Fails on Memory, Not Compute #
LoRA trains small low-rank adapter matrices and keeps the pretrained weights frozen. That single design choice removes most of the gradient and optimizer memory, because only the adapters need them. QLoRA goes one step further. It stores the frozen base model in 4-bit form, usually NF4 with double quantization, and pairs it with paged optimizers that spill optimizer state to CPU memory when the GPU runs short. The Hugging Face PEFT documentation describes both techniques, and the numbers below assume the QLoRA variant.
Hugging Face summarized the payoff in its bitsandbytes announcement: “This method enables 33B model finetuning on a single 24GB GPU and 65B model finetuning on a single 46GB GPU.” You can read the full explanation in the Hugging Face 4-bit post. Documentation from the UK’s Isambard-AI service makes the same point at 8B scale: “Full fine-tuning of an 8 billion parameter model does not fit on a single GPU without additional sharding techniques, which are outside the scope of this tutorial, whereas both LoRA and QLoRA comfortably do.”
So the base weights are not your problem. Six other consumers of VRAM are, and each one scales with a different knob:
- Quantized base weights. Fixed by the model. About 4.13 bits per weight once double quantization trims the 0.5-bit block overhead by roughly 0.37 bit.
- Embeddings and output head. Not quantized, and larger than most people expect for models with big vocabularies.
- Adapter, gradients and optimizer state. Grow linearly with the LoRA rank and the number of target modules.
- Saved activations. Grow linearly with batch size and sequence length, and with layer count unless gradient checkpointing is on.
- Logits. Grow with batch times sequence times vocabulary size, in fp32. This is the silent killer.
- Fixed overhead. The CUDA context, kernel workspaces and allocator fragmentation.
CloudMinister’s guide gives practical QLoRA ranges by model size. Treat them as a starting point, not a promise, because they assume moderate sequence lengths.
| Model size | QLoRA VRAM range | Typical card class |
|---|---|---|
| 7B | 12 to 16 GB | 16 GB consumer card |
| 13B | 16 to 24 GB | 24 GB consumer card |
| 33B | 24 to 48 GB | 48 GB workstation card |
| 70B | 48 to 80 GB | 80 GB data center card |
The ranges are wide for a reason. Push the sequence length from 512 to 4,096 tokens and a run that sat at the bottom of its range can jump to the top, or past it. A budget turns that vague range into a number for your exact model and settings.
What You Will Build #
The project is a small toolkit called vramlab. It fine-tunes a base model to turn messy support tickets into strict JSON, and it spends most of its effort making sure that run fits your GPU. The task is deliberately boring. A synthetic ticket dataset keeps the focus on memory, and it means you need no external data download.
The files, in the order you will create them:
requirements.txtandcheck_env.pypin and verify the software stack.common.pyholds the model , the 4-bit config and the LoRA config, shared by every script.data.pygenerates 800 training rows and 100 validation rows.budget.pypredicts peak VRAM from a model config, with no weights downloaded.probe.pyruns three real training steps on random tokens and records peak memory.sweep.pyprobes a grid of batch size, sequence length and rank, then compares measurements with predictions.fit.pypicks the largest configuration that fits under a headroom limit.train.py,evaluate.pyandexport.pytrain the adapter, score it against the untouched base model, and merge it.
The whole loop takes about 85 minutes on a single 24 GB to 32 GB card, most of it model during the sweep. Budget more time on a slower disk, because every probe reloads the base model from storage.
Prerequisites and Versions #
You need a Linux or Windows machine with an NVIDIA GPU, a working driver, and a Hugging Face account if your chosen base model is gated. The version baseline below comes from the current Hugging Face release notes and CloudMinister’s hardware checklist.
| Component | Version or size | Why it matters |
|---|---|---|
| Transformers | 5.24.1 | Newest version in the official documentation. Requires PEFT 0.22.0 or newer |
| PEFT | 0.22.0 or newer | Provides LoRA and the k-bit preparation helper |
| bitsandbytes | Latest release | Supplies 4-bit NF4 and the paged 8-bit optimizer |
| PyTorch | A build matching your CUDA toolkit | Must support your GPU architecture |
| CUDA | 12.8 or newer on Blackwell cards | Blackwell GPUs need it |
| System RAM | 64 GB or more | Model and paged optimizer state use CPU memory |
| Fast storage | 500 GB to 1 TB of NVMe | Datasets, base models and checkpoints |
For hardware, any 24 GB card handles an 8B-class model with room to experiment. The RTX 5090 is NVIDIA’s current flagship GeForce card. According to NVIDIA’s launch announcement it carries 32 GB of GDDR7 and started at $1,999, and NVIDIA’s user guide reportedly calls for a power supply of at least 1,000 W. No official NVIDIA source guarantees that a particular LLM trains on it, which is exactly why you measure instead of trusting a spec sheet.
Steps 1 to 3: Environment, GPU Check and the Model Gate #
These three steps take about 15 minutes and prevent the most common wasted afternoon: discovering at step nine that your CUDA build or your base model was wrong from the start.
Step 1: Create the project and pin the environment
Make a clean directory and a virtual environment. Install PyTorch first, using the build that matches your CUDA toolkit from the selector on the PyTorch site, because the generic wheel may not include kernels for a new architecture. Then install the rest from a pinned file.
mkdir vramlab && cd vramlab
python3 -m venv .venv
source .venv/bin/activate
cat > requirements.txt <<'EOF'
transformers==5.24.0
peft>=0.22.0
bitsandbytes
accelerate
EOF
pip install -r requirements.txt
huggingface-cli login
Pin Transformers exactly and let PEFT float upward. Transformers 5.24.0 requires PEFT 0.22.0 or newer, so the floor on PEFT is a hard constraint while the ceiling is not. Leave bitsandbytes unpinned for now and record the version you got in your lab notes, since 4-bit kernels change between releases.
Step 2: Verify the GPU and the CUDA stack
Before any model loads, print what Python actually sees. This script is short on purpose. It reports package versions, the CUDA version PyTorch was built against, free and total VRAM, and bf16 support.
import importlib.metadata as md
import torch
for pkg in ["torch", "transformers", "peft", "bitsandbytes", "accelerate"]:
try:
print(f"{pkg:<14}{md.version(pkg)}")
except md.PackageNotFoundError:
print(f"{pkg:<14}MISSING")
print("cuda available:", torch.cuda.is_available())
if torch.cuda.is_available():
props = torch.cuda.get_device_properties(0)
free, total = torch.cuda.mem_get_info()
print("device ", props.name)
print("compute cap ", f"{props.major}.{props.minor}")
print("torch cuda ", torch.version.cuda)
print(f"vram total {total / 1024**3:.2f} GiB")
print(f"vram free {free / 1024**3:.2f} GiB")
print("bf16 support ", torch.cuda.is_bf16_supported())
Run it with python check_env.py. On a healthy 32 GB card the output looks like the sample below. The versions and sizes are illustrative, so compare the shape of the output rather than the exact digits.
torch (your build)
transformers 5.24.0
peft 0.22.0
bitsandbytes (your build)
accelerate (your build)
cuda available: True
device NVIDIA GeForce RTX 5090
compute cap (your value)
torch cuda 12.8
vram total 31.36 GiB
vram free 30.12 GiB
bf16 support True
Two details deserve attention. First, the gap between total and free VRAM tells you what your desktop already consumes. A browser with hardware acceleration and a compositor can eat one to two GiB, which matters when you plan to run at 90 percent of the card. Second, a card marketed as 32 GB reports a little under that in GiB, because the marketing figure is in decimal gigabytes. Always budget in GiB, the unit PyTorch reports.
Step 3: Apply the model selection gate
Not every open-weight checkpoint is a good QLoRA target, and November 2026 released plenty of tempting ones. Run each candidate through six checks before you spend a download on it:
- Repository and license. Confirm the Hugging Face repo is the official one and that the license allows your use.
- Tokenizer. It must load with
AutoTokenizerand ship an end-of-sequence token. - Architecture type. Dense, mixture-of-experts, or multimodal. Each changes the memory math and the adapter targets.
- Library support. The architecture must exist in Transformers 5.24.0 and work with PEFT 0.22.0 or newer.
- Quantization support. bitsandbytes 4-bit must work, or the model must ship in a format you can handle.
- Context length. Long contexts inflate activation and logit memory fast.
Take two real examples. Thinking Machines Lab released Inkling 2 Mini in November 2026, and its model card describes a general-purpose multimodal model that takes text and images and produces text. Public descriptions reportedly characterize it as a looped-transformer mixture-of-experts model with about 26 billion physical parameters and 3 billion active per token. The official checkpoint is a single file of about 20 GB in mixed NVFP4 and MXFP8 precision, and the model page recommends 32 GB or more of VRAM for running it. One third-party write-up warns that the checkpoint may need roughly 53 GB after dequantization on hardware that cannot compute those formats. Unsloth’s release notes say the model supports LoRA and QLoRA, including optional vision-layer tuning, and that route is the one to follow if you want this model specifically.
That model fails two of the six checks for the plain Transformers loop used here. It is multimodal, and its expert layers do not use the gate_proj and up_proj module names that the target list below assumes. The estimator would need a rewrite for it, so treat it as an advanced exercise.
Meta’s latest confirmed Llama release is still the Llama 4 pair of Scout and Maverick from April 5, 2025, per Meta’s announcement, and both are mixture-of-experts models. The same caveat applies. For a first run, pick a dense text-only decoder in the 7B to 8B class. The default in the code below is meta-llama/Llama-3.1-8B, the checkpoint the PEFT documentation itself uses in its examples. It is gated, so accept its license on the model page first. Any dense decoder with the standard Llama-style projection names works if you set the BASE_MODEL environment variable.
Now create the shared . Every later script imports it, which guarantees that the probe, the training run and the evaluation load the model identically. That consistency is the whole point, because a budget only holds if the thing you measured is the thing you train.
import os
import torch
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
BASE_MODEL = os.environ.get("BASE_MODEL", "meta-llama/Llama-3.1-8B")
TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
GIB = 1024 ** 3
def gib(n_bytes):
return n_bytes / GIB
def bnb_config():
return BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
def load_tokenizer():
tok = AutoTokenizer.from_pretrained(BASE_MODEL)
if tok.pad_token is None:
tok.pad_token = tok.eos_token
tok.padding_side = "right"
return tok
def load_base():
return AutoModelForCausalLM.from_pretrained(
BASE_MODEL,
quantization_config=bnb_config(),
dtype=torch.bfloat16,
device_map={"": 0},
)
def load_model(rank, dropout=0.05, checkpointing=True):
model = load_base()
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=checkpointing)
cfg = LoraConfig(
r=rank,
lora_alpha=2 * rank,
lora_dropout=dropout,
target_modules=TARGETS,
bias="none",
task_type="CAUSAL_LM",
)
return get_peft_model(model, cfg)
Three choices in this file shape the memory budget. The 4-bit config enables double quantization, which shaves the quantization constants. The call to prepare_model_for_kbit_training turns on gradient checkpointing and makes the input embeddings require gradients, and depending on your PEFT release it may also upcast the half-precision parameters outside the quantized layers to fp32. Where that happens, the embedding and head memory doubles, a cost you will see in the estimator output shortly. The probe in step 6 reveals whether your release does it. And lora_alpha is set to twice the rank, a common convention that keeps the adapter scale constant as you change rank during the sweep.
Pitfall to watch: if dtype= raises a TypeError, you are on an older Transformers release that still expects torch_dtype=. Upgrade to the pinned version instead of editing the call.
Step 4: Generate a Synthetic Ticket Dataset #
The training data exists to give the run something real to chew on, not to win a benchmark. Each row pairs a messy support ticket with a strict JSON answer holding four fields: category, severity, product and order ID. A script generates 800 training rows and 100 validation rows from fixed templates, with a seeded random generator so every run produces identical files.
import json
import random
random.seed(7)
PRODUCTS = ["router X2", "dock D4", "camera C1", "monitor M27", "keyboard K8", "hub H6"]
CATEGORIES = ["billing", "shipping", "defect", "setup", "refund"]
SEVERITIES = ["low", "medium", "high"]
OPENERS = ["Hi team,", "Hello,", "Urgent:", "Quick question.", "Need help please."]
BODIES = {
"billing": "I was charged twice for my {product} on order {order}.",
"shipping": "My {product} from order {order} has not arrived after two weeks.",
"defect": "The {product} from order {order} stopped working after three days.",
"setup": "I cannot finish the setup of my {product}, order {order}.",
"refund": "Please refund the {product} on order {order}, it was a gift.",
}
SEVERITY_HINT = {"low": "No rush.", "medium": "Please reply this week.", "high": "I need this fixed today."}
def make_row():
cat, sev, prod = random.choice(CATEGORIES), random.choice(SEVERITIES), random.choice(PRODUCTS)
order = f"A{random.randint(10000, 99999)}"
text = " ".join([random.choice(OPENERS), BODIES[cat].format(product=prod, order=order), SEVERITY_HINT[sev]])
target = {"category": cat, "severity": sev, "product": prod, "order_id": order}
prompt = f"### Ticket:\n{text}\n### JSON:\n"
return {"prompt": prompt, "completion": json.dumps(target, separators=(",", ":"))}
def write(path, n):
with open(path, "w") as f:
for _ in range(n):
f.write(json.dumps(make_row()) + "\n")
if __name__ == "__main__":
write("train.jsonl", 800)
write("val.jsonl", 100)
print("wrote train.jsonl (800) and val.jsonl (100)")
Run python data.py and check the first line of train.jsonl. You should see a prompt that ends with ### JSON: and a completion that is one compact JSON object.
{"prompt": "### Ticket:\nHi team, The monitor M27 from order A95319 stopped working after three days. No rush.\n### JSON:\n", "completion": "{\"category\":\"defect\",\"severity\":\"low\",\"product\":\"monitor M27\",\"order_id\":\"A95319\"}"}
The prompt format avoids chat templates on purpose. A plain prefix works with any base model, including ones that ship no template at all, and it removes one variable from the memory comparison. The trade-off is that you must append the end-of-sequence token yourself, which train.py does later.
Notice how short these rows are. A typical ticket plus answer tokenizes to well under 100 tokens, while the sweep will test sequence lengths of 512 to 2,048. That gap is intentional. The collator pads each batch only to its longest member, so real training uses less memory than the budget predicts. You size the budget for the worst case you might ever feed the model, and the typical case then runs with slack. If your real data has long documents, the budget describes your normal case instead.
Step 5: Write the Analytic Budget Estimator #
The estimator reads only the model’s config.json, which weighs a few kilobytes, so you can compare ten candidate models in seconds without down a single weight file. It adds up the nine consumers of VRAM you listed earlier.
import argparse
import json
from transformers import AutoConfig
from common import BASE_MODEL, GIB
NF4_BITS = 4.5 - 0.37
FIXED_OVERHEAD_GIB = 1.2 # CUDA context, cuBLAS workspaces, kernels
def text_config(cfg):
return getattr(cfg, "text_config", None) or cfg
def estimate(cfg, batch, seq, rank, checkpointing=True, upcast_embeddings=True):
cfg = text_config(cfg)
h = cfg.hidden_size
layers = cfg.num_hidden_layers
inter = cfg.intermediate_size
heads = cfg.num_attention_heads
kv_heads = getattr(cfg, "num_key_value_heads", heads)
head_dim = getattr(cfg, "head_dim", None) or h // heads
vocab = cfg.vocab_size
tied = getattr(cfg, "tie_word_embeddings", False)
q_out, kv_out = heads * head_dim, kv_heads * head_dim
proj = [(h, q_out), (h, kv_out), (h, kv_out), (q_out, h), (h, inter), (h, inter), (inter, h)]
linear_params = layers * sum(i * o for i, o in proj)
embed_params = vocab * h * (1 if tied else 2)
norm_params = layers * 2 * h + h
lora_params = layers * sum(rank * (i + o) for i, o in proj)
tokens = batch * seq
per_layer_live = tokens * (h * 10 + inter * 3) * 2
if checkpointing:
activations = layers * tokens * h * 2 + per_layer_live
else:
activations = layers * per_layer_live
parts = {
"quantized_weights": linear_params * NF4_BITS / 8,
"embeddings_and_head": embed_params * (4 if upcast_embeddings else 2),
"norms": norm_params * 4,
"adapter_fp32": lora_params * 4,
"adapter_grads": lora_params * 4,
"optimizer_8bit": lora_params * 2,
"activations": activations,
"logits_fp32": tokens * vocab * 4 * 2,
"fixed_overhead": FIXED_OVERHEAD_GIB * GIB,
}
gib_parts = {k: round(v / GIB, 3) for k, v in parts.items()}
gib_parts["total"] = round(sum(parts.values()) / GIB, 3)
gib_parts["lora_params_m"] = round(lora_params / 1e6, 2)
return gib_parts
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--batch", type=int, default=2)
ap.add_argument("--seq", type=int, default=1024)
ap.add_argument("--rank", type=int, default=16)
ap.add_argument("--no-ckpt", action="store_true")
ap.add_argument("--bf16-embeddings", action="store_true")
args = ap.parse_args()
cfg = AutoConfig.from_pretrained(BASE_MODEL)
out = estimate(cfg, args.batch, args.seq, args.rank,
checkpointing=not args.no_ckpt,
upcast_embeddings=not args.bf16_embeddings)
print(json.dumps({"model": BASE_MODEL, "batch": args.batch, "seq": args.seq,
"rank": args.rank, **out}, indent=2))
if __name__ == "__main__":
main()
Walk through the arithmetic once, because understanding it is what lets you debug the numbers later.
Quantized weights multiply every projection matrix parameter by 4.13 bits, the NF4 cost after double quantization. Embeddings and head stay unquantized, and the estimator assumes the upcast to fp32 by default, which is why the flag --bf16-embeddings exists to test the other case. The adapter adds rank x (in + out) parameters per target projection per layer, stored in fp32 along with an fp32 gradient. The optimizer uses 2 bytes per adapter parameter, which models the 8-bit paged AdamW used in training. Activations with gradient checkpointing store one hidden-state tensor per layer plus the live working set of a single layer. Logits are stored in fp32 and counted twice, once for the raw output and once for the loss computation’s copy.
Run it for an 8B-class dense config, with a hidden size of 4,096, 32 layers, a 14,336-wide feed-forward block, 8 key-value heads and a vocabulary of roughly 128,000 tokens. Your own model prints its own numbers.
python budget.py --batch 2 --seq 1024 --rank 16
{
"model": "meta-llama/Llama-3.1-8B",
"batch": 2,
"seq": 1024,
"rank": 16,
"quantized_weights": 3.356,
"embeddings_and_head": 3.914,
"norms": 0.001,
"adapter_fp32": 0.156,
"adapter_grads": 0.156,
"optimizer_8bit": 0.078,
"activations": 0.82,
"logits_fp32": 1.957,
"fixed_overhead": 1.2,
"total": 11.639,
"lora_params_m": 41.94
}
Every figure is in GiB. Three lines in that output should change how you think about LoRA fine tuning. The embeddings and head cost more than the 4-bit transformer body, 3.9 GiB against 3.4 GiB, because 128,000 vocabulary entries times a 4,096-wide hidden state, twice, is a lot of fp32. The adapter, its gradient and its optimizer together cost under 0.4 GiB, so rank is nearly free at this size. And the logits already cost more than the activations at a batch of 2 and a sequence of 1,024.
The table below shows how the estimate moves across five settings, plus two switches. These are outputs of the script above for the same example config, so they illustrate the shape of the curve rather than any measured run.
| Batch | Sequence | Rank | Logits (GiB) | Estimated total (GiB) |
|---|---|---|---|---|
| 1 | 512 | 8 | Not listed | Not listed |
| 2 | 1,024 | 16 | Not listed | Not listed |
| 4 | 1,024 | 16 | Not listed | Not listed |
| 4 | 2,048 | 16 | Not listed | Not listed |
| 8 | 2,048 | 64 | Not listed | Not listed |
Two switches matter just as much. Turning gradient checkpointing off at batch 2 and sequence 1,024 raises the memory estimate noticeably, which is why load_model defaults it on. Keeping the embeddings in bf16 instead of fp32 lowers the estimate for the same configuration. Whether your PEFT release performs that upcast decides which number is true, and the probe settles the question.
Step 6: Probe the Real Peak Memory #
An estimate is a hypothesis. The probe tests it by running three genuine training steps on random token IDs of exactly the requested shape, then reading PyTorch’s own peak-memory counters. Random tokens make the measurement independent of your dataset, and three steps are enough to warm the allocator, trigger the optimizer’s first state allocation and reach the true peak.
import argparse
import json
import time
import bitsandbytes as bnb
import torch
from common import BASE_MODEL, gib, load_model
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--batch", type=int, required=True)
ap.add_argument("--seq", type=int, required=True)
ap.add_argument("--rank", type=int, required=True)
ap.add_argument("--steps", type=int, default=3)
ap.add_argument("--no-ckpt", action="store_true")
ap.add_argument("--out", default="probes.jsonl")
args = ap.parse_args()
record = {"model": BASE_MODEL, "batch": args.batch, "seq": args.seq, "rank": args.rank,
"ckpt": not args.no_ckpt, "status": "ok"}
torch.cuda.reset_peak_memory_stats()
try:
model = load_model(args.rank, checkpointing=not args.no_ckpt)
record["load_gib"] = round(gib(torch.cuda.max_memory_allocated()), 3)
model.train()
params = [p for p in model.parameters() if p.requires_grad]
opt = bnb.optim.PagedAdamW8bit(params, lr=1e-4)
vocab = model.config.get_text_config().vocab_size
start = time.time()
for _ in range(args.steps):
ids = torch.randint(0, vocab, (args.batch, args.seq), device="cuda")
loss = model(input_ids=ids, labels=ids).loss
loss.backward()
opt.step()
opt.zero_grad(set_to_none=True)
torch.cuda.synchronize()
record["sec_per_step"] = round((time.time() - start) / args.steps, 3)
except torch.cuda.OutOfMemoryError:
record["status"] = "oom"
record["peak_alloc_gib"] = round(gib(torch.cuda.max_memory_allocated()), 3)
record["peak_reserved_gib"] = round(gib(torch.cuda.max_memory_reserved()), 3)
record["device_total_gib"] = round(gib(torch.cuda.get_device_properties(0).total_memory), 3)
with open(args.out, "a") as f:
f.write(json.dumps(record) + "\n")
print(json.dumps(record))
if __name__ == "__main__":
main()
The script records two peaks on purpose. Peak allocated is memory held by live tensors and is the number to compare with the estimator. Peak reserved is what PyTorch’s caching allocator grabbed from the driver, including fragmentation, and it is the number that decides whether you hit an out-of-memory error. The gap between them is usually a few percent but can balloon with variable sequence lengths.
Run a single probe to confirm the loop works:
python probe.py --batch 2 --seq 1024 --rank 16
{"model": "meta-llama/Llama-3.1-8B", "batch": 2, "seq": 1024, "rank": 16, "ckpt": true, "status": "ok", "load_gib": 8.1, "sec_per_step": 1.4, "peak_alloc_gib": 11.9, "peak_reserved_gib": 12.6, "device_total_gib": 31.36}
Those values are an illustration of the output format, not a measurement you should expect to reproduce. What you should look for in your own run is the relationship between load_gib and the estimator. Right after , the card should hold roughly the quantized weights, the embeddings and head, the norms and the fresh adapter, so compare load_gib with the estimator’s figure for your config. If your load_gib lands near 5.5 GiB instead, your PEFT release is not upcasting the embeddings, and you should rerun the estimator with --bf16-embeddings.
The probe catches torch.cuda.OutOfMemoryError and records the status as oom instead of crashing. That detail matters in the next step, because a sweep that dies on its first impossible configuration tells you nothing about the possible ones.
Steps 7 and 8: Sweep the Grid and Calibrate the Estimator #
One probe tells you about one configuration. A sweep tells you where the cliff is. The script below runs the probe in a fresh subprocess for every combination of batch size, sequence length and rank, so an out-of-memory crash can never poison the next run with a fragmented allocator. It also skips larger batches once a smaller one has already failed at the same sequence length and rank, which prunes the grid hard.
import itertools
import json
import statistics
import subprocess
import sys
from transformers import AutoConfig
from budget import estimate
from common import BASE_MODEL
BATCHES = [1, 2, 4, 8]
SEQS = [512, 1024, 2048]
RANKS = [8, 16, 64]
OUT = "probes.jsonl"
def run_probe(batch, seq, rank):
cmd = [sys.executable, "probe.py", "--batch", str(batch), "--seq", str(seq),
"--rank", str(rank), "--out", OUT]
subprocess.run(cmd, check=False, capture_output=True, text=True)
def main():
open(OUT, "w").close()
oom_at = {}
for seq, rank, batch in itertools.product(SEQS, RANKS, BATCHES):
if oom_at.get((seq, rank), 10 ** 9) <= batch:
continue
run_probe(batch, seq, rank)
last = json.loads(open(OUT).read().strip().splitlines()[-1])
if last["status"] == "oom":
oom_at[(seq, rank)] = batch
cfg = AutoConfig.from_pretrained(BASE_MODEL)
rows, ratios = [], []
for line in open(OUT):
r = json.loads(line)
est = estimate(cfg, r["batch"], r["seq"], r["rank"], r["ckpt"])["total"]
r["estimate_gib"] = est
if r["status"] == "ok":
r["ratio"] = round(r["peak_alloc_gib"] / est, 3)
ratios.append(r["ratio"])
rows.append(r)
print("batch seq rank status estimate peak_alloc ratio")
for r in rows:
print(f'{r["batch"]:>5} {r["seq"]:>5} {r["rank"]:>5} {r["status"]:<6} '
f'{r["estimate_gib"]:>8.2f} {r["peak_alloc_gib"]:>10.2f} {r.get("ratio", "-")}')
if ratios:
calib = {"median_ratio": round(statistics.median(ratios), 3),
"min_ratio": min(ratios), "max_ratio": max(ratios), "n": len(ratios)}
json.dump(calib, open("calibration.json", "w"), indent=2)
print("calibration:", calib)
if __name__ == "__main__":
main()
Step 7: Run the sweep
Start it and leave it alone. Every probe reloads the base model, so the grid of 4 batch sizes, 3 sequence lengths and 3 ranks (36 combinations at most) is dominated by load time rather than compute.
python sweep.py
The final table pairs each estimate with its measurement. The rows below show the format with illustrative values, abbreviated to five configurations.
batch seq rank status estimate peak_alloc ratio
1 512 8 ok 9.36 9.10 0.972
2 1024 16 ok 11.64 11.90 1.022
4 1024 16 ok 14.42 14.90 1.033
4 2048 16 ok 19.97 20.60 1.032
8 2048 64 oom 32.25 31.20 -
calibration: {'median_ratio': 1.027, 'min_ratio': 0.972, 'max_ratio': 1.033, 'n': 4}
Read the failure row carefully. The estimator said the configuration would not fit on the card, and the probe confirmed an out-of-memory error. That is the estimator doing its job: it flagged a configuration as impossible before you wasted a training run on it. The recorded peak is simply where the allocator gave up.
Step 8: Calibrate and extrapolate
The ratio column is the real product of the sweep. A median near 1.0 with a narrow spread means your accounting is sound. Save that median and use it to check configurations you did not probe, such as a 4,096-token sequence that would take another ten minutes to measure. The script below applies the calibration to any new shape.
import argparse
import json
from transformers import AutoConfig
from budget import estimate
from common import BASE_MODEL
ap = argparse.ArgumentParser()
ap.add_argument("--batch", type=int, required=True)
ap.add_argument("--seq", type=int, required=True)
ap.add_argument("--rank", type=int, required=True)
ap.add_argument("--headroom", type=float, default=0.90)
ap.add_argument("--device-gib", type=float, required=True)
args = ap.parse_args()
ratio = json.load(open("calibration.json"))["median_ratio"]
raw = estimate(AutoConfig.from_pretrained(BASE_MODEL), args.batch, args.seq, args.rank)["total"]
calibrated = raw * ratio
limit = args.headroom * args.device_gib
print(f"raw estimate {raw:.2f} GiB")
print(f"calibrated (x{ratio}) {calibrated:.2f} GiB")
print(f"limit {limit:.2f} GiB")
print("verdict ", "fits" if calibrated <= limit else "does not fit")
python predict.py --batch 2 --seq 4096 --rank 16 --device-gib 31.36
raw estimate 19.97 GiB
calibrated (x1.027) 20.51 GiB
limit 28.22 GiB
verdict fits
Treat predictions that sit more than one batch step beyond your probed region with suspicion. The estimator is linear in batch and sequence length, but real kernels switch strategies as shapes grow, so verify the final choice with one real probe. A wide spread in the ratio column, say from 0.8 to 1.3, signals a modeling error rather than noise. The usual culprits are tied embeddings, a missing upcast flag, or an architecture whose attention memory does not follow the formula.
Step 9: Fit the Largest Safe Configuration #
Now turn measurements into a decision. fit.py reads every successful probe, discards any whose peak reserved memory exceeds a headroom fraction of the card, and picks the survivor with the longest sequence, then the highest rank, then the largest micro-batch. It then computes the gradient accumulation steps needed to reach an effective batch of 16.
import argparse
import json
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--probes", default="probes.jsonl")
ap.add_argument("--headroom", type=float, default=0.90)
ap.add_argument("--effective-batch", type=int, default=16)
ap.add_argument("--min-rank", type=int, default=16)
args = ap.parse_args()
rows = [json.loads(line) for line in open(args.probes)]
ok = [r for r in rows if r["status"] == "ok"]
if not ok:
raise SystemExit("no successful probe: lower BATCHES, SEQS or RANKS in sweep.py")
budget = args.headroom * ok[0]["device_total_gib"]
fits = [r for r in ok if r["peak_reserved_gib"] <= budget and r["rank"] >= args.min_rank]
if not fits:
raise SystemExit(f"nothing fits {budget:.1f} GiB with rank >= {args.min_rank}")
best = max(fits, key=lambda r: (r["seq"], r["rank"], r["batch"]))
micro = best["batch"]
accum = max(1, args.effective_batch // micro)
pick = {"micro_batch": micro, "grad_accum": accum, "seq": best["seq"], "rank": best["rank"],
"peak_reserved_gib": best["peak_reserved_gib"], "budget_gib": round(budget, 2)}
json.dump(pick, open("best.json", "w"), indent=2)
print(json.dumps(pick, indent=2))
if __name__ == "__main__":
main()
python fit.py --headroom 0.90 --effective-batch 16
{
"micro_batch": 4,
"grad_accum": 4,
"seq": 2048,
"rank": 64,
"peak_reserved_gib": 22.9,
"budget_gib": 28.22
}
The 90 percent headroom is the setting people argue about. It leaves roughly 3 GiB free on a 32 GB card. That buffer absorbs allocator fragmentation, a desktop session that grows, and the occasional batch whose longest sequence is longer than the probe assumed. Drop it lower on a shared workstation. Raise it to 95 percent only on a headless server with nothing else on the GPU.
An effective batch of 16 to 32 through gradient accumulation is the range CloudMinister recommends for QLoRA runs, and it costs no extra VRAM because accumulation reuses the same micro-batch memory. That is why the script trades micro-batch size for accumulation steps instead of chasing the biggest micro-batch it can fit. If you want to change the priority order, edit the key in the max call. Prefer batch over sequence length if your real data is short, because longer padded sequences waste compute without helping. Once the budget says a high rank fits, the next question is whether it helps quality, and the site’s LoRA rank sweep tutorial measures exactly that.
Steps 10 and 11: Train, Then Prove the Adapter Helps #
Step 10: Train with the fitted configuration
The training script reads best.json, so the budget you just built drives the run directly. It tokenizes prompt and completion separately, masks the prompt tokens with -100 so the loss only covers the JSON answer, appends the end-of-sequence token, and pads each batch dynamically. A small callback adds the peak reserved memory to every log line, so you can watch the budget hold in real time.
import json
import torch
from torch.utils.data import Dataset
from transformers import Trainer, TrainerCallback, TrainingArguments
from common import gib, load_model, load_tokenizer
best = json.load(open("best.json"))
tok = load_tokenizer()
class TicketData(Dataset):
def __init__(self, path, max_len):
self.rows = []
for line in open(path):
r = json.loads(line)
p_ids = tok(r["prompt"], add_special_tokens=True)["input_ids"]
c_ids = tok(r["completion"], add_special_tokens=False)["input_ids"] + [tok.eos_token_id]
ids = (p_ids + c_ids)[:max_len]
labels = ([-100] * len(p_ids) + c_ids)[:max_len]
self.rows.append((ids, labels))
def __len__(self):
return len(self.rows)
def __getitem__(self, i):
return self.rows[i]
def collate(batch):
width = max(len(ids) for ids, _ in batch)
ids = torch.full((len(batch), width), tok.pad_token_id, dtype=torch.long)
lab = torch.full((len(batch), width), -100, dtype=torch.long)
mask = torch.zeros((len(batch), width), dtype=torch.long)
for i, (a, b) in enumerate(batch):
ids[i, :len(a)] = torch.tensor(a)
lab[i, :len(b)] = torch.tensor(b)
mask[i, :len(a)] = 1
return {"input_ids": ids, "labels": lab, "attention_mask": mask}
class PeakMemory(TrainerCallback):
def on_log(self, args, state, control, logs=None, **kw):
if logs is not None:
logs["peak_gib"] = round(gib(torch.cuda.max_memory_reserved()), 2)
model = load_model(best["rank"])
model.print_trainable_parameters()
args = TrainingArguments(
output_dir="runs",
per_device_train_batch_size=best["micro_batch"],
gradient_accumulation_steps=best["grad_accum"],
num_train_epochs=2,
learning_rate=2e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.03,
max_grad_norm=0.3,
optim="paged_adamw_8bit",
bf16=True,
logging_steps=5,
save_strategy="no",
report_to="none",
remove_unused_columns=False,
gradient_checkpointing=False,
)
trainer = Trainer(model=model, args=args, train_dataset=TicketData("train.jsonl", best["seq"]),
data_collator=collate, callbacks=[PeakMemory()])
trainer.train()
model.save_pretrained("adapter")
tok.save_pretrained("adapter")
print("final peak reserved GiB:", round(gib(torch.cuda.max_memory_reserved()), 2))
Several settings follow published guidance. The max gradient norm of 0.3 matches the QLoRA paper’s value as quoted by CloudMinister. LoRA dropout of 0.05 sits at the low end of the 0.05 to 0.1 range that CloudMinister suggests for small datasets. The optimizer is the paged 8-bit AdamW, the same one the probe measured. And gradient_checkpointing=False in the arguments is correct, because prepare_model_for_kbit_training already switched checkpointing on. Enabling it twice adds nothing and muddies the setup.
python train.py
trainable params: 167,772,160 || trainable%: (small fraction of total)
{'loss': 2.31, 'grad_norm': 0.9, 'learning_rate': 0.0002, 'epoch': 0.1, 'peak_gib': 22.9}
{'loss': 0.42, 'grad_norm': 0.5, 'learning_rate': 0.00019, 'epoch': 0.5, 'peak_gib': 22.9}
{'loss': 0.03, 'grad_norm': 0.2, 'learning_rate': 0.00011, 'epoch': 1.5, 'peak_gib': 22.9}
final peak reserved GiB: 22.9
The loss values are illustrative. What counts is the peak_gib column. It should sit flat at or slightly below the number fit.py printed, because the probe used the worst-case sequence length. If it creeps upward across logs, you have a memory leak or an unusually long example, and the troubleshooting section covers both. With 800 rows, an effective batch of 16 and 2 epochs, the run takes 100 optimizer steps.
Step 11: Evaluate against the untouched base model
Training loss proves the adapter learned something. Evaluation proves it learned the right thing. The script loads the adapter, generates greedy completions for all 100 validation tickets, and scores three numbers: the share of outputs that parse as JSON, the share of individual fields that match, and the share of rows where all four fields match. Then it disables the adapter with PEFT’s context manager and repeats the run on the plain base model, so you get a same-hardware, same-prompt baseline in one pass.
import json
import torch
from peft import PeftModel
from common import gib, load_base, load_tokenizer
tok = load_tokenizer()
tok.padding_side = "left"
model = PeftModel.from_pretrained(load_base(), "adapter")
model.eval()
rows = [json.loads(line) for line in open("val.jsonl")]
FIELDS = ["category", "severity", "product", "order_id"]
def generate(prompts):
enc = tok(prompts, return_tensors="pt", padding=True).to("cuda")
with torch.no_grad():
out = model.generate(**enc, max_new_tokens=80, do_sample=False, pad_token_id=tok.pad_token_id)
texts = tok.batch_decode(out[:, enc["input_ids"].shape[1]:], skip_special_tokens=True)
return [t.strip().split("\n")[0] for t in texts]
def score(preds):
valid, field_hits, exact = 0, 0, 0
for pred, row in zip(preds, rows):
gold = json.loads(row["completion"])
try:
obj = json.loads(pred)
except json.JSONDecodeError:
continue
valid += 1
hits = sum(obj.get(k) == gold[k] for k in FIELDS)
field_hits += hits
exact += hits == len(FIELDS)
n = len(rows)
return {"valid_json": valid / n, "field_accuracy": field_hits / (n * len(FIELDS)), "exact_match": exact / n}
def run():
preds = []
for i in range(0, len(rows), 16):
preds += generate([r["prompt"] for r in rows[i:i + 16]])
return score(preds)
tuned = run()
with model.disable_adapter():
base = run()
print("base :", json.dumps(base))
print("tuned :", json.dumps(tuned))
print("inference peak GiB:", round(gib(torch.cuda.max_memory_reserved()), 2))
python evaluate.py
base : {"valid_json": 0.31, "field_accuracy": 0.22, "exact_match": 0.0}
tuned : {"valid_json": 1.0, "field_accuracy": 0.99, "exact_match": 0.96}
inference peak GiB: 9.4
These numbers are illustrative of the pattern, and the tuned scores will be near the ceiling on any synthetic task this regular. They say nothing about how the method performs on your messy real data, so replace data.py with real labeled examples before drawing conclusions. The inference peak, by contrast, is a number worth keeping. It shows that serving the adapter on a 4-bit base takes a fraction of the training peak, because gradients, optimizer state and saved activations are gone.
Step 12: Merge the Adapter and Re-Check the Budget #
An adapter is a small file that only works next to its base model. Merging bakes the low-rank update into the base weights and produces a standalone checkpoint that any runtime can load.
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM
from common import BASE_MODEL, load_tokenizer
base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.bfloat16, device_map={"": "cpu"})
merged = PeftModel.from_pretrained(base, "adapter").merge_and_unload()
merged.save_pretrained("merged", safe_serialization=True)
load_tokenizer().save_pretrained("merged")
print("saved merged bf16 model to ./merged")
The script loads the base model in bf16 on the CPU, which costs roughly two bytes per parameter in system RAM, so an 8B model wants about 16 GB plus working space. That is the real reason the prerequisites list 64 GB of RAM. The merge itself needs no GPU.
One subtlety deserves a test rather than a leap of faith. You trained the adapter against NF4-dequantized weights, and you are merging it into the original bf16 weights. The two differ slightly, so the merged model can behave a little differently from the adapter-on-4-bit version you evaluated. Point evaluate.py at the merged directory, or serve it and rerun your validation set, before you ship it. If the scores drop noticeably, keep serving the adapter on the quantized base instead of merging.
Seven Common Pitfalls in LoRA Fine-Tuning #
Each of these has wasted a rented GPU hour somewhere. The budget workflow catches most of them, but only if you know what the numbers are warning about.
- Reading marketing gigabytes as GiB. A card sold as 32 GB exposes a little under 32 GiB to PyTorch, and your desktop takes a slice before your script starts. Budget against the
vram totalandvram freelines fromcheck_env.py, never against the box. - Ignoring the logits tensor. At a 128,000-token vocabulary, the fp32 logits for a batch of 8 at 2,048 tokens cost more than 15 GiB in the estimator above, nearly half of that configuration’s total. People shrink the rank to save memory and never touch the real culprit. Cut the batch or the sequence length first.
- Budgeting for the average sequence. Memory peaks on the longest batch, not the typical one. A run that holds 14 GiB for six hours can die at hour seven when one long document arrives. Size the budget for the maximum length you truncate to.
- Comparing against allocated memory when deciding if it fits. Allocated memory excludes the allocator’s cached blocks and fragmentation. Peak reserved is the number the driver enforces, so
fit.pyfilters on it. - Running the sweep in one process. After an out-of-memory error the caching allocator can hold fragmented blocks, which makes the next probe look worse than it is. Subprocess isolation costs a model reload per probe and buys honest measurements.
- Training on the prompt. Without label masking, the model spends capacity learning to reproduce the ticket text instead of the JSON. Loss looks great and the output is mediocre. The
-100labels on the prompt tokens intrain.pyprevent it. - Merging without re-evaluating. The adapter learned against dequantized 4-bit weights. Merging it into bf16 weights shifts the result slightly. Always rerun the validation set on the merged model before you replace anything in production.
Troubleshooting: 10 Failures and Their Fixes #
Work through these in order. The first four cover memory, the next three cover installation and numerics, and the last three cover behavior.
- Out of memory while the model. Training has not started, so the culprit is the load. Check
nvidia-smifor other processes holding VRAM, confirm the 4-bit config is actually passed tofrom_pretrained, and make suredevice_map={"": 0}keeps the whole model on one GPU. A model loaded in bf16 by mistake needs about four times the memory of its 4-bit form. - Out of memory on the first backward pass. The forward pass fit but the backward did not. The usual suspect is the logits tensor and the loss computation on top of it. Halve the batch size before touching anything else, then shorten the sequence length.
- Out of memory after hundreds of steps. One long example or fragmentation crossed the line. Set the environment variable
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:Truebefore launching, lower the headroom setting infit.py, and truncate inputs at the length you budgeted for. - The estimate is far from the measurement. A ratio outside 0.8 to 1.3 means the model differs from the formula. Check
tie_word_embeddingsin the config, rerun with--bf16-embeddingsto test the upcast theory, and remember that mixture-of-experts and multimodal checkpoints need their own accounting. - TypeError on
dtype. You are running a Transformers release older than the pinned 5.24.0, where the argument was still calledtorch_dtype. Upgrade withpip install -r requirements.txtrather than editing the . - bitsandbytes cannot find CUDA or fails on a new GPU. Confirm that PyTorch reports CUDA 12.8 or newer on Blackwell cards, then reinstall the latest bitsandbytes. Running
python -m bitsandbytesprints a diagnostic that names the missing library. - Loss turns to NaN. The learning rate is too high for your rank, or the GPU lacks bf16 support. Drop the rate from 2e-4 to 1e-4, keep the gradient clip at 0.3, and check the
bf16 supportline from the environment script. - Loss never moves. Print one batch of labels. If every value is -100, truncation cut the completion off, so raise the sequence length or shorten the prompt. A prompt-heavy dataset with a tiny
max_lenproduces exactly this. - Generation never stops or repeats the JSON. The end-of-sequence token is missing from training labels. Confirm
train.pyappendstok.eos_token_idto the completion and thatevaluate.pysplits on the first newline, as written. ValueError: Target modules not found. Your architecture names its projections differently. Print[n for n, _ in model.named_modules()], find the linear layer names, and editTARGETSincommon.py.
If a sweep crawls, the cause is almost always disk. Every probe reloads the base model from the Hugging Face cache, so keep that cache on NVMe, and set HF_HUB_OFFLINE=1 once the model is downloaded to stop pointless network checks.
Advanced Tips for Squeezing More Out of One GPU #
Once the baseline works, a handful of changes move the budget in your favor. Each one trades something, so measure with the probe before you adopt it.
| Knob | Memory grows with | What lowering it costs |
|---|---|---|
| Batch size | Activations and logits, linearly | More accumulation steps, slower wall time |
| Sequence length | Activations and logits, linearly | Truncated or chunked training examples |
| LoRA rank | Adapter, gradients and optimizer state | Less adapter capacity |
| Target modules | Adapter size | Fewer layers can adapt |
| Gradient checkpointing | Stored activations | About one extra forward pass of compute |
| Vocabulary size | Logits and embeddings | Fixed by the model, so choose the model |
Beyond the table, five ideas are worth trying.
Compute the loss only where it matters. For short completions inside long prompts, slice the hidden states to the label positions before the output head. The logits then cover a few dozen tokens per row instead of the whole sequence, which erases the largest term in the budget. It needs a custom forward wrapper, so test it carefully against the standard loss.
Try LoRA+. The PEFT documentation describes LoRA+, which uses different learning rates for the A and B adapter matrices and is reported to increase fine-tuning speed by up to 2x and performance by 1 to 2 percent. It adds no memory.
Let PEFT redistribute rank. The PEFT docs also describe EVA, which allocates rank unevenly across layers, with the maximum for a layer set to the base rank times a factor that defaults to 2.0. The documentation notes a small initialization overhead of typically one to two minutes for 64 batches, so budget that into short runs.
Go multi-GPU only when you must. PEFT’s tensor-parallel support for LoRA requires Transformers 5.4.0 or newer, and the DTensor-based API needs PEFT 0.21.1 or newer with Transformers 5.17.0 or newer. The pinned versions in this project satisfy both, but sharding adds communication cost and debugging complexity that a single 32 GB card avoids.
Treat the new models as a separate project. The newest releases, Inkling 2 Mini among them, arrive with their own fine-tuning recipes. Unsloth’s v0.1.925-beta release reportedly added Inkling fine-tuning support, and a third-party guide reports batch size 1, gradient accumulation of 4 and an 8-bit AdamW with rank 16 on attention and routed-expert targets. Adapt the estimator to the model’s real layer shapes first, then rerun the sweep.
Rent or Buy: What the Budget Costs in Dollars #
The sweep is cheap enough to run on rented hardware before you commit to buying anything. One report dated November 16, 2026 lists Lambda’s self-serve rates at $1.09 an hour for an A6000, $3.79 for an H100 PCIe and $7.99 for a B200 SXM6. Treat those as a secondary-source snapshot, since the official pricing pages were not retrieved for confirmation. To estimate your own cost, multiply the hourly rate by the time your sweep takes, and remember that storage and idle time add to it.
If you plan to buy, the RTX 5090’s $1,999 launch price from NVIDIA’s January 2025 announcement is the only official figure on record, and street prices may differ. Buying also adds the power supply, the rest of the PC and electricity, while renting only costs the hourly rate. The two cards differ, so treat any comparison as a rough guide that favors renting for occasional fine-tuning and buying for daily use.
Rented servers add one more habit. CloudMinister suggests an idle alert that fires when GPU utilization stays below 5 percent for 15 minutes, with the server stopped when it triggers. A forgotten box costs more than any tuning mistake. For wider context on model sizes and where this workflow fits, the site’s AI and machine learning section tracks the open-weight releases that keep changing these budgets.
Frequently Asked Questions #
How much VRAM does LoRA fine tuning need?
It depends on the model size, the sequence length and the batch size. CloudMinister’s practical QLoRA ranges are 12 to 16 GB for a 7B model, 16 to 24 GB for 13B, 24 to 48 GB for 33B and 48 to 80 GB for 70B. The estimator built above turns those ranges into a number for your exact setup, and the probe confirms it.
What is the difference between LoRA and QLoRA?
LoRA trains small adapter matrices while the pretrained weights stay frozen. QLoRA applies the same adapter method but stores the frozen base model in 4-bit form, typically NF4 with double quantization and paged optimizers. That quantization is what lets bigger models fit on one card.
Can I fine-tune a model on a single RTX 5090?
An 8B-class dense model fits comfortably in the example numbers above, with room for longer sequences. No official NVIDIA source promises that any particular model trains on the card, so run the probe. Larger and multimodal models need their own checks.
Why does my estimate differ from the measured memory?
Usual causes are tied embeddings, an fp32 upcast of the embeddings that your PEFT release does or does not perform, and architectures such as mixture-of-experts whose layers do not follow the dense formula. Rerun the sweep, read the ratio column and fix the formula until the spread narrows.
Should I merge the adapter or keep it separate?
Keep it separate if you serve several adapters on one base model or if the merged scores drop. Merge it if you need a standalone checkpoint for a runtime that does not support adapters. Evaluate after merging either way.
Is the synthetic ticket task realistic?
No, and it is not meant to be. It is regular enough that the tuned model scores near the ceiling, which isolates the memory behavior. Swap in your own labeled data before judging quality.
What changed with the newest open-weight models?
Thinking Machines Lab released the open-weight Inkling 2 Mini in November 2026. It is multimodal, uses a mixture-of-experts design and ships in mixed NVFP4 and MXFP8 precision, so a plain dense QLoRA loop does not apply to it directly. Meta’s last confirmed Llama release, per its own announcement, remains the April 2025 Llama 4 generation. For a first run on one GPU, a dense 7B to 8B model remains the practical choice.