Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 139/ 160
07. Deep Learning & NLP

Fine-Tuning Pre-trained Hugging Face Models

Fine-tune Transformers for classification/NER with Hugging Face Trainer workflows.

AdvancedHF Models · Fine-tune3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Fine-tuning takes a model that already understands language and teaches it your specific job, such as sorting your emails, by showing it a few thousand examples with the right answers.

Think of it like…

Taking a graduate who has already read widely and giving them a short, focused course on your company's documents. A gentle pace preserves what they know, and testing them on questions they haven't seen shows whether they actually learned your domain.

Where you’ve seen it

A team fine-tunes a 110-million-parameter BERT-style encoder to classify 8,000 support tickets into 6 categories. Tokenisation truncates to 128 tokens with dynamic padding. With batch size 16 there are 8,000 / 16 = 500 steps per epoch, 1,500 over 3 epochs, and a 10% warm-up of 150 steps before the learning rate of 2e-5 decays linearly; weight decay is 0.01, evaluation runs every epoch and load_best_model_at_end restores the best checkpoint by macro-F1. Full fine-tuning in float32 with AdamW needs 110M × 4 bytes = 440 MB for weights, 440 MB for gradients and 880 MB for optimiser state, 1.76 GB before activations. A LoRA variant with rank 8 on the query and value projections of 12 layers (hidden size 768) adds 2 × 768 × 8 = 12,288 parameters per adapted matrix, 2 × 12 × 12,288 = 294,912 trainable parameters, about 0.27% of the model. Because fine-tuning is seed-sensitive, they run five seeds: macro-F1 of 0.872, 0.879, 0.868, 0.881 and 0.875 (illustrative) averages 0.875 with a standard deviation of about 0.005, against 0.81 for the TF-IDF baseline. A first run with a learning rate of 1e-3 collapsed to predicting one class, which is why 2e-5 became the default. They keep duplicates out of the test set, log the exact checkpoint, tokenizer and library versions, and publish a model card describing the data and its limits.

Words you’ll hear

Trainer
Hugging Face's high-level training loop with evaluation, checkpointing and logging.
Dynamic padding
Padding each batch to its own longest sequence rather than a global maximum.
LoRA
Low-rank adapters trained while the base weights stay frozen.
Checkpoint
A saved model state; the best one by validation metric is usually kept.

Visual diagram

Loading interactive diagram

Theory & deep dive

The Trainer workflow and its settings

Load the data with datasets, then tokenizer(texts, truncation=True, max_length=128); use DataCollatorWithPadding so each batch pads only to its longest example, which cuts wasted compute. Load AutoModelForSequenceClassification.from_pretrained(name, num_labels=6), which adds a randomly initialised head on the pretrained encoder. TrainingArguments carries the recipe: learning rate 2e-5 (range 1e-5 to 5e-5), epochs 2 to 4, batch size 16 or 32, weight decay 0.01, warm-up ratio 0.1, evaluation and save each epoch and load_best_model_at_end=True with metric_for_best_model set to your metric. For 8,000 examples and batch size 16: 500 steps per epoch, 1,500 over 3 epochs, 150 warm-up steps.

Write compute_metrics to return the metric you actually care about (macro-F1 for imbalanced classes, entity-level F1 for NER via seqeval). For token classification, align word-level labels to subword tokens: label the first subword and set the rest to −100 so the loss ignores them. For imbalanced classes, pass class weights through a custom loss or oversample. Set a seed, log the library versions and save the tokenizer with the model so inference uses identical preprocessing.

Step arithmetic

8,000 examples ÷ 16 = 500 steps per epoch. 3 epochs = 1,500 steps. Warm-up ratio 0.1 = 150 steps. With gradient accumulation of 2 the effective batch is 32 and the optimiser steps 750 times in total.

Key takeaway: Use a small learning rate, dynamic padding, the right task head and a compute_metrics function that matches the business metric.

Memory, LoRA, seeds and evaluation discipline

Full fine-tuning in float32 with AdamW holds weights, gradients and two optimiser tensors per parameter: for 110 million parameters, 440 MB + 440 MB + 880 MB = 1.76 GB, plus activations that scale with batch size and sequence length. Mixed precision (fp16 or bf16) and gradient checkpointing reduce this. LoRA freezes the base model and adds low-rank matrices A (d × r) and B (r × d) to selected projections: 2 × 768 × 8 = 12,288 parameters per adapted matrix, so adapting query and value in 12 layers trains 294,912 parameters (0.27% of the model), makes the saved adapter a few megabytes and lets one base model serve many tasks. For multi-billion-parameter models, LoRA (with quantisation, as in QLoRA) is often the only practical route on a single GPU.

