4.1 When to Fine-Tune vs. Prompt Engineer vs. RAG
flowchart TD
Q1{"Do you require\ndomain-specific behavior?"}
Q1 -->|No| P1["Prompt Engineering + Few-Shot Examples"]
Q1 -->|Yes| Q2{"Is the requirement about\nFacts vs. Behavior/Style?"}
Q2 -->|Facts / Changing Knowledge| RAG["RAG (Retrieval-Augmented Generation)\n• Up-to-date documentation\n• Avoids catastrophic forgetting"]
Q2 -->|Tone / Formatting / Reasoning| Q3{"Dataset Size & Budget?"}
Q3 -->|< 1K Examples| Few["In-Context Few-Shot Prompting"]
Q3 -->|1K - 50K Examples| LoRA["PEFT / LoRA / QLoRA\n(Single GPU / Low Cost / Modular)"]
Q3 -->|50K+ Examples + High Budget| Full["Full Fine-Tuning\n(Dedicated Multi-GPU Cluster)"]
| Scenario | Approach | Architectural Justification |
|---|---|---|
| Teaching new domain facts | RAG | Fine-tuning is unreliable for factual recall, hallucinates, and quickly becomes stale |
| Enforcing strict output JSON schemas | Fine-Tuning / LoRA | Enforces format consistency at lower token latency than massive few-shot prompts |
| Regulated legal/medical terminology | Fine-Tuning + RAG | Fine-tuning internalizes domain vocabulary; RAG supplies exact verified source paragraphs |
| Cost reduction at scale | Distillation / Fine-Tuning | Replaces an expensive frontier model with a lightweight 8B model fine-tuned on synthetic outputs |
4.2 Full Fine-Tuning
Updates 100% of model parameters. Requires multi-GPU clusters (8× A100/H100), substantial labeled datasets (10K+ to 100K+ examples), and carries serious risk of catastrophic forgetting (losing general common-sense reasoning). Reserved exclusively for foundational domain adaptations.
4.3 LoRA (Low-Rank Adaptation)
Freezes the pretrained foundation weights and injects trainable rank-decomposition matrices into transformer attention projections ($W_q, W_v, W_k, W_o$):
$$W’ = W_0 + \Delta W = W_0 + \frac{\alpha}{r} (B \cdot A)$$ (where $W_0 \in \mathbb{R}^{d \times k}$, $B \in \mathbb{R}^{d \times r}$, $A \in \mathbb{R}^{r \times k}$, and rank $r \ll \min(d, k)$)
flowchart LR
Input["Input Activation (X)"]
subgraph BaseWeight["Frozen Pretrained Weights (W_0)"]
W["Base Matrix (d × k)\n(No Gradients Computed)"]
end
subgraph LoRAAdapter["Trainable LoRA Adapters (r << d)"]
A["Matrix A (d × r)\n(Gaussian Initialized)"]
B["Matrix B (r × k)\n(Zero Initialized)"]
A --> B
end
Input --> BaseWeight
Input --> LoRAAdapter
Sum["Add: W_0 · X + (α/r) · B · A · X"]
BaseWeight --> Sum
LoRAAdapter --> Sum
Sum --> Out["Output Activation (Y)"]
Why LoRA is the Enterprise Standard:
- Drastically Reduced Parameter Count: Trains only 0.1% to 1% of total parameters, lowering VRAM requirements by over 60%.
- Prevents Catastrophic Forgetting: The underlying base model remains mathematically untouched.
- Dynamic Adapter Swapping: Multiple LoRA adapters (e.g., Customer Support adapter vs. Code Review adapter) can be swapped in real-time on a single shared foundation model instance in VRAM.
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3.1-8B-Instruct",
load_in_4bit=True # QLoRA
)
lora_config = LoraConfig(
r=16, # Rank — higher = more capacity
lora_alpha=32, # Scaling factor
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
lora_dropout=0.05,
task_type="CAUSAL_LM"
)
model = get_peft_model(model, lora_config)
4.4 QLoRA (Quantized LoRA)
Quantizes the base model to 4-bit precision, then applies LoRA adapters on top. Runs on a single consumer GPU (even an RTX 4090). The most budget-friendly fine-tuning option — ideal for experimentation and smaller enterprise teams.
4.5 DoRA and AdaLoRA (Advanced PEFT Variants)
- DoRA (Weight-Decomposed Low-Rank Adaptation): Decomposes pretrained weight into magnitude and direction components, applying LoRA-style updates only to the directional component. This more closely mimics full fine-tuning’s learning behavior while retaining LoRA’s parameter efficiency, generally yielding better quality than vanilla LoRA at the same rank.
- AdaLoRA (Adaptive LoRA): Dynamically allocates the parameter budget (rank) across weight matrices during training based on importance scores — instead of a fixed rank everywhere, more capacity goes to the layers that matter most for the task, improving efficiency over static-rank LoRA.
4.6 Prompt Tuning, P-Tuning v2, Prefix Tuning, Adapters
| Method | Mechanism | Trainable Params | Notes |
|---|---|---|---|
| Prompt Tuning | Learns a small set of continuous “soft prompt” embeddings prepended to input | Very small (<0.1%) | Simple, but limited expressiveness; scales well only on very large base models |
| P-Tuning v2 | Learns continuous prompts injected at every transformer layer (not just input) | Small | More expressive than prompt tuning; competitive with fine-tuning across model scales and task types |
| Prefix Tuning | Prepends learned continuous vectors to the key/value pairs at each attention layer | Small | Effective for generation tasks; keeps base model frozen |
| Adapters | Inserts small bottleneck feed-forward layers between transformer blocks | Small-Medium | Modular — different adapters can be swapped per task without retraining |
4.7 RLHF (Reinforcement Learning from Human Feedback)
Step 1: Supervised Fine-Tuning (SFT) on instruction data
Step 2: Train a Reward Model on human preference pairs (A vs B rankings)
Step 3: PPO (Proximal Policy Optimization) to maximize reward while staying
close to the SFT policy (via KL penalty)
Used by OpenAI (InstructGPT/ChatGPT) and Anthropic (Claude) for alignment and safety/behavior shaping. Complex, expensive, and requires substantial human annotation infrastructure.
4.8 RLAIF (Reinforcement Learning from AI Feedback)
Replaces human preference labeling with AI-generated preference judgments (typically from a strong “critic” LLM), dramatically reducing annotation cost and turnaround time versus RLHF while retaining much of the alignment benefit. Increasingly used to scale preference-tuning pipelines where human annotation is a bottleneck.
4.9 DPO (Direct Preference Optimization)
A simplification of RLHF that removes the need for a separate reward model entirely — it directly optimizes the policy from preference pairs using a closed-form loss derived from the RLHF objective. Cheaper, more stable to train, and increasingly the preferred method for alignment/preference-tuning over classic RLHF.
4.10 Fine-Tuning Data Preparation Checklist
- [ ] Minimum 500-1,000 high-quality examples (more for complex tasks; 10K-50K+ for LoRA on nuanced domains)
- [ ] Consistent format (instruction/input/output)
- [ ] Representative of production distribution
- [ ] Include edge cases and negative examples
- [ ] Deduplicated and cleaned
- [ ] Train/validation/test split (80/10/10)
- [ ] Human-reviewed for quality (domain experts for specialized fields)
Section 4 — Interview Q&A
Q: Explain the difference between LoRA and full fine-tuning. When would you choose each? A: Full fine-tuning updates all model parameters, requiring 8×A100-class GPU clusters, thousands of dollars per run, and risking catastrophic forgetting of general capabilities. LoRA freezes the base model and injects small trainable rank-decomposed matrices into attention layers, updating only 0.1-1% of parameters, running on 1-2 GPUs, and preserving general capabilities. I’d choose LoRA/QLoRA in nearly all enterprise cases — e.g., fine-tuning an 8B model on 10K-50K domain-specific examples to teach output formatting and domain reasoning patterns, since the base model already understands general language and just needs task specialization. Full fine-tuning is justified only with 100K+ training examples, a task radically different from general language, and the GPU/MLOps budget to support it. Practical progression: start with prompt engineering + RAG, escalate to LoRA if accuracy is insufficient, and treat full fine-tuning as the last resort.
Q: Explain quantization and when you would recommend it. A: Quantization reduces model weight precision from FP32/FP16 down to INT8 or INT4, shrinking memory footprint and accelerating inference. For a 70B model: FP16 needs ~140GB, INT8 (GPTQ) ~70GB with <1% quality degradation, INT4 (AWQ/GPTQ) ~35GB with 1-3% degradation, GGUF Q4 ~35GB with 2-5% degradation for local/edge use. I recommend it when self-hosting to reduce GPU count (fitting a 70B model on one A100 instead of two), for edge/limited-hardware deployment, and for latency-sensitive applications. I don’t recommend it when using managed APIs (the provider already optimizes this) or for tasks demanding maximum quality like medical/legal reasoning — and quantization should be applied after fine-tuning, not during.
Q: What’s the difference between RLHF and DPO, and why has DPO become popular? A: RLHF is a three-stage pipeline: supervised fine-tuning, then training a separate reward model on human preference pairs, then using PPO to optimize the policy against that reward model while constraining drift via a KL penalty. It’s effective but complex, unstable to tune, and expensive to run at scale. DPO reformulates the same underlying objective into a direct, closed-form loss over preference pairs — eliminating the separate reward model and the RL optimization loop entirely. It’s simpler to implement, more stable to train, and has become the preferred method for most enterprise alignment/preference-tuning work, with RLHF reserved for cases needing the more general reward-modeling flexibility (and RLAIF as a lower-cost alternative to human-labeled RLHF).
Q: What is P-tuning v2 and how does it differ from prompt tuning? A: Prompt tuning learns a small set of continuous embeddings prepended only to the input layer — simple but limited in expressiveness, and it typically only becomes competitive with fine-tuning at very large model scales. P-tuning v2 instead injects learned continuous prompts at every transformer layer (similar in spirit to prefix tuning), which gives it much more capacity to influence intermediate representations and makes it competitive with full fine-tuning across a broader range of model sizes and task types, while still keeping the base model frozen and trainable parameter count small.