LLM Core Mechanics: Attention, Decoding Strategies, and LoRA
Machine LearningModel answerLast updated
Walk through how Transformers process sequences, how beam search compares to other decoding methods, and how LoRA cuts fine-tuning costs.
Modern large language models rest on a small number of foundational ideas. Being able to explain those ideas precisely — including the reasoning behind specific design choices — is a reliable signal of depth in an ML interview.
Answer all three parts in order. For each part, go far enough that you could field follow-up questions on the details.
Assume a decoder-only architecture (the dominant design in current LLMs) unless a part explicitly calls for something else.
Part 1 — How a Transformer processes a sequence
Describe what happens inside a single Transformer block and across the full forward pass. Your answer should cover:
- How self-attention is computed: the role of the query, key, and value projections; why the dot products are scaled before the softmax; and what the output represents
- What multi-head attention adds over a single attention head
- How the model knows the order of tokens given that attention itself is position-agnostic
- What the feed-forward sublayer, residual connections, and layer normalization each contribute
- How a causal mask makes autoregressive generation possible, and what that implies for inference cost as sequence length grows
Part 2 — Decoding strategies: beam search and its alternatives
Explain how beam search turns a trained model into a text generator. Your answer should cover:
- The algorithm step by step: what a "beam" is, how candidates are scored and pruned at each step, and how generation ends
- Why raw cumulative log-probabilities favor short outputs and how that is corrected
- How beam search compares to greedy decoding and to sampling-based methods in terms of output quality, diversity, and cost
- The kinds of tasks where beam search is a strong choice and the kinds where it works against you
Part 3 — LoRA: efficient fine-tuning via low-rank adaptation
Explain the LoRA method and the practical decisions that come with using it. Your answer should cover:
- The mathematical idea behind the low-rank weight update and why the initialization is set up the way it is
- A concrete worked example showing how many trainable parameters LoRA introduces compared to full fine-tuning
- The key hyperparameters (rank, scaling factor, which modules to target) and the intuition behind choosing them
- How a LoRA-adapted model is deployed, including the trade-offs between merging the adapter into the base weights versus keeping them separate
- The main failure modes and limitations to be aware of
Hints
Hint 1
For Part 1, work through the attention formula step by step before explaining why each piece is there — the scaling factor has a specific numerical motivation tied to the variance of dot products in high dimensions.
Hint 2
For Part 2, think about what 'greedy' decoding is doing as a degenerate case of beam search with width 1, then reason about what you gain and what you pay as you widen the beam.
Hint 3
For Part 3, start with the shapes: if a weight matrix is d × d, a rank-r factorization has two matrices of shapes d × r and r × d. Counting those parameters for a realistic d makes the savings concrete.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Transformer internals
Self-attention mechanics
For each token in the sequence, the model projects its embedding into three vectors — a query (Q), a key (K), and a value (V) — using learned weight matrices. The attention scores are computed as dot products between each query and all keys, then scaled by 1/√d_k where d_k is the key dimension. Without that scaling, dot products in high-dimensional spaces tend to have large variance, which pushes the softmax into saturation and kills gradient flow. After the softmax, the scores become a probability distribution over positions, and the output is a weighted sum of the value vectors. In matrix form: Attention(Q, K, V) = softmax(QKᵀ / √d_k) V.
Multi-head attention
Running a single attention computation forces the model to compress everything into one set of relationship scores. Multi-head attention splits the embedding dimension into h heads, each running its own Q/K/V projections in a lower-dimensional subspace. The outputs are concatenated and projected back to the full dimension. This lets different heads specialize — one might track syntactic dependencies, another coreference — without extra depth.
Positional information
Attention has no notion of order: shuffling the input tokens gives identical attention scores. Position is injected by adding a positional encoding to each token embedding before the first layer. Fixed sinusoidal encodings (original Transformer) use frequencies that let the model extrapolate; learned absolute positions are simpler but cap at a fixed context length. Rotary positional embeddings (RoPE), common in current LLMs, encode position by rotating the Q and K vectors, which preserves relative distances naturally and extends more gracefully to longer contexts.
Block structure
Each Transformer block applies multi-head attention, followed by a position-wise feed-forward network (typically two linear layers with a nonlinearity, expanding to ~4× the model dimension then contracting back). Both sublayers are wrapped with a residual connection (output = sublayer(x) + x) and layer normalization. Residuals prevent gradient vanishing at depth; layer norm stabilizes activations across the feature dimension at each token independently.
Causal masking and autoregressive cost
A decoder-only LLM is trained to predict the next token given all previous tokens. The causal mask sets all attention scores above the diagonal to −∞ before the softmax, so position i can only attend to positions ≤ i. At inference, each new token requires a full forward pass, and the attention computation over past tokens scales as O(n²) in sequence length — the dominant cost bottleneck for long generations. KV caching avoids recomputing keys and values for already-processed tokens, trading memory for speed.
Part 2 — Beam search
The algorithm
Beam search maintains a fixed-size set of k candidate sequences ("beams") at each step. At step t, every beam is extended by every vocabulary token, producing k × |V| candidates. Each candidate is scored by its cumulative log-probability (sum of log P of each token given its prefix). The top k candidates by score are kept; the rest are discarded. A beam is retired when it produces an end-of-sequence token; generation stops when all beams are retired or a maximum length is hit.
Length normalization
Cumulative log-probabilities are always negative, so longer sequences get lower scores by construction. Without correction, beam search strongly favors short outputs. Length normalization divides the score by sequence length raised to a penalty exponent (typically around 0.6–0.8), tuned on a validation set.
Comparison with greedy and sampling
Greedy decoding is beam search with k=1: pick the single highest-probability token at every step. It is fast but myopic — committing to an early token can close off a much better overall sequence. Beam search with k > 1 recovers some of that, but at k × cost per step. Sampling-based methods (temperature sampling, top-k, nucleus/top-p) draw from the probability distribution rather than maximizing it. They produce more diverse, less repetitive output, which matters for open-ended generation. The trade-off: sampling can produce incoherent text; beam search produces fluent but often generic text.
When to use each
Beam search is well-suited to tasks with a target output that has limited acceptable variation: machine translation, summarization with strict length constraints, or structured prediction where fluency and faithfulness are more important than diversity. It is a poor fit for creative writing, dialogue, or instruction following — these tasks reward diversity and natural variation that beam search suppresses. Most production chat and assistant systems use sampling with top-p and a temperature below 1.
Part 3 — LoRA
The core idea
Full fine-tuning updates every parameter of a pretrained model, which is expensive in GPU memory and storage. LoRA (Low-Rank Adaptation) freezes the original weights entirely and injects a low-rank update alongside them. For a weight matrix W of shape d × d, LoRA adds ΔW = BA, where B is d × r and A is r × d, with r ≪ d. Only A and B are trained. B is initialized to zeros so that ΔW = 0 at the start of fine-tuning, meaning training begins from exactly the pretrained model's behavior.
Parameter savings — worked example
For a weight matrix with d = 4096 (typical for a ~7B parameter model): full fine-tuning of that matrix trains 4096 × 4096 = 16.8M parameters. With rank r = 16, LoRA trains 4096 × 16 + 16 × 4096 = 131K parameters — about 0.8% of the original. Applied to all attention projection matrices in every layer, total trainable parameters are typically 1–5% of the base model, with GPU memory for gradients and optimizer state reduced proportionally.
Key hyperparameters
- Rank r: controls adapter capacity. r = 4–16 covers most fine-tuning tasks; going higher approaches full fine-tuning in cost without always improving results.
- Scaling factor α: the update is applied as (α/r) × BA. Setting α = r is a common default that keeps the effective learning rate stable across different rank choices.
- Target modules: attention projections (Q, K, V, output) are the standard targets. Adding the feed-forward layers helps on tasks requiring factual updates but increases cost.
Deployment: merge vs. separate
After training, B and A can be merged back into W (W' = W + BA), producing a single weight matrix with no inference overhead. This is the right choice when serving a single fine-tuned variant. Keeping adapters separate allows hot-swapping multiple fine-tuned behaviors on top of one base model copy, which matters in multi-tenant or multi-task serving — the base model weights are loaded once and adapters are loaded per request. The cost is a small per-layer addition at inference time.
Limitations
LoRA struggles when the target task is very far from the pretraining distribution — the frozen base weights may not contain the right representations to adapt from. Very low ranks can underfit nuanced tasks. Because the base model is frozen, LoRA cannot correct deep factual errors baked into pretraining; retrieval-augmented generation is a better tool for that.