LLM Internals: Architecture, Fine-Tuning, and Evaluation
Machine LearningModel answerLast updated
Explain decoder-only Transformer internals, compare positional encoding schemes, choose a PEFT strategy, and design an evaluation pipeline for a production LLM.
Large Language Model Architecture, Tuning, and Evaluation
Modern LLM development spans several interconnected concerns: understanding how the model is built, how to adapt it efficiently, how to keep it from overfitting, and how to know whether it actually works.
Address all four areas below. Be specific — name components, give formulas where they help, and ground your fine-tuning discussion in real experience.
Part 1 — Architecture
- Compare encoder–decoder models (e.g., T5, BART) and decoder-only models (e.g., GPT, LLaMA, Mistral). What makes decoder-only the dominant choice for general-purpose language models today?
- Walk through the layers in a decoder-only block: causal self-attention, the feed-forward sublayer, normalization placement, and residual connections. Explain what each component does and why it is designed the way it is.
Part 2 — Positional Encodings
Compare the three main families — absolute (sinusoidal or learned), relative (e.g., ALiBi, T5 biases), and rotary (RoPE) — on the following dimensions:
- How position information enters the computation
- Extrapolation behavior beyond training length
- Compatibility with efficient attention implementations
- Parameter cost
Part 3 — Parameter-Efficient Fine-Tuning
You have a 7B-parameter base model and a domain-specific supervised dataset. Describe your fine-tuning approach:
- When would you choose LoRA, QLoRA, adapters, or full fine-tuning?
- What are the practical trade-offs in memory, latency, and quality for each?
- Briefly describe a real (or realistic) fine-tuning project: task, data size, method, hyperparameters, and measured outcome.
Part 4 — Regularization and Evaluation
- What techniques prevent overfitting during fine-tuning? Cover data-side and training-side strategies.
- How do you evaluate an LLM? Distinguish intrinsic from extrinsic metrics, and offline from online validation. What can go wrong if you rely on only one type?
Hints
Hint 1
For the architecture comparison, anchor your answer on what makes decoder-only models easy to scale and serve: a single training objective, a uniform stack, and a KV cache that pairs naturally with autoregressive generation.
Hint 2
RoPE encodes relative position inside the attention dot product by rotating query and key vectors — think about why that makes it cache-friendly and why naive length extrapolation still fails.
Hint 3
Structure your fine-tuning story as: task → data → method choice (with reasoning) → key hyperparameters → measured result. Interviewers weight the reasoning behind method choice at least as heavily as the outcome numbers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer covers
This question tests breadth and depth together. The goal is to show you can describe each component precisely, explain why design choices were made, and connect theory to practical experience with concrete numbers.
1. Encoder–decoder vs. decoder-only
| Encoder–decoder (T5, BART) | Decoder-only (GPT, LLaMA, Mistral) | |
|---|---|---|
| Attention | Bidirectional encoder + causal decoder with cross-attention | Single causal self-attention stack |
| Pretraining objective | Span corruption / seq2seq denoising | Next-token prediction |
| Best fit | Long input, short output (translation, summarization) | Open-ended generation, instruction following, in-context learning |
| Weaknesses | Two separate stacks; awkward for chat-style tasks | Left-context-only for prompt tokens (mitigated at scale) |
Decoder-only became dominant for three structural reasons:
- Every token in every sequence contributes a training signal, so data efficiency is higher.
- A single uniform stack is simpler to scale and to serve.
- Pretraining, instruction tuning, and generation share the same autoregressive format, so the KV cache works without modification.
2. The decoder-only block
Tokens are embedded as x ∈ ℝ^{n×d}. Each of the L blocks applies two sublayers with pre-norm:
h = x + Attn(Norm(x))
y = h + FFN(Norm(h))
The model ends with a final norm, a linear LM head (often weight-tied to the embedding table), and a softmax over the vocabulary.
Causal self-attention. Queries, keys, and values are computed as Q=XW_Q, K=XW_K, V=XW_V, split across H heads. Each head computes:
softmax((QKᵀ / √d_h) + M) · V
where M is the causal mask (−∞ above the diagonal). Outputs are concatenated and projected by W_O. The O(n²) attention memory is the scaling bottleneck; FlashAttention avoids materializing the full n×n matrix. During inference, past K/V pairs are cached so each new token costs O(nd). Grouped-query attention (GQA) shares K/V heads across query-head groups, shrinking the KV cache by a factor of H/G with minimal quality loss.
Feed-forward block. Applied position-wise; typically holds ~two-thirds of a layer's parameters. The classic form is W₂ · GELU(W₁x) with hidden size 4d. LLaMA-style models use SwiGLU: W₂(SiLU(W₁x) ⊙ W₃x) with hidden size ~(8/3)d, keeping the parameter count similar while improving expressiveness.
Normalization. Pre-norm stabilizes gradients through deep stacks and removes the need for learning-rate warmup tricks. RMSNorm — x / RMS(x) · g, dropping mean-centering and bias — is cheaper than LayerNorm and performs equally well.
Residual connections. Each block learns an additive correction to a shared residual stream. Without them, training 30–100+ layer models is practically infeasible due to gradient vanishing.
3. Positional encodings
Attention is permutation-invariant by construction, so position must be explicitly injected.
| Method | How it works | Extrapolation | Cache-friendly | Parameters |
|---|---|---|---|---|
| Absolute sinusoidal | Fixed sinusoids added to input embeddings | Poor | Yes | 0 |
| Absolute learned | Learned embedding table up to max length | Hard cutoff | Yes | d × L_max |
| ALiBi | Adds linear penalty `−slope· | m−n | ` per head to attention scores | Good zero-shot |
| T5 relative bias | Bucketed learned bias added per layer | Moderate | Harder to fuse | Small |
| RoPE | Rotates each 2-D (q, k) pair by angle m·θ_i; encodes relative offset in the dot product | Fails naively; fixable | Yes | 0 |
RoPE is now the default. Its key properties: no added parameters, zero inference overhead, and the relative-position signal lives inside the dot product so it composes naturally with KV caching and FlashAttention. Its main limitation is that naive extrapolation beyond training length fails — handled in practice by position interpolation, NTK-aware base scaling, or YaRN plus a short fine-tune at the longer context.
ALiBi gives the best out-of-the-box length generalization but imposes a recency bias that can hurt tasks requiring long-range retrieval.
4. Fine-tuning and PEFT
Method selection:
- LoRA — freeze the base weights
Wand learn a low-rank updateΔW = BAwhereB ∈ ℝ^{d×r},A ∈ ℝ^{r×k}, and r ≪ d. Typically 0.1–1% of parameters. B is zero-initialized, so training starts from the base. The update merges into W at inference, adding zero latency. Default choice for most tasks. - QLoRA — LoRA on a 4-bit NF4 quantized frozen base. Use when GPU memory is the binding constraint (a 65B model on one 48GB GPU). Slightly slower to train.
- Adapters — small bottleneck MLPs inserted inside blocks. Modular and composable across tasks, but they cannot be merged, so they add inference latency. Best when multi-task composition is the priority.
- Full fine-tuning — highest ceiling, especially for large domain shifts. Requires ~16 bytes/param with Adam in mixed precision, so it needs multi-GPU (ZeRO / FSDP). Highest catastrophic-forgetting risk.
- Prompt tuning — fewest parameters; works well at large scale for narrow tasks. Consumes context length and underperforms on smaller models.
Rule of thumb: start with LoRA or QLoRA. Upgrade to full fine-tuning only if you have large data and the base model must change substantially. Always ask first whether RAG or prompt engineering solves the problem without training.
Concrete example: Fine-tuned a 7B LLaMA-family model for support-ticket triage and summarization on ~40k curated instruction pairs. Used QLoRA (4-bit NF4, r=16, α=32, applied to all attention and MLP projections) on a single A100 80GB. Trained for 3 epochs at LR 2e-4 with a cosine schedule; loss masked to response tokens only. Task F1 improved from 0.71 (prompted base) to 0.86, validated on a held-out set with human spot-checks.
5. Preventing overfitting and evaluation
Regularization:
- Data-side: deduplicate (including near-duplicates), scrub eval contamination, balance the task mix, and blend in general instruction data to slow catastrophic forgetting.
- Training-side: dropout (if used), weight decay, label smoothing, gradient clipping, early stopping on a held-out loss or task metric. Use a cosine or linear decay schedule; avoid training past the point of diminishing validation return.
Evaluation — a two-axis view:
| Intrinsic | Extrinsic | |
|---|---|---|
| Offline | Perplexity, BLEU, ROUGE, BERTScore, accuracy on benchmark suites (MMLU, HellaSwag) | Task-specific F1/accuracy, human eval (Likert, side-by-side), LLM-as-judge |
| Online | Token-level latency, throughput | User engagement, task completion rate, CSAT, downstream business metric |
Common mistakes:
- Optimizing only perplexity. A lower perplexity does not always correlate with downstream task quality.
- Benchmark contamination. If training data overlaps with the benchmark, scores are inflated.
- Skipping online evaluation. A model that looks strong offline can still fail to improve business metrics due to distribution shift or UX factors.
- Using LLM-as-judge without calibration. The judge model has its own biases and verbosity preferences; always validate judge scores against human ratings on a calibration set.
A robust pipeline runs offline evals on held-out benchmarks and human raters first, then gates production traffic through an A/B test monitored on both quality and latency metrics.