HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 25 of 25 — Generative AI Fundamentals
advanced Chapter 25 of 25

Generative AI Interview Questions and Cheat Sheet

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

Generative AI Interview Questions: What Is GenAI and How Does It Work?

Generative AI uses models that learn patterns from data and generate outputs such as text, code, images or audio. A text LLM predicts a probability distribution over the next token, selects one token, appends it to the sequence and repeats until it reaches a stopping condition. In an interview, explain what the model learns, how it produces an output and where that process can fail.

1. How do AI, ML, deep learning and GenAI differ?

AI is the broad field of building systems that perform tasks such as planning, perception or decision-making. Machine learning is a branch of AI in which models learn from examples or experience. Deep learning is a branch of ML that uses multilayer neural networks. Generative AI describes a capability. Most modern GenAI systems use deep learning, but probabilistic models such as hidden Markov models can also generate sequences.

Data format is a poor way to distinguish these terms. A rule-based helpdesk bot can work without training examples. A conventional ML classifier can use features extracted from text. A deep CNN can classify images without generating any, and the same Transformer building blocks can support either classification or generation. Ask what the system learns and what output the task requires.

2. What is the difference between generative and discriminative models?

A generative model can model p(x), a joint distribution p(x, y), or a conditional distribution over structured outputs, such as p(image | caption). A discriminative classifier can estimate p(y | x), as logistic regression does, or learn a decision boundary without calibrated probabilities, as a standard SVM does. The presence of a conditional probability does not settle the distinction: what matters is whether the model learns to generate structured samples or predict a target such as a class label. A joint generative model can also classify by comparing posterior probabilities across labels.

LLM Interview Questions on Transformers and Self-Attention

3. What is an LLM, and what happens inside a Transformer?

An LLM is a language model trained at scale. There is no universal parameter threshold for the term. GPT and Llama are model families, and modern LLMs commonly use the Transformer architecture. For a causal LLM, pretraining typically minimises -sum_t log p(x_t | x_1, ..., x_(t-1)). The targets come from shifting the original token sequence by one position, so this objective does not require human-provided labels for each token.

A two-token causal attention diagram shows query, key and value projections, a masked score matrix and weighted output rows.
The causal mask blocks future positions before softmax converts each score row into weights.

The model looks up token embeddings and uses position information, which may be added to those embeddings or applied to queries and keys, depending on the design. Attention layers mix information across positions, while feed-forward layers transform each position separately. Residual connections and normalisation help train stacked blocks. In a decoder-only LLM, an output projection maps the final hidden state at each position to vocabulary logits. An encoder-only model such as BERT can attend bidirectionally and use its representations for classification. An encoder-decoder model adds cross-attention so its decoder can use the encoder's output.

During causal training, known sequence positions can be processed in parallel with a mask. During ordinary autoregressive decoding, each new token depends on earlier generated tokens, so generation proceeds sequentially. A KV cache saves earlier key and value projections to avoid recomputing them at every step, trading memory for speed. For a sequence of length n, dense self-attention still computes on the order of n² pairwise scores during prompt processing.

4. How does self-attention work? A worked numerical example

In scaled dot-product attention, each query compares itself with the keys at allowed positions. Softmax normalises the scores across keys for each query, and the resulting weights mix the values. The formula is softmax(QK^T / sqrt(d_k) + M)V, where d_k is the key dimension and M is an additive mask. The scale keeps dot products from typically growing with dimension and pushing softmax towards saturation. Multi-head attention repeats the operation with different learned projections, concatenates the head outputs and applies an output projection.

Take two keys [1, 0] and [0, 1], with values [2, 0] and [0, 4]. The second token's query is [sqrt(2), 0]. Its raw scores are [sqrt(2), 0], its scaled scores are [1, 0], and softmax gives approximately [0.7311, 0.2689]. The weighted value is [1.4621, 1.0758]. Under a causal mask, the first token cannot see the second, so its output is exactly the first value.

import math
import torch

q = torch.tensor([[math.sqrt(2), 0.0],
                  [math.sqrt(2), 0.0]])
k = torch.eye(2)
v = torch.tensor([[2.0, 0.0], [0.0, 4.0]])

scores = (q @ k.T) / math.sqrt(k.shape[-1])
future = torch.ones_like(scores, dtype=torch.bool).triu(diagonal=1)
weights = scores.masked_fill(future, float("-inf")).softmax(dim=-1)
print(weights @ v)
# tensor([[2.0000, 0.0000],
#         [1.4621, 1.0758]])

What Are Tokens, Embeddings, Prompts and Sampling Parameters?

5. How do token IDs differ from embeddings?

Tokenization maps text to model-specific units, often subwords or byte sequences, and then to integer IDs. The numerical difference between two IDs says nothing about similarity. For an embedding matrix E of shape [vocabulary_size, hidden_size], token ID i selects row E[i]. The initial row is shared across occurrences of that token, but its hidden state after Transformer layers depends on context. The same piece of text can produce different IDs under different tokenizers, so check the deployed model before estimating sequence length or cost.

