AI & Machine LearningAI Engineering · Part 8 of 8

Fine-Tuning LLMs in Production: LoRA, QLoRA, and When Not to Bother

A practical guide to fine-tuning: when it beats prompting and RAG, how LoRA and QLoRA work, how to build the dataset, how to evaluate, and how to ship an adapter without regretting it.

December 1, 202618 min read
AI/MLFine-TuningLoRAQLoRALLMMLOps

Picture a support-ticket router. Every incoming ticket goes to an LLM with a prompt that has grown to 2,400 tokens: a taxonomy of 38 categories, a dozen rules about edge cases, and fifteen few-shot examples that someone added one at a time, each after a misrouted ticket. It works most of the time. It also costs 2,400 input tokens on every single call, it takes a noticeable moment to respond, and every time someone adds a sixteenth example to fix one category, two other categories get slightly worse.

That is an illustration, not a war story, but if you have built anything on top of an LLM the shape will be familiar. At some point someone in the room says: "Should we just fine-tune a model for this?"

Sometimes the right answer is yes. More often it is "not yet", and occasionally it is "that would not help at all". This post is about telling those three apart, and then doing the fine-tune properly when it is the right call. We will cover what fine-tuning changes and what it does not, how LoRA and QLoRA make it affordable, how to build a dataset that is worth training on, how to evaluate the result, and what it takes to run a fine-tuned model in production alongside the Java services that call it.

What fine-tuning changes, and what it does not

There are three levers for changing what an LLM does for you, and they act on different things.

Prompting changes the instructions. It is the cheapest lever and the fastest to iterate on. Its cost is paid on every request, in tokens and latency, and its ceiling is the model's ability to follow a long, complicated set of instructions consistently.

Retrieval (RAG) changes the knowledge available at request time. If the problem is "the model does not know our return policy" or "the answer changed last Tuesday", retrieval is the lever. I covered that pipeline in RAG at Scale.

Fine-tuning changes the weights, which means it changes behavior: the format the model produces by default, the tone it writes in, the decision boundary it applies to a classification, the domain vocabulary it handles fluently. It bakes a pattern in so you no longer have to describe it on every call.

The most common mistake is reaching for fine-tuning to solve a knowledge problem. A fine-tuned model does absorb some facts from its training data, but unreliably, and it cannot tell you where a fact came from or notice that the fact went stale. If your documents change weekly, a model fine-tuned on last month's documents is confidently out of date. Knowledge belongs in retrieval. Behavior belongs in weights.

The second most common mistake is fine-tuning to fix a problem that a better prompt or a stricter output schema would have fixed in an afternoon.

Here is the decision flow I'd use:

And the same idea as a table:

SymptomLikely leverWhy
Answers are wrong because facts are missing or outdatedRAGKnowledge changes faster than you can retrain
Output format drifts despite detailed instructionsStructured outputs first, then fine-tuningSchema enforcement is cheaper than training
Prompt has grown huge to cover many edge casesFine-tuningMove the pattern from tokens into weights
A large model is accurate but too slow or costly at volumeFine-tune a smaller modelNarrow tasks rarely need a general-purpose giant
Tone or domain style is offFine-tuningStyle is behavior, and behavior lives in weights
Task definition changes every sprintPromptingRetraining cannot keep up with a moving target

The situations where fine-tuning earns its keep tend to look alike: a narrow, stable, high-volume task where a smaller specialized model can match a larger general one. Classification, routing, extraction into a fixed schema, rewriting into a house style, and domain-specific code or query generation are the usual candidates.

Full fine-tuning, and why almost nobody does it

Full fine-tuning updates every weight in the model. For a model with several billion parameters, that means holding the weights, their gradients, and optimizer state in GPU memory at once. With an optimizer like AdamW that keeps two extra values per parameter, the training footprint is several times the size of the model itself. It also produces a complete new copy of the model for every task. Ten tasks means ten multi-gigabyte checkpoints to store, version, and serve.

There is a subtler cost as well. When every weight is free to move, a small dataset can pull the model a long way from where it started, and it can lose general abilities it had before. This is usually called catastrophic forgetting. You train a model to classify tickets and discover it has become worse at following ordinary instructions.

Parameter-efficient fine-tuning (PEFT) methods address all three problems by freezing the original weights and training a small number of new ones. LoRA is the method that became the default.

LoRA: the mental model

LoRA stands for Low-Rank Adaptation, from the 2021 paper by Hu and colleagues. The idea rests on one observation: when you fine-tune a large model for a specific task, the change to each weight matrix does not need the full expressive power of that matrix. It can be approximated well by a low-rank matrix.

