LLM AI Infrastructure Interview Questions: Attention, Distributed Training, and Inference Optimization

    This article provides a structured review of common interview questions for large language model AI infrastructure roles. It covers Transformer attention fundamentals and implementation details, the evolution from MHA to MQA/GQA and long-context techniques, distributed training parallelism and memory accounting, inference optimization such as KV cache management, continuous batching, quantization, and speculative decoding, as well as engineering practices for stability and performance analysis.

    LLM AI Infrastructure Interview Questions: Attention, Distributed Training, and Inference Optimization

    1. Introduction: Why AI Infrastructure Interviews Focus on Fundamentals

    Context windows for mainstream large models have grown from a few thousand tokens in early systems to 128K and even 256K levels today. This progress is not simply a matter of adding more parameters. It reflects years of architecture and systems engineering work across dozens of core papers. Attention mechanisms have evolved from the original multi-head attention into many variants, training frameworks have moved from single-machine single-GPU setups to clusters with tens of thousands of GPUs, and inference engines have advanced from naive implementations to highly optimized systems. Each step in this evolution is a core topic in AI infrastructure interviews.

    For candidates in AI infrastructure, interviewers are really evaluating three things. First, do you understand why these technologies were invented? Second, are you clear about the engineering trade-offs of each approach? Third, can you translate theory into code and system-level implementation? This article walks through these high-frequency questions one by one.

    2. Fundamentals: Transformer and Attention Mechanisms

    2.1 Why Attention Replaced RNN/LSTM

    This is a classic opening question. Before attention mechanisms appeared, sequence modeling was dominated by recurrent structures for a long time, but those structures had two critical weaknesses:

    • No parallel training: Recurrent structures require token-by-token sequential computation. Computation later in the sequence must wait for earlier parts to finish. This severely wastes the large-scale parallelism of modern GPUs, and long-text training can take months.
    • Decaying long-range dependencies: Information is diluted as it is passed step by step. Semantic links between the beginning and end of a sequence are difficult to preserve, and vanishing gradients make the problem worse.

    The self-attention mechanism proposed in 2017 established direct connections between any two positions in a sequence with a single matrix operation. The path length dropped from O(N) to O(1), and the entire sequence could be processed in parallel. Under the same hardware conditions, training efficiency improved by more than an order of magnitude compared with recurrent structures. This directly enabled the era of large-model scaling.

    2.2 Writing Multi-Head Attention (MHA) by Hand

    Interviewers often ask candidates to write the core implementation of MHA on the spot to test their grasp of tensor transformation details. Key points include Q/K/V linear projections, splitting by head, scaled dot product, mask handling, and output concatenation.

    1. import torch
    2. import torch.nn as nn
    3. import math
    4. class MultiHeadAttention(nn.Module):
    5. """Illustrative implementation of multi-head attention (MHA)"""
    6. def __init__(self, d_model: int, num_heads: int, dropout: float = 0.1):
    7. super().__init__()
    8. assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
    9. self.d_model = d_model
    10. self.num_heads = num_heads
    11. self.head_dim = d_model // num_heads
    12. # Q, K, V linear projections
    13. self.q_proj = nn.Linear(d_model, d_model)
    14. self.k_proj = nn.Linear(d_model, d_model)
    15. self.v_proj = nn.Linear(d_model, d_model)
    16. self.out_proj = nn.Linear(d_model, d_model)
    17. self.dropout = nn.Dropout(dropout)
    18. self.scale = math.sqrt(self.head_dim)
    19. def forward(self, query, key, value, mask=None):
    20. batch_size, seq_len, _ = query.shape
    21. # Linear projections and split into heads: (B, H, L, D_head)
    22. Q = self.q_proj(query).view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
    23. K = self.k_proj(key).view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
    24. V = self.v_proj(value).view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
    25. # Scaled dot-product attention scores
    26. scores = torch.matmul(Q, K.transpose(-2, -1)) / self.scale
    27. if mask is not None:
    28. scores = scores.masked_fill(mask == 0, float("-inf"))
    29. attn = self.dropout(torch.softmax(scores, dim=-1))
    30. # Weighted sum and merge heads
    31. out = torch.matmul(attn, V)
    32. out = out.transpose(1, 2).contiguous().view(batch_size, seq_len, self.d_model)
    33. return self.out_proj(out)

    2.3 Why Divide by √d_k

    This is a common follow-up question. When head_dim is large, the variance of the dot product between Q and K grows linearly with the dimension. This makes the softmax input too large and pushes gradients toward saturation in the flat region of softmax, causing unstable training. Dividing by √d_k normalizes the variance of attention scores to roughly 1, ensuring healthy gradient flow. Further follow-ups may involve Xavier initialization and variance derivation. Candidates should be able to derive it on the spot: assuming each component of q and k is independent and identically distributed with mean 0 and variance 1, the variance of the dot product is d_k, so the scaling factor is √d_k.

    3. Advanced Topics: The Evolution of Attention Mechanisms

    3.1 MQA and GQA: Reducing Inference Memory Pressure

    The bottleneck of standard MHA during inference is the KV cache: each head must cache its own K/V, and memory usage grows linearly with sequence length for long sequences. This led to two levels of improvement:

    • Multi-Query Attention (MQA): All query heads share the same K/V. KV cache memory usage drops to 1/H of the original, and inference throughput improves significantly, but expressive capacity suffers to some extent.
    • Grouped-Query Attention (GQA): A compromise between MHA and MQA. Query heads are grouped, and K/V is shared within each group. This achieves a better balance between memory savings and model quality and has become a standard choice for mainstream large models.

    In interviews, you should be able to clearly state the KV cache memory formulas for the three approaches. Let L be the number of layers, H the number of heads, D the head dimension, and N the sequence length. MHA KV cache is 2·L·H·D·N, GQA with G groups is 2·L·G·D·N, and MQA is 2·L·D·N.

    3.2 Quadratic Complexity and Sparse/Linear Attention

    Standard attention has O(N²) computational and memory complexity, which is the core obstacle for long context. Improvement paths around this problem are frequent interview topics:

    • Sparse attention: Each token attends only to a local window, specific strides, or important tokens such as anchor tokens. Complexity is reduced to O(N·w), where w is the window size. Representative ideas include sliding windows and dynamic sparse selection.
    • Linear attention: Kernel-function approximation changes the computation order. It first computes K^T·V and then multiplies by Q, reducing complexity to O(N·d²). This is suitable for very long sequences but requires balancing approximation error and accuracy loss.
    • Hybrid architectures: Some layers use full attention to preserve global modeling capability, while other layers use sparse/local attention to reduce cost. This is a common engineering practice in current long-context models.

    3.3 Evolution of Positional Encoding

    Positional encoding is another main thread in long-context interviews. Common topics include:

    • Absolute positional encoding: Early approaches add fixed or learnable position vectors to the input. Extrapolation ability is poor.
    • Rotary Position Embedding (RoPE): Position information is encoded as a rotation operation on Q/K, so attention scores naturally carry relative position information. This has become the mainstream approach.
    • Length extrapolation techniques: These include position interpolation, which compresses long-sequence positions back into the training range, NTK-aware scaling, and dynamically adjusting the rotary base frequency. Interviews often ask why direct extrapolation fails: high-frequency rotation angles not seen during training cause the attention score distribution to shift.

    4. System-Level Topics: Distributed Training

    4.1 Overview of Parallelism Strategies

    Training at the scale of tens of thousands of GPUs is a core capability area for AI infrastructure roles. You must be proficient in four types of parallelism and their combinations:

    • Data parallelism (DP): Each GPU holds a full model replica and splits the data. Improved versions shard parameters, gradients, and optimizer states, following the three-stage zero-redundancy optimization idea, to eliminate redundancy. Memory usage can drop by an order of magnitude.
    • Tensor parallelism (TP): Weight matrices within a layer are split by row or column across GPUs, with All-Reduce inside the layer. Communication volume is large, so it is usually limited to a single machine’s high-speed interconnect domain.
    • Pipeline parallelism (PP): Layers are split across devices, and micro-batches fill pipeline bubbles. You need to understand bubble ratio calculation: bubble ratio ≈ (p−1)/(m+p−1), where p is the number of pipeline stages and m is the number of micro-batches.
    • Sequence/context parallelism (SP/CP): Splitting along the sequence dimension specifically addresses activation memory in long-context scenarios, usually combined with ring communication following the Ring Attention idea.

    High-frequency follow-ups include: how to design a 3D parallel partitioning scheme for a 70B-class model on a cluster with thousands of GPUs, what communication primitives each parallel dimension uses (All-Reduce / All-Gather / Reduce-Scatter / P2P), and how to overlap communication and computation.

    4.2 Memory Accounting

    Interviewers often ask candidates to estimate training memory. The classic accounting under mixed-precision training is roughly 16–20 bytes per parameter: 2 bytes for parameters, 2 bytes for gradients, 8 bytes for optimizer states, and a master weight copy. Activation memory is additional. Activation memory is quadratically related to sequence length in the attention part, so long-context training must be combined with gradient checkpointing, selective recomputation, and sequence parallelism. Being able to calculate this by hand is a key dividing line between memorized answers and real experience.

    5. Inference Topics: The Three-Way Trade-Off Among Throughput, Latency, and Memory

    5.1 KV Cache and the PagedAttention Idea

    During autoregressive decoding, every step must read all historical KV, making it a typical memory-bound workload. Core topics include:

    • KV cache memory estimation: Quickly estimate per-request memory using the number of GQA groups, number of layers, sequence length, and precision bit width.
    • Paged memory management: Borrowing from operating system virtual memory, KV cache is divided into fixed-size blocks allocated on demand. This eliminates internal and external fragmentation and raises memory utilization from below 40% to near full capacity, supporting larger batch sizes.

    5.2 Continuous Batching and Scheduling

    Static batching causes significant wasted computation because sequence lengths are uneven. Continuous batching dynamically inserts new requests and removes completed requests at the token level, which is key to high throughput in inference engines. Further topics include the computational differences between prefill and decode: prefill is compute-bound, while decode is memory-bound. Other topics include PD-separated deployment and how chunked prefill avoids long requests blocking decoding.

    5.3 Quantization and Speculative Decoding

    • Quantization: Weight-only quantization, such as 4-bit, mainly saves memory bandwidth and accelerates decoding. Weight-activation joint quantization, such as 8-bit, can use low-precision matrix multiplication units to accelerate computation. You need to understand sources of quantization error and calibration methods, including per-channel scaling and smoothing outlier activation channels.
    • Speculative decoding: A small model drafts multiple tokens, and the large model verifies them in parallel in one pass. This turns serial decoding into parallel verification and achieves several times speedup without changing the output distribution. Interviews often ask about the relationship between acceptance rate and speedup.

    6. Engineering Skills and Open-Ended Questions

    6.1 Stability and Failure Handling

    In large-scale training, hardware failures are the norm rather than the exception. High-frequency questions include: how to design checkpoint saving and fast recovery strategies, how to locate loss spikes and automatically roll back, how to detect and remove stragglers, and how asynchronous checkpointing reduces training pauses.

    6.2 Performance Analysis and Optimization Methodology

    Strong candidates should be able to explain a closed-loop performance analysis process. First, use instrumentation and profiling to distinguish whether the workload is compute-bound or communication/memory-bound. Then apply targeted optimizations such as operator fusion, communication-computation overlap, memory reuse, and kernel-level optimization. Finally, validate with MFU (Model FLOPs Utilization) as an end-to-end metric. Mature industry clusters typically achieve MFU in the 35%–55% range. Being able to explain where the remaining compute goes—communication, bubbles, recomputation, and data loading—is a significant plus.

    6.3 Cloud Deployment Perspective

    In enterprise deployment scenarios, AI infrastructure is often built on general-purpose cloud infrastructure: container platforms for elastic scheduling, object storage for model weights and training data, message queues to decouple data pipelines, and logging, monitoring, and alerting to ensure observability of training jobs. For example, general-purpose cloud products from mainstream cloud providers can be used to quickly build a full-chain platform from data management and distributed training to inference serving. This is also a practical framework for answering system design questions in interviews.

    7. Conclusion

    The essence of AI infrastructure interviews is to test whether candidates can move fluidly across three layers: algorithm principles, system implementation, and engineering trade-offs. A useful approach is to build a knowledge tree along the main line of attention mechanism evolution → long-context techniques → distributed training → inference optimization → stability and performance engineering. For each topic, prepare three levels: one sentence to explain the motivation, one paragraph to explain the principle, and one piece of code or one calculation to prove that you have actually done the work. With these three levels in place, you can handle follow-up questions calmly regardless of how the interviewer probes.