A retrieval embedding serves another purpose. An embedding model maps a query or chunk to a fixed-length vector so a search system can rank candidates. A retrieval pipeline normally uses one compatible query and document encoding setup. Averaging arbitrary token vectors from a generation model can produce a vector of the right shape while still giving poor search results.

6. What makes a prompt production-ready?

State the task, allowed evidence, output schema and what to do when information is missing. Zero-shot prompting supplies no examples; one-shot uses one; few-shot uses several to demonstrate the expected pattern. Role instructions can set tone and scope but cannot grant real permissions or enforce access controls. For multi-step tasks, ask for checkable intermediate results, such as subtotals or evidence IDs. A fluent explanation does not prove the answer is correct. Validate fields and allowed values in application code, even when the provider supports structured output.

7. How do temperature, top-k and top-p affect decoding?

For positive temperature T, sampling uses softmax(logits / T) before any subsequent truncation. Lower T sharpens the distribution and higher T flattens it. APIs that accept zero usually treat it as a special decoding mode, since division by zero is undefined. Top-k keeps the k highest-scoring candidates. Top-p keeps the smallest ranked prefix whose cumulative probability reaches p. The retained probabilities are renormalised before sampling. Check the serving implementation for supported parameters and operation order.

Given probabilities [0.55, 0.25, 0.12, 0.08], top-k of 2 keeps the first two and rescales them to [0.6875, 0.3125]. Top-p of 0.9 keeps three because the first two sum to 0.80 and the first three sum to 0.92. Lower variability can help with repeatable tests, but it does not make an unsupported answer factual.

RAG vs Fine-Tuning Interview Questions: Retrieval, Vector Search and LoRA

8. How does RAG work, and how do you debug retrieval?

Retrieval-augmented generation, or RAG, supplies evidence at inference time. During indexing, split documents into chunks and store their embeddings with metadata such as source ID, revision and access scope. At query time, search the authorised corpus, rerank candidates if needed and assemble the most useful chunks within the context budget. Ask the generator for claims supported by those chunks, with citations or an explicit statement that evidence is missing.

A RAG pipeline separates document indexing from query-time retrieval and shows how retrieved chunks enter the generation prompt.
Retrieved chunks become prompt evidence, while citation IDs point back to their source documents.

Debug retrieval before rewriting the generation prompt. For labelled queries with known supporting chunks, measure how much of the relevant evidence appears in the top k with recall@k. If recall is low, inspect chunk boundaries, filters, embedding quality and indexing freshness. Exact terms such as policy IDs can benefit from keyword search combined with dense retrieval. If the evidence is retrieved but the answer is wrong, check whether prompt assembly dropped the passage, whether sources conflict and whether each citation actually supports its claim.

9. What does a vector database do?

Cosine similarity is (q · d) / (||q|| ||d||). Once both nonzero vectors have unit norm, ranking by inner product gives the same order as ranking by cosine similarity. Exact search scans the candidate vectors. Approximate indexes such as HNSW or IVF trade retrieval recall for latency and use different memory and build-time budgets. Use an exact-search baseline before tuning an approximate index. FAISS is a similarity search library. Systems such as Milvus and Weaviate also manage stored records and metadata queries, so the choice includes operational needs beyond search speed.

10. When should you fine-tune, and how does LoRA work?

Use RAG for current or access-controlled facts, such as a company's travel policy. Consider fine-tuning when evaluated prompts leave a repeatable behaviour gap, such as mapping support tickets to a fixed taxonomy. Supervised fine-tuning uses example outputs; continued pretraining can use unlabelled domain text. You can combine the approaches: retrieve the current policy and use an adapted model to produce a consistent review format.

PEFT means parameter-efficient fine-tuning. A common LoRA formulation freezes a weight matrix W and trains an update (alpha / r)BA, where A is r × d_in and B is d_out × r. For a 4096 × 4096 projection and rank 8, the two factors contain 65,536 trainable parameters instead of 16,777,216 in that full weight matrix. The base weights still exist, and training still requires activations and backpropagation. Compare held-out task performance and regressions with the prompt-only baseline before adopting the adapter.

How Do You Reduce LLM Hallucinations and Evaluate Answers?

11. Why do hallucinations happen, and what should you measure?

A hallucination is a false or unsupported claim presented as if it were established. Examples include a fabricated reference, an invented reimbursement limit and a real citation attached to an unrelated claim. Next-token prediction rewards fitting language patterns; it does not check an external source of truth. Missing evidence, ambiguous questions and conflicting documents can all produce plausible errors. Separate those cases before choosing a fix.