Take one weight matrix W in the model, with shape d × k. Full fine-tuning learns an update ΔW of the same shape. LoRA instead writes the update as the product of two much smaller matrices:

W' = W + (alpha / r) * B * A

W : d × k   (frozen, never updated)
B : d × r   (trainable, initialised to zero)
A : r × k   (trainable, initialised randomly)
r : the rank, typically 4 to 64

Because B starts at zero, the product B * A is zero at the start of training, so the adapted model begins exactly where the base model was. Training then nudges A and B only.

The parameter savings are large. For a 4096 by 4096 attention projection matrix, the full update has about 16.8 million values. With rank 16, LoRA trains 16 × (4096 + 4096), which is 131,072 values. That is under 1% of the original matrix. Across a whole model, LoRA commonly trains well below 1% of the total parameters.

Three properties follow from this design, and each matters in production:

  1. The base model is untouched. One copy of the base weights can serve many tasks. Each task is a small adapter file, often tens of megabytes instead of many gigabytes.
  2. Forgetting is limited. The update is constrained to a low-rank subspace and the original weights are frozen, so the model cannot drift as far as it can under full fine-tuning.
  3. The adapter can be merged. After training you can compute W + (alpha / r) * B * A once and save the result as ordinary weights. A merged model has no extra layers and no added inference latency.

The hyperparameters that matter

Rank (r) controls the capacity of the adapter. Low ranks (4 to 16) are usually enough for classification, extraction, and style tasks. Higher ranks (32 to 64 and beyond) help when the task is far from what the base model already does. More rank is not automatically better: on a small dataset, extra capacity mostly buys extra overfitting.

Alpha (lora_alpha) scales the update. A common starting point is to set alpha equal to the rank or to twice the rank. What matters is the ratio alpha / r, which acts like a multiplier on the adapter's learning rate.

Target modules decide which matrices get adapters. The original paper adapted only the query and value projections in attention. Later practice, including the QLoRA paper, found that adapting all the linear layers (attention and MLP) tends to give better results for the same data, at the cost of more trainable parameters.

Dropout (lora_dropout) is regularisation on the adapter path. Values around 0.05 to 0.1 are typical for small datasets.

QLoRA: fitting the base model on one GPU

LoRA cuts the number of trainable parameters, but the frozen base model still has to sit in GPU memory during training. For a large model in 16-bit precision that alone can exceed a single GPU.

QLoRA, from Dettmers and colleagues in 2023, deals with this by quantizing the frozen base model to 4 bits and training LoRA adapters on top of it. It combines three techniques:

  • 4-bit NormalFloat (NF4) quantization. Neural network weights are roughly normally distributed, so NF4 places its 16 quantization levels to suit that distribution instead of spacing them evenly.
  • Double quantization. The quantization constants themselves are quantized, saving a little more memory per parameter.
  • Paged optimizers. Optimizer state can spill to CPU memory during spikes, which avoids out-of-memory crashes on long sequences.

The gradients flow through the frozen 4-bit weights into the adapters, which stay in higher precision. The paper reported that this approach could match 16-bit fine-tuning quality on its benchmarks while cutting memory enough to fine-tune a 65-billion-parameter model on a single 48 GB GPU.

The trade-off is speed. Quantized training is slower per step than training in 16-bit, because weights are dequantized on the fly. If you have the memory for plain LoRA, it is usually faster. If you do not, QLoRA is what makes the job possible at all.

Full fine-tuningLoRAQLoRA
Trainable parameters100%Typically under 1%Typically under 1%
Base model precision in training16-bit16-bit4-bit
GPU memoryHighestModerateLowest
Training speed per stepBaselineFasterSlower than LoRA
Artifact per taskFull model copySmall adapterSmall adapter
Forgetting riskHighestLowerLower

The dataset is the project

Most of the outcome of a fine-tune is decided before any GPU is switched on. The model will learn exactly what the examples show, including the mistakes. A few hundred clean, consistent examples routinely beat several thousand noisy ones.

Where examples come from

  • Production logs with human corrections. The best source. Real inputs, with the output a person actually accepted or fixed.
  • Existing labelled data. Ticket categories, tagged documents, reviewed code.
  • Distillation from a larger model. Run a stronger model with your long, careful prompt over real inputs, review a sample, and use the outputs to train a smaller model. This is the cleanest route to "the same quality at a fraction of the cost". Check the provider's terms before training on another model's outputs.
  • Hand-written examples. Slow, but valuable for rare edge cases the logs do not cover.

