SysArt
Book a briefing
SysArt

Private LLMs and RAG

Fine-Tuning Small Language Models with Domain-Specific Data On-Premises

How to fine-tune small language models on domain data on-premises: when it beats RAG, LoRA and QLoRA, domain-adaptive pretraining, data quality and evaluation.

Last reviewed by SysArt AI Architecture Team10 min readHow we review

In short

Fine-tuning adapts a pre-trained small language model to your tasks by training it further on your own examples. On-premises, parameter-efficient methods such as LoRA and QLoRA make this feasible on one or a few GPUs, while training data stays inside your boundary. Results depend most on a precise task definition, clean data and honest evaluation.

Key takeaways

  • Fine-tune when the gap is behaviour, such as formats, terminology or a classification scheme; use retrieval when the gap is knowledge that changes or must be cited.
  • LoRA trains small low-rank matrices on a frozen base model; QLoRA adds a 4-bit quantised base, which let its authors fine-tune a 65-billion-parameter model on a single 48 GB GPU.
  • Continued pretraining on unlabelled domain text can improve downstream tasks, but recent research recommends LoRA for instruction fine-tuning rather than for continued pretraining.
  • Data quality outweighs volume: define the task precisely, deduplicate, check labels and keep evaluation data separate from training data.
  • Test for forgetting as well as gains, and version every adapter with its base model, data and evaluation results.
Professional working at a computer station in a modern office environment

When does fine-tuning beat prompting and retrieval?

Fine-tuning pays off when the gap between a general model and your needs is behaviour, such as output formats, domain terminology, a classification scheme or reasoning conventions, rather than missing knowledge. For knowledge that changes or must be cited, retrieval is usually the better tool, and many systems combine the two.

Small language models, meaning open-weight models with a few billion parameters, handle general tasks well and run on modest hardware, but general capability is not domain expertise. A model that has never seen your document conventions, product codes or ticket categories will be inconsistent however carefully you write prompts. Fine-tuning changes the weights so that the behaviour is consistent without long instructions, which saves context-window space and latency on every request.

Use the right tool for each gap:

  • Prompting is the baseline: cheap to change, and the reference that every fine-tuned model must beat.
  • Retrieval-augmented generation supplies current facts and their sources at question time, as described on our enterprise RAG page.
  • Fine-tuning teaches stable behaviour: formats, labels, style and domain language.

Doing this on-premises keeps proprietary training data, often the most sensitive material an organisation holds, inside its own infrastructure. Check the model licence before you start, because it governs what you may do with a fine-tuned derivative; our guide to open-weight model licences covers the differences. For an introduction to the technique itself, read what fine-tuning is.

Which adaptation method fits your hardware?

Full fine-tuning updates every weight and needs the most memory; LoRA trains small adapter matrices on a frozen model; QLoRA trains LoRA adapters on a base model quantised to 4 bits, which cuts memory further.

MethodWhat is trainedMemory profileMain trade-off
Full fine-tuningAll weightsWeights, gradients and optimiser states for every parameterMost capacity to learn, most memory, most forgetting
LoRASmall low-rank matrices added to frozen weightsFar fewer trainable parameters and optimiser statesLess capacity per run; adapters are small and swappable
QLoRALoRA adapters on a frozen base quantised to 4 bitsLowest of the threeQuantisation adds engineering steps to the pipeline

Full fine-tuning. Every parameter needs a gradient and an optimiser state during training, so memory grows quickly with model size. The QLoRA authors note that regular 16-bit fine-tuning of the 65-billion-parameter LLaMA model needs more than 780 GB of GPU memory. Smaller models need proportionally less, but full fine-tuning remains the most demanding option on a fixed on-premises fleet.

LoRA. Low-Rank Adaptation freezes the pre-trained weights and injects trainable rank-decomposition matrices into the Transformer’s layers. For GPT-3 175B, its authors report 10,000 times fewer trainable parameters and a third of the GPU memory compared with full fine-tuning with Adam, quality on par with or better than full fine-tuning on the models they tested, and, unlike adapter layers, no additional inference latency.

QLoRA. QLoRA backpropagates through a frozen base model quantised to 4 bits into LoRA adapters. It introduced the 4-bit NormalFloat (NF4) data type, double quantisation of the quantisation constants, and paged optimisers to absorb memory spikes, and it fine-tuned a 65-billion-parameter model on a single 48 GB GPU while preserving 16-bit fine-tuning task performance.

LoRA has trade-offs. Biderman and colleagues compared it with full fine-tuning on programming and mathematics and found that, in standard low-rank settings, LoRA substantially underperformed full fine-tuning on the target domain while better preserving performance on other tasks; full fine-tuning learned weight changes with a rank 10 to 100 times greater than typical LoRA configurations. On a fixed fleet, LoRA or QLoRA is the natural place to start. If quality on the target task falls short, compare with full fine-tuning before adding more data. To size the GPUs that will serve the result, use the LLM GPU sizing calculator.

What does transfer learning add beyond task fine-tuning?

