Finetuning Large Language Models
For teams operationalizing LLMs, the key decision is not only whether to fine-tune, but where to place the training boundary in the delivery pipeline. A frozen-backbone approach shifts most complexity into feature extraction and downstream modeling, which can simplify rollout when model access is constrained or when multiple small tasks share the same embeddings. Full fine-tuning, by contrast, pushes more work into model training, validation, and artifact management, so release engineering has to account for longer cycles, larger checkpoints, and tighter experiment tracking.
The architectural trade-off is lifecycle overhead versus task specificity. Once a model is adapted, teams need a repeatable path for dataset versioning, evaluation gates, and rollback. That matters because changes to prompts, adapters, or output layers can affect not only accuracy but also latency, memory use, and retraining frequency. In production, these differences influence whether a model can run on existing GPU capacity, whether batching remains effective, and how easily one shared base model can support multiple products without duplication.
Governance and integration are also part of the engineering cost. Fine-tuned models become versioned dependencies inside application stacks, so downstream services must know which model variant they are calling, which data it was trained on, and how to detect drift after deployment. For organizations already using retrieval or prompt-based workflows, this creates a practical selection problem: use adaptation when task behavior must be baked into the model, or preserve a lighter-weight orchestration layer when the change rate is high and the knowledge source should stay external.
In the rapidly evolving field of artificial intelligence, utilizing large language models (LLMs) efficiently and effectively has become increasingly important. But we can use large language models in many different ways, which can be overwhelming if you are starting out. In essence, we can use pretrained large language models for new tasks in two main ways: in-context learning and finetuning. In this article, we will briefly go over what in-context learning means, and then we will go over the various ways we can finetune LLMs.
In-Context Learning and Indexing
Since GPT-2 (Radford et al.) and GPT-3 (Brown et al.), we have seen that generative large language models (LLMs) pretrained on a general text corpus are capable ofย in-context learning, which doesnโt require us to further train or finetune pretrained LLMs if we want to perform specific or new tasks that the LLM wasnโt explicitly trained on. Instead, we can directly provide a few examples of a target task via the input prompt, as illustrated in the example below.