Evaluate answers on distinct axes: correctness against a reference, grounding in the supplied evidence, citation validity and appropriate abstention. An answer can quote a stale policy faithfully and still be wrong for the requested date. Build a test set with answerable questions, questions with no supporting passage and questions about superseded policies. Track incorrect answers and unnecessary abstentions separately. For high-impact outputs, use deterministic checks for values such as dates or totals and route unresolved cases to a reviewer.

Other practical LLM limits include finite context, variable instruction following and latency that grows with long inputs or outputs. Adding more context can help if evidence was missing, but it also consumes budget and can introduce conflicts. Compare the same test cases before and after a change, and report results by failure type so an improvement on simple questions does not hide regressions on important ones.

How Do AI Agents and Multimodal Systems Work in Production?

12. What separates an agent from a fixed workflow?

A fixed workflow follows predefined steps. An agent can choose its next step based on a goal, current state and tool results. For example, a support agent might look up an order, notice that delivery status is missing and request a second lookup. In tool calling, the model proposes a structured call; the application validates arguments, checks permissions, runs the operation and returns the result. State can include conversation history and selected task records. Set step and time budgets, log actions and require approval for consequential writes. If a lookup and a template solve the task, start with that simpler workflow.

13. How does a multimodal model handle images or audio?

Multimodal systems process or generate more than one modality. A vision-language model may encode image patches as feature vectors and project them into representations the language decoder can attend to. An image generator can condition a denoising network on a text representation. Input and output capabilities differ by model: Whisper transcribes audio to text, while Stable Diffusion models can use text to generate images. Evaluate by modality. For scanned documents, measure transcription and field extraction errors separately from downstream answer errors.

14. How would you design a GenAI application end to end?

For an internal travel-policy assistant, define the contract first: answer for the employee's region and travel date, cite the governing clause, and abstain when the policy is unavailable. Version the corpus, enforce document permissions during retrieval and start with a read-only RAG pipeline. Validate returned citation IDs against retrieved passages. Add human checks for citation support and test whether any retrieved text can override application instructions. Record model and index versions, retrieval results, latency and token use without storing sensitive content unnecessarily. Compare against a keyword-search baseline, test with real question patterns, and keep a fallback to direct policy search.

Generative AI Interview Cheat Sheet

TopicMechanism to recallDistinction to state
Transformer and attentionMask, softmax across keys, weighted valuesParallel processing of known tokens differs from sequential generation.
LLM and tokenizationToken IDs select embedding rows; logits score the vocabularyRetrieval embeddings are trained or selected for similarity search.
DecodingTemperature rescales logits; top-k and top-p truncate candidatesSampling controls variability, not factual accuracy.
RAG and vector searchIndex, retrieve, rerank and pass evidenceRelevant retrieval and faithful generation require separate tests.
LoRATrain a low-rank update while freezing selected base weightsFewer trainable parameters do not eliminate base model costs.
Agents and multimodal AITool selection from state; encoding and generation by modalityTool authority belongs to the application; supported modalities depend on the model.

Key Takeaways

  • Classify GenAI by what it models and produces, rather than by architecture alone.
  • Trace an LLM answer from token IDs through attention, vocabulary logits and decoding.
  • Choose RAG for changing evidence and fine-tuning for measured behaviour gaps.
  • Measure retrieval recall, citation support and task correctness separately.
  • Treat tool calls as proposed actions that application code must authorise.
  • Answer design questions with a baseline, a measurable failure mode and a fallback.

Frequently Asked Questions

How should I structure an advanced GenAI interview answer?

Start with a one-sentence definition, then describe the data flow or objective. Give a concrete example with one design constraint, such as a dated policy or a latency budget. End with a failure mode and a measurement. This structure helps the interviewer distinguish what you have memorised from what you can diagnose.

Can RAG work without a vector database?

Yes. RAG needs a way to retrieve relevant evidence. For a small corpus, exact vector search in memory may be sufficient. For policy IDs or product codes, keyword search or a structured database query may work better. Select a retrieval method by testing evidence recall, access controls, update behaviour and query latency.

Does temperature zero make an LLM deterministic?

Many APIs use temperature zero to request greedy decoding, which selects the highest-scoring token at each step. Exact repeatability can still depend on tied scores, numerical differences, provider updates and the wider application pipeline. For regression tests, pin versions where possible, record configuration and test required properties as well as exact text.

What is the difference between a context window and model memory?

The context window limits the token sequence a model can process in a request, subject to the provider's input and output rules. Application memory stores information outside the model and can retrieve selected records for a later request. A KV cache speeds up inference within a sequence. Neither mechanism updates the model's trained weights.

Is fine-tuning a good way to teach a model current facts?

Fine-tuning can change factual associations, but those changes are difficult to audit, update individually or cite reliably. For facts that change or depend on access permissions, retrieve authoritative records at request time. Consider tuning separately if an evaluation shows repeated failures in formatting, classification or applying a stable procedure.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course