Transfer learning is why fine-tuning works with modest data: a pre-trained model already understands language, and you only adapt it. A second phase of pretraining on unlabelled domain text, before supervised fine-tuning, can add further gains when your domain’s language differs markedly from general text.

Training a language model from scratch needs data and compute far beyond what most enterprises can dedicate on-premises. Starting from a pre-trained model sidesteps that. The question is how far to adapt it before teaching the task.

In “Don’t Stop Pretraining”, Gururangan and colleagues studied four domains (biomedical and computer science publications, news, and reviews) and eight classification tasks. They found that a second phase of pretraining on in-domain text, which they call domain-adaptive pretraining, improved performance in both high- and low-resource settings; that pretraining on the task’s own unlabelled data, task-adaptive pretraining, helped even after domain-adaptive pretraining; and that multi-phase adaptive pretraining offered large gains in task performance.

A pipeline built on these findings has up to three stages:

  1. Domain-adaptive pretraining (optional): continue pretraining on deduplicated, unlabelled domain documents with the next-token objective, so that the model absorbs vocabulary and document structure.
  2. Supervised fine-tuning: train on labelled input and output examples of the target task, in the base model’s chat or instruction format.
  3. Evaluation and release: compare with the baseline and the previous version before anything ships.

Choose the training method per stage. Biderman and colleagues recommend LoRA for instruction fine-tuning rather than continued pretraining: in continued pretraining, the gap between LoRA and full fine-tuning did not close even at high ranks. If domain-adaptive pretraining matters for your case, budget for full-parameter training, or first test whether supervised fine-tuning alone is enough.

How should you prepare domain data?

Define the task precisely, build examples that match what the model will see in production, then clean, deduplicate and split the data before training. Data preparation decides more of the outcome than hyperparameter tuning does.

Start from the task. “Understand our domain” is not a task; “classify support tickets into our categories” or “produce structured summaries of engineering reports” is. The task defines the examples: inputs that look like production inputs, and outputs that look exactly like what you want back.

Format consistently. Write examples in the base model’s chat template, with system, user and assistant turns, and keep the system message the same across examples so that the model learns one stable role.

Prefer quality over volume. The QLoRA authors found data quality far more important than dataset size: a 9,000-example dataset outperformed a 450,000-example subsample of another dataset on chatbot performance. Review a random sample by hand for contradictions, label noise and outputs that do not follow from their inputs, and check that the class balance matches production or is deliberately rebalanced.

Deduplicate. Lee and colleagues found that common language-modelling datasets contain many near-duplicate examples and long repeated substrings, and that more than 1% of the unprompted output of models trained on them was copied verbatim from the training data. Models trained on deduplicated data emitted memorised text ten times less often and needed fewer training steps to reach the same or better accuracy. The authors also found train-test overlap affecting more than 4% of the validation sets of standard datasets, so deduplicate your evaluation set against your training data as well.

Protect personal data. Because models can reproduce training text, treat a fine-tuned model or adapter as at least as sensitive as its training data. Minimise and pseudonymise personal data before training and document the legal basis; our guide to GDPR-compliant LLMs covers the data protection questions.

Augment with care. Paraphrased inputs, varied non-essential details and candidate examples generated by a larger model can extend a small dataset, but review generated examples before they enter training.

How do you run a fine-tuning job step by step?

Run fine-tuning as an experiment, with a baseline, a controlled configuration, monitored training and a comparison on held-out data. Five steps cover it.

  1. Establish a baseline. Evaluate the base model, with your best prompt and retrieval set-up, on a held-out test set using task metrics: accuracy and per-class F1 for classification, field-level precision and recall for extraction, and rubric scores with human review for generation.
  2. Configure the run. Apply LoRA to all linear layers: the QLoRA authors found this necessary to match full fine-tuning, and Biderman and colleagues found that attention-only adapters underperformed. Rank depends on the task. QLoRA found that rank mattered little once all layers were adapted, while the code experiments of Biderman and colleagues found ranks of 16 to 64 insufficient; they recommend 256 where memory allows, with the scaling factor alpha set to twice the rank, and suggest sweeping learning rates between 1e-5 and 5e-4 and choosing the highest that trains stably. If memory is tight, gradient checkpointing trades extra computation for lower memory use.
  3. Monitor training. Track training loss, validation loss and task metrics at each evaluation step. Validation loss that stalls while training loss keeps falling means the model is memorising rather than learning, and with small datasets this can happen early.
  4. Evaluate the result. Run the same test set as the baseline, read a sample of outputs to check that the model learned the domain rather than surface formatting, and test ambiguous, out-of-distribution and adversarial inputs.
  5. Iterate or ship. If results fall short, diagnose before retraining, because weak or noisy data, overfitting and an undersized adapter need different fixes. If results meet the bar, ship the adapter or merge it into the base weights.

How do you detect forgetting and silent failures?

Compare the fine-tuned model with the base model on your task and on a general-capability and safety test set, because a falling training loss and fluent outputs prove nothing about either.

