Fine-tuning a language model is the continued training of a ready-made LLM on additional data. Choosing a setup comes down to two different decisions: what to teach the model and which parameters to change. SFT, DPO, and continued pretraining define the training objective; full fine-tuning, LoRA, and QLoRA describe how parameters are updated and stored. So contrasting “SFT or LoRA” is incorrect: SFT can be done through LoRA.
Prepared by AI Studio by Vladimir Lomtev on November 11, 2026 for technical leaders, developers, and LLM product owners. This article breaks down methods for adapting text-based language models, the structure of training data, experiment settings, and output release. Image, speech, and computer vision models have their own fine-tuning setups; not all of the settings from this guide can be applied to them.
This is a technical review based on the official Transformers, PEFT, and TRL documentation, as well as the original LoRA and QLoRA papers. We did not run our own training, quality comparisons, or GPU memory measurements. The data examples below are for learning purposes; they show the structure, not a ready-to-use dataset or a verified training result. Budget, contract, and cloud offering questions are collected separately in FAQ on Fine-Tuning with Company Data.
Contents
- What fine-tuning means and how it differs from pretraining
- First choose the training objective, then the way to change the weights
- How full model fine-tuning works
- How LoRA works: matrices, rank, and scaling
- Which layers to train and why a larger rank does not guarantee success
- What QLoRA adds and why training does not become fully 4-bit
- How SFT differs from continued pretraining and DPO
- What data for SFT and preference training looks like
- Why the tokenizer, chat template, and loss mask matter so much
- How to prepare data and split the datasets
- Which parameters control the experiment
- Why a falling training loss does not prove improvement
- What is saved after LoRA and how to release the result
- What other methods are worth knowing: DoRA, prompt tuning, and distillation
- How to choose a setup for your task
- Common questions about fine-tuning and adapters
What fine-tuning means and how it differs from pretraining
During training, the model receives token sequences, makes predictions, and updates trainable parameters to reduce the error function — loss. Fine-tuning usually starts from already trained weights: the model does not learn language from scratch, but adapts to additional data and a specific objective. Training in Transformers.
Under the single term “fine-tuning,” different tasks are often hidden:
- Continued pretraining on domain-specific texts: the model keeps learning language modeling on a new corpus.
- SFT, supervised fine-tuning: training on examples of desired behavior, such as dialogs or input–correct answer pairs.
- Preference training, for example DPO: for one prompt, the model is shown a more preferred and a less preferred answer.
- Reinforcement learning: behavior is changed based on a reward signal defined separately from simple reference continuation.
These stages can be combined, but it is not necessary to use all of them for every project. For classifying support tickets with a clear reference answer, it makes sense to start with SFT. If the model can answer, but systematically chooses an undesirable style or strategy among several acceptable ones, preference training may be needed. The available approaches and trainers are outlined in the TRL overview.
Instruction tuning usually means SFT on instructions and responses. PEFT, parameter-efficient fine-tuning, is a family of methods that train only a small portion of the parameters or added components. LoRA is part of PEFT; PEFT is not limited to LoRA.
First choose the training objective, then the way to change the weights
It is useful to consider the two axes separately.
| Objective | What data is needed | What result is expected |
|---|---|---|
| Continued pretraining | Texts from a suitable domain | Adaptation to the text distribution and terminology |
| SFT | Inputs and reference answers or dialogs | More reliable reproduction of the desired behavior |
| DPO | A prompt and a pair of answers with a preference | Shifting preference toward the selected answer |
| Reinforcement learning methods | Prompts and a defined reward signal | Optimizing behavior relative to the reward |
This table describes objectives, not guaranteed improvements. A corpus with errors, poor reference answers, or a misdefined reward can entrench undesirable behavior. The TRL documentation separately distinguishes language modeling, prompt-completion, and preference formats.
The second axis is which parameters are updated:
| Method | What is trained | What to pay attention to |
|---|---|---|
| Full fine-tuning | All weights of the base model selected for training | Gradients and optimizer state require additional resources |
| Partial update | Preselected layers or components | The choice of frozen and trainable parts affects adaptation capabilities |
| LoRA | Small additive matrices, with the base usually frozen | You need to choose the target layers, rank, and how to apply the adapter |
| QLoRA | LoRA adapters on top of a low-bit frozen base | Compatibility of quantization, compute precision, and training |
This gives you a specific setup, for example, SFT + LoRA for changing the response format or SFT + QLoRA, if base memory is critical. The word LoRA by itself does not tell you which examples were used or which loss function was optimized.
How full model fine-tuning works
In full fine-tuning, all parameters included in the optimizer are updated. This makes it possible to adjust the model across the entire network, but it creates large training states: in addition to weights, you need gradients, optimizer states, and activations for the backward pass. Memory also depends on sequence length, batch size, compute precision, and device sharding. Transformers training guide.
The file size of a finished model does not show how much memory full training will require. You cannot take the weight estimate for inference and present it as the requirement for a training server. Distribution techniques, activation checkpointing, and the optimizer change the picture, so the blanket recommendation that “one GPU is enough for any medium-size model” is unreliable.
Full updating is considered when the limits of the adapter approach have been confirmed by comparison, and when there is data and resources for a controlled experiment. Choosing it just because the word “full” sounds more reliable is not a good idea. Both LoRA and full fine-tuning can overfit on a narrow dataset.
How LoRA works: matrices, rank, and scaling
LoRA, Low-Rank Adaptation, keeps the base weight matrix and trains a small low-rank addition. In simplified form:
W_new = W_base + s × B × A
If the base matrix has size d_out × d_in, the additive matrices can be represented as d_out × r and r × d_in. The parameter r, or rank, limits the size of this addition. Instead of changing the whole matrix, two smaller ones are trained. This is the core principle of the original LoRA paper.
For a hypothetical square 4096 × 4096 matrix, the original number of parameters is 16,777,216. With rank 16, the two additive matrices contain 4096 × 16 + 16 × 4096 = 131,072 parameters. That is 128 times fewer for the additive update of this one matrix. This calculation does not mean the whole model or total GPU memory becomes 128 times smaller: the base weights are still needed, as are training activations.
In a typical PEFT configuration, the update scale is tied to lora_alpha / r; for rank-stabilized LoRA, a different dependence is used — on the square root of the rank. So comparing only r without the scale and method variant is not enough. PEFT LoRA guide.
An adapter does not have an independent ability to answer without the base model. It describes changes to specific components of a specific model. This matters for storage, versioning, and deployment.
Which layers to train and why a larger rank does not guarantee success
The target_modules parameter determines which modules get LoRA added to them. In a Transformer, these can be attention projections and linear layers in other blocks. Module names differ across architectures; a list from someone else’s example cannot be automatically transferred to your model.
PEFT also supports broader choices such as target_modules="all-linear". For QLoRA-like training, the documentation describes applying adapters to all linear layers. But this is not a universal optimum: the number of trainable parameters and the model’s ability to adapt both change. For some MoE architectures, the targets may be parameters arranged differently from standard linear modules. Configuring target modules in PEFT.
Increasing rank expands the update space and the adapter’s resource usage. It does not fix contradictory labels, an incorrect chat template, or training on the wrong tokens. If the model outputs valid JSON but chooses the wrong contact category, adding rank without analyzing the data may not solve anything.
For the first comparison, keep the base model, data, training objective, and target modules fixed. Then change one significant factor at a time. This is a proposed experiment order, not a comparison of configurations we have already run.
What QLoRA adds and why training does not become fully four-bit
QLoRA combines LoRA with a quantized base model. The base weights are stored compactly and remain frozen; trainable additions make it possible to adapt behavior. The original paper describes NF4, double quantization, and paged optimizers. This is a coordinated resource-saving method, not just a file with “Q4” in its name. The original QLoRA paper.
Storing the base in four bits does not mean all multiplications, activations, and gradients are also four-bit. Storage precision and compute precision are set separately. The PEFT documentation gives an NF4 setup with BF16 computation, preparation through prepare_model_for_kbit_training and then adding LoRA. This is the sequence for a supported combination of libraries and hardware. Quantization and PEFT.
Here, “double quantization” means additional compression of quantization constants, not two consecutive training passes or a standard re-conversion of a Q4 file. NF4 is a representation type in this scheme; it is not identical to any INT4 or Q4_K_M.
QLoRA reduces part of the cost, but it does not remove dependence on example length or training batch size. With long conversations, activations can take up a lot of memory. The claim “the weights fit, so training will definitely run” is wrong.
How SFT differs from continued pretraining and DPO
In SFT , the model learns to produce the desired continuation for a given input. For example, a customer message should be turned into a short support reply or into a record with a category and extracted fields. What matters is not only the text, but also which tokens the loss is computed on. How SFTTrainer works.
Continued pretraining on industry texts can change knowledge of terminology and domain patterns. But it does not turn weights into a governed database of current policies with verifiable references. A model can absorb facts, but precise updates, deletions, and reproducible citation require a different mechanism. For changeable company documents, teams often keep RAG; behavioral adaptation can be added separately if needed. The task difference is explained in detail in the comparison of RAG, fine-tuning, and prompt engineering.
DPO, Direct Preference Optimization, uses preferences: for one prompt there is a chosen response chosen and a rejected one rejected. The method changes relative preference based on a reference policy; this is a different training objective than simply reproducing a single reference. The implementation may precompute reference model scores, so the physical training setup depends on the configuration. DPOTrainer.
DPO should not be added automatically after any SFT. If the “preferred” answer is simply longer and the expert picks it because of length, the model may learn that bias. The preference rule should reflect the desired property: correctness, completeness, tone, or compliance with a constraint.
What SFT and preference-training data look like
For dialog SFT, records with the roles system, user, assistant, are suitable if the selected trainer and template support that format. Here is a fictional example of one record. It illustrates the dialog structure; one example is not enough to determine whether a dataset is suitable.
{
"messages": [
{"role": "system", "content": "Identify the request category. Return JSON with the fields category and order_id. Do not invent a missing order number."},
{"role": "user", "content": "Order 104 arrived with a damaged lid. How do I request a replacement?"},
{"role": "assistant", "content": "{\"category\":\"damaged_item\",\"order_id\":\"104\"}"}
]
}
The reference defines the format and category, but does not invent a replacement procedure or promise a refund. If the goal is data extraction, do not quietly train the model to invent service rules as well. A missing order number should be represented in the way required by the schema, consistently across the entire dataset.
For DPO, the structure is different. The following example shows a preference for an answer that does not invent order status:
{
"prompt": "Has order 104 already shipped? There is no status data.",
"chosen": "I don’t have data on the status of order 104. To answer, I need to check the order system.",
"rejected": "Yes, order 104 has shipped and will arrive tomorrow."
}
This is a training pair, not the result of an experiment. The messages and prompt/chosen/rejected schemas are described in the TRL format documentation. A specific loader may expect JSONL, a dataset object, or another container; JSON with fields by itself does not guarantee compatibility with the full training pipeline.
Why the tokenizer, chat template, and loss mask matter
The tokenizer converts text into tokens. The chat template turns role-based messages into a sequence with the model’s special markers. The loss mask determines which positions are included in the error calculation. These three components are easy to confuse, even though they solve different problems.
A dialog in JSON is not yet a ready-to-train representation. If the template does not match the model, it may see the wrong message boundaries or extra special tokens. The Transformers documentation separately warns about duplicating special tokens when formatting manually and tokenizing again. Chat templates.
For prompt-completion datasets, SFTTrainer supports training on the completion. For conversational datasets, the assistant_only_loss=True mode lets you compute loss only on assistant answers, but it requires a compatible template that can mark the relevant spans. Support and automatic preparation depend on the model family and library version. One flag does not fix an arbitrary template. Loss configuration in SFTTrainer.
A practical question before a long run: which exact tokens will the model be trained to predict in this record? Make sure the desired answer is included in the sequence and was not cut off by the length limit, and that the user text did not become the training target against the intent. This matters especially for long conversations, where the reference is at the end.
How to prepare data and split the datasets
Start with rules that define a good answer. For the damaged-item example, you need category definitions, limits on allowed values, and a rule for missing data. If experts label the same situation differently, the model will receive conflicting objectives.
The dataset should include typical and edge-case inputs: an explicit order number, a missing number, multiple numbers, a typo, and a message without enough context. Synthetic records can expand coverage, but their labels and facts need review. They do not prove quality on real cases. The limitations are covered in the FAQ on synthetic data.
Split the data by dependency source. Replies from the same conversation, nearly identical requests, and template variations of one document should not be split carelessly between train and test: the model may see in training nearly the same example it is later evaluated on. If future requests matter, consider a time-based split. This is a methodological recommendation, not a universal sample ratio.
Train is used for training. Validation helps you choose settings and stopping. Test is needed for final evaluation after selection. Repeatedly tuning parameters based on test errors gradually turns the test set into another validation set.
There is no universal number of examples. What matters is input diversity, consistency of references, task difficulty, and the model’s starting capabilities. Corpus size and number of passes should be considered together: repeating a narrow set many times does not create new independent situations.
Which parameters control the experiment
| Parameter | What it affects | Common interpretation mistake |
|---|---|---|
| Learning rate | The size of updates to trainable parameters | Transferring a value from full fine-tuning to LoRA without checking |
| Number of epochs or steps | How many updates the model receives | Assuming longer is always better |
| Batch size and accumulation | The composition of one update and resource usage | Looking only at the number of examples on one GPU |
| Maximum length | Which parts of the examples are included in training | Quietly cutting off the reference answer |
| Rank r and alpha | The capacity and scale of the LoRA update | Changing r without accounting for the scaling variant |
| Target modules | Where the model receives the trainable extension | Copying layer names from a different architecture |
| Packing | Combining examples into sequences | Including examples without understanding the separation of examples and trainer behavior |
| Loss mask | Which tokens create the training signal | Training on irrelevant roles or empty target spans |
The settings for these mechanisms are described in PEFT LoRA and SFTTrainer. The table explains what the parameters mean; there is no ready-made universal set of values here.
To preserve reproducibility, record the dataset revision, tokenizer and template, library versions, data preparation and split, training configuration, and checkpoint source. It is useful to save the random seed, but by itself it does not guarantee the same result on any hardware and software stack.
Why a falling training loss does not yet prove improvement
Training loss shows how much the model is fitting the training sequences. It may memorize repetitions, reproduce style better, and at the same time answer new inputs worse. Evaluation on held-out data is needed precisely to separate overfitting from useful transfer.
In an order-number extraction task, you should check separately whether the JSON is valid, whether the category is correct, whether the number was extracted properly, and whether a made-up number appeared when none was present. A general impression that “the answer looks professional” will not catch such errors.
Compare the adapted and base model on the same inputs and with the same generation settings. If the template, system prompt, and connected search all changed at the same time, the result cannot be fully attributed to LoRA. For important general-purpose functions, keep a set of regression tests to catch side effects and degradations.
Possible causes of problems differ. A decline after several passes may point to overfitting; equally bad behavior from the start may indicate bad data or format; truncation may be caused by a length limit or end-of-sequence handling. These are diagnostic hypotheses that should be checked against run artifacts. The article does not claim any firsthand observations about these failures.
What is saved after LoRA and how to deploy the result
When saving a PEFT adapter, the file adapter_model.safetensors contains the adapter parameters, and adapter_config.json contains its configuration and base-model information. This is not the full set of base weights. Reconstructing it requires compatible source weights; it is better to record the exact revision explicitly. PEFT checkpoint format.
There are two main ways to use it: load the base model and adapter together, or merge a supported adapter into the base weights. PEFT documents merge_and_unload, but merge availability depends on the method and quantization scheme. You should not assume that any low-bit checkpoint supports any merge operation. Ways to combine models and adapters.
If the model is exported and quantized for inference after merging, that creates another object to validate. You need to test exactly the file and engine that will go into production. The reasons are explained in the practical guide to quantization and GGUF.
The dataset, tokenizer, template, and settings are just as important for reproducing training as the final adapter. If the base model changes, compatibility is not automatic. Rollback should restore the entire agreed set of components, not just the weight file.
What else is worth knowing: DoRA, prompt tuning, and distillation
DoRA extends the adapter approach by separating changes in weight direction and magnitude. In PEFT, it is enabled with a separate setting and has its own requirements and limitations. It is an option to compare for a specific task, not a guaranteed improvement over any LoRA. The documentation also describes different initializations and rank variants: it is worth studying them after you understand the data and the baseline setup. LoRA and DoRA variants.
Prompt tuning and prefix tuning train additional continuous representations at the model input or inside the mechanism. This is not the same as a human manually editing a text prompt. They belong to parameter-efficient adaptation, but they differ from LoRA in where and how the trainable addition is applied. Introduction to PEFT.
Distillation uses a teacher model as the source of the training signal for a student. For example, the teacher’s answers can become material for SFT of the student; this requires quality checks and rights to use the data. Distillation and LoRA can be part of the same project because they answer different questions: where the signal comes from and which parameters are updated. A separate breakdown of LLM distillation.
How to choose a scheme for your task
If the model is not getting the needed up-to-date facts, first provide access to the source: document search, an API, or a database. If the facts are available but the answer consistently breaks the required format and examples in the prompt do not help, consider SFT. If resources are limited, compare LoRA or QLoRA with the available base model.
If the task is to change the preference between acceptable answers and you have reliable pairwise evaluations, consider DPO. If the model performs poorly with the language and distribution of industry texts, the question of continued pretraining deserves separate study. These options may require different data, so a company’s general archive cannot be treated as a ready-made universal dataset.
Full fine-tuning should be chosen only when the need is confirmed and resources are available. Parameter-efficient methods are a useful starting point for comparison, but the decision depends on the quality of the specific operation. Increase the complexity of the setup only after you understand the error in the simpler version.
Common questions about fine-tuning and adapters
Is LoRA a smaller model?
No. The adapter is small, but it still needs the base model at runtime. A compact adapter file should not be compared with a full checkpoint as if they were two independent implementations of the same task.
Are QLoRA and Q4_K_M the same thing?
No. QLoRA is a training scheme for an adapter on top of a quantized base. Q4_K_M is a tensor representation variant in the GGUF ecosystem. The fact that GGUF runs successfully does not mean that the same copy is ready for training through TRL.
Can a model be trained only on company documents?
It is possible to continue language training on text if the rights, data, and tools allow it. Training for the desired answers requires examples of the relevant behavior. Documents, SFT dialogues, and preference pairs are different training signals.
Can an adapter reveal training data?
An adapter method by itself is not a de-identification mechanism or a guarantee of confidentiality. Sensitive data must be handled according to established rules before training, access to artifacts must be restricted, and the system’s behavior must be tested separately. The claim that “we train only small matrices, so leaks are impossible” is unfounded.
How Vladimir Lomtev’s AI studio helps adapt a language model
Vladimir Lomtev’s AI studio can prepare data for fine-tuning, fine-tune and test an LLM, deploy it, and integrate it with corporate data sources. The method is chosen based on the required behavior, available data, and infrastructure constraints, without promising results from the LoRA or QLoRA name alone.
The first step is to choose one process and describe the model’s current errors, the source data, and the criterion for an acceptable response. That makes it clear whether you need a new training signal or whether it’s enough to change access to information and the prompt. Discuss the task.
Bottom line: fine-tuning starts with a training task
First, define what you want the model to learn: continue domain-specific text, reproduce reference answers, or prefer one answer over another. Then choose how to change the parameters: fully, partially, or through an adapter. LoRA and QLoRA help manage resources, but they do not replace correct data, prompt design, and evaluation.
The project deliverable is a coordinated set of base weights, an adapter or full weights, a tokenizer, settings, and confirmed constraints. You need to test the behavior of the final service on new inputs. A small adapter file and a falling training loss by themselves still do not show that the task has been solved.