Scrub personal data and secrets before anything goes into a training set. A model can memorise and repeat rare strings from its training data, so an API key or a customer's phone number in the dataset is a leak waiting to happen.

Format

For chat models, the common format is JSONL with one conversation per line. Train with the same system prompt you will use at inference time. A mismatch between the two is one of the most frequent causes of a fine-tune that scores well offline and behaves oddly in production.

Json
{"messages": [{"role": "system", "content": "Route the support ticket. Reply with JSON only."}, {"role": "user", "content": "I was charged twice for my November invoice."}, {"role": "assistant", "content": "{\"category\": \"billing.duplicate_charge\", \"priority\": \"high\"}"}]}
{"messages": [{"role": "system", "content": "Route the support ticket. Reply with JSON only."}, {"role": "user", "content": "How do I export my data to CSV?"}, {"role": "assistant", "content": "{\"category\": \"howto.export\", \"priority\": \"low\"}"}]}

Split before you do anything else

Hold out a test set first and do not look at it while iterating. Then a small script handles deduplication and the split:

Python
import hashlib
import json
import random
from collections import Counter

def load(path):
    with open(path) as f:
        return [json.loads(line) for line in f if line.strip()]

def user_text(example):
    return next(m["content"] for m in example["messages"] if m["role"] == "user")

def label(example):
    return json.loads(example["messages"][-1]["content"])["category"]

examples = load("tickets_labelled.jsonl")

# 1. Drop exact and near-exact duplicates on the normalised user text.
seen, unique = set(), []
for ex in examples:
    key = hashlib.sha256(" ".join(user_text(ex).lower().split()).encode()).hexdigest()
    if key not in seen:
        seen.add(key)
        unique.append(ex)

# 2. Look at the class balance before training, not after.
print(Counter(label(ex) for ex in unique).most_common())

# 3. Deterministic split: 80% train, 10% validation, 10% test.
random.Random(42).shuffle(unique)
n = len(unique)
splits = {
    "train": unique[: int(n * 0.8)],
    "val": unique[int(n * 0.8) : int(n * 0.9)],
    "test": unique[int(n * 0.9) :],
}
for name, rows in splits.items():
    with open(f"tickets_{name}.jsonl", "w") as f:
        for row in rows:
            f.write(json.dumps(row) + "\n")

Deduplicating before the split matters. If the same ticket text lands in both train and test, your test score measures memorisation and will overstate real accuracy. If your data has a time dimension, a better split is by date: train on older tickets, test on the most recent ones, which is closer to what production will look like.

Three dataset problems account for most disappointing fine-tunes:

  • Inconsistent labels. If two annotators route the same kind of ticket to different categories, the model learns the disagreement. Fix the labelling guide, then relabel.
  • Missing negatives. If every training example has a confident answer, the model never learns to say "unknown" or "needs a human". Include examples of the refusal or fallback behavior you want.
  • Skewed coverage. If 70% of examples are one category, the model will favour it. Balance the set or at least make sure rare categories have enough examples to learn from.

A QLoRA training run with Hugging Face PEFT

Here is a minimal training script using transformers, peft, bitsandbytes, and datasets. The base model name is a placeholder. Pick an open-weight instruct model whose licence permits your use.

Python
import torch
from datasets import load_dataset
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    BitsAndBytesConfig,
    DataCollatorForLanguageModeling,
    Trainer,
    TrainingArguments,
)

BASE_MODEL = "your-org/your-base-instruct-model"  # placeholder

# 4-bit NF4 quantization with double quantization: the QLoRA recipe.
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
)

tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    quantization_config=bnb_config,
    device_map="auto",
)
model = prepare_model_for_kbit_training(model)

