Decoder Transformers, Beam Search, and Low-Rank Adaptation
Medium · Machine Learning · Machine Learning Engineer · Technical Screen
Prompt
Walk an interviewer through three core pillars of contemporary large language models, treating each pillar sequentially in full mathematical and systems depth:
- Decoder-Transformer sequence modeling: Explain how query/key/value projections compute self-attention and why similarity scores are rescaled; what running multiple parallel heads contributes; how token order is encoded; how position-wise feed-forward networks, skip connections, and layer normalization interact inside a block; and how causal attention masks support parallel training and step-by-step decoding. (State up front whether you are focusing on modern decoder-only stacks or sequence-to-sequence encoder-decoder stacks.)
- Beam search decoding: Walk through how fixed-width beam search expands, scores, normalizes, and terminates candidate sequences; compare its behavior and resource profile against greedy decoding and stochastic token sampling; and identify tasks where beam search shines versus tasks where it degrades output quality. (Clarify whether the target setting is closed-ended transduction or open-ended dialogue.)
- Low-Rank Adaptation (LoRA): Formulate how LoRA injects trainable low-rank factors alongside frozen base weights, explain why it dramatically lowers fine-tuning memory and checkpoint size, detail its main hyperparameters, and contrast production serving modes.
Scope & Expectations
- Transformer mechanics & runtime scaling: Cover
Q, K, Vprojections,sqrt(d_k)variance scaling, causal masking, multi-head splitting, positional schemes (such as RoPE or learned embeddings), pre-norm residual + FFN block layout, next-token cross-entropy loss, and autoregressive decoding cost with KV caching. - Beam search algorithm & decoder comparison: Detail beam width pruning, log-probability accumulation,
<eos>hypothesis completion, length-penalty normalization, compute/KV-cache overhead, and concrete trade-offs versus greedy search and temperature /top-k/top-psampling. - LoRA parameterization, memory math, & deployment: Specify the
(alpha / r) * B @ Adecomposition andB = 0initialization, work through an explicit parameter and optimizer-VRAM calculation, and discuss rankr, scalingalpha, adapted linear layers, weight merging versus dynamic multi-adapter serving, and practical limitations.
Step-by-step walkthrough
Self-attention: queries, keys, values, and scaling by sqrt(d_k)
Scope: We examine the causal decoder-only stack behind models like GPT, Llama, and Qwen. Sequence-to-sequence encoder-decoder models add an unmasked bidirectional encoder plus a cross-attention sublayer in each decoder block.
Every input token enters a Transformer layer as a vector
xof widthd_model(its token embedding — a learned numeric vector representing the token — combined with position information). Self-attention lets each token gather relevant context from earlier tokens in the sequence by projectingxthrough three learned weight matrices:q = x @ Wq (Query, width d_k): "What kind of information am I looking for?" k = x @ Wk (Key, width d_k): "What kind of information do I contain?" v = x @ Wv (Value, width d_v): "What payload do I pass along if selected?" Attention(Q, K, V) = softmax( (Q @ K^T) / sqrt(d_k) + M ) @ VFor a sequence of
ntokens, stacking their vectors into matricesQ (n x d_k),K (n x d_k), andV (n x d_v)letsQ @ K^Tcompute alln x npairwise dot-product similarity scores at once: entry(i, j)measures how strongly tokeni's query matches tokenj's key. Applying softmax (a functionexp(s_j) / sum_m exp(s_m)that converts raw real-numbered scores into positive weights summing to1.0) row by row turns those scores into attention weights, and multiplying byVproduces a weighted average of value vectors for every token. (Mis the causal mask covered in the next card.)Why divide by
sqrt(d_k)? Suppose each coordinate ofqandkis roughly independent with mean0and variance1. Each productq_m * k_mthen has mean0and variance1, so summingd_kindependent products givesq · ka variance ofd_kand a standard deviation ofsqrt(d_k). Whend_k = 64, raw dot products routinely spread out by±8or more. Feeding large gaps intosoftmaxpushes almost all probability onto the single largest score (saturation), where the slopep_j * (1 - p_j)collapses toward zero and gradients vanish during training:Case Scores Softmax probabilities Peak slope p*(1-p) ----------------------- --------------- ------------------------------ ------------------ Unscaled (d_k = 64) [12, 4, -4] [0.99966, 0.00034, 0.0000001] 0.00034 (vanished!) Scaled by sqrt(64) = 8 [1.5, 0.5, -0.5] [0.665, 0.245, 0.090] 0.223 (healthy!)Dividing by
sqrt(d_k)rescales the variance back to1regardless of head width, keeping softmax weights smooth enough for gradients to flow.import numpy as np def causal_self_attention(X, Wq, Wk, Wv): """Compute one causal self-attention head. X: (n, d_model) -> output: (n, d_v).""" Q = X @ Wq # (n, d_k) queries K = X @ Wk # (n, d_k) keys V = X @ Wv # (n, d_v) values d_k = Q.shape[1] # Raw pairwise similarity scaled so score variance stays near 1.0. scores = (Q @ K.T) / np.sqrt(d_k) # (n, n) # Causal mask: forbid position i from attending to any future position j > i. n = X.shape[0] future_mask = np.triu(np.ones((n, n), dtype=bool), k=1) scores = np.where(future_mask, -np.inf, scores) # Subtract row maximum before exp() to prevent floating-point overflow. row_max = scores.max(axis=1, keepdims=True) exp_scores = np.exp(scores - row_max) weights = exp_scores / exp_scores.sum(axis=1, keepdims=True) return weights @ VCausal masking, multi-head attention, and positional encoding
Causal masking: A decoder-only LLM learns to predict token
i + 1given only tokens1 .. i. If positionicould read positioni + 1during training, it would trivially cheat by copying the answer. Setting every upper-triangular entry(i, j)withj > iin maskMto-infmakesexp(-inf) = 0after softmax:Causal mask M for n = 4 tokens: key 0 key 1 key 2 key 3 query 0 [ 0 -inf -inf -inf ] -> sees token 0 only query 1 [ 0 0 -inf -inf ] -> sees tokens 0..1 query 2 [ 0 0 0 -inf ] -> sees tokens 0..2 query 3 [ 0 0 0 0 ] -> sees tokens 0..3Because no token ever peeks ahead, a single forward pass computes valid predictions for all
npositions in parallel during training!Multi-head attention (MHA): One attention head produces only one set of mixing weights per token, forcing distinct relationships (such as "which noun does this pronoun refer to?" and "what was the immediately preceding word?") to compete for a single average. Multi-head attention splits
d_modelintohsmaller heads of widthd_head = d_model / h, runs separate(Wq_m, Wk_m, Wv_m)projections in parallel, concatenates allhoutputs back to widthd_model, and mixes them through an output matrixWo (d_model x d_model). Ford_model = 768andh = 12heads of width64, total projection weights are4 * d_model^2— the exact same parameter count as one full-width head, with far richer expressiveness.Positional information: Without positional signals (and ignoring the mask), self-attention is permutation-equivariant — shuffling the input words shuffles the output vectors in the exact same way, so
"dog bites man"and"man bites dog"would share identical representations per word. Four main schemes inject order: - Sinusoidal absolute (original Transformer): Adds deterministicsin/coswaves of geometric wavelengths to input embeddings. - Learned absolute (e.g., GPT-2): Adds a trainable lookup vectorP[pos]per index, which cannot extrapolate past its trained context limit (such as1,024tokens). - RoPE (Rotary Position Embedding, used in Llama / Qwen / Mistral): Rotates 2D coordinate pairs insideqandkby an angle proportional to token index (m * theta). Because the dot product between two rotated vectors depends only on the angle difference(m - n) * theta, attention scores naturally depend on relative distancem - n. - ALiBi: Leaves embeddings untouched and subtracts a linear distance penalty-slope * (i - j)directly from attention scores.Decoder block, cross-entropy training, and KV-cached generation
Each Transformer decoder layer wraps multi-head attention and a position-wise feed-forward network (FFN) inside residual connections (
x + sublayer(...), an identity highway that lets gradients flow straight back through dozens of layers without vanishing) and pre-normalization (applying LayerNorm or RMSNorm before each sublayer to keep activation magnitudes stable in deep stacks):Input stream x (n x d_model) | +---> Norm(x) ---> Causal Multi-Head Attention ---> (+) ---> h |____________________________________________________| | +---> Norm(h) ---> FFN: W2( act(W1 z) ) ----------> (+) ---> Output (n x d_model)- Feed-forward sublayer (
FFN): Applies the exact same two-layer MLP independently to each token vector (d_model -> 4 * d_model -> d_model, or a gated 3-matrix SwiGLU variant in modern LLMs). NoticeFFNholds2 * d_model * (4 * d_model) = 8 * d_model^2weights — two thirds of a standard block's12 * d_model^2parameters! - Quick parameter sanity check (GPT-2 small): With
12layers,d_model = 768, vocabulary50,257, and1,024learned positions:12 * (12 * 768^2) = 84.9Mblock weights +50,257 * 768 = 38.6Mtied token embeddings +1,024 * 768 = 0.8Mposition embeddings ≈ 124M parameters, matching its published size.
Training objective: Next-token cross-entropy loss averaged over all
Ttokens:loss = -(1 / T) * sum_{t=1..T} log p(x_t | x_1 .. x_{t-1}). Exponentiating the loss gives perplexity (exp(loss)), which measures effective branching uncertainty: if the model assigns probability0.25to every true next token,loss = -ln(0.25) = 1.386nats andperplexity = exp(1.386) = 4(as uncertain as rolling a fair 4-sided die at each word).Autoregressive generation and cost: At inference, the model processes the prompt and predicts one token at a time, appending each chosen token back into the input (autoregressive generation). A full pass over
ntokens costsO(n^2 * d_model)per layer in attention (Q @ K^Tandweights @ V) plusO(n * d_model^2)in linear projections and the FFN. Recomputing earlier tokens from scratch at every step would wastefully turn generatingNtokens intoO(N^3 * d_model)attention work. Instead, engines maintain a KV cache storing past tokens'KandVvectors: at stept, only the single newest token computes itsq, k, vand attends across thetcached keys inO(t * d_model)attention work per layer (O(N * (n + N) * d_model)total acrossNgenerated tokens), at the cost of memory growing linearly with sequence length.- Feed-forward sublayer (
Beam search: keeping the top-k candidate prefixes
Once the model outputs next-token probabilities, a decoding algorithm chooses actual words. Greedy decoding picks the single highest-probability token at every step. That is fast, but locally optimal choices can trap you: a slightly less likely first word might unlock a vastly higher-probability phrase on step 2.
Beam search hedges its bets by keeping the top
khighest-scoring partial sequences (wherekis the beam width) alive at every step: 1. Start with a single empty prefix()with cumulative log-probability0.0. 2. Expand each active beam with every token in vocabularyV(k * Vcandidates total), addinglog p(token | prefix)to its running score. We sum log-probabilities (log(a * b) = log a + log b) rather than multiplying raw probabilities because multiplying dozens of numbers like0.1quickly underflows (rounds down to0.0in floating-point arithmetic). 3. Sort candidates by score. Move any top candidate ending in the end-of-sequence (eos) token into afinishedpool so it stops consuming an active beam slot, and keep the topkunfinished candidates as the next step's activebeams. 4. Stop oncekfinished hypotheses are collected, no active beams remain, ormax_lenis reached (for unnormalized log-probabilities, adding tokens only makes scores more negative, so you can stop as soon as the best active beam falls below the best finished hypothesis).See how
k = 2beats greedy decoding on a 2-step toy vocabulary:Step 1 probabilities: A: 0.50 B: 0.40 C: 0.10 Step 2 probabilities after A: X: 0.40 Y: 0.30 Z: 0.30 Step 2 probabilities after B: X: 0.90 Y: 0.05 Z: 0.05 Greedy (k = 1): Step 1 -> picks A (0.50), discards B! Step 2 -> picks X (0.40) -> outputs "AX" with p = 0.50 * 0.40 = 0.20 (log p = -1.609) Beam search (k = 2): Step 1 -> keeps A (0.50) and B (0.40) Step 2 -> expands both: AX=0.20, AY=0.15, AZ=0.15, BX=0.36, BY=0.02, BZ=0.02 -> keeps BX (0.36) and AX (0.20) -> best is "BX" with p = 0.36 (log p = -1.022)!def _raw_score(candidate): return candidate[1] def beam_search(next_log_probs, beam_width, max_len, eos, alpha=1.0): """Decode with beam search; next_log_probs(prefix) -> {token: log_prob}.""" # beams holds active (token_tuple, cumulative_log_prob) hypotheses. beams = [((), 0.0)] finished = [] for _ in range(max_len): candidates = [] for tokens, cumulative_logp in beams: for token, step_logp in next_log_probs(tokens).items(): candidates.append((tokens + (token,), cumulative_logp + step_logp)) # Rank all extensions from highest (least negative) log-prob to lowest. candidates.sort(key=_raw_score, reverse=True) beams = [] for tokens, cumulative_logp in candidates: if tokens[-1] == eos: finished.append((tokens, cumulative_logp)) else: beams.append((tokens, cumulative_logp)) if len(beams) == beam_width: break if len(finished) >= beam_width or not beams: break # Only fall back to unfinished beams if max_len cut the search short early. pool = finished if len(finished) >= beam_width else finished + beams best_hypothesis = None for tokens, cumulative_logp in pool: length_factor = max(1, len(tokens)) ** alpha normalized_score = cumulative_logp / length_factor if best_hypothesis is None or normalized_score > best_hypothesis[1]: best_hypothesis = (tokens, normalized_score) return best_hypothesisLength penalties and decoding resource overhead
Every probability
pis at most1, so everylog pis<= 0. Without adjustment, every extra word subtracts from a sequence's cumulative score, unfairly penalizing longer sentences and rewarding premature<eos>tokens! Length normalization fixes this by dividing cumulative log-probability by a length penalty|Y|^alpha(withalphatypically tuned on a validation set around0.6–1.0):Formula: normalized_score(Y) = log p(Y) / |Y|^alpha Compare two finished candidates: Short Y_s: 2 tokens, log p = -2.0 (avg -1.00 per token) Long Y_l: 6 tokens, log p = -3.0 (avg -0.50 per token — much more confident per word!) alpha = 0.0 (raw): Y_s = -2.00, Y_l = -3.00 --> Short wins (-2.00 > -3.00) alpha = 0.6: Y_s = -1.32, Y_l = -1.02 --> Long wins (-1.02 > -1.32) alpha = 1.0 (mean): Y_s = -1.00, Y_l = -0.50 --> Long wins (-0.50 > -1.00)(Google NMT popularized a gentler variant,
((5 + |Y|) / 6)^alpha, which dampens the penalty on very short 1–4 token sequences; atalpha = 0.6above it scores-1.82vs-2.09, still favoringY_s.)Compute and memory cost: At each step, all
kactive beams run as a batch through the Transformer, multiplying per-token FLOPs by roughlykcompared with greedy decoding (wall-clock latency grows by less thankwhen GPU compute is underutilized, because decoding is memory-bandwidth bound). The KV cache must also storekactive trajectories (kx cache memory), unless the serving engine uses paged prefix sharing so beams branching from a common prefix share earlier KV blocks.Greedy vs beam search vs sampling: picking the right decoder
Answering the second clarifying question comes down to whether the task has one narrow target answer or many valid open-ended responses:
Property Greedy ( k = 1)Beam Search ( k > 1)Sampling ( temperature,top-k,top-p)Objective Most likely next token Approximate highest-probability full sequence Random draw from shaped distribution Deterministic? Yes Yes No (unless random seed is fixed) Compute & KV cache 1x~k x1xBest suited for Deterministic code/JSON, extraction, fast baselines Machine translation, speech recognition, short factual transduction Open-ended chat, creative writing, brainstorming, pass@k coding - Sampling controls: Dividing logits by temperature
Tbefore softmax sharpens probabilities toward greedy asT -> 0and flattens them toward uniform forT > 1. To stop rare low-probability tail tokens from derailing coherence, top-k sampling restricts draws to thekhighest-probability tokens, while top-p (nucleus) sampling dynamically restricts draws to the smallest set of top tokens whose cumulative probability reachesp(e.g.,p = 0.9). - Why beam search hurts open-ended chat: In open-ended dialogue, probability mass is spread across thousands of good phrasings, while the mathematical mode (highest-likelihood sequence) tends to be bland, short, or stuck in self-reinforcing repetition loops — and spending
kx GPU cost to get blander answers is a poor trade.
- Sampling controls: Dividing logits by temperature
LoRA: freezing the base weights and training low-rank adapters
Full fine-tuning updates every entry of every pretrained weight matrix
W0 (d_out x d_in). LoRA (Low-Rank Adaptation) relies on an empirical insight: when adapting an already-capable pretrained LLM to a downstream task, the learned weight changeDelta_Whas low matrix rank (meaning its columns are combinations of just a handfulrof underlying directions, withr << min(d_in, d_out)). LoRA freezesW0completely and representsDelta_Was the product of two thin matricesB (d_out x r)andA (r x d_in):h = W0 @ x + (alpha / r) * (B @ (A @ x)) Frozen base path: x (d_in) ------> [ W0: d_out x d_in (frozen) ] ------> (+) ---> h (d_out) Trainable LoRA path: x (d_in) -> [ A: r x d_in ] -> (r) -> [ B: d_out x r ] -^Initialization rule (critical): Initialize
Awith small random Gaussian values and initializeB = 0. At training step 0,B @ A = 0, so the adapted model behaves identically to the pretrained base model instead of injecting random noise! On step 1,Breceives a non-zero gradient (whileA's gradient is0becauseB = 0); from step 2 onward, bothAandBupdate together.Worked parameter and memory count: - Single
4096 x 4096projection withr = 8: - Full matrix:4096 * 4096 = 16,777,216trainable weights. - LoRA (A+B):(8 * 4096) + (4096 * 8) = 65,536trainable weights —0.39%(256xfewer)! - Llama 2 7B (6.74Bparameters,32layers) adaptingWqandWvwithr = 8: - Trainable weights:2 * 32 * 65,536 = 4.19M(0.062%of6.74B). - Training VRAM: Mixed-precision Adam stores16bytes per trainable parameter (2B bf16 weight +2B bf16 grad +4B fp32 master weight +8B fp32 Adamm, vmoments). Full fine-tuning needs6.74B * 16 B ≈ 108 GBbefore activations! With LoRA, frozenW0sits in bf16 (6.74B * 2 B ≈ 13.5 GB) and optimizer + gradient state for4.19Madapter weights takes only4.19M * 16 B ≈ 67 MB(activation memory is still needed because gradients flow backward through frozen layers to reach earlier adapters). Each saved adapter checkpoint is just~8.4 MBinstead of13.5 GB.import numpy as np def lora_forward(x, W0, A, B, alpha, r): """Compute frozen base projection plus scaled rank-r adapter update.""" # Multiply (A @ x) first so intermediate vector has tiny width r: O(r * (d_in + d_out)). base_out = W0 @ x adapter_out = B @ (A @ x) return base_out + (alpha / r) * adapter_outLoRA hyperparameters, serving strategies, and limitations
Key hyperparameters: - Rank
r(typically4to64): Controls adapter capacity. Narrow formatting or style tasks often saturate atr = 8–16; complex multi-step reasoning or broad domain shifts benefit fromr = 32–64. - Scalingalpha: Scaling the adapter output byalpha / rkeeps initial update magnitudes stable when changingr, so you rarely have to retune the learning rate from scratch when sweepingr(commonlyalpha = 16oralpha = 2 * r; a variant called rsLoRA usesalpha / sqrt(r)so larger ranks do not shrink per-component updates). LoRA typically uses a ~5–10xlarger learning rate than full fine-tuning (e.g.,1e-4to2e-4), plus small adapter dropout (0.05) on small datasets. - Target modules: While the original LoRA paper adapted only attentionWqandWv, adapting all linear layers (Wq, Wk, Wv, Woplus FFN projections) consistently matches full fine-tuning much more closely for the same total trainable parameter budget.Serving a LoRA model: - Single-tenant (merge offline): Fold the trained adapter directly into the base weights once (
W_merged = W0 + (alpha / r) * (B @ A)). Inference runs with zero extra latency and zero extra memory. (Caveat: ifW0is quantized to 4-bit, adding a bf16 product directly into 4-bit grid values causes rounding loss — either merge in bf16 before re-quantizing or serve unmerged.) - Multi-tenant (unmerged dynamic adapters): Keep one frozen base model in GPU memory and load dozens of tiny8–50 MBper-customer adapters on demand, routing requests inside the same GPU batch (as in S-LoRA / vLLM) for negligibleO(r * (d_in + d_out))extra FLOPs per token.Limitations: LoRA cannot match full fine-tuning when injecting massive amounts of brand-new factual knowledge (continued pretraining on a new language or codebase), does not eliminate activation memory (inputs
xto adapted layers must still be saved fordA), cuts backward FLOPs by only ~33% (input-gradient matmuls throughW0^Tstill run), and ties each adapter to the exact base checkpoint version it was trained on.
Intuition & how it works
Modern LLMs rest on three complementary ideas — how they process text, how they choose output words, and how we customize them cheaply:
1. Transformer self-attention works like a room of researchers where every word holds up a search slip (Query: what I need), an index label (Key: what I offer), and a note card (Value: my content), pulling a weighted blend of notes from earlier words in one parallel matrix pass.
2. Beam search decoding works like keeping your top k best route options open on a road trip instead of committing irreversibly at every intersection, avoiding dead-end local traps when looking for one high-probability answer.
3. LoRA fine-tuning works like taping a thin, transparent correction sheet (B @ A) over a massive printed encyclopedia (W0) instead of reprinting all 7 billion numbers for every custom task.
Naive alternatives fail at each stage: unscaled dot products grow with vector width d_k and saturate softmax (the function turning raw scores into probabilities summing to 1) so training gradients vanish; greedy single-token decoding throws away runner-up prefixes that become much stronger one word later; and full fine-tuning requires storing optimizer states roughly 8x larger than the model weights themselves (~108 GB for a 7B model).
Walk through a concrete mini-trace across all three pieces:
- Scaled causal attention: With head width d_k = 64, raw dot products [12, 4, -4] produce softmax [0.99966, 0.00034, 0.0000001] (gradient slope 0.00034), whereas dividing by sqrt(64) = 8 gives [1.5, 0.5, -0.5] and smooth weights [0.665, 0.245, 0.090] (slope 0.223), while -inf in future slots blocks peeking ahead.
- Beam search (k = 2): If step 1 gives A: 0.5, B: 0.4 and step 2 gives P(X|A) = 0.4 vs P(X|B) = 0.9, greedy locks into AX (0.20), whereas k = 2 keeps both A and B and discovers BX (0.36).
- LoRA (r = 8): Replacing updates to a 4096 x 4096 weight matrix (16,777,216 params) with B (4096 x 8) @ A (8 x 4096) trains just 65,536 weights (256x fewer), starting at B = 0 so step-0 behavior matches W0 exactly.
Key points
- Scaled causal self-attention: Computes
softmax(Q K^T / sqrt(d_k) + M) V. Dividing bysqrt(d_k)keeps dot-product variance near1, preventing softmax saturation; setting future entries(j > i)of the causal maskMto-infenables parallel training of all next-token predictions without leaking future tokens. - Multi-head attention and position: Splitting
d_modelintohheads of widthd_model / hplus output projectionWokeeps parameter count at4 * d_model^2while letting heads specialize. Because raw attention is permutation-equivariant (insensitive to word order), position must be injected via sinusoidal/learned embeddings, RoPE (rotatingq, kpairs so dot products depend on relative offsetm - n), or ALiBi (distance score penalties). - Pre-norm block, objective, and KV cache: Each block computes
h = x + MHA(Norm(x))thenh + FFN(Norm(h)), where the feed-forward network (FFN) holds two thirds (8 * d_model^2) of block weights and residual connections (x + ...) preserve gradient flow. Training minimizes next-token cross-entropy (perplexity = exp(loss)); inference uses a KV cache (storing pastK, Vtensors) to drop per-step attention fromO(n^2 d)toO(t d)per layer. - Beam search vs greedy vs sampling: Beam search tracks
kprefixes scored by cumulative log-probability (summing logs avoids floating-point underflow, where tiny multiplied probabilities round to0), moves<eos>sequences to a finished pool, and divides by|Y|^alpha(length normalization) so negative step scores do not bias toward short outputs. Use beam search for closed-ended tasks (translation, ASR) and temperature / top-p sampling for open-ended chat. - LoRA mechanics and economics: Freezes
W0and learns(alpha / r) * B @ AwithArandom andB = 0. On a6.74Bmodel (r = 8onWq, Wv), parameter/optimizer memory drops from~108 GB(mixed-precision Adam at16bytes/param) to~13.5 GBfrozen bf16 weights +~67 MBadapter state (plus activations), and adapters can either merge intoW0for zero inference latency or swap dynamically per request.
Common mistakes
- Dividing attention scores by
d_kinstead ofsqrt(d_k): Standard deviation scales with the square root of variance (sqrt(d_k)), so dividing byd_kover-shrinks scores toward0as heads widen. - Claiming
hattention heads multiply parameters byh: Each head has widthd_model / h, so total attention weights stay4 * d_model^2regardless ofh. - Thinking causal masking is only used during generation: During inference with a KV cache, future tokens do not even exist yet during step-by-step decoding; causal masking is essential during training (and prompt prefill) so all positions train simultaneously without cheating.
- Calling beam search exact MAP decoding, or multiplying raw probabilities: Beam search is an approximate heuristic (the winning sequence's prefix can fall outside the top
kearly on), multiplying probabilities underflows to0.0, and skipping length normalization biases toward premature<eos>tokens. - Initializing both LoRA matrices
AandBrandomly (or both to zero): Both random corrupts the pretrained model at step 0; both zero causes zero gradients for both matrices (dAmultiplies byBanddBmultiplies byA) so neither ever learns! - Claiming LoRA eliminates activation memory or speeds up inference: Backpropagation through deep adapters still requires saving layer inputs
xfor activation gradients, and merged LoRA has identical1xinference speed (while unmerged adds tinyO(r d)work).
Follow-up questions
- How does caching past key and value tensors accelerate token-by-token decoding, and what hardware bottlenecks constrain it? Because causal masking ensures past tokens'
KandVvectors never depend on future tokens, caching them avoids recomputing the entire prefix on every generated word, cutting per-step attention FLOPs fromO(t^2 d)toO(t d)per layer. The bottleneck shifts from compute to GPU memory capacity and memory bandwidth: on Llama 2 7B (32layers,4096KV width, bf16 =2bytes), each token consumes2 (K,V) * 32 * 4096 * 2 B = 0.5 MiB, meaning2 GiBfor one4,096-token conversation or32 GiBacross a batch of16, and every decode step must stream the entire cache from HBM. Standard mitigations include Grouped-Query Attention (GQA) (sharing eachK, Vhead across 4–8 query heads to shrink the cache 4–8x), paged KV allocation (PagedAttention) to eliminate fragmentation, FP8/INT4 KV quantization, and sliding-window attention. - What causes beam search to fall into bland phrasing or repetition loops during open-ended dialogue, and how do you counteract that? Beam search hunts for high-probability sequences, and in open-ended text probability mass concentrates on bland, safe phrases — plus Transformer self-attention exhibits positive feedback where once a phrase appears in context, repeating it receives high next-token probability, causing wider beams to lock onto loops even faster. Mitigations include switching to nucleus (
top-p) ortop-ksampling with temperature, applying repetition or frequency penalties to already-generated token logits, enforcing no-repeat n-gram constraints (forbidding any 3-gram or 4-gram from appearing twice), or using diverse beam search (penalizing beam groups for picking identical tokens). - Suppose you are adapting an LLM for multi-turn tool calling with LoRA—which projection layers would you target and how would you select rank r? Adapt all linear projections (
Wq, Wk, Wv, Woplus the FFNup,gate, anddownmatrices) rather than justWq, Wv, because reliable tool calling requires both attending accurately over long JSON schemas/tool outputs and emitting strict structured syntax from the FFN layers. Sweep ranks such asr in {8, 16, 32, 64}(keepingalpha / rcalibrated) and pick the smallestrwhere held-out tool metrics (schema validity, tool choice, exact argument match, and multi-turn task completion) plateau without degrading general instruction benchmarks. Mask the cross-entropy loss so gradients are computed only on assistant turns (tool calls and final answers, never user prompts or returned tool JSON), include "no tool needed" examples to prevent over-calling, and if you add new special tokens like<tool_call>, make the embedding andlm_headlayers trainable too since LoRA adapters inside blocks never update token embeddings. - In what ways does QLoRA alter GPU memory consumption and training trade-offs relative to standard 16-bit LoRA? QLoRA quantizes the frozen base weights
W0from 16-bit bf16 down to 4-bit NormalFloat (NF4) — an information-theoretically optimal 4-bit grid for bell-curved neural weights — using 64-weight blocks, and applies double quantization (quantizing the 32-bit block scale factors themselves to 8-bit, shrinking scale overhead from0.5bits to0.127bits per parameter), while keeping LoRA adapters(A, B)in bf16 and dequantizingW0tiles on the fly during matrix multiplication. For a6.74Bmodel, base-weight VRAM drops nearly4xfrom~13.5 GBto6.74B * 4.127 / 8 ≈ 3.5 GB, and paged optimizers offload temporary optimizer memory spikes to CPU RAM, making it possible to fine-tune a 65B–70B model on a single 48 GB GPU at the cost of roughly20–35%slower training throughput from on-the-fly dequantization.
Follow-up questions
- How does caching past key and value tensors accelerate token-by-token decoding, and what hardware bottlenecks constrain it?
- What causes beam search to fall into bland phrasing or repetition loops during open-ended dialogue, and how do you counteract that?
- Suppose you are adapting an LLM for multi-turn tool calling with LoRA—which projection layers would you target and how would you select rank r?
- In what ways does QLoRA alter GPU memory consumption and training trade-offs relative to standard 16-bit LoRA?
Similar questions
- Core ML Optimization, Regularization, and Encoding
- Transformer Block Internals, Math, and Feed-Forward Role
- Overfitting Remedies and Mean Squared Error Fundamentals
- Engineering Dependable LLM Tool Use: Structured Outputs, Recovery, and Loop Control
- Immutable State Engine for a Folder Tree
- Longest Repeat-Free Substring Ignoring Case
More UiPath interview questions
- Immutable State Engine for a Folder Tree Easy
- Stopping-Score Cap Probability Under Uniform Draws Medium
- Engineering Dependable LLM Tool Use: Structured Outputs, Recovery, and Loop Control Medium Pro
- Shortest Knight-Style Jumps on an Unbounded Grid Medium Pro
- Longest Repeat-Free Substring Ignoring Case Medium Pro
- End-to-End Project Walkthrough and Engineering Ownership Medium Pro
- Core ML Optimization, Regularization, and Encoding Easy Pro
- Transformer Block Internals, Math, and Feed-Forward Role Medium Pro
- Storage Architecture and Query Consistency Guarantees Hard Pro
- Bidirectional Bubble Sort with Adaptive Bounds Medium Pro