All topics

LLMs and GenAI interview questions

220 questions with answers. 3,453 open jobs in India ask for LLMs and GenAI.

  1. CNNs and RNNs don’t use positional embeddings. Why do transformers use positional embeddings?

    CNNs and RNNs don’t use positional embeddings because these models inherently capture positional information through convolutional filters or recurrence over time steps. However, the Transformer model uses the self-attention mechanism, which processes all tokens in parallel without any notion of sequence or order.

    Positional embeddings inject explicit information about each token’s position in the sequence, allowing transformers to understand word order and relative distances between tokens. This helps them model sequential dependencies and sentence structure effectively, compensating for the parallel and order-agnostic nature of self-attention mechanisms.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  2. Tell me the basic steps involved in running an inference query on an LLM.

    Running an inference query on an LLM involves the following steps:

    • Tokenization: The input text is first broken down into tokens, and then the tokens are mapped to their IDs in the model’s vocabulary.

    • Prefill Phase: The embedding layer converts these token IDs into embeddings, and then the decoder layers process these embeddings simultaneously to compute intermediate states (keys and values). This parallel processing establishes the context for generating new tokens.

    • Decoding Phase: The model generates output tokens one at a time autoregressively, each based on previously generated tokens and cached states, continuing until a stopping condition is met.

    • Detokenization: Finally, the generated tokens are converted back into human-readable text.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  3. Explain how KV Cache accelerates LLM inference.

    KV Cache speeds up LLM inference by storing the attention key (K) and value (V) representations that were computed for previous tokens. This allows the model to reuse them instead of recalculating them at each decoding step. During text generation, only the query for the latest token is computed and then combined with the cached K and V vectors to produce the next token, significantly reducing redundant computation.

    This dramatically speeds up inference—often delivering several-fold faster token generation. However, the cache consumes substantial GPU memory, which is why techniques like KV cache offloading and compression are used to balance speed and memory efficiency in large-scale LLM serving.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  4. How does quantization affect inference speed and memory requirements?

    Quantization reduces the numerical precision of LLM's parameters, such as converting 32-bit floating-point weights to lower bit widths like 8-bit integers or 4-bit values. This compression dramatically decreases the model's memory footprint, often by 50-75% or more, enabling deployment on smaller devices and allowing more data to fit into cache memory.

    Simultaneously, quantization speeds up inference because lower-precision operations require fewer computational resources and can be processed faster by modern hardware optimized for such formats.

    However, this efficiency gain may come at a small cost to model accuracy, necessitating calibration or quantization-aware training to minimize performance degradation. Overall, quantization is a vital technique for reducing memory usage and improving inference speed in practical LLM applications.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  5. How do you handle the large memory requirements of KV cache in LLM inference?

    Handling large KV Cache memory requirements in LLM inference is crucial for high-throughput serving and long context windows, as the cache size grows linearly with sequence length and batch size. We can handle large memory requirements of KV Cache in LLM inference using techniques like PagedAttention, Grouped-Query, Multi-Query Attention, Quantization, or Cache Offloading.

    PagedAttention manages the cache using fixed-size blocks like an operating system's virtual memory, reduces memory fragmentation, and enables higher batch sizes. Grouped-Query Attention (GQA) or Multi-Query Attention (MQA) decreases the size of the KV cache by reducing the number of Key/Value heads.

    Finally, strategies such as quantizing the KV cache (e.g., to INT8) or offloading inactive cache data to cheaper storage (like CPU RAM) also help manage the memory footprint effectively.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  6. After tokenization, how are tokens converted into embeddings in the Transformer model?

    Tokens, represented as integer IDs after tokenization, are converted into embeddings using a lookup table called an embedding matrix. For every token in the model's vocabulary, this matrix has a dense, fixed-size vector (the embedding).

    Specifically, the token ID is used as an index to retrieve its corresponding high-dimensional vector from the embedding matrix. This retrieved vector is the numerical representation that captures the token's semantic and syntactic meaning. The embeddings of input tokens are then processed by the subsequent transformer layers.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  7. Explain why subword tokenization is preferred over word-level tokenization in the Transformer model.

    Subword tokenization, such as Byte-Pair Encoding (BPE) in the Transformer model, offers several advantages over word-level tokenization by handling out-of-vocabulary words and balancing vocabulary size. It effectively handles out-of-vocabulary (OOV) words (unseen words, i.e., words not in the model vocabulary) by breaking them into known subwords, significantly improving coverage of rare or unseen words.

    This method also results in a smaller, manageable vocabulary size compared to the vast lexicon of word-level tokenization, while still providing the semantic benefits of word-level units. Finally, it helps the model learn about morphology (prefixes, suffixes) by segmenting words into meaningful parts.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  8. Explain the trade-offs in using a large vocabulary in LLMs.

    Using a large vocabulary in LLMs allows the model to represent words more precisely and reduce token fragmentation, improving understanding of rare or domain-specific terms. However, it increases the size of the embedding and output layers, leading to higher memory usage and slower training.

    Larger vocabularies also make softmax computations more expensive and may lead to a sparser representation of less frequent tokens, potentially hindering effective learning for those words. Therefore, models often moderate vocabulary sizes to ensure a balance between linguistic coverage and computational efficiency.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  9. Explain how self-attention is computed in the Transformer model step by step.

    Self-attention in the Transformer model is computed by first projecting each input token into three vectors: queries, keys, and values using learned weight matrices. Then, attention scores are calculated by taking the dot product of a query with all keys, scaled by the square root of the key dimension to stabilize gradients.

    These scores are normalized using the softmax function to obtain attention weights, representing the importance of each token relative to others. Finally, each token's output is computed as the weighted sum of the value vectors, allowing the model to capture contextual relationships within the input sequence.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  10. What is the computational complexity of self-attention in the Transformer model?

    The computational complexity of the self-attention mechanism in the Transformer model is primarily quadratic with respect to the sequence length $n$. Formally, it is O($n^2$.d). The O($n^2$.d) comes from computing the attention scores between all pairs of tokens. Since there are $n$ x $n$ = $n^2$ pairwise interactions, and each involves a dot product of d dimensional vectors, this results in $n^2$.d operations.

    The quadratic complexity with respect to sequence length $n$ makes self-attention computationally expensive for long sequences. However, this design allows the model to capture relationships between all tokens simultaneously, which is crucial for its performance. Despite its quadratic complexity, it remains faster than traditional RNNs in practice due to parallelization benefits.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  11. How do Transformer model address the vanishing gradient problem?

    Transformers address the vanishing gradient problem primarily through the use of residual (skip) connections and layer normalization. Residual connections allow gradients to flow directly through the network by adding the input of a layer to its output, preventing gradients from shrinking during backpropagation.

    Layer normalization helps stabilize training by keeping activations within a consistent range, which controls the scale of gradients. Additionally, the self-attention mechanism enables direct information flow between tokens, reducing the depth of dependency and further mitigating gradient vanishing.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  12. What is tokenization, and why is it necessary in LLMs?

    Tokenization is the process of converting raw text into smaller, discrete units called tokens, which can be words, sub-words, or characters. This step is necessary in LLMs because models cannot directly process raw strings of text; they require numerical input.

    Tokenization allows mapping the input text to a vocabulary of known tokens. These tokens are then converted into numerical representations called embeddings. These embeddings are then used by LLMs for training and inference, fundamentally enabling input text processing.

    ☕ Support the Author

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  13. Explain the role of token embeddings in the Transformer model.

    Token embeddings in the Transformer model encode syntactic and semantic information. These embeddings are obtained from an embedding matrix, where each token’s index maps to a fixed-size vector. These token embeddings are combined with positional embeddings to help the model retain word order. These enriched representations are then passed into the subsequent Transformer model layers, enabling context-aware understanding and text generation.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  14. Explain the working of the embedding layer in the transformer model.

    The main purpose of the embedding layer in the transformer model is to convert input token IDs into dense, continuous vectors called embeddings. Each token is first represented as a one-hot vector and then multiplied with an embedding matrix to produce the token embedding.

    These token embeddings are then combined with positional embeddings to retain information about token order within the sequence. To summarize, the embedding layer transform the sequence of tokens represented as integer IDs into the sequence of embeddings. These embeddings are then processed by the subsequent layers to inject contextual information.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  15. What is the role of self-attention in the Transformer model, and why is it called “self-attention”?

    The self-attention mechanism enables the model to compute context-rich representation for each token by allowing the tokens to attend to all tokens in the input sequence. These context-rich representations capture long-range dependencies and relationships.

    The mechanism is called “self-attention” because the attention is computed within the same sequence - each token attends to itself and others without external input. This process helps build rich contextual embeddings crucial for understanding meaning and structure in text.

    👨🏻‍💻 LLM Engineer Toolkit

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  16. What is the purpose of the encoder in a transformer model?

    The purpose of the encoder in a transformer model is to process the entire input sequence and generate context-aware numerical representations. The encoder uses multi-head self-attention and feed-forward neural networks to capture the relationships and dependencies between all the tokens to generate context-rich token representations. These context-rich token representations are then passed to the decoder, which generates the output sequence.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  17. What is the purpose of the decoder in a transformer model?

    The purpose of the decoder in a transformer model is to generate the output sequence based on the contextual representations provided by the encoder and the previously generated tokens.

    The decoder layers use (i) masked self-attention to ensure that predictions for the current step rely solely on previously generated outputs and (ii) encoder-decoder attention to focus on the most relevant parts of the encoder's final output when generating each output token.

    In simple words, the decoder transforms the encoder’s output (contextual representations) into the desired output token by token.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  18. How does the encoder-decoder structure work at a high level in the Transformer model?

    The encoder-decoder structure in a Transformer is used for sequence-to-sequence tasks like machine translation. At a high level, the encoder processes the entire input sequence simultaneously, using self-attention to create rich, context-aware vector representations (the encoded state).

    The decoder then uses a separate self-attention mechanism, masked to prevent looking ahead, to generate the output sequence one token at a time, autoregressively. The decoder also incorporates an encoder-decoder attention layer, allowing it to focus on the most relevant parts of the encoder's output for each token it generates.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  19. What is the purpose of scaling in the self-attention mechanism in the Transformer model?

    The purpose of scaling in the self-attention mechanism of a Transformer model is to stabilize training by controlling the magnitude of the dot-product values between query and key vectors. Without scaling, the dot products can grow large in high-dimensional spaces, resulting in extremely small gradients that slow down or destabilize learning.

    To prevent this, the dot products are divided by the square root of the key dimension, which keeps the attention scores in a range that leads to more effective gradient flow and stable optimization. Thus, the scaling step ensures that the self-attention mechanism can effectively focus on relevant tokens of the input sequence without numerical issues during training.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  20. Why does the Transformer model use multiple self-attention heads instead of a single self-attention head?

    Transformer models use multiple self-attention heads instead of a single one because they enable the model to capture diverse relationships and patterns in the input. This is similar to using multiple flashlights to illuminate different aspects of a scene.

    Using a single head would restrict the model to one form of relationship, limiting its capacity to fully understand the input data. Multi-head attention, by allowing the model to capture diverse relationships, results in richer contextual representations and subsequently better performance across NLP tasks.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  21. How are the outputs of multiple heads combined and projected back in the multi-head attention in the Transformer model?

    In the multi-head attention model of the Transformer, the outputs from multiple self-attention heads are first computed independently, each producing a contextually weighted representation of the input in different subspaces. These outputs are then concatenated along the feature dimension to form a single combined vector.

    This concatenated result is passed through a final linear projection layer, which projects it back into the model’s expected dimension for further processing. This mechanism allows the model to integrate diverse information captured by each head into a unified representation.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  22. How does masked self-attention differ from regular self-attention, and where is it used in a Transformer?

    Masked self-attention differs from regular self-attention by restricting the attention mechanism so that each position in the sequence can only attend to earlier positions and itself, preventing access to future tokens. This is essential for autoregressive tasks like text generation, where tokens are generated sequentially one by one.

    Regular self-attention allows every token to attend to all tokens in the sequence, which is useful in encoder layers for understanding context bidirectionally. Masked self-attention is specifically used in the decoder layers of the Transformer model to ensure that the model predicts tokens one at a time without peeking ahead.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  23. Discuss the pros and cons of the self-attention mechanism in the Transformer model.

    Self-attention enables the Transformer model to capture long-range dependencies (contextual relationships) between tokens in the input sequence efficiently. It allows for parallel computation, improving training speed compared to recurrent models.

    However, its quadratic time complexity with respect to sequence length and large memory footprint make it computationally expensive for long inputs.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  24. What is the purpose of masked self-attention in the Transformer decoder?

    During output generation, masked self-attention in the decoder prevents the model from looking ahead by blocking access to future tokens during generation. This means that when predicting a token, the model is restricted to attending only to the tokens that come before it in the sequence.

    This ensures (i) auto-regressive behavior, allowing the model to generate text one token at a time, and (ii) the model learns to make predictions based solely on past context, maintaining the integrity and correctness of language modeling.

    ☕ Support the Author

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  25. Explain how masking works in masked self-attention in Transformer.

    Masking in masked self-attention (used in the Transformer's decoder) prevents the model from attending to future tokens in the sequence. It's achieved by setting the attention scores for those future positions to a very large negative number (like −∞), so that the softmax function turns them into zero. This ensures that the prediction for the current token only relies on the known preceding tokens, preserving the auto-regressive property.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  26. Explain why self-attention in the decoder is referred to as cross-attention. How does it differ from self-attention in the encoder?

    Self-attention in the decoder is referred to as cross-attention because it involves attending to the encoder's output while generating each token in the decoder. Specifically, in cross-attention, the queries come from the decoder's previous layer, while the keys and values come from the encoder's output, allowing the decoder to focus on relevant parts of the input sequence.

    This differs from self-attention in the encoder, where the attention mechanism operates solely within the input sequence itself, with queries, keys, and values all derived from the same data. Thus, the encoder’s self-attention captures internal dependencies, while the decoder’s cross-attention links the decoder to the encoder representations for contextual generation.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  27. What is the softmax function, and where is it applied in the Transformer model?

    The softmax function is a mathematical operation that converts a vector of raw scores (logits) into a probability distribution, where each value lies between 0 and 1, and all values sum to 1. In the Transformer model, softmax is applied in the output layer during token prediction to transform the model's raw score outputs into probabilities over the vocabulary, enabling the selection of the most likely next token.

    Additionally, softmax is used within the self-attention mechanism to normalize the attention weights. This normalization allows the model to weigh the importance of different input tokens effectively. Thus, softmax plays a crucial role in handling probabilities both in self-attention and final predictions.​

    👨🏻‍💻 LLM Engineer Toolkit

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  28. What is the purpose of residual (skip) connections in Transformer model layers?

    The main purpose of residual (skip) connections in Transformer layers is to allow the gradients to flow directly through the network during backpropagation. This helps to mitigate the vanishing gradient problem in deep networks, ensuring effective training.

    Specifically, they enable the output of a layer to be Layer Input + Layer Output rather than just the Layer Output. This means the layer learns an additive change rather than a new representation entirely. This facilitates training very deep architectures, leading to better overall performance.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  29. Why is layer normalization used, and where is it applied in Transformer?

    Layer normalization is used in Transformer to stabilize and accelerate training by normalizing the inputs across features within each layer, ensuring that activations have a mean of zero and variance of one. This normalization helps control the scale of gradients during backpropagation, preventing issues like exploding or vanishing gradients.

    In Transformer architectures, layer normalization is applied before the self-attention and feedforward sublayers (Pre-LN) or after these sublayers within the residual connections (Post-LN). The Pre-LN variant improves gradient stability and allows faster training without requiring learning rate warm-up, while Post-LN was used in the original Transformer but can lead to unstable gradients if not carefully managed.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

  30. What is cross-entropy loss, and how is it applied during transformer training?

    Cross-entropy loss measures the difference between the predicted probability distribution of a model and the true distribution of target labels. In Transformer training, it quantifies how well the model predicts the next token by comparing its output logits (after softmax) with the actual token index.

    The loss penalizes incorrect predictions with higher values, encouraging the model to assign greater probability to the correct token. Minimizing the cross-entropy loss through backpropagation helps optimize the model’s parameters for accurate sequence generation.

    From LLM Interview Questions and Answers Hub (Apache 2.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.