The 3 Conventional Feature-Based and Finetuning Approaches
In-context learning is a valuable and user-friendly method for situations where direct access to the large language model (LLM) is limited, such as when interacting with the LLM through an API or user interface. However, if we have access to the LLM, adapting and finetuning it on a target task using data from a target domain usually leads to superior results. So, how can we adapt a model to a target task? There are three conventional approaches outlined in the figure below.
1) Feature-Based Approach
In the feature-based approach, we load a pretrained LLM and apply it to our target dataset. Here, we are particularly interested in generating the output embeddings for the training set, which we can use as input features to train a classification model. While this approach is particularly common for embedding-focused like BERT, we can also extract embeddings from generative GPT-style model. The classification model can then be a logistic regression model, a random forest, or XGBoost โ whatever our hearts desire. (However, based on my experience, linear classifiers like logistic regression perform best here.) Conceptually, we can illustrate the feature-based approach with the following code:model = AutoModel.from_pretrained("distilbert-base-uncased")
# ...
# tokenize dataset
# ...
# generate embeddings
@torch.inference_mode()
def get_output_embeddings(batch):
output = model(
batch["input_ids"],
attention_mask=batch["attention_mask"]
).last_hidden_state[:, 0]
return {"features": output}
dataset_features = dataset_tokenized.map(
get_output_embeddings, batched=True, batch_size=10)
X_train = np.array(imdb_features["train"]["features"])
y_train = np.array(imdb_features["train"]["label"])
X_val = np.array(imdb_features["validation"]["features"])
y_val = np.array(imdb_features["validation"]["label"])
X_test = np.array(imdb_features["test"]["features"])
y_test = np.array(imdb_features["test"]["label"])
# train classifier
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
clf.fit(X_train, y_train)
print("Training accuracy", clf.score(X_train, y_train))
print("Validation accuracy", clf.score(X_val, y_val))
print("test accuracy", clf.score(X_test, y_test))
(Interested readers can find the full code exampleย here.)
2) Finetuning I โ Updating The Output Layers
A popular approach related to the feature-based approach described above is finetuning the output layers (we will refer to this approach asย finetuning I). Similar to the feature-based approach, we keep the parameters of the pretrained LLM frozen. We only train the newly added output layers, analogous to training a logistic regression classifier or small multilayer perceptron on the embedded features. In code, this would look as follows:model = AutoModelForSequenceClassification.from_pretrained(
"distilbert-base-uncased",
num_labels=2
)
# freeze all layers
for param in model.parameters():
param.requires_grad = False
# then unfreeze the two last layers (output layers)
for param in model.pre_classifier.parameters():
param.requires_grad = True
for param in model.classifier.parameters():
param.requires_grad = True
# finetune model
lightning_model = CustomLightningModule(model)
trainer = L.Trainer(
max_epochs=3,
...
)
trainer.fit(
model=lightning_model,
train_dataloaders=train_loader,
val_dataloaders=val_loader)
# evaluate model
trainer.test(lightning_model, dataloaders=test_loader)
(Interested readers can find the complete code exampleย here.)
In theory, this approach should perform similarly well, in terms of modeling performance and speed, as the feature-based approach since we use the same frozen backbone model. However, since the feature-based approach makes it slightly easier to pre-compute and store the embedded features for the training dataset, the feature-based approach may be more convenient for specific practical scenarios.
3) Finetuning II โ Updating All Layers
While the original BERT paper (Devlin et al.) reported that finetuning only the output layer can result in modeling performance comparable to finetuning all layers, which is substantially more expensive since more parameters are involved. For instance, a BERT base model has approximately 110 million parameters. However, the final layer of a BERT base model for binary classification consists of merely 1,500 parameters. Furthermore, the last two layers of a BERT base model account for 60,000 parameters โ thatโs only around 0.6% of the total model size. Our mileage will vary based on how similar our target task and target domain is to the dataset the model was pretrained on. But in practice, finetuning all layers almost always results in superior modeling performance. So, when optimizing the modeling performance, the gold standard for using pretrained LLMs is to update all layers (here referred to as finetuning II). Conceptually finetuning II is very similar to finetuning I. The only difference is that we do not freeze the parameters of the pretrained LLM but finetune them as well:model = AutoModelForSequenceClassification.from_pretrained(
"distilbert-base-uncased",
num_labels=2
)
# don't freeze layers
# for param in model.parameters():
# param.requires_grad = False
# finetune model
lightning_model = LightningModel(model)
trainer = L.Trainer(
max_epochs=3,
...
)
trainer.fit(
model=lightning_model,
train_dataloaders=train_loader,
val_dataloaders=val_loader)
# evaluate model
trainer.test(lightning_model, dataloaders=test_loader)
(Interested readers can find the complete code exampleย here.)
If you are curious about some real-world results, the code snippets above were used to train a movie review classifier using a pretrained DistilBERT base model (you can access the code notebooksย here):
- 1) Feature-based approach with logistic regression: 83% test accuracy
- 2) Finetuning I, updating the last 2 layers: 87% accuracy
- 3) Finetuning II, updating all layers: 92% accuracy.


Parameter-Efficient Finetuning
Parameter-efficient finetuningย allows us to reuse pretrained models while minimizing the computational and resource footprints. In sum, parameter-efficient finetuning is useful for at least 5 reasons:- Reduced computational costs (requires fewer GPUs and GPU time);
- Faster training times (finishes training faster);
- Lower hardware requirements (works with smaller GPUs & less smemory);
- Better modeling performance (reduces overfitting);
- Less storage (majority of weights can be shared across different tasks).

Reinforcement Learning with Human Feedback
In Reinforcement Learning with Human Feedback (RLHF), a pretrained model is finetuned using a combination of supervised learning and reinforcement learning — the approach was popularized by the original ChatGPT model, which was in turn based on InstructGPT (Ouyang et al.). In RLHF, human feedback is collected by having humans rank or rate different model outputs, providing a reward signal. The collected reward labels can then be used to train a reward model that is then in turn used to guide the LLMs adaptation to human preferences. The reward model itself is learned via supervised learning (typically using a pretrained LLM as base model). Next, the reward model is used to update the pretrained LLM that is to be adapted to human preferences — the training uses a flavor of reinforcement learning called proximal policy optimization (Schulman et al.).
Conclusion
Fine-tuning all layers of a pretrained LLM remains the gold standard for adapting to new target tasks, but there are several efficient alternatives for using pretrained transformers. Methods such as feature-based approaches, in-context learning, and parameter-efficient finetuning techniques enable effective application of LLMs to new tasks while minimizing computational costs and resources. Moreover, reinforcement learning with human feedback (RLHF) serves as an alternative to supervised finetuning, potentially enhancing model performance.
Enjoyed this article? Sign up for our newsletter to receive regular insights and stay connected.
