AI / AI model fine tuning concepts Interview questions
Last updated
1. What is fine-tuning of an AI model?
Fine-tuning means taking an already pre-trained model and continuing its training on a smaller, task-specific dataset, so it adapts to a particular domain, style, or task. The starting point is the pre-trained weights, not random values.
The model already knows general patterns such as grammar, code structure, or visual features. That is why fine-tuning needs far less data and compute than training from scratch. A few hundred to a few thousand good examples is often enough for a focused task.
Typical uses: classifying support tickets, making an LLM reply in a company's tone, or extracting fields into a fixed JSON schema.
Take quiz
randomly initialized weights
the weights of an already pre-trained model
an empty model with no layers
The model already learned general patterns during pre-training
The model ignores most of the new examples
Fine-tuning skips the backward pass
2. What is a pre-trained foundation model?
A foundation model is a large model trained on broad, mostly unlabeled data with a self-supervised objective, such as predicting the next token or a masked token. It learns general representations that can be adapted to many downstream tasks.
Three common families you will meet in interviews:
| Family | Pre-training objective | Architecture |
| BERT-style | Masked token prediction | Encoder |
| GPT-style | Next-token prediction | Decoder |
| T5-style | Text-to-text span corruption | Encoder-decoder |
Fine-tuning, prompting, or RAG then specialize this general model for a real use case.
Take quiz
image segmentation masks
next-token prediction
k-means clustering of embeddings
reinforcement learning from human feedback
next-token prediction in a decoder
masked token prediction
3. What is transfer learning?
Transfer learning reuses knowledge learned on one task or dataset to improve performance on another. Fine-tuning is one form of it: you keep the learned weights and keep training them.
Two common styles exist:
| Aspect | Feature extraction | Fine-tuning |
| Base weights | Frozen | Updated (some or all layers) |
| Trained part | New task head only | Head plus base layers |
| Data needed | Less | More |
| Forgetting risk | None for the base | Higher |
Example: take an image model pre-trained on ImageNet, freeze it, and train a new 5-class head for plant diseases. If accuracy plateaus, unfreeze the top layers and train them at a low learning rate.
Take quiz
Every layer of the base model
Only the new task-specific head
Only the tokenizer merges
a form of transfer learning where pre-trained weights are further updated
a way to compress a model into fewer bits
a method of generating synthetic data
a way to cache prompts
4. What are the types of fine-tuning?
The main types differ by which weights change and what signal drives training:
- Full fine-tuning - every weight is updated.
- Parameter-efficient fine-tuning (PEFT) - LoRA, adapters, prefix and prompt tuning update a tiny subset.
- Supervised / instruction tuning - learns from prompt-response pairs.
- Preference tuning - RLHF or DPO learn from human or AI preference comparisons.
- Continued pretraining - next-token training on raw domain text.
Real projects often chain them, for example continued pretraining, then SFT with LoRA, then DPO.
Take quiz
LoRA
Gradient checkpointing
DPO
instruction tuning
preference optimization
feature extraction
continued pretraining
5. What is supervised fine-tuning (SFT)?
SFT trains a model on labeled input-output pairs using the same cross-entropy loss as pre-training, but on curated examples. For chat LLMs, each example is a prompt plus the ideal response.
The model learns to imitate those responses. SFT is usually the first stage after pre-training and also the starting point for RLHF or DPO.
A typical JSONL record looks like this:
{"messages": [ {"role": "user", "content": "Summarize: The server crashed at 2 AM..."}, {"role": "assistant", "content": "A 2 AM server crash caused downtime; a patch fixed it."} ]}
Take quiz
a prompt and the ideal response
only unlabeled raw text
a reward score without any text
after deployment only
instead of pre-training in every case
after the test set is finalized
before RLHF or DPO
6. What is instruction tuning?
Instruction tuning is SFT on a broad collection of (instruction, response) pairs across many tasks, so the model learns to follow natural-language instructions instead of just continuing text. FLAN and the SFT stage of InstructGPT are well-known examples.
A base model given "Translate to French: hello" may keep writing more English. An instruction-tuned model simply answers. Task variety matters because it helps the model generalize to instructions it never saw in training.
Datasets such as FLAN pack many tasks into instruction templates, for example summarization, sentiment, and question answering. Mixing task types and phrasings is what lets one model handle a request it has never seen verbatim.
Take quiz
tokenizer vocabulary size
GPU memory bandwidth
following natural-language instructions across tasks
to make the file larger
to avoid needing a validation set
so the model generalizes to unseen instructions
to disable the chat template
7. What is parameter-efficient fine-tuning (PEFT)?
PEFT adapts a model by training only a very small number of extra or selected parameters, often under 1-2% of the total, while the rest of the pre-trained weights stay frozen.
Why teams use it:
- Lower GPU memory, because no optimizer states are kept for frozen weights.
- Tiny checkpoints, megabytes instead of gigabytes.
- Many task adapters can share one base model.
- Less catastrophic forgetting.
Common methods: LoRA, adapters, prefix tuning, prompt tuning, IA3, and BitFit.
In interviews, mention the trade-off: PEFT can slightly trail full fine-tuning on very large domain shifts, but for most task adaptation the gap is small and the cost savings are large.
Take quiz
Train only a small set of parameters while freezing the rest
Train all layers on a smaller dataset
Delete layers to shrink the model
larger than the base model
megabytes in size, since only adapter weights are saved
identical in size to the base model
a single 1 KB text file
8. What is LoRA?
Low-Rank Adaptation (LoRA) freezes a pre-trained weight matrix W and learns its update as the product of two small matrices: ΔW = B x A. If W is d x k, then A is r x k and B is d x r, with the rank r much smaller than d and k.
The forward pass becomes h = Wx + (alpha / r) * B(Ax). A starts random and B starts at zero, so training begins from the exact behavior of the base model.
Example: a 4096 x 4096 layer has about 16.8M weights. At rank 8, LoRA trains only 65,536 of them (about 0.4%).
from peft import LoraConfig, get_peft_model config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj", "v_proj"], lora_dropout=0.05, task_type="CAUSAL_LM") model = get_peft_model(model, config)
Take quiz
As a product of two low-rank matrices
As a full copy of W
As a pruned version of W
So the adapted model starts identical to the base model
To skip gradient computation for B forever
To quantize the weights to 4 bits
To double the rank
9. What is QLoRA?
QLoRA fine-tunes LoRA adapters on top of a base model that is quantized to 4-bit. The 4-bit base stays frozen, the adapters are kept in 16-bit, and gradients flow through the dequantized weights into the adapters.
Three ideas make it work:
- NF4 - a 4-bit NormalFloat data type suited to normally distributed weights.
- Double quantization - quantizes the quantization constants too.
- Paged optimizers - move optimizer state to CPU RAM during memory spikes.
In the QLoRA paper (Dettmers et al., 2023), this let a 65B model be fine-tuned on a single 48 GB GPU.
Take quiz
FP32
NormalFloat4 (NF4)
binary 1-bit signs
the 4-bit base weights
the LoRA adapter weights only
the tokenizer embeddings only
the paged optimizer buffers
10. What is a learning rate in fine-tuning?
The learning rate sets how large a step the optimizer takes on every update. In fine-tuning it must be smaller than in pre-training, because the weights are already good and big steps can wreck them.
Typical starting points: full fine-tuning of LLMs around 1e-5 to 5e-5, and LoRA around 1e-4 to 2e-4. LoRA tolerates more because its adapters start near zero. Most setups add a short warmup and then a cosine or linear decay.
If the loss spikes right after training starts, the rate is probably too high. If it barely moves after a few hundred steps, it is probably too low. A quick sweep over two or three values saves a lot of wasted GPU hours.
Take quiz
Pre-trained weights are already good and large steps can damage them
Small rates enlarge the dataset
GPUs cannot run large rates
LoRA adapters
full fine-tuning of all layers
continued pretraining of a 70B model
11. What is catastrophic forgetting?
Catastrophic forgetting is when a model loses earlier abilities after being fine-tuned on a new task, because gradient updates overwrite weights that earlier skills depended on.
Example: a model fine-tuned heavily on legal contracts starts making mistakes on basic arithmetic or drops its multilingual ability.
Common mitigations: lower learning rate, fewer epochs, LoRA with a frozen base, mixing in general replay data, and regularization such as EWC.
A practical check is to run the fine-tuned model on held-out prompts that worked before fine-tuning. A big drop compared with the base model is the clearest evidence of forgetting.
Take quiz
the model loses earlier abilities after training on a new task
the GPU runs out of memory mid-training
the tokenizer drops rare words
Mixing some general data into the fine-tuning set
Raising the learning rate
Training for many more epochs
Removing the validation set
12. What is overfitting in fine-tuning?
Overfitting happens when the model memorizes training examples instead of learning the underlying pattern. Training loss keeps dropping, but validation loss flattens or rises. Small datasets and too many epochs make it likely.
Warning signs: the model repeats training answers word for word, and does poorly on paraphrased inputs.
Fixes: more diverse data, fewer epochs, early stopping, weight decay, dropout, or a lower LoRA rank.
Concrete example: a model trained for 10 epochs on 300 support replies may quote them nearly verbatim, yet fail when a customer words the same problem differently. Checking validation loss every 50-100 steps catches this early.
Take quiz
Training loss rises while validation loss falls
Both losses stay exactly at zero from step 1
Training loss decreases while validation loss increases
Removing the validation set
Doubling the epochs
Early stopping on validation loss
Raising the learning rate tenfold
13. What is a fine-tuning dataset made of?
It depends on the tuning method. Each format carries only what that method needs:
| Method | Record format | Example |
| Classification | text + label | "Refund not received" -> billing |
| Instruction / SFT | prompt + response | Question and ideal answer |
| Preference (DPO) | prompt + chosen + rejected | Two answers, one preferred |
| Continued pretraining | raw text | Journal articles, code files |
Whatever the format, the data should match how the model will be used in production.
Every example should show the exact behavior you want in production, including tone, length, and edge cases such as refusals or "I don't know" answers.
Take quiz
only a single class label per prompt
a prompt with a numeric embedding
a prompt with a chosen and a rejected response
raw domain text for continued pretraining
classification text-label pairs
preference pairs for DPO
14. What is RLHF?
Reinforcement Learning from Human Feedback aligns a model's outputs with human preferences. Humans rank several responses to the same prompt, a reward model learns to predict those rankings, and the language model is then optimized (commonly with PPO) to earn higher reward.
A KL penalty against the SFT model keeps the policy from drifting into odd outputs that merely game the reward model.
RLHF helped move raw instruction-following models toward the helpful chat behavior users expect, as described in the InstructGPT work. Its main downsides are labeling cost and complexity, since several models must be held in memory at once.
Take quiz
compiler output of generated code
token frequency counts
human rankings of model responses
To keep the policy close to the reference model and limit reward hacking
To speed up tokenization
To enlarge the context window
To remove the need for a reward model
15. What is the purpose of a validation set in fine-tuning?
The validation set is data the model never trains on, used during training to monitor generalization. You use it to compare hyperparameters, pick the best checkpoint, and trigger early stopping.
It is not the same as the test set. The test set is touched once at the end for an unbiased final score. If you tune against the test set, it stops being unbiased. Common splits are 80/10/10, or 90/5/5 for large datasets.
Example: with 10,000 examples, a 90/5/5 split keeps 500 for validation and 500 for the final test. Evaluating on validation every 100 steps shows exactly when improvement stops.
Take quiz
test set
validation set
the pre-training corpus
To add more training data later
To get an unbiased final estimate after all tuning decisions
To compute the learning rate
To store adapter weights
16. What are epochs and batch size in fine-tuning?
An epoch is one full pass over the training set. Batch size is how many examples are processed before one weight update. Steps per epoch = dataset size / batch size.
Example: 10,000 examples with batch size 16 gives 625 steps per epoch.
LLM SFT usually runs just 1-3 epochs, because more passes encourage memorization. A larger batch gives steadier gradients but needs more memory, which is where gradient accumulation helps.
Rule of thumb: if validation loss starts climbing in epoch 2 or 3, stop there. On very small datasets, the best checkpoint may even come before the first epoch ends.
Take quiz
200
20,000
500
50
More passes increase memorization of the training data
The optimizer stops working after epoch 3
Batch size must shrink every epoch
17. What is perplexity?
Perplexity is the exponential of the average negative log-likelihood per token. It tells you how surprised the model is by held-out text. Lower is better. A perplexity of 10 means the model is about as unsure as choosing uniformly among 10 tokens at each step.
Limits: it is only comparable with the same tokenizer and the same text, and it says nothing about helpfulness or factual accuracy. It suits continued pretraining well, and instruction-tuned models need task-based evaluation too.
Take quiz
the model has more parameters
the model predicts held-out text better
the dataset is larger
Perplexity is defined only for image models
It only works in fp32
Per-token values depend on how the text is split into tokens
It ignores the validation set
18. What is the role of the tokenizer in fine-tuning?
The tokenizer converts text into the token IDs that the model's embedding layer expects. You must use the same tokenizer as the base model. Swapping it breaks the mapping between IDs and learned embeddings.
Also keep special tokens and the chat template consistent. If your training examples lack the EOS token, the model never learns where to stop. When you add new tokens, resize the embedding matrix and train it:
tokenizer.add_tokens(["<ticket_id>"]) model.resize_token_embeddings(len(tokenizer))
Padding is another tokenizer detail. Decoder models usually need pad_token set (often to the EOS token) and a consistent padding side, otherwise batches can be misaligned.
Take quiz
Set the learning rate to zero
Delete the attention layers
Resize the model's embedding matrix
the batch size was a power of two
the validation split was too small
the EOS token is missing from training examples
the LoRA rank was too low
19. What is prompt tuning?
Prompt tuning learns a small set of continuous soft prompt embeddings that are prepended to the input embeddings, while the entire model stays frozen. Only those vectors are trained, for example 20-100 virtual tokens times the hidden size.
Soft prompts are not human-readable text. Lester et al. (2021) found the method gets closer to full fine-tuning as model size grows.
Prompt tuning is attractive because one frozen model can serve many tasks, each with its own tiny prompt file of a few kilobytes. Its weakness is sensitivity to initialization and weaker results on smaller models, so most practitioners reach for LoRA first.
Take quiz
all attention weights
the output vocabulary
the learned soft prompt embeddings only
plain text edited by hand
stored as SQL rows
continuous vectors learned by gradient descent
ignored at inference
20. What is adapter tuning?
Adapter tuning inserts small bottleneck modules inside each transformer layer and trains only those, with the base model frozen. Each adapter projects the hidden state down to a small dimension, applies a nonlinearity, projects back up, and adds a residual connection (Houlsby et al., 2019).
Unlike LoRA, adapters add extra layers that stay in the forward path, so they add a little inference latency and cannot be folded into the original weights.
Adapters were among the first PEFT methods and influenced LoRA. LoRA became more popular because it adds zero latency after merging and is easier to configure.
Take quiz
a second full transformer decoder
down-projection, nonlinearity, up-projection with a residual connection
a hash table lookup
can always be merged into W with zero extra latency
need no training at all
add extra layers that remain at inference time
21. What is Direct Preference Optimization (DPO)?
DPO trains a model directly from preference pairs (a chosen and a rejected response) using a classification-style loss. There is no separate reward model and no RL sampling loop.
The loss pushes up the log-probability margin of the chosen response over the rejected one, measured relative to a frozen reference model and scaled by beta. You need an SFT model as the reference and a dataset of preference pairs. It is simpler and usually more stable than PPO-based RLHF.
Take quiz
the separate reward model and the RL sampling loop
the need for any training data
the base model
how strongly the policy is kept near the reference model
the batch size
the tokenizer vocabulary
the number of GPUs
22. When should you fine-tune instead of using prompt engineering?
Fine-tune when prompting has plateaued and the gap is about behavior: a strict output format, a consistent tone, a specialized task, or a need for shorter prompts and lower latency from a smaller model. Always try better prompts and few-shot examples first, because they are cheap and reversible.
| Prefer prompt engineering when | Prefer fine-tuning when |
| Requirements change weekly | Behavior is stable and well defined |
| You have few or no labeled examples | You have hundreds or thousands of good examples |
| You are prototyping | You need consistent output at high volume |
| Facts change often (consider RAG) | You want a small model to match a large one on one task |
Take quiz
Product facts that change daily
Having no examples yet
A one-off prototype
Needing a consistent JSON output style across millions of calls
Training from scratch
Better prompts with few-shot examples
Quantizing to 2-bit
23. What is the difference between fine-tuning and RAG?
Fine-tuning changes the model's weights. RAG leaves the model alone and injects retrieved documents into the prompt at inference time.
| Aspect | Fine-tuning | RAG |
| What changes | Weights | Context at query time |
| Best for | Style, format, task skills | Fresh or private knowledge |
| Updating knowledge | Retrain | Update the index |
| Citations | Hard | Natural |
| Cost shape | Upfront training | Retrieval on every query |
They are not exclusive. Many systems fine-tune for tone and format, then use RAG for facts.
Decision shortcut: if the model needs to know something that changes or is private, use RAG. If it needs to behave differently, such as following a strict schema or house style, fine-tune. Many teams also fine-tune the model to use retrieved context faithfully.
Take quiz
full fine-tuning each hour
RAG over an indexed catalog
continued pretraining every week
the retrieval index
model behavior and style by updating weights
the vector database schema
the chunk size
24. How does LoRA reduce trainable parameters?
A full update to a d x k matrix needs d*k parameters. LoRA replaces it with two factors, B (d x r) and A (r x k), which need only r*(d + k). This works because weight updates during adaptation tend to have low intrinsic rank.
| Setup (4096 x 4096 layer) | Trainable parameters |
| Full update | 16,777,216 |
| LoRA r = 16 | 131,072 |
| LoRA r = 8 | 65,536 |
Optimizer states (Adam keeps two per parameter) are held only for these small matrices, which is where most of the memory saving comes from.
In practice, rank 8-16 is a common starting point, and you raise it only if the adapter underfits.
Take quiz
16,777,216
65,536
8,192
524,288
Adam states are kept only for the small adapter matrices
Adam is silently swapped for SGD
Weights are stored on disk during training
25. How does QLoRA fit a large model on one GPU?
It attacks each memory component. A 65B model in 16-bit needs about 130 GB for weights alone. In 4-bit NF4 that drops to roughly 33 GB, and double quantization shaves a bit more.
- The base model is loaded in 4-bit and frozen.
- Small 16-bit LoRA adapters are the only trainable weights, so gradients and Adam states are tiny.
- Paged optimizers spill optimizer state to CPU RAM when GPU memory spikes.
- Gradient checkpointing recomputes activations instead of storing them.
During the forward and backward pass, 4-bit blocks are dequantized to bf16 on the fly for the matrix multiplication.
The QLoRA paper reported that 4-bit NF4 with adapters matched 16-bit fine-tuning quality on the benchmarks it tested, so the memory saving did not cost accuracy there.
Take quiz
about 130 GB
about 8 GB
about 33 GB
about 260 GB
memory spikes, by moving optimizer state to CPU RAM
token padding
learning rate decay
26. Why does catastrophic forgetting happen and how do you reduce it?
The loss only measures the new task. Gradient updates move shared weights to lower that loss, and nothing in the objective protects what older skills relied on. A high learning rate, many epochs, and narrow data all make the drift worse.
| Technique | Why it helps |
| Lower LR, fewer epochs | Weights drift less |
| LoRA / PEFT | Base weights stay frozen |
| Replay data | Old skills remain in the loss |
| EWC-style regularization | Penalizes changes to important weights |
| Weight interpolation with base | Recovers general ability |
Interview tip: say that you measure forgetting explicitly, by running a fixed general evaluation set before and after fine-tuning, rather than assuming the mitigation worked.
Take quiz
Updates minimize only the new-task loss and shift shared weights
The tokenizer is replaced during training
Validation data leaks into training
Gradient accumulation
Beam search
Sequence packing
Elastic Weight Consolidation
27. How do you choose the learning rate for fine-tuning?
Start from the published default for your method, then run a short sweep rather than guessing. Common grids are {1e-5, 2e-5, 5e-5} for full fine-tuning and {1e-4, 2e-4} for LoRA.
- Pick a grid and run each value for a few hundred steps.
- Use warmup (roughly 3-10% of steps) followed by cosine or linear decay.
- Read the loss curve: spikes or NaN mean too high, a nearly flat curve means too low.
- Re-check if you change batch size, since larger batches usually tolerate a higher rate.
Do not tune the rate on the test set. Use validation loss, and confirm the winner with the task metric, since the lowest loss does not always give the best answers.
Take quiz
Increase the number of epochs
Lower the learning rate
Add more LoRA layers
Load weights faster from disk
Ramp the rate up gradually to avoid unstable early updates
Freeze the base model
Increase the vocabulary size
28. What is the difference between full fine-tuning and PEFT?
Full fine-tuning updates every weight. PEFT trains a tiny add-on and leaves the base untouched.
| Aspect | Full fine-tuning | PEFT (e.g. LoRA) |
| Trainable params | 100% | About 0.1-2% |
| GPU memory | About 16 bytes/param with AdamW | Far lower |
| Checkpoint size | Full model | Megabytes |
| Forgetting risk | Higher | Lower |
| Best fit | Large domain shift, lots of data | Most task adaptation |
| Serving | One model per task | Swap adapters on one base |
Rule of thumb: begin with LoRA or QLoRA. Move to full fine-tuning only if a well-tuned adapter at a higher rank still underperforms on your validation metric and you can afford the extra memory, storage, and forgetting risk. Many production teams never need to make that jump.
Take quiz
full fine-tuning for each task
training from scratch for each task
PEFT with swappable adapters
a tiny dataset of 50 examples on one consumer GPU
when checkpoints must stay under 50 MB
Large domain shift with plenty of data and compute
29. Explain the execution flow of RLHF?
RLHF runs in three stages: SFT, reward modeling, and policy optimization.
flowchart TD
A["Pre-trained model"] --> B["SFT on human demonstrations"]
B --> C["Sample several responses per prompt"]
C --> D["Humans rank the responses"]
D --> E["Train reward model on rankings"]
E --> F["PPO optimizes policy with KL penalty"]
F --> G["Aligned model"]
- SFT gives a model that can answer in the right format.
- Reward model is trained on human rankings to score any response.
- PPO generates responses, scores them with the reward model, and updates the policy while a KL term keeps it near the SFT model.
RLHF needs a policy, a reference model, a reward model, and often a value model in memory at once, which is a big reason DPO became popular.
Take quiz
Supervised fine-tuning on demonstrations
PPO policy update
Reward model deployment
The trained reward model
The validation perplexity
The tokenizer
A BLEU score on the test set
30. What is the difference between RLHF and DPO?
Both learn from preferences. RLHF does it with an explicit reward model and RL, while DPO folds the preference signal straight into a supervised-style loss.
| Aspect | RLHF (PPO) | DPO |
| Pipeline | SFT + reward model + PPO | SFT + DPO loss |
| Models in memory | Policy, reference, reward, value | Policy and reference |
| Data | Rankings for RM, then online samples | Offline preference pairs |
| Stability | Sensitive to hyperparameters | Simpler, more stable |
| Exploration | Online, can discover new outputs | Limited to dataset coverage |
Rule of thumb: pick DPO when you already have preference pairs and want a simple, stable pipeline. Pick online RL when the model must explore and improve beyond the examples in a fixed dataset, such as with verifiable rewards.
Take quiz
RLHF with PPO
DPO
Instruction tuning
live environment rollouts only
unlabeled images
a reward model's gradients
a fixed offline set of preference pairs
31. Why does data quality matter more than quantity in fine-tuning?
Most knowledge comes from pre-training. Fine-tuning mainly teaches format, style, and task behavior, so a small clean set can be enough. The LIMA study (2023) fine-tuned a 65B LLaMA model on about 1,000 carefully curated examples and got strong instruction-following.
Noise hurts directly. Inconsistent labels teach inconsistent behavior, wrong answers get imitated, and duplicates push the model toward memorization.
- Check answers for correctness and one consistent style.
- Keep prompts diverse.
- Deduplicate.
- Review the length distribution.
Example: 800 expert-written support replies in one consistent voice usually beat 20,000 scraped replies of mixed quality. Time spent on review and cleaning pays back more than collecting extra volume.
Take quiz
about 1,000 curated examples can yield strong instruction-following
only datasets above 1 million examples work
fine-tuning cannot change response style
faster convergence
smaller checkpoints
a larger vocabulary
inconsistent model behavior at inference
32. How do you prepare a dataset for instruction tuning?
- Define the target behavior and collect or write representative prompts.
- Convert to chat-style JSONL with consistent roles.
- Apply the base model's chat template so training matches inference.
- Clean and deduplicate, then filter bad or off-topic samples.
- Balance categories so one task does not dominate.
- Split into train, validation, and test, grouping related items together.
- Check token lengths against your max sequence length.
{"messages": [{"role": "system", "content": "You are a billing assistant."}, {"role": "user", "content": "Why was I charged twice?"}, {"role": "assistant", "content": "A duplicate charge usually reverses in 3-5 days..."}]}
Before training, print a few formatted examples exactly as the model will see them, including special tokens. Template bugs are one of the most common and most avoidable fine-tuning failures.
Take quiz
Shuffle after training
Increase the LoRA rank
Deduplicate before splitting
To reduce file size
Training format must match the format used at inference
To avoid needing a tokenizer
To raise the learning rate
33. How do you evaluate a fine-tuned model?
Use several layers, because no single score tells the whole story:
- Task metrics on a held-out test set.
- LLM-as-judge with a rubric, or pairwise comparison against a baseline.
- Human review of a sample, especially failure cases.
- Regression checks on general benchmarks to catch forgetting.
- Safety checks before release.
| Task | Typical metric |
| Classification | Accuracy, F1 |
| Field extraction | Exact match, JSON validity |
| Summarization | Judge scores plus ROUGE |
| Chat quality | Pairwise win rate |
Always compare against the base model with a good prompt, not against nothing.
Keep the evaluation set fixed across experiments so scores stay comparable, and stratify it by category so you can see which kinds of requests improved and which got worse.
Take quiz
a randomly initialized model
the loss from the previous epoch
the base model with a well-crafted prompt
exact match and JSON validity
perplexity alone
image FID score
tokens per second
34. How do you detect overfitting during fine-tuning?
Log training and validation loss at regular intervals. When training loss keeps falling and validation loss turns upward, the model has started memorizing. Also track the task metric on the validation set and spot-check outputs for memorized phrases.
In Hugging Face Trainer you can automate the response:
args = TrainingArguments( eval_strategy="steps", eval_steps=100, save_strategy="steps", save_steps=100, load_best_model_at_end=True, metric_for_best_model="eval_loss") trainer = Trainer(..., args=args, callbacks=[EarlyStoppingCallback(early_stopping_patience=3)])
Do not rely on training loss alone. A model can reach very low training loss simply by memorizing, so also run a few unseen prompts after each checkpoint and compare the answers with the base model. Keep several checkpoints so you can roll back to the best one.
Take quiz
load_best_model_at_end
gradient_checkpointing
warmup_ratio
report_to
Train four times longer
Remove the validation set
Use the checkpoint near step 400 or stop early
35. Why is a loss mask applied on prompt tokens in SFT?
In SFT you usually want the model to learn to produce the answer, not to predict the user's question. So the loss is computed only on response tokens. Otherwise capacity is spent modeling prompts, and with long prompts and short answers the useful gradient signal gets diluted.
In Hugging Face, labels set to -100 are ignored by the cross-entropy loss:
labels = input_ids.clone() labels[:prompt_len] = -100
Training on the prompt too is sometimes tried with small datasets, but the evidence is mixed.
Check your framework's defaults. TRL's SFTTrainer offers options to train on completions or assistant messages only, while a plain Trainer computes loss on every token unless you set the labels yourself.
Take quiz
0
1
-100
99999
padding tokens
all tokens equally
response tokens only
36. What is the difference between LoRA rank and alpha?
Rank (r) is the inner dimension of the two LoRA matrices and sets adapter capacity. Alpha is a scaling numerator, and the update is multiplied by alpha / r before being added to the frozen output.
| Parameter | Controls | If you increase it |
| r | Capacity and trainable parameter count | More expressive, more memory |
| alpha | Strength of the adapter's contribution | Larger effective updates, similar to a higher LR |
A common recipe is r between 8 and 64, with alpha equal to r or 2r.
If a LoRA run underfits, raise rank or learning rate. If it overfits or drifts from base behavior, lower alpha or rank. Change one knob at a time so you can tell which one helped.
Take quiz
2
0.5
16
48
adapter capacity and trainable parameter count
tokenizer vocabulary
context length
the number of attention heads
37. Which LoRA target modules should you choose?
The original LoRA paper adapted only the attention query and value projections. QLoRA later found that adapting all linear layers is needed to match full fine-tuning quality.
For Llama-style models that means q_proj, k_proj, v_proj, o_proj plus the MLP layers gate_proj, up_proj, and down_proj. More targets mean more trainable parameters and memory, so choose based on your budget. PEFT can select them for you:
LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
Trade-off example: attention-only LoRA on a 7B model trains a few million parameters and runs fast. Adding the MLP layers multiplies that several times over, but it usually helps on tasks that need real new skills. Start with all linear layers at a modest rank, then trim if memory is tight.
Take quiz
target_modules="embed"
task_type="ALL"
target_modules="all-linear"
embeddings and LM head
query and value projections
layer norms and biases
38. How does gradient accumulation help in fine-tuning?
It runs several small micro-batches forward and backward, summing gradients, and applies one optimizer step afterward. The effective batch size is micro-batch x accumulation steps x number of GPUs.
Example: micro-batch 4, accumulation 8, one GPU gives an effective batch of 32 without ever holding 32 sequences of activations in memory. The cost is time: each update takes longer.
TrainingArguments(per_device_train_batch_size=4, gradient_accumulation_steps=8)
One caveat: some library versions have had bugs in how loss is averaged across micro-batches when sequence lengths differ, so keep your training library up to date. Also note that learning-rate schedules count optimizer steps, not micro-batches, so warmup length should be set accordingly.
Take quiz
128
32
64
8
extra time per update for lower memory use
accuracy for tokenizer size
memory for disk space
39. Why is mixed precision (bf16) used in fine-tuning?
Lower precision halves the memory for weights and activations and speeds up tensor-core math. bf16 keeps the same 8-bit exponent as fp32, so it handles the same value range and needs no loss scaling. fp16 has a narrower range and can overflow or underflow.
| Format | Bits | Exponent bits | Loss scaling |
| fp32 | 32 | 8 | Not needed |
| fp16 | 16 | 5 | Usually needed |
| bf16 | 16 | 8 | Not needed |
Master weights and Adam states are often kept in fp32. bf16 needs a GPU generation such as A100 or RTX 30-series and newer.
In Hugging Face you enable it with bf16=True in TrainingArguments. On older GPUs without bf16 support, fall back to fp16 with the built-in loss scaler.
Take quiz
It has more mantissa bits for precision
It stores 8-bit integers
It has the same exponent range as fp32, so no loss scaling is needed
too many mantissa bits
a tokenizer mismatch
its limited exponent range causing overflow or underflow
using LoRA
40. How does prompt tuning differ from prefix tuning?
Both train continuous vectors with a frozen model, but they inject them in different places.
| Aspect | Prompt tuning | Prefix tuning |
| Where vectors go | Input embeddings only | Keys and values in every layer |
| Trainable params | Fewer | More |
| Small-model quality | Weaker | Stronger |
| Training stability | Sensitive to initialization | Often uses a reparameterization MLP |
Prefix tuning came first (Li and Liang, 2021) and was designed for generation tasks. Prompt tuning (Lester et al., 2021) simplifies it by touching only the input layer, so it has the fewest trainable parameters but depends more on model scale. Both keep the base frozen, so one model can serve many tasks by swapping small prefix files at request time.
Take quiz
prompt tuning
BitFit
feature extraction
prefix tuning
inside every feed-forward block
at the input embedding layer only
after the softmax output
41. How do you estimate GPU memory needed for fine-tuning?
Add up four parts: weights, gradients, optimizer states, and activations. For full fine-tuning with AdamW in mixed precision, a common rule is about 16 bytes per parameter: 2 for bf16 weights, 2 for gradients, 4 for an fp32 master copy, and 8 for the two Adam moments.
| Method | Approx. bytes/param | 7B model (before activations) |
| Full fine-tuning, AdamW | 16 | About 112 GB |
| LoRA, bf16 base | About 2 | About 14 GB plus adapters |
| QLoRA, 4-bit base | About 0.5 | About 4 GB plus overhead |
Activations scale with batch size and sequence length. Gradient checkpointing trades extra compute for much lower activation memory.
Take quiz
about 14 GB
about 4 GB
about 1 TB
about 112 GB
gradient checkpointing
weight tying
label smoothing
42. What happens when you fine-tune with too high a learning rate?
The loss spikes, diverges, or turns into NaN. Even when it stays finite, large steps erase pre-trained knowledge, so outputs can become gibberish or noticeably worse than the base model.
- Lower the learning rate by 3-10x.
- Add or lengthen warmup.
- Enable gradient clipping, for example
max_grad_norm=1.0. - Restart from the last healthy checkpoint rather than the corrupted one.
Recovery matters too. If the run already diverged, reload the last stable checkpoint instead of continuing, because a few bad updates can leave the model in a poor region that more training rarely repairs. Log the gradient norm so you can spot trouble before the loss visibly breaks.
Take quiz
gradient clipping
dropout on labels
a larger vocabulary
loss spikes or becomes NaN
loss falls smoothly to zero in 10 steps
the validation set shrinks
43. How do you merge LoRA adapters into a base model?
Merging computes W' = W + (alpha / r) x B x A for every adapted layer, so inference needs no extra adapter computation. With PEFT it takes a few lines:
base = AutoModelForCausalLM.from_pretrained(base_id, torch_dtype=torch.bfloat16) model = PeftModel.from_pretrained(base, "adapter_dir") merged = model.merge_and_unload() merged.save_pretrained("merged_model")
For QLoRA, load the base in bf16 or fp16 for the merge, not in 4-bit, to avoid rounding errors from merging into quantized weights. If you want to hot-swap adapters per task, keep them unmerged.
After merging, run a quick sanity test comparing merged outputs with the adapter-attached model on a few prompts. They should match closely, apart from tiny numerical differences.
Take quiz
prepare_model_for_kbit_training()
get_peft_model_state_dict()
merge_and_unload()
bf16 makes the adapter larger
4-bit models cannot be saved
To avoid rounding errors from merging into quantized weights
bf16 removes the need for alpha
44. How can you prevent data leakage between train and test sets?
Leakage inflates your scores and hides real weaknesses. Guard against it before training starts:
- Deduplicate first, including near-duplicates (MinHash or embedding similarity), then split.
- Split by group - by customer, document, conversation, or time - not by random row.
- Check for benchmark contamination against public test sets.
- Never tune hyperparameters on the test set.
- For synthetic data, make sure test prompts were not seeded from training items.
A common blind spot is time. For logs or tickets, train on older data and test on newer data, since random splits let the model peek at patterns from the future. Report the contamination checks you ran alongside the scores, so reviewers can trust the numbers.
Take quiz
Shuffle the rows harder
Split by customer ID
Increase the number of epochs
gradient clipping
tokenizer merging
MinHash or embedding similarity
weight decay
45. What is model distillation and how does it relate to fine-tuning?
Distillation trains a smaller student to mimic a larger teacher, either through the teacher's soft probabilities or through text the teacher generates. In LLM practice it is often just SFT of a small model on teacher outputs, so it is fine-tuning with a different data source.
Watch for two risks: the student inherits the teacher's mistakes, and the teacher's license may restrict using its outputs for training. Filter the generated data for quality before training.
Example: use a large model to write 20,000 answers to your prompts, filter them with a judge or rules, then fine-tune a 7B model on them. The small model is cheaper to serve and is often close to the teacher on that narrow task.
Take quiz
random noise
its own untouched pre-training corpus
outputs generated by a stronger teacher model
the teacher weights get deleted
the student inherits teacher mistakes and licensing limits may apply
tokenizers merge automatically
the learning rate becomes negative
46. How do you troubleshoot a fine-tuned model that outputs repetitive text?
Work through the likely causes in order, cheapest checks first:
- EOS token missing or wrong in training targets, so the model never learns to stop.
- Chat template mismatch between training and inference.
- Generation settings: very low temperature; try
repetition_penalty=1.1orno_repeat_ngram_size. - Low-diversity or duplicated training data.
- Overtraining: compare an earlier checkpoint.
Typical case: a model fine-tuned on support emails loops the same sentence at the end of every reply, and the training file shows many examples with no EOS token. Adding it and retraining fixes the loop, while changing temperature only masks it. Rule out data problems before tweaking decoding parameters.
Take quiz
the GPU model number
that the EOS token is present in training targets
the number of LoRA dropout layers
num_train_epochs
repetition_penalty
warmup_steps
lora_alpha
47. Explain the lifecycle of a fine-tuning project?
A healthy project is a loop, not a straight line.
flowchart TD
A["Define task and success metric"] --> B["Baseline with prompting or RAG"]
B --> C["Collect and clean data"]
C --> D["Choose base model and method"]
D --> E["Train and tune hyperparameters"]
E --> F["Evaluate against baseline"]
F --> G{Meets target?}
G -- No --> C
G -- Yes --> H[Deploy]
H --> I["Monitor and retrain"]
Most failures trace back to the data step, which is why evaluation usually sends you back there rather than to the optimizer.
Track every run (data version, hyperparameters, metrics) so you can reproduce the best result and explain why one run beat another.
Take quiz
deploying to production
merging adapters
defining the task and success metric, then a prompting baseline
improving the data and rerunning training
deleting the test set
switching off monitoring
48. How do you fine-tune safely to avoid losing safety alignment?
Research such as Qi et al. (2023) found that even benign fine-tuning can weaken a model's safety behavior. Treat safety as something you test, not something you inherit.
- Mix safety and refusal examples into the training data.
- Use a lower learning rate, LoRA, or fewer epochs to limit drift.
- Run a safety and red-team evaluation before and after training.
- Keep input and output moderation in front of the model.
- Review training data for harmful content, and limit who can access the weights.
Treat the safety check as a release gate. If the fine-tuned model refuses noticeably less often than the base on your red-team prompts, fix the data or training setup before shipping, not after.
Take quiz
weaken a model's safety behavior
always strengthen refusals
never alter outputs
tokenizer retraining
vocabulary pruning
safety and red-team evaluation
adapter merging
49. What is the difference between continued pretraining and SFT?
| Aspect | Continued pretraining | SFT |
| Data | Raw unlabeled domain text | Prompt-response pairs |
| Loss on | All tokens | Response tokens |
| Goal | Absorb domain language and knowledge | Teach task behavior and format |
| Typical scale | Millions to billions of tokens | Hundreds to tens of thousands of examples |
| Order | Comes first | Comes after |
Example: feeding 2B tokens of medical journals to teach terminology is continued pretraining. Teaching the model to answer patient-intake questions in a fixed format is SFT.
They are often combined: continue pretraining on domain text, run SFT for behavior, then apply DPO for preferences. Skipping continued pretraining is fine when the base model already handles the domain vocabulary well.
Take quiz
SFT
DPO
continued pretraining
prompt tuning
every token in a raw corpus
reward scores
the response tokens
the tokenizer merges
50. How can you optimize fine-tuning cost?
Cost scales with model size, tokens processed, and GPU time, so attack each:
- Start with the smallest base model that meets your metric.
- Use LoRA or QLoRA to fit cheaper GPUs.
- Deduplicate and trim data; quality beats volume.
- Cap sequence length and use sequence packing to avoid padding waste.
- Run 1-3 epochs with early stopping.
- Use spot instances with frequent checkpoints.
- Do hyperparameter sweeps on a data subset.
Measure cost per quality point, not raw cost. A run that costs half but loses five points on your metric may be more expensive once you count the failures it causes downstream. Track tokens trained and GPU-hours for every run so budgets stay predictable.