lora_config = LoraConfig(
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    target_modules="all-linear",
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()  # sanity check: should be a small fraction

dataset = load_dataset(
    "json",
    data_files={"train": "tickets_train.jsonl", "val": "tickets_val.jsonl"},
)

def tokenize(example):
    # Use the model's own chat template so training matches inference.
    text = tokenizer.apply_chat_template(example["messages"], tokenize=False)
    return tokenizer(text, truncation=True, max_length=1024)

tokenized = dataset.map(tokenize, remove_columns=dataset["train"].column_names)

args = TrainingArguments(
    output_dir="out/ticket-router-lora",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,   # effective batch size of 16
    learning_rate=2e-4,
    lr_scheduler_type="cosine",
    warmup_ratio=0.05,
    logging_steps=10,
    eval_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
    metric_for_best_model="eval_loss",
    greater_is_better=False,
    bf16=True,
    report_to="none",
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=tokenized["train"],
    eval_dataset=tokenized["val"],
    data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
trainer.train()

model.save_pretrained("out/ticket-router-lora/adapter")
tokenizer.save_pretrained("out/ticket-router-lora/adapter")

A few notes on the choices here.

Learning rate. LoRA adapters tolerate much higher learning rates than full fine-tuning. Values in the range of 1e-4 to 2e-4 are common starting points, where full fine-tuning would use something ten times smaller.

Epochs. Two to four is usual for small datasets. Watch the validation loss: when training loss keeps falling and validation loss turns upward, the model has started memorising. load_best_model_at_end keeps the checkpoint from before that point.

Chat template. Every model family formats conversations with its own special tokens. apply_chat_template uses the tokenizer's built-in template so you do not hand-roll it and get it subtly wrong.

Loss masking. This minimal script computes loss over the whole sequence, including the system and user turns. For better results, mask the loss so the model is only trained on the assistant's reply. Libraries such as TRL's SFTTrainer handle that for you, and it is worth switching to one once the basic loop works.

If you would prefer not to run GPUs at all, hosted fine-tuning APIs from the major providers take the same JSONL format, run the training for you, and hand back a model ID. You give up control over hyperparameters and the ability to hold the weights, and you gain not having to operate training infrastructure. For a first fine-tune of a narrow task, that is often the right trade.

Evaluation: prove it beats the prompt

A fine-tune is only worth shipping if it beats the alternative you already have. That means the baseline is not "the base model with no prompt". The baseline is your best prompt, with few-shot examples, on the strongest model you would otherwise use.

Run both on the same held-out test set and compare task metrics, not loss:

  • Classification and routing: accuracy, and per-class precision and recall. An overall accuracy number hides a category the model never predicts.
  • Extraction: exact match per field, plus the rate of outputs that fail to parse.
  • Generation: a rubric scored by people on a sample, or by a judge model that you have spot-checked against human scores.

Then add a second, smaller test set that has nothing to do with your task: general instructions, a few safety-relevant prompts, some out-of-scope requests. This is the regression set. It tells you whether the model forgot how to behave outside the narrow lane you trained it on. A ticket router that now answers "what is the capital of France" with a billing category has a problem you want to find before your users do.

Finally, measure what you were actually trying to improve. If the goal was cost and latency, record tokens per request and latency percentiles for both options. A typical result for a narrow task is that the fine-tuned model needs a prompt of a couple of hundred tokens where the baseline needed a couple of thousand. That difference, multiplied by your request volume, is the business case.

Serving a fine-tuned model

You have two ways to deploy a LoRA adapter.

Merge it. Fold the adapter into the base weights and serve the result as an ordinary model. No extra latency, and any inference server can load it. Merge into a full-precision copy of the base model, not the 4-bit one you trained against, and then quantize the merged model for serving if you need to.

Python
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM

base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16)
merged = PeftModel.from_pretrained(base, "out/ticket-router-lora/adapter").merge_and_unload()
merged.save_pretrained("out/ticket-router-merged")

Keep it separate. Inference servers such as vLLM can load one base model and attach multiple LoRA adapters, selecting the adapter per request. This is the pattern for multi-tenant or multi-task setups: one set of base weights in GPU memory, many small adapters on top. There is a small per-request overhead compared with a merged model.

From the application side, a fine-tuned model behind an OpenAI-compatible endpoint looks like any other model. The part worth designing is what happens when it is unavailable or returns something unusable. In a Spring Boot service, I'd keep the model name in configuration and wrap the call with a fallback to the general model and the long prompt:

Java
@Service
public class TicketRouter {

    private final ChatClient tunedClient;     // small fine-tuned model, short prompt
    private final ChatClient fallbackClient;  // general model, full prompt with examples
    private final ObjectMapper mapper;

    public TicketRouter(@Qualifier("tunedChatClient") ChatClient tunedClient,
                        @Qualifier("fallbackChatClient") ChatClient fallbackClient,
                        ObjectMapper mapper) {
        this.tunedClient = tunedClient;
        this.fallbackClient = fallbackClient;
        this.mapper = mapper;
    }

    @CircuitBreaker(name = "tunedRouter", fallbackMethod = "routeWithFallback")
    public Routing route(String ticketText) {
        String json = tunedClient.prompt()
                .system("Route the support ticket. Reply with JSON only.")
                .user(ticketText)
                .call()
                .content();
        return parse(json);
    }

    Routing routeWithFallback(String ticketText, Throwable cause) {
        String json = fallbackClient.prompt()
                .system(Prompts.FULL_ROUTING_PROMPT)
                .user(ticketText)
                .call()
                .content();
        return parse(json);
    }

    private Routing parse(String json) {
        try {
            return mapper.readValue(json, Routing.class);
        } catch (JsonProcessingException e) {
            throw new IllegalStateException("Model returned unparseable routing", e);
        }
    }

    public record Routing(String category, String priority) {}
}

The parse failure throws on purpose, so the circuit breaker counts malformed outputs as failures and routes to the fallback. The same circuit breaker mechanics from Building Resilient Systems apply here without changes. A model is a dependency like any other.

The costs that show up after launch

Training is the cheap part. A LoRA run on a few thousand examples takes minutes to hours. The ongoing costs are where fine-tuning projects quietly become expensive.

You own a model now. With a prompt, a base-model upgrade is a config change and an eval run. With a fine-tune, an adapter is tied to the exact base model it was trained on. When that base model is retired or a better one arrives, you retrain, re-evaluate, and redeploy. Keep the dataset and training script versioned together so that retraining is a pipeline run and not an archaeology project.

The world drifts. New product lines add ticket categories. Customers start phrasing things differently. The model's accuracy decays without any error appearing in a log. Sample production traffic regularly, label a slice, and track the same metrics you used at launch. Decide in advance what drop triggers a retrain.

Every change is a release. Adding a category to a prompt takes a minute. Adding a category to a fine-tuned model means collecting examples, retraining, and running the full evaluation. If the task definition is still moving, this friction is the strongest argument for staying with prompts for now.

Traceability matters. Version adapters like any other artifact: the base model identifier, a hash of the dataset, the hyperparameters, and the evaluation results should travel together. When someone asks why the model routed a ticket a certain way in March, you want to know exactly which adapter was serving.

When not to fine-tune

To be direct about it, I would not fine-tune when:

  • The failure is about knowledge. Use retrieval.
  • You have not written an eval set. Without one you cannot tell whether the fine-tune helped, and building it often reveals that a prompt fix is enough.
  • You have fewer than about a hundred good examples. Put them in the prompt as few-shot examples and keep collecting.
  • The task changes monthly. The retraining loop will not keep up.
  • Volume is low. If the prompt-token savings amount to a few dollars a month, the maintenance burden is not worth it.
  • A newer base model already solves it. Check before investing. A task that needed a fine-tune a year ago may now work with a short prompt.

What I'd do

If I were starting on the ticket router from the opening, this is the order I'd work in:

  1. Write the eval set first. A couple of hundred real tickets with agreed labels, split off and locked away.
  2. Push the prompt as far as it goes. Structured outputs, a tighter taxonomy description, better few-shot selection. Record the score, the token count, and the latency. This is the baseline to beat.
  3. Log everything. Every production input and output, with any human correction. This becomes the training set.
  4. Distil when the numbers justify it. Once there are a few thousand reviewed examples and the per-request cost of the long prompt is a visible line item, fine-tune a smaller open-weight model with QLoRA, or use a hosted fine-tuning API if running GPUs is not something the team wants to own.
  5. Ship behind a fallback. Serve the fine-tuned model first, fall back to the general model with the long prompt, and compare the two on sampled traffic for a few weeks.
  6. Schedule the retrain. Put drift monitoring and a retraining pipeline in place before calling it done.

Recap

  • Fine-tuning changes behavior, not knowledge. Use retrieval for facts and fine-tuning for format, style, and narrow decisions.
  • LoRA freezes the base model and trains a low-rank update, usually under 1% of the parameters. QLoRA adds 4-bit quantization of the base model so the job fits on a single GPU.
  • The dataset decides the result. A few hundred consistent, deduplicated, well-labelled examples beat thousands of noisy ones.
  • The baseline is your best prompt, not the untuned model. Evaluate on a held-out test set and a separate regression set.
  • The real cost is ownership: retraining on base-model changes, monitoring drift, and treating every behavior change as a release.

Further reading


Subscribe to the newsletter to get the next deep dive in your inbox. If you're hiring for a remote senior Java and AI engineering role, my resume and background are on the About page.

R

Ravi Kant Shukla

Senior Java + AI engineer. 9+ years in system design, Kafka, microservices, and LLM/RAG pipelines.

Enjoyed this post?

Get new deep dives and the week's AI news by email. No spam.

Comments (0)

Loading comments...

Leave a comment

Your email will not be displayed publicly.