AI

How to Fine Tune an LLM: A Step-by-Step Guide

How to fine tune an LLM: decide if you need it, prepare data, pick LoRA or QLoRA, train with Hugging Face TRL, evaluate and deploy. With memory math.

By OmniAI Editorial · Nov 21, 2026 · 14 min read

Here is how to fine tune an LLM in one sentence: you take a pre-trained open model, prepare a few hundred to a few thousand examples of the inputs and outputs you want, and continue training the model on them, usually with a parameter-efficient method such as LoRA or QLoRA so it fits on a single GPU. The workflow is: decide whether fine-tuning is the right tool, pick a base model, format your data, train with a library such as Hugging Face TRL, evaluate against the original model, and deploy the result. Fine-tuning changes how a model behaves (its format, tone, and skill at a narrow task); it's not the best way to teach it new facts.

This guide covers how to fine tune an LLM end to end: when it's worth it, how to prepare custom data, how much GPU memory each method needs (with a worked example), the training code, evaluation, deployment, cost and common mistakes. One recent change matters before you start: OpenAI is winding down its fine-tuning platform, so most new projects fine-tune open models.

Should You Fine-Tune at All?

Fine-tuning is powerful, but it's often not the first tool to reach for. Most problems that look like "the model doesn't know enough" are better solved by giving it the right information at run time. Use this table to decide:

Your problemBest first toolWhy
The model doesn't know your documents, products or recent factsRetrieval (RAG)Facts change; retrieval keeps answers current and cites sources
Output format or tone is inconsistentBetter prompts, then fine-tuningPrompts fix most cases; fine-tuning makes it reliable at scale
A narrow task (classification, extraction, routing) needs high accuracyFine-tuningSmall fine-tuned models can match much larger general ones
You need a smaller, cheaper or faster model for one jobFine-tuning (often with distillation)Shorter prompts and a small model cut cost and latency
The model refuses or misunderstands domain-specific instructionsFew-shot prompting, then fine-tuningExamples in the prompt often fix it without training
You want the model to follow a long, fixed style guideFine-tuningSaves sending the guide in every prompt

OpenAI's own guidance is a useful rule: set up evaluations first, and only invest in fine-tuning once you can measure whether the fine-tuned model actually beats the base model. Our comparison of fine-tuning vs RAG goes deeper on that choice.

How Fine-Tuning Works

A pre-trained LLM has learned general language from huge amounts of text. Fine-tuning continues training on a much smaller, focused dataset, nudging the model's weights so it produces outputs more like your examples. The most common form is supervised fine-tuning (SFT): you show the model prompts paired with the ideal responses, and it learns to produce those responses.

There are three main ways to do it:

  • Full fine-tuning updates every weight in the model. It gives the most flexibility but needs the most memory, often several GPUs for models above a few billion parameters.
  • LoRA (low-rank adaptation) freezes the original weights and trains small extra matrices ("adapters") inserted into the model. The LoRA paper reports that, compared with full fine-tuning of GPT-3 175B with Adam, LoRA cut the number of trainable parameters by 10,000 times and GPU memory by 3 times.
  • QLoRA loads the frozen base model in 4-bit precision and trains LoRA adapters on top. The QLoRA paper showed it could fine-tune a 65-billion-parameter model on a single 48 GB GPU while keeping the quality of 16-bit fine-tuning.

Our guide to LoRA vs QLoRA compares the two adapter methods in detail.

Five circles on an ink line, alternating grey and light, with the larger middle circle orange.
Fine-tuning runs in steps; training is only one of them.

Step 1: Pick a Base Model

Choose the base model before you prepare data, because its chat template and size shape everything else.

  • Start from an instruction-tuned ("instruct" or "chat") version if you want a conversational or instruction-following model. Base models without instruction tuning need far more data.
  • Pick the smallest model that could work. A 1–8 billion parameter model fine-tuned on a narrow task often beats a much larger general model on that task, and it's cheaper to train and serve.
  • Check the license. Open-weight models come with different licenses; some restrict commercial use or require attribution.
  • Check language and domain coverage. If your data is in Turkish or full of code, test the base model on a few samples first.

Step 2: Prepare Your Data (Fine-Tune LLM With Custom Data)

Data quality decides the result more than any training setting. To fine tune llm with custom data, turn your material into examples of exactly the behavior you want.

Most libraries expect a conversational format with a list of messages per example, stored as JSON Lines (one example per line). This is the format Hugging Face TRL documents for conversational datasets:

{"messages": [{"role": "system", "content": "You are a support assistant for Acme. Answer in two sentences."}, {"role": "user", "content": "How do I reset my password?"}, {"role": "assistant", "content": "Go to Settings, then Security, and choose Reset password. You'll get an email with a link that works for 30 minutes."}]}

