PrepStack › AI › Fine-tuning LLMs
Fine-tuning LLMs interview cheat sheet
When to fine-tune, LoRA/QLoRA, SFT, DPO vs RLHF, data, GPU memory and serving
Interviewers want to see that you know when fine-tuning is the right tool (and when prompting or RAG is cheaper), how LoRA and QLoRA work and why they fit on one GPU, how to build a clean dataset, and how preference tuning (RLHF, DPO, GRPO) differs from SFT. Senior rounds add GPU memory math, distributed training and serving many adapters. The Python demos use only the standard library and show the math; the Hugging Face snippets use current TRL/PEFT APIs and are shown without output.
15-minute revision
- Try prompting first, then RAG, then fine-tuning. Fine-tuning teaches behaviour, format and style; RAG supplies fresh or private facts. They combine well.
- Types: continued pre-training (raw domain text), SFT / instruction tuning (prompt → answer pairs), preference tuning (chosen vs rejected), distillation (big teacher → small student).
- Full fine-tuning updates every weight (~16 bytes/param with AdamW in mixed precision). PEFT freezes the base and trains a tiny add-on.
- LoRA:
W' = W + (alpha/r)·B·AwithAr×k andBd×r.Bstarts at zero, so training starts from the base model. Typicalr8–64,alpha= r or 2r. - LoRA on all linear layers of an 8B model at r=16 is ~42M trainable params (~0.5%). The adapter file is tens of MB, not 16 GB.
- Merge adapters (
merge_and_unload) for zero extra latency, or keep them separate to hot-swap many tasks on one base (vLLM multi-LoRA). - QLoRA = 4-bit NF4 frozen base + double quantisation of the scales + paged optimisers + LoRA adapters in bf16. An 8B model trains on a single 24 GB GPU.
- Other PEFT: prompt/prefix tuning (learned virtual tokens), adapters (small bottleneck layers, add latency), IA3 (learned scaling vectors), DoRA (LoRA on direction + separate magnitude).
- Data: quality beats quantity. A few hundred to a few thousand clean, diverse, deduplicated examples in the model's own chat template, with a held-out eval split.
- Mask the prompt: labels of prompt tokens are
-100, so loss is only on the assistant answer. - Start points: LoRA LR ~
1e-4–2e-4, full FT ~1e-5, DPO ~5e-7–5e-6; 1–3 epochs; warmup a few %; effective batch = per-device × grad-accum × GPUs. - Overfitting: train loss falls while eval loss rises, the model parrots training answers. Catastrophic forgetting: general skills drop. Fix with fewer epochs, lower LR, LoRA, mixed-in general data.
- RLHF = SFT → reward model on human comparisons → PPO with a KL penalty to the SFT model. Powerful but needs 4 models and is unstable.
- DPO skips the reward model: a classification loss on chosen vs rejected relative to a frozen reference. ORPO drops the reference, KTO needs only thumbs up/down, GRPO is online RL with group-relative rewards (no critic).
- Save memory with bf16 mixed precision, gradient checkpointing, 8-bit/paged optimisers, and ZeRO / FSDP sharding across GPUs.
- Ship: evaluate against the base model on a task eval set and general benchmarks, then quantise (GPTQ, AWQ, GGUF) and serve with vLLM/TGI/llama.cpp.
When and what to fine-tune
What fine-tuning is & its types
Fine-tuning keeps training a pre-trained model on your own data so it changes how it behaves.
- A base LLM is pre-trained on trillions of tokens to predict the next token. Everything after that (SFT, preference tuning, RL) is called post-training.
- Continued pre-training (CPT): more next-token training on raw domain text (legal, medical, a new language). Adds vocabulary and domain knowledge; needs a lot of data and compute.
- Supervised fine-tuning (SFT) / instruction tuning: train on prompt → ideal answer pairs. Teaches format, tone, task skills and tool-call style. This is what most teams mean by fine-tuning.
- Preference tuning: train on pairs of a better and a worse answer (RLHF with PPO, DPO, ORPO, KTO) or on a reward signal (GRPO). Improves helpfulness, safety and style beyond imitation.
- Distillation: a large teacher model writes answers (or gives its probabilities) and a small student is fine-tuned on them. Gives most of the quality at a fraction of the cost and latency.
- The usual order for an open model is: base → (CPT) → SFT → preference tuning. Most product teams start from an already instruction-tuned model and do only SFT, maybe followed by DPO.
Interview questions
- What is fine-tuning and why would you do it?
- Difference between pre-training and fine-tuning?
- What is instruction tuning?
- What is knowledge distillation for LLMs?
Prompting vs RAG vs fine-tuning
Prompting and RAG change what the model sees; fine-tuning changes the model itself.
- Prompt engineering is the cheapest and fastest to iterate. Always build a baseline and an eval set with it first.
- RAG retrieves documents at query time and puts them in the prompt. Best for knowledge: private, changing or citable facts. Updating knowledge means re-indexing, not retraining.
- Fine-tuning is best for behaviour: a strict output format, a house style, a narrow classification or extraction task, tool-calling patterns, or shrinking long prompts into the weights.
- Fine-tuning a small model can cut cost and latency a lot compared to prompting a large model, once traffic is high enough.
- They are not exclusive. A common production setup is a fine-tuned model that is good at using retrieved context (RAG + FT, sometimes called RAFT).
Interview questions
- When would you choose fine-tuning over RAG?
- Can fine-tuning teach a model new facts?
- A team wants to fine-tune because their prompt is 6,000 tokens long. Is that a good reason?
- How do you decide in practice?
Full fine-tuning vs PEFT
Full fine-tuning updates every weight; PEFT freezes the model and trains a small number of new parameters.
- Full fine-tuning gives the most capacity but needs memory for weights, gradients and optimizer state for every parameter, and saves a full copy of the model per task.
- PEFT (parameter-efficient fine-tuning) trains well under 1–2% of the parameters. Gradients and optimizer state exist only for those, so memory drops by several times.
- Each PEFT task is a small adapter file (MBs), so one base model can serve many tasks.
- Because the base is frozen, PEFT forgets less of the model's general skills (it learns less, but also forgets less).
- For most SFT tasks LoRA gets close to full fine-tuning. Full FT still wins for large domain shifts and continued pre-training with lots of data.
Interview questions
- What is PEFT and why is it popular?
- When would you still do full fine-tuning?
- Does PEFT make inference faster?
LoRA, QLoRA and other PEFT methods
LoRA: low-rank adaptation
LoRA freezes W and learns the weight change as the product of two thin matrices, ΔW = B·A.
- Idea: the update a task needs has low intrinsic rank. So instead of learning a full d×k matrix ΔW, learn
B(d×r) andA(r×k) with r much smaller than d and k. - Forward pass:
h = W·x + (alpha/r)·B·A·x. OnlyAandBget gradients;Wis frozen. - Initialisation:
Ais random andBis zero, soB·A = 0and training starts exactly at the base model. - Trainable params per matrix:
r·(d + k)instead ofd·k. For a 4096×4096 projection at r=16 that is 131K instead of 16.8M (128× fewer). - After training you can merge:
W' = W + (alpha/r)·B·A. The merged model has the same shape and speed as the base. - In PEFT:
LoraConfig+get_peft_model(model, config). TRL trainers acceptpeft_config=and do this for you.
Interview questions
- Explain how LoRA works.
- Why does a low-rank update work at all?
- Why is B initialised to zero and not both matrices random?
- How many parameters does LoRA add for a 4096×4096 layer at rank 8?
LoRA hyperparameters: rank, alpha, targets
Rank sets capacity, alpha sets the update's strength, and target modules set where adapters go.
r(rank): capacity of the update. 8–16 for style/format tasks, 32–64+ for harder tasks or more data. Higher r means more params and memory but not always better results.lora_alpha: the update is scaled byalpha / r. Common rules:alpha = roralpha = 2r. If you change r, keep the ratio to avoid re-tuning LR.- rsLoRA (
use_rslora=True) scales byalpha / sqrt(r)instead, which keeps training stable at high ranks. target_modules: which linear layers get adapters. The original paper used onlyq_proj/v_proj; today"all-linear"(attention + MLP) is the common default and usually works better.lora_dropout(0–0.1) regularises the adapter.modules_to_savetrains and saves extra full layers, e.g. a classifier head or resized embeddings after adding tokens.- LR for LoRA is much higher than for full FT (about 1e-4 to 2e-4) because only a small, zero-started update is learned.
Interview questions
- What do
randlora_alphacontrol? - Which layers should you apply LoRA to?
- Your LoRA run shows no improvement. What do you check?
QLoRA: 4-bit NF4, double quantisation, paged optimisers
QLoRA trains LoRA adapters on top of a frozen base model stored in 4-bit NF4, so large models fit on one GPU.
- The frozen base is stored in 4-bit NormalFloat (NF4): 16 levels placed at quantiles of a normal distribution, which suits normally distributed weights better than evenly spaced INT4.
- Quantisation is block-wise (64 weights per block in the paper), each block with its own absmax scale, so one outlier only hurts its own block.
- Double quantisation quantises those per-block scales to 8-bit too, cutting the overhead from about 0.5 to about 0.127 bits per parameter.
- Paged optimisers use NVIDIA unified memory so optimizer state can spill to CPU RAM during memory spikes instead of crashing with out-of-memory.
- Compute happens in bf16: weights are dequantised on the fly for each matmul, and gradients flow through them into the bf16 LoRA adapters.
- Result: a 65B model fine-tuned on one 48 GB GPU in the paper; today an 8B model fits easily on a 24 GB card. Cost: slower steps than plain LoRA because weights are dequantised on every forward and backward pass.
Interview questions
- What is QLoRA and what are its three main ideas?
- Why NF4 instead of plain INT4?
- QLoRA vs LoRA: which do you pick?
- Can you merge a QLoRA adapter?
Other PEFT: prompt/prefix tuning, adapters, IA3, DoRA
PEFT methods differ in where the trainable parameters live: input tokens, extra layers, scaling vectors or low-rank updates.
- Prompt tuning: learn a few virtual token embeddings prepended to the input. Tiny (thousands of params), works well only on large models and simple tasks.
- Prefix tuning: learn prefix key/value vectors for every layer's attention, not just the input. More expressive than prompt tuning. P-tuning uses a small encoder to produce the prompt embeddings.
- Adapters (Houlsby-style): small bottleneck MLPs inserted after attention/FFN blocks. Good quality, but they add sequential layers, so inference latency goes up and they cannot be merged.
- IA3: learns vectors that rescale keys, values and FFN activations. Even fewer params than LoRA; mergeable.
- DoRA: splits each weight into magnitude and direction, applies LoRA to the direction and trains the magnitude separately. Often beats LoRA at the same rank;
use_dora=Truein PEFT. - LoRA variants worth naming: rsLoRA (rank-stable scaling), PiSSA (init from principal singular vectors), LoftQ (init that reduces quantisation error).
Interview questions
- Difference between prompt tuning and prefix tuning?
- Why did LoRA largely replace adapter layers?
- What is DoRA and when would you use it?
Data and training
Dataset format, chat templates & loss masking
Store examples as JSONL messages, render them with the model's own chat template, and compute loss only on the answers.
- Common formats: conversational
{"messages": [{"role": "user", ...}, {"role": "assistant", ...}]}, prompt-completion{"prompt": ..., "completion": ...}, and preference{"prompt", "chosen", "rejected"}. - A chat template turns the list of messages into the exact token string the model was trained on, with role markers and special tokens (ChatML
<|im_start|>, Llama 3 headers, etc.). Usetokenizer.apply_chat_template. - Training and inference must use the same template. A mismatch is the most common reason a fine-tuned model “ignores” its training.
- Loss masking: set the labels of system/user tokens to
-100(PyTorch's ignore index) so the model learns to write answers, not to predict the user's question. - In TRL, prompt-completion datasets mask the prompt by default (
completion_only_loss), andassistant_only_loss=Truemasks everything except assistant turns in chat data. - Packing puts several short examples into one sequence to avoid wasted padding; it speeds up training a lot on short data.
Interview questions
- What is a chat template and why does it matter for fine-tuning?
- Why mask the prompt tokens in the loss?
- What is packing and what is its risk?
Data quality: size, dedup, splits & synthetic data
A small, clean, diverse dataset beats a large noisy one; always hold out an eval split.
- Quality > quantity: the LIMA paper got strong results from about 1,000 carefully chosen examples. Hundreds of great examples beat tens of thousands of messy ones.
- Data should look like real production traffic: same input style, length, languages, edge cases, and the exact output format you want.
- Clean it: remove empty or wrong answers, PII and secrets, broken formatting, and duplicates (exact via hashing, near-duplicates via MinHash or embedding similarity).
- Split into train / eval (and test) before any tuning, with a fixed seed. Dedup across splits too, or eval scores will be inflated by leakage.
- Synthetic data: use a strong model to generate or rewrite examples (self-instruct, Evol-Instruct, distillation). Filter it with rules, an LLM judge, and human spot checks. Check the provider's terms first.
- Balance the classes/tasks, and include refusals or "I don't know" examples if you want that behaviour.
Interview questions
- How much data do you need to fine-tune an LLM?
- How do you create a fine-tuning dataset when you have no labelled data?
- Why is deduplication important?
Hyperparameters: LR, epochs, batch, warmup, accumulation
Learning rate matters most; then epochs and effective batch size. Warmup and a decaying schedule keep training stable.
- Learning rate: full FT ~
1e-5to2e-5; LoRA/QLoRA ~1e-4to2e-4; DPO ~5e-7to5e-6. Too high → loss spikes or forgetting; too low → nothing changes. - Epochs: 1–3 for SFT. More epochs on small data quickly lead to memorisation. Watch eval loss, not a fixed number.
- Effective batch size = per-device batch × gradient accumulation steps × number of GPUs. Typical 16–128 sequences.
- Gradient accumulation sums gradients over several micro-batches before one optimizer step, giving a big effective batch on small GPUs (more time, not more memory).
- Warmup ramps LR from ~0 over the first few % of steps so early large gradients don't wreck the pre-trained weights. Then decay (cosine or linear) to near zero.
- Also: max sequence length (memory grows with it), weight decay (0–0.1), gradient clipping (max norm 1.0), and a fixed seed.
Interview questions
- What is gradient accumulation and why use it?
- Why use learning-rate warmup?
- Why is the LoRA learning rate much higher than for full fine-tuning?
- Loss went down fast and then flat at near zero after epoch 2. Good or bad?
Catastrophic forgetting & overfitting
Overfitting is memorising your data; catastrophic forgetting is losing skills the model had before.
- Overfitting signs: train loss keeps falling while eval loss rises; the model repeats training answers word for word; it fails on slightly rephrased inputs.
- Catastrophic forgetting signs: the model gets worse at general chat, reasoning, coding or safety refusals that the base handled; it forces the trained format onto unrelated prompts.
- Fixes for overfitting: more and more diverse data, fewer epochs, lower LR, dropout, early stopping, smaller rank.
- Fixes for forgetting: use PEFT instead of full FT, lower LR, fewer steps, mix in general instruction data (replay, ~5–20%), and keep the KL/reference constraint in preference tuning.
- Measure both: a task eval (did we improve?) and a regression eval of general benchmarks and safety prompts (did we break anything?).
Interview questions
- What is catastrophic forgetting and how do you prevent it?
- How do you detect overfitting during fine-tuning?
- Your fine-tuned support bot answers every question, even 'write a poem', in the support JSON format. What happened?
Preference tuning and alignment
RLHF pipeline: reward model + PPO
RLHF trains a reward model on human comparisons, then uses PPO to make the policy maximise that reward without drifting too far.
- Step 1, SFT: fine-tune on demonstrations to get a good starting policy.
- Step 2, reward model (RM): humans rank pairs of answers; train a model (an LLM with a scalar head) to give the preferred answer a higher score using a Bradley-Terry pairwise loss.
- Step 3, PPO: the policy generates answers, the RM scores them, and PPO updates the policy to increase reward. A KL penalty against the frozen SFT (reference) model stops it from drifting into gibberish that fools the RM.
- PPO needs four models in memory: policy, reference, reward model and a value (critic) model. That's why it's expensive and hard to tune.
- Reward hacking: the policy finds outputs the RM scores highly but humans don't like (too long, flattering). The KL term and better RMs limit it.
- RLAIF replaces human labels with an AI judge (e.g. Constitutional AI). RLVR uses verifiable rewards like unit tests or exact math answers.
Interview questions
- Walk me through RLHF.
- Why is there a KL penalty in RLHF?
- What is reward hacking? Give an example.
DPO, ORPO, KTO and GRPO compared
DPO turns preference learning into a simple classification loss; ORPO, KTO and GRPO trade off data needs, models in memory and online sampling.
- DPO: loss =
−log σ(β·[(log π(y⁺) − log π_ref(y⁺)) − (log π(y⁻) − log π_ref(y⁻))]). It raises the chosen answer's likelihood relative to the reference and lowers the rejected one. No reward model, no sampling. - β (default 0.1 in TRL) controls how far the policy may move from the reference: higher β keeps it closer.
- ORPO: adds an odds-ratio penalty to the normal SFT loss, so SFT and preference alignment happen in one stage with no reference model.
- KTO: needs only unpaired labels (this answer is good / bad), based on prospect theory. Useful when you have thumbs-up/down logs, not pairs.
- GRPO (DeepSeekMath, DeepSeek-R1): online RL. Sample G answers per prompt, score them with reward functions, and use
(r − mean) / stdwithin the group as the advantage. No critic model. Great with verifiable rewards (math, code, format). - Typical pipeline today: SFT → DPO for chat quality/safety, or SFT → GRPO for reasoning with checkable answers.
Interview questions
- Difference between RLHF (PPO) and DPO?
- What does β do in DPO?
- Why did GRPO become popular for reasoning models?
- You have thumbs-up/down feedback from production, not pairs. Which method?
- Compare ORPO with DPO.
GPU memory, scale and tools
GPU memory math, mixed precision & gradient checkpointing
Training memory = weights + gradients + optimizer state + activations; precision, PEFT and checkpointing shrink each part.
- Inference in bf16 needs ~2 bytes per parameter (8B ≈ 16 GB) plus the KV cache.
- Full fine-tuning with AdamW in mixed precision needs ~16 bytes per parameter: bf16 weights (2) + bf16 grads (2) + fp32 master weights (4) + Adam momentum and variance (4 + 4). 8B ≈ 128 GB before activations.
- Mixed precision: run matmuls in bf16 (or fp16) for speed and memory while keeping fp32 master weights for accurate updates. Prefer bf16: same range as fp32, so no loss scaling; fp16 needs a loss scaler to avoid underflow.
- Activations grow with batch × sequence length × layers × hidden size. Gradient checkpointing stores only some activations and recomputes the rest in backward: much less memory for ~20–30% more compute.
- Other savers: 8-bit or paged optimisers, FlashAttention (memory-efficient attention), shorter
max_length, smaller micro-batch + gradient accumulation, and CPU offload. - Rule of thumb: LoRA ≈ base weights in bf16 + small extra; QLoRA ≈ about a quarter of that for the base.
Interview questions
- How much GPU memory do you need to fully fine-tune a 7B model?
- What is gradient checkpointing?
- bf16 vs fp16 for training?
Multi-GPU: DeepSpeed ZeRO and FSDP
ZeRO and FSDP shard optimizer state, gradients and weights across GPUs so each one holds only a slice.
- Data parallel (DDP): every GPU holds a full copy of model, grads and optimizer, and processes different batches. Simple but memory doesn't shrink.
- ZeRO stage 1 shards the optimizer state; stage 2 also shards gradients; stage 3 also shards the weights, gathering each layer's weights just before use.
- ZeRO-Offload / Infinity move optimizer state or weights to CPU RAM or NVMe to fit even bigger models, at a speed cost.
- PyTorch FSDP (Fully Sharded Data Parallel) is PyTorch's native version of ZeRO-3; FSDP2 is the newer per-parameter sharding API. Hugging Face Accelerate can drive either DeepSpeed or FSDP from a config.
- Tensor parallel (split each matmul) and pipeline parallel (split layers across GPUs) are used for very large models, usually combined with sharding.
- For most LoRA/QLoRA jobs a single GPU or plain DDP is enough; sharding matters for full fine-tuning of 7B+ models.
Interview questions
- Explain the ZeRO stages.
- DeepSpeed vs FSDP?
- You must fully fine-tune a 70B model on 8×80 GB GPUs. Is it possible?
Tools: TRL, PEFT, Unsloth, Axolotl, OpenAI API
Hugging Face TRL + PEFT is the standard code stack; Unsloth and Axolotl make it faster or config-driven; hosted APIs hide the GPUs.
- Transformers loads models and tokenizers; PEFT adds LoRA/DoRA/IA3/prompt tuning; bitsandbytes gives 4/8-bit quantisation; TRL has trainers for SFT, DPO, KTO, GRPO, reward modelling and more.
- Unsloth: drop-in faster LoRA/QLoRA training with custom kernels, lower memory and good single-GPU notebooks.
- Axolotl: YAML-config wrapper around HF/PEFT/TRL/DeepSpeed/FSDP. Good for reproducible runs without writing training code. LLaMA-Factory and torchtune are similar options.
- Hosted fine-tuning: OpenAI, Google Vertex AI, AWS Bedrock, Together, Fireworks and others take a JSONL file and return a model ID. No infra, but limited control and you can't download weights.
- OpenAI's flow: upload JSONL (
purpose="fine-tune"), create a job withmodel,training_fileandmethod(supervised; DPO and reinforcement also exist), then call theft:...model. Note: OpenAI has announced it is winding down self-serve fine-tuning (no new users; job creation ends December 15, 2026), so check the current status. - Track runs with W&B, MLflow or TensorBoard (
report_to=), and push adapters to the Hugging Face Hub or a model registry.
Interview questions
- What libraries would you use to fine-tune an open model?
- Hosted fine-tuning API vs self-hosted open model?
- What is the minimum OpenAI needs for a fine-tuning job?
Evaluate, deploy and cost
Evaluating a fine-tuned model
Compare against the base model on a held-out task set, general benchmarks and safety prompts, not just training loss.
- Loss and perplexity on the eval split show training health, but they are not task quality.
- Task metrics on a held-out test set: exact match/F1 for extraction, accuracy for classification, JSON-schema validity, unit tests for code, ROUGE/BLEU only as weak signals.
- LLM-as-a-judge with a rubric and pairwise comparison (fine-tuned vs base) for open-ended answers. Calibrate it against human ratings.
- Regression checks: general benchmarks (e.g. MMLU-Pro, IFEval, GSM8K via
lm-evaluation-harness) and a safety set, to catch forgetting. - Online: A/B test or shadow traffic, and watch user feedback, latency and cost per request.
- Always compare against the baseline (best prompt on base model, and RAG if relevant) so you know fine-tuning was worth it.
Interview questions
- How do you evaluate a fine-tuned LLM?
- Is lower eval loss always a better model?
- How do you check that fine-tuning didn't break general abilities?
Quantisation for deployment: GPTQ, AWQ, GGUF
After fine-tuning, merge the adapter and quantise the model so it serves faster and on smaller GPUs or CPUs.
- Post-training quantisation (PTQ) stores weights in 8/4-bit after training. Weight-only 4-bit cuts memory ~4× with small quality loss.
- GPTQ: layer-by-layer quantisation that uses a small calibration set and second-order (Hessian) information to minimise each layer's output error. Fast GPU kernels.
- AWQ (activation-aware weight quantisation): finds the ~1% most salient weight channels from activation statistics and scales them to protect them. Good accuracy, fast, popular in vLLM.
- GGUF: the llama.cpp file format with many quant types (
Q8_0,Q5_K_M,Q4_K_M...). Runs on CPU, Apple Silicon and GPUs via llama.cpp, Ollama and LM Studio. - Also: FP8 on H100-class GPUs (near-lossless, fast), and bitsandbytes NF4/INT8 (easy, but usually slower for serving).
- Workflow: train LoRA → merge into bf16 base → quantise → re-run your eval on the quantised model.
Interview questions
- GPTQ vs AWQ vs GGUF?
- How do you deploy a LoRA fine-tuned model quantised?
- What is the difference between quantisation-aware training and post-training quantisation?
Merging & serving adapters (vLLM multi-LoRA)
Merge one adapter for maximum speed, or keep many adapters separate and route requests to them on one shared base model.
- Merged:
W' = W + (alpha/r)·B·A, saved as a normal model. Zero overhead, but one full model per task. - Unmerged multi-adapter: one base model in GPU memory plus many small adapters. Each request picks its adapter. Hundreds of customers or tasks can share one GPU.
- vLLM: start with
enable_lora=True; pass aLoRARequest(name, id, path)per request, or start the OpenAI-compatible server with--lora-modules name=path. Requests then use the adapter name asmodel. - Batched multi-LoRA kernels (S-LoRA / Punica style) let requests for different adapters run in the same batch. Limits:
max_lorasper batch andmax_lora_rank. - Adapters can also be loaded at runtime (
/v1/load_lora_adapterwithVLLM_ALLOW_RUNTIME_LORA_UPDATING=True); vLLM warns to use this only in trusted environments. - In PEFT you can hold several adapters (
load_adapter,set_adapter) and even combine them (add_weighted_adapter), or merge with methods like TIES/DARE.
Interview questions
- Should you merge LoRA adapters before serving?
- How does vLLM serve many LoRA adapters efficiently?
- A customer-specific SaaS feature needs 200 fine-tuned variants. Design it.
Cost of fine-tuning
Training cost scales with tokens × epochs × model size, but data work and serving usually cost more than the training run.
- Trained tokens = examples × average tokens × epochs. Hosted APIs bill on this; self-hosted cost is GPU-hours.
- Training compute grows roughly with 6 × parameters × tokens FLOPs for full training; LoRA saves memory, not most of the forward/backward compute.
- A small LoRA/QLoRA SFT on an 8B model often costs single to low double-digit dollars of GPU time. The real costs are data collection, labelling and evaluation.
- Serving is the ongoing cost: a dedicated GPU 24/7, or per-token prices for hosted fine-tuned models (often higher than the base model's price).
- Savings: start with a smaller model, QLoRA, packing, shorter sequences, fewer epochs, spot GPUs, and multi-LoRA serving instead of one GPU per variant.
- Break-even: fine-tuning a small model pays off when it replaces many calls to a large model or cuts very long prompts.
Interview questions
- How would you estimate the cost of a fine-tuning project?
- When does fine-tuning save money compared to prompting a big model?
- Does LoRA reduce training compute?