Forgetting. Fine-tuning can erode skills outside the target domain, such as following instructions, reasoning or refusing unsafe requests. Biderman and colleagues found that LoRA better maintained the base model’s performance on tasks outside the target domain than full fine-tuning did, and mitigated forgetting more than common regularisation techniques such as weight decay and dropout. If regressions appear, lower the learning rate, shorten training, or move from full fine-tuning to LoRA.

Silent failure. A model can produce fluent, well-formatted text and still get the task wrong, usually because the training data did not match production. Build the held-out set to mirror production exactly: if production receives noisy OCR text or several languages, so must the test set. Use a scoring rubric for human review, and measure agreement between reviewers on a shared sample before trusting their scores.

Before replacing a live system, run the fine-tuned model in shadow mode or as a small canary against the current solution on real traffic, and promote it only when it beats the incumbent on the agreed metrics.

How do you serve and govern fine-tuned models?

Serve adapters per request on a shared base model, or merge them into a single model, and version every artefact with its base model, data and evaluation results.

Serving several domains. One base model with several LoRA adapters needs far less memory than several full models. vLLM serves adapters per request on top of a base model: you enable them with --enable-lora, register each with --lora-modules, and limit how many and how large they may be with settings such as max_loras and max_lora_rank. Its runtime API for loading adapters carries security risks, and vLLM advises against using it in production unless the environment is isolated and fully trusted, so deploy adapters through your release pipeline instead.

Merging. The LoRA authors note that the adapter matrices can be merged into the base weights, so a merged model adds no inference latency. A merged model is a new full artefact, though, and needs the full release process. Plan storage accordingly: in 16-bit precision, every full copy of a 7-billion-parameter model takes about 14 GB.

Versioning and compatibility. An adapter is valid only for the base model revision, tokenizer and chat template it was trained with. Record those, together with the dataset version, training configuration and evaluation report, in your model registry, and retrain or re-validate adapters whenever the base model changes.

Separation of duties. Restrict who can submit training jobs, approve artefacts and activate them in production. Adapter weights change model behaviour as surely as code does.

Monitoring and retraining. Monitor production quality with the metrics you used in evaluation, collect user feedback, and watch for drift as inputs change. Feed reviewed production examples back into the next training round, within the limits your data protection assessment allows.

SysArt designs and implements fine-tuning pipelines, adapter serving and evaluation on client infrastructure as part of private LLM and on-premises AI programmes.

Featured image by Sam Moghadam on Unsplash.

Frequently asked questions

When should I fine-tune instead of using RAG or prompting?

Start with prompting as the baseline. Choose retrieval-augmented generation when the model lacks knowledge that changes often or must be cited, because updating documents is easier than retraining. Choose fine-tuning when the gap is behaviour: a fixed output format, domain terminology, a classification scheme or a house style that prompts cannot enforce reliably. Many production systems combine both, with a fine-tuned model answering from retrieved sources.

How much GPU memory does fine-tuning a small language model need?

It depends mainly on the method. Full fine-tuning keeps gradients and optimiser states for every parameter: the QLoRA authors cite more than 780 GB of GPU memory for regular 16-bit fine-tuning of a 65-billion-parameter model. LoRA trains only small adapter matrices, and QLoRA also quantises the frozen base to 4 bits, which fitted that 65-billion-parameter model on a single 48 GB GPU. Small models need proportionally less.

Is LoRA as good as full fine-tuning?

Sometimes, but not always. The LoRA paper reports results on par with or better than full fine-tuning on RoBERTa, DeBERTa, GPT-2 and GPT-3. A 2024 study on programming and mathematics found that LoRA, in standard low-rank settings, substantially underperformed full fine-tuning on the target domain, but better preserved the base model's performance on other tasks. Measure both the gain on the target task and any loss elsewhere.

How many training examples do I need?

There is no reliable fixed number; quality and relevance matter more than size. The QLoRA authors found that a 9,000-example dataset outperformed a 450,000-example subsample of another dataset on chatbot performance. Start with a clean, representative set that matches the production task, measure it against a held-out evaluation set, and add examples where the evaluation shows gaps rather than adding volume for its own sake.

Which LoRA settings should I start with?

Apply LoRA to all linear layers, not only attention: the QLoRA authors found this necessary to match full fine-tuning, and a 2024 study found attention-only adapters underperformed. On rank, QLoRA found it mattered little once all layers were adapted, while the 2024 study found ranks of 16 to 64 insufficient for code and suggests 256 where memory allows, with alpha at twice the rank. Tune the learning rate on validation data.

What is catastrophic forgetting, and how do I detect it?

Catastrophic forgetting is the loss of general capabilities, such as following instructions or refusing unsafe requests, while a model learns a new domain. Detect it by running a general-capability and safety test set before and after fine-tuning, alongside your task test set. A 2024 comparison found that LoRA forgets less than full fine-tuning. If regressions appear, lower the learning rate, shorten training or switch to LoRA.

Related insights

Plan your private AI with people who build it

Book a briefing. We look at your use case, data and constraints, and you leave with the deployment options and governance steps that fit.