Guidelines that hold across tools:

  • Show the exact output you want, including format, length and tone. The model copies what it sees.
  • Cover the real variety of inputs: short and long questions, typos, edge cases and requests the model should decline.
  • Start with a few hundred good examples. OpenAI's platform required at least 10 examples, but that's a technical minimum; noticeable improvements usually need far more. Quality beats quantity: 500 clean examples often outperform 5,000 noisy ones.
  • Hold out 10–20% for evaluation, and never train on it.
  • Remove personal data and secrets before training; a fine-tuned model can repeat what it was trained on.

What about PDFs and documents? A common request is to fine tune on a PDF. Raw document text teaches the model style, not reliable recall of facts. If you want the model to answer questions about documents, use retrieval instead, or convert the documents into question-and-answer pairs and combine fine-tuning with retrieval. Fine-tuning alone is a poor way to store facts that must be exactly right.

Step 3: Estimate GPU Memory (Worked Example)

Before renting or buying hardware, estimate memory. Hugging Face's documentation on model memory gives the building blocks for full training with mixed precision and the AdamW optimizer: 6 bytes per parameter for weights (a 16-bit copy plus a 32-bit main copy), 8 bytes for optimizer states and 4 bytes for gradients, which adds up to about 18 bytes per parameter before activations.

Here's what that means for an 8-billion-parameter model:

MethodWhat's in GPU memoryRough memory for an 8B model
Full fine-tuning (mixed precision, AdamW)~18 bytes per parameter + activations~144 GB plus activations: several data-center GPUs
LoRA (base in 16-bit, small adapters trained)~2 bytes per parameter for frozen weights + adapters, their optimizer states + activations~16 GB for weights plus a few GB more: a 24 GB GPU with small batches
QLoRA (base in 4-bit)~0.5 bytes per parameter + adapters + activations~4–5 GB for weights plus overhead: a 12–16 GB GPU

Activations grow with batch size and sequence length, which is why a model that "fits" can still run out of memory with long examples. Gradient checkpointing, smaller batches with gradient accumulation, and shorter maximum sequence lengths are the usual fixes. For choosing hardware, see our guide to the best GPU for LLMs.

Three bars on an ink baseline: a tall grey bar, a medium light bar and a short orange bar.
Full fine-tuning needs the most GPU memory, LoRA far less, and QLoRA the least.

Step 4: How to Fine Tune an LLM With LoRA in Hugging Face TRL

To fine tune an LLM with LoRA in code, Hugging Face's TRL library has an SFTTrainer that handles chat templates, tokenization and training, and it integrates with the PEFT library for LoRA. The minimal pattern below follows TRL's documentation; it loads your JSON Lines file and trains a LoRA adapter on a small Qwen model:

from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

dataset = load_dataset("json", data_files="train.jsonl", split="train")

trainer = SFTTrainer(
    model="Qwen/Qwen3-0.6B",
    train_dataset=dataset,
    args=SFTConfig(output_dir="my-finetune", learning_rate=1e-4),
    peft_config=LoraConfig(r=16, lora_alpha=16, target_modules="all-linear"),
)
trainer.train()

A few notes on the settings, from the TRL and PEFT documentation:

  • Learning rate: TRL's default for SFTConfig is 2e-5, which suits full fine-tuning. When training adapters, TRL suggests a higher rate of about 1e-4, because only the new parameters are learning.
  • `r` (rank): the size of the LoRA matrices. A higher rank gives the adapter more capacity and more parameters to train; 8 to 16 is a common starting range.
  • `lora_alpha`: a scaling factor, often set equal to r or twice it.
  • `target_modules="all-linear"`: applies LoRA to all linear layers, as in the QLoRA paper, instead of listing layer names that differ between architectures.
  • Train only on answers: with a conversational dataset you can set assistant_only_loss=True in SFTConfig, so the loss is computed only on the assistant's replies, not on the user's questions.

For QLoRA, you load the base model in 4-bit with the bitsandbytes integration in Transformers and pass it to the trainer; the rest stays the same. Tools such as Unsloth (which TRL integrates with), Axolotl and LLaMA-Factory wrap these steps with config files and memory optimizations if you'd rather not write code.

How to Fine Tune an LLM Locally

To learn how to fine tune an LLM locally, start small: a 0.5–3 billion parameter model with QLoRA runs on many consumer GPUs with 8–16 GB of memory, and a 7–8 billion parameter model with QLoRA is practical on a 16–24 GB card. You need a recent NVIDIA GPU for the widest tool support; Apple silicon Macs can fine-tune smaller models with Apple's MLX framework, and AMD GPUs work with some tools through ROCm.

Local fine-tuning gives you privacy (your data never leaves the machine) and no per-hour cost once you own the hardware. Cloud GPUs make sense for larger models, full fine-tuning or when you need results quickly. Either way, run a tiny test (a few dozen steps on 50 examples) before the full job to catch format and memory problems early.

Step 5: Evaluate the Result

