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:

  1. 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.)
  2. 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.)
  3. 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, V projections, 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-p sampling.
  • LoRA parameterization, memory math, & deployment: Specify the (alpha / r) * B @ A decomposition and B = 0 initialization, work through an explicit parameter and optimizer-VRAM calculation, and discuss rank r, scaling alpha, adapted linear layers, weight merging versus dynamic multi-adapter serving, and practical limitations.

Step-by-step walkthrough

  1. 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 x of width d_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 projecting x through 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 ) @ V
    

    For a sequence of n tokens, stacking their vectors into matrices Q (n x d_k), K (n x d_k), and V (n x d_v) lets Q @ K^T compute all n x n pairwise dot-product similarity scores at once: entry (i, j) measures how strongly token i's query matches token j's key. Applying softmax (a function exp(s_j) / sum_m exp(s_m) that converts raw real-numbered scores into positive weights summing to 1.0) row by row turns those scores into attention weights, and multiplying by V produces a weighted average of value vectors for every token. (M is the causal mask covered in the next card.)

    Why divide by sqrt(d_k)? Suppose each coordinate of q and k is roughly independent with mean 0 and variance 1. Each product q_m * k_m then has mean 0 and variance 1, so summing d_k independent products gives q · k a variance of d_k and a standard deviation of sqrt(d_k). When d_k = 64, raw dot products routinely spread out by ±8 or more. Feeding large gaps into softmax pushes almost all probability onto the single largest score (saturation), where the slope p_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 to 1 regardless 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 @ V
    
  2. Causal masking, multi-head attention, and positional encoding

    Causal masking: A decoder-only LLM learns to predict token i + 1 given only tokens 1 .. i. If position i could read position i + 1 during training, it would trivially cheat by copying the answer. Setting every upper-triangular entry (i, j) with j > i in mask M to -inf makes exp(-inf) = 0 after 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..3
    

    Because no token ever peeks ahead, a single forward pass computes valid predictions for all n positions 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_model into h smaller heads of width d_head = d_model / h, runs separate (Wq_m, Wk_m, Wv_m) projections in parallel, concatenates all h outputs back to width d_model, and mixes them through an output matrix Wo (d_model x d_model). For d_model = 768 and h = 12 heads of width 64, total projection weights are 4 * 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 deterministic sin / cos waves of geometric wavelengths to input embeddings. - Learned absolute (e.g., GPT-2): Adds a trainable lookup vector P[pos] per index, which cannot extrapolate past its trained context limit (such as 1,024 tokens). - RoPE (Rotary Position Embedding, used in Llama / Qwen / Mistral): Rotates 2D coordinate pairs inside q and k by 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 distance m - n. - ALiBi: Leaves embeddings untouched and subtracts a linear distance penalty -slope * (i - j) directly from attention scores.

  3. 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). Notice FFN holds 2 * d_model * (4 * d_model) = 8 * d_model^2 weights — two thirds of a standard block's 12 * d_model^2 parameters!
    • Quick parameter sanity check (GPT-2 small): With 12 layers, d_model = 768, vocabulary 50,257, and 1,024 learned positions: 12 * (12 * 768^2) = 84.9M block weights + 50,257 * 768 = 38.6M tied token embeddings + 1,024 * 768 = 0.8M position embeddings ≈ 124M parameters, matching its published size.

    Training objective: Next-token cross-entropy loss averaged over all T tokens: 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 probability 0.25 to every true next token, loss = -ln(0.25) = 1.386 nats and perplexity = 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 n tokens costs O(n^2 * d_model) per layer in attention (Q @ K^T and weights @ V) plus O(n * d_model^2) in linear projections and the FFN. Recomputing earlier tokens from scratch at every step would wastefully turn generating N tokens into O(N^3 * d_model) attention work. Instead, engines maintain a KV cache storing past tokens' K and V vectors: at step t, only the single newest token computes its q, k, v and attends across the t cached keys in O(t * d_model) attention work per layer (O(N * (n + N) * d_model) total across N generated tokens), at the cost of memory growing linearly with sequence length.

  4. 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 k highest-scoring partial sequences (where k is the beam width) alive at every step: 1. Start with a single empty prefix () with cumulative log-probability 0.0. 2. Expand each active beam with every token in vocabulary V (k * V candidates total), adding log 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 like 0.1 quickly underflows (rounds down to 0.0 in floating-point arithmetic). 3. Sort candidates by score. Move any top candidate ending in the end-of-sequence (eos) token into a finished pool so it stops consuming an active beam slot, and keep the top k unfinished candidates as the next step's active beams. 4. Stop once k finished hypotheses are collected, no active beams remain, or max_len is 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 = 2 beats 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_hypothesis
    
  5. Length penalties and decoding resource overhead

    Every probability p is at most 1, so every log p is <= 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 (with alpha typically tuned on a validation set around 0.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; at alpha = 0.6 above it scores -1.82 vs -2.09, still favoring Y_s.)

    Compute and memory cost: At each step, all k active beams run as a batch through the Transformer, multiplying per-token FLOPs by roughly k compared with greedy decoding (wall-clock latency grows by less than k when GPU compute is underutilized, because decoding is memory-bandwidth bound). The KV cache must also store k active trajectories (kx cache memory), unless the serving engine uses paged prefix sharing so beams branching from a common prefix share earlier KV blocks.

  6. 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 x 1x
    Best 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 T before softmax sharpens probabilities toward greedy as T -> 0 and flattens them toward uniform for T > 1. To stop rare low-probability tail tokens from derailing coherence, top-k sampling restricts draws to the k highest-probability tokens, while top-p (nucleus) sampling dynamically restricts draws to the smallest set of top tokens whose cumulative probability reaches p (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.
  7. 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 change Delta_W has low matrix rank (meaning its columns are combinations of just a handful r of underlying directions, with r << min(d_in, d_out)). LoRA freezes W0 completely and represents Delta_W as the product of two thin matrices B (d_out x r) and A (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 A with small random Gaussian values and initialize B = 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, B receives a non-zero gradient (while A's gradient is 0 because B = 0); from step 2 onward, both A and B update together.

    Worked parameter and memory count: - Single 4096 x 4096 projection with r = 8: - Full matrix: 4096 * 4096 = 16,777,216 trainable weights. - LoRA (A + B): (8 * 4096) + (4096 * 8) = 65,536 trainable weights — 0.39% (256x fewer)! - Llama 2 7B (6.74B parameters, 32 layers) adapting Wq and Wv with r = 8: - Trainable weights: 2 * 32 * 65,536 = 4.19M (0.062% of 6.74B). - Training VRAM: Mixed-precision Adam stores 16 bytes per trainable parameter (2B bf16 weight + 2B bf16 grad + 4B fp32 master weight + 8B fp32 Adam m, v moments). Full fine-tuning needs 6.74B * 16 B ≈ 108 GB before activations! With LoRA, frozen W0 sits in bf16 (6.74B * 2 B ≈ 13.5 GB) and optimizer + gradient state for 4.19M adapter weights takes only 4.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 MB instead of 13.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_out
    
  8. LoRA hyperparameters, serving strategies, and limitations

    Key hyperparameters: - Rank r (typically 4 to 64): Controls adapter capacity. Narrow formatting or style tasks often saturate at r = 8–16; complex multi-step reasoning or broad domain shifts benefit from r = 32–64. - Scaling alpha: Scaling the adapter output by alpha / r keeps initial update magnitudes stable when changing r, so you rarely have to retune the learning rate from scratch when sweeping r (commonly alpha = 16 or alpha = 2 * r; a variant called rsLoRA uses alpha / sqrt(r) so larger ranks do not shrink per-component updates). LoRA typically uses a ~5–10x larger learning rate than full fine-tuning (e.g., 1e-4 to 2e-4), plus small adapter dropout (0.05) on small datasets. - Target modules: While the original LoRA paper adapted only attention Wq and Wv, adapting all linear layers (Wq, Wk, Wv, Wo plus 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: if W0 is 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 tiny 8–50 MB per-customer adapters on demand, routing requests inside the same GPU batch (as in S-LoRA / vLLM) for negligible O(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 x to adapted layers must still be saved for dA), cuts backward FLOPs by only ~33% (input-gradient matmuls through W0^T still 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 by sqrt(d_k) keeps dot-product variance near 1, preventing softmax saturation; setting future entries (j > i) of the causal mask M to -inf enables parallel training of all next-token predictions without leaking future tokens.
  • Multi-head attention and position: Splitting d_model into h heads of width d_model / h plus output projection Wo keeps parameter count at 4 * d_model^2 while letting heads specialize. Because raw attention is permutation-equivariant (insensitive to word order), position must be injected via sinusoidal/learned embeddings, RoPE (rotating q, k pairs so dot products depend on relative offset m - n), or ALiBi (distance score penalties).
  • Pre-norm block, objective, and KV cache: Each block computes h = x + MHA(Norm(x)) then h + 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 past K, V tensors) to drop per-step attention from O(n^2 d) to O(t d) per layer.
  • Beam search vs greedy vs sampling: Beam search tracks k prefixes scored by cumulative log-probability (summing logs avoids floating-point underflow, where tiny multiplied probabilities round to 0), 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 W0 and learns (alpha / r) * B @ A with A random and B = 0. On a 6.74B model (r = 8 on Wq, Wv), parameter/optimizer memory drops from ~108 GB (mixed-precision Adam at 16 bytes/param) to ~13.5 GB frozen bf16 weights + ~67 MB adapter state (plus activations), and adapters can either merge into W0 for zero inference latency or swap dynamically per request.

Common mistakes

  • Dividing attention scores by d_k instead of sqrt(d_k): Standard deviation scales with the square root of variance (sqrt(d_k)), so dividing by d_k over-shrinks scores toward 0 as heads widen.
  • Claiming h attention heads multiply parameters by h: Each head has width d_model / h, so total attention weights stay 4 * d_model^2 regardless of h.
  • 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 k early on), multiplying probabilities underflows to 0.0, and skipping length normalization biases toward premature <eos> tokens.
  • Initializing both LoRA matrices A and B randomly (or both to zero): Both random corrupts the pretrained model at step 0; both zero causes zero gradients for both matrices (dA multiplies by B and dB multiplies by A) so neither ever learns!
  • Claiming LoRA eliminates activation memory or speeds up inference: Backpropagation through deep adapters still requires saving layer inputs x for activation gradients, and merged LoRA has identical 1x inference speed (while unmerged adds tiny O(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' K and V vectors never depend on future tokens, caching them avoids recomputing the entire prefix on every generated word, cutting per-step attention FLOPs from O(t^2 d) to O(t d) per layer. The bottleneck shifts from compute to GPU memory capacity and memory bandwidth: on Llama 2 7B (32 layers, 4096 KV width, bf16 = 2 bytes), each token consumes 2 (K,V) * 32 * 4096 * 2 B = 0.5 MiB, meaning 2 GiB for one 4,096-token conversation or 32 GiB across a batch of 16, and every decode step must stream the entire cache from HBM. Standard mitigations include Grouped-Query Attention (GQA) (sharing each K, V head 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) or top-k sampling 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, Wo plus the FFN up, gate, and down matrices) rather than just Wq, 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 as r in {8, 16, 32, 64} (keeping alpha / r calibrated) and pick the smallest r where 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 and lm_head layers 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 W0 from 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 from 0.5 bits to 0.127 bits per parameter), while keeping LoRA adapters (A, B) in bf16 and dequantizing W0 tiles on the fly during matrix multiplication. For a 6.74B model, base-weight VRAM drops nearly 4x from ~13.5 GB to 6.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 roughly 20–35% slower training throughput from on-the-fly dequantization.

Follow-up questions

Similar questions

More UiPath interview questions

All 13 UiPath questions →