Fine-tuning has noticeable seed variance, so report the mean and spread over several seeds (0.872, 0.879, 0.868, 0.881 and 0.875 average 0.875 with a standard deviation of about 0.005) and compare to the simple baseline on the same splits. Guard against leakage and duplicates between train and test, and against truncation that cuts away the part of the text that carries the label. If validation is flat and training loss collapses, the learning rate is likely too high; if both are flat, the learning rate may be too low or labels noisy. Finally, check latency and size for deployment (distilled or quantised models may suffice) and document the data, intended use and limitations in a model card.

LoRA parameter count

Hidden size 768, rank 8: each adapted matrix gains A (768 × 8) and B (8 × 768) = 6,144 + 6,144 = 12,288 parameters. Query and value in 12 layers: 24 matrices × 12,288 = 294,912 trainable parameters, about 0.27% of 110 million.

Key takeaway: Budget memory up front, consider LoRA for large models and report results across seeds against a strong baseline.

How it works, step by step

Step 1 of 4
Data scientist

1. Prepare and split the data

Clean labels, split by customer or document source and remove duplicates across the splits.

8,000 tickets · 6 classes
Key numbers at this step
Fit
TF-IDF baseline first

When to use it & trade-offs

What it is

Fine-tuning adapts a pretrained transformer to your labelled data. With Hugging Face the workflow is: load a dataset (datasets), tokenise it with the model's own tokenizer (truncation to a maximum length, dynamic padding per batch), load a pretrained checkpoint with a task head (AutoModelForSequenceClassification or AutoModelForTokenClassification), configure TrainingArguments (learning rate, epochs, batch size, weight decay, warm-up, evaluation and save strategy), pass a compute_metrics function and call Trainer.train(). Parameter-efficient methods such as LoRA freeze the base model and train small low-rank adapters, cutting memory and storage. Fine-tuning usually beats TF-IDF baselines when you have a few thousand labelled examples and text where context matters.

Why it matters: Pretrained models already know grammar, semantics and a lot of world knowledge, so with a few thousand labelled examples you can reach accuracy that training from scratch cannot. But fine-tuning has sharp edges: a learning rate that is too high destroys pretrained knowledge, results vary noticeably by random seed, long documents get silently truncated, label alignment for token tasks is easy to get wrong and full fine-tuning of even a 110-million-parameter model needs gigabytes of memory. Knowing the recipe, the numbers and the checks makes the difference between a reproducible gain and a lucky run.

When to reach for it

  • Ticket, intent and document classification with thousands of labels
  • Domain-specific NER with token classification heads
  • Adapting a model to a specialised vocabulary with LoRA

When to avoid or be careful

  • A high learning rate such as 1e-3 on a pretrained transformer
  • Reporting a single-seed result as the final number
  • Evaluating on a test set that contains near-duplicates of training examples

Fine-tuning options

Full fine-tuning
Best for: Small to medium encoders with enough GPU memory

Strengths: Maximum adaptation.

Watch out: 1.76 GB for a 110M model; one copy per task.

LoRA / adapters
Best for: Large models, many tasks, limited memory

Strengths: 0.27% trainable; tiny checkpoints.

Watch out: Slightly lower ceiling in some tasks; extra tooling.

Feature extraction (frozen encoder + classifier)
Best for: Very small datasets and quick baselines

Strengths: Cheap and stable.

Watch out: Lower accuracy than fine-tuning.

Interview signals & numbers to know

When this topic comes up

  • “Walk me through fine-tuning BERT for classification”
  • Full fine-tuning versus LoRA
  • Why results vary across seeds
  • Label alignment for NER
  • Memory needed for fine-tuning

Benchmarks & rules of thumb

1.76 GB -
float32 AdamW memory for a 110M-parameter model before activations
294,912 -
LoRA parameters at rank 8 on q and v in a 12-layer, 768-wide model
2e-5 -
a common fine-tuning learning rate

Common mistakes & follow-ups

Common interview mistakes

  • Using the pretraining learning rate scale and wiping out useful weights.
  • Truncating away the sentence that contains the label signal.
  • Not saving the tokenizer with the model.

Likely interviewer follow-ups

  • How would you fine-tune a model larger than your GPU memory?
  • How do you make fine-tuning results reproducible?
  • What do you do when the baseline matches the fine-tuned model?
Interview tip: Report seed variance and the baseline score together; a gain smaller than the spread is not a gain.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Fine-Tuning Pre-trained Hugging Face Models with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Attention Mechanism & Transformer Overview
Next topic
Intro to LLMs & RAG for Data Scientists