Never judge a fine-tuned model by a few chat messages. Compare it with the base model on the held-out test set:

  1. Automatic checks: for classification or extraction, measure accuracy, precision and recall, or exact-match rates for structured outputs.
  2. Model-graded checks: for open-ended answers, use a rubric and a strong judge model, plus spot checks by people.
  3. Regression checks: test general abilities the model should keep. Fine-tuning on a narrow task can make a model worse at others, a problem known as catastrophic forgetting.
  4. Watch the training curves: if training loss keeps falling while evaluation loss rises, the model is memorizing (overfitting). Stop earlier, use fewer epochs or add more varied data.

If the fine-tuned model doesn't clearly beat the base model with a good prompt, don't ship it.

Step 6: Deploy the Fine-Tuned Model

After training you have either a full model or a LoRA adapter, a small file that only works together with its base model. You have three common options:

  • Serve the adapter with the base model. Inference servers such as vLLM can load LoRA adapters on top of a base model, and can even serve several adapters at once.
  • Merge the adapter into the base model. PEFT's merge_and_unload() combines the adapter weights with the base weights, which removes the extra latency of a separate adapter. Save the merged model in Safetensors format.
  • Run it locally. Ollama can build a model from a directory of Safetensors weights for supported architectures (FROM <model directory> in a Modelfile), or from a GGUF file if you've converted and quantized the merged model.

Keep the base model name, adapter settings, dataset version and evaluation scores together, so you can reproduce or roll back the model later.

Hosted Fine-Tuning: What Changed

For years, the easiest route was uploading a JSON Lines file to a hosted service such as OpenAI's fine-tuning API. OpenAI's documentation now says it's winding down its fine-tuning platform: it's no longer open to new users, eligible existing customers can create training jobs until January 6, 2027 (unless the base model shuts down earlier), and fine-tuned models stay available until their base model is retired.

Other cloud platforms still offer managed fine-tuning for some models, and several providers fine-tune and host open-weight models for you. Check each provider's current model list and terms before you build a workflow around it. Open models have a practical advantage here: you keep the weights, so a provider change doesn't take your model away.

Fine Tune LLM Cost

Fine tune LLM cost has three parts:

  1. Compute: GPU hours × hourly price. LoRA and QLoRA on a small model and a few thousand examples is a small job; full fine-tuning of larger models multiplies the memory and time. Run a short test to measure time per step, then multiply by the number of steps (examples × epochs ÷ batch size).
  2. Data: collecting, cleaning and reviewing examples is usually the biggest cost, measured in people's time.
  3. Serving: a fine-tuned open model needs a GPU or a hosting provider. A smaller fine-tuned model can be cheaper to serve than a large general model with long prompts, which is often the real payoff.

A useful way to decide: compare the monthly cost of your current setup (large model, long prompts) with the cost of training once and serving a smaller fine-tuned model. Shorter prompts, prompt caching and routing easy requests to smaller models are cheaper levers to try before training anything.

Common Fine-Tuning Mistakes

  • Fine-tuning to add facts. The model learns style and patterns; facts it saw a few times are recalled unreliably. Use retrieval for knowledge.
  • No evaluation set. Without a held-out test and a baseline, you can't tell whether training helped.
  • Inconsistent examples. If your examples disagree on format or answers, the model learns the disagreement.
  • Wrong chat template. Training with one prompt format and running with another quietly ruins results. Let the trainer apply the model's own template.
  • Too many epochs. Small datasets overfit fast; start with one to three epochs and watch evaluation loss.
  • Skipping a tiny test run. A five-minute run catches broken data and memory errors before an expensive job.

FAQ

How much data do I need to fine-tune an LLM?

There's no fixed number, but a few hundred high-quality examples is a realistic starting point for a narrow task, and a few thousand for broader behavior. Quality and variety matter more than volume. Start small, evaluate, and add examples where the model fails.

Can I fine-tune an LLM on a single GPU?

Yes. With QLoRA, small and mid-sized models (up to roughly 8 billion parameters) fine-tune on a single consumer GPU with 12–24 GB of memory, and the QLoRA paper showed even a 65-billion-parameter model fitting on one 48 GB GPU.

What is the difference between fine-tuning and RAG?

Fine-tuning changes the model's weights to change how it behaves, such as its format, tone or skill at a narrow task. RAG leaves the model unchanged and gives it relevant documents at query time, which is better for facts that change or must be cited.

How long does it take to fine-tune an LLM?

It depends on model size, data size and hardware. A LoRA run on a small model with a few thousand examples can finish in minutes to hours on one GPU, while full fine-tuning of large models can take days on several GPUs. Measure time per step on a short test run to estimate your own.

Can I still fine-tune OpenAI models?

Only if you're an eligible existing customer. OpenAI says its fine-tuning platform is winding down, is closed to new users, and accepts new training jobs until January 6, 2027. For new projects, fine-tuning open-weight models with tools like Hugging Face TRL is the main path.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog