Skip to main content
AI & Data Science

Artificial Intelligence (AI) Interview Questions

All Levels (Junior to Staff)16 Questions

Artificial Intelligence architecture interview guide covering transformer attention, RLHF, tokenization, context caching, and inference scaling.

25 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Artificial Intelligence (AI) Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do subword tokenizers (BPE, WordPiece) work, and why do tokenization quirks cause LLM failures on numbers, whitespace, and non-English text?

Senior Engineering Answer

Subword tokenizers iteratively merge the most frequent adjacent byte or character pairs into a fixed vocabulary (typically 32k–128k tokens), balancing sequence length against out-of-vocabulary resilience. Because numbers are split arbitrarily based on corpus frequency (e.g., 2026 vs 202 vs 6) and leading spaces attach to words (' hello' != 'hello'), LLMs struggle with character-level tasks (counting letters, reversing strings), arithmetic alignment, and non-Latin languages where a single word consumes 3–5x more tokens—increasing latency and eating into the context window.

Production Code Example
import tiktoken

enc = tiktoken.get_encoding("cl100k_base")
print(enc.encode("Strawberry"))  # [26395, 1689, 2678]
print(enc.encode("123456789"))   # [4513, 10961, 20022]
Common Interview Trap / Anti-Pattern:

Assuming 1 word equals 1 token or forgetting that JSON keys, indentation whitespace, and non-English scripts inflate token costs dramatically.

Question #2FundamentalJunior

What do temperature, top-p (nucleus sampling), and top-k actually do to next-token logits during LLM decoding?

Senior Engineering Answer

Before softmax, the model produces raw logits z_i across the vocabulary. Dividing logits by temperature T (softmax(z_i / T)) sharpens the distribution when T < 1 (deterministic/focused) and flattens it when T > 1 (creative/noisy); T = 0 corresponds to greedy argmax decoding. Top-k truncates sampling to the k highest-probability tokens, while top-p (nucleus sampling) dynamically selects the smallest set of top tokens whose cumulative probability exceeds p—adapting to high-uncertainty vs peaked distributions.

Production Code Example
import torch

def sample_next_token(logits, temperature=0.7, top_p=0.9):
    probs = torch.softmax(logits / temperature, dim=-1)
    sorted_probs, sorted_idx = torch.sort(probs, descending=True)
    cum_probs = torch.cumsum(sorted_probs, dim=-1)
    sorted_probs[cum_probs - sorted_probs > top_p] = 0.0
    sorted_probs /= sorted_probs.sum()
    return sorted_idx[torch.multinomial(sorted_probs, 1)]
Common Interview Trap / Anti-Pattern:

Temperature = 0 is often still non-deterministic across GPU batches due to floating-point reduction order and MoE routing ties.

Question #3FundamentalJunior

Walk through a standard Retrieval-Augmented Generation (RAG) pipeline and explain how embedding similarity, chunking, and metadata filtering work together.

Senior Engineering Answer

At ingestion time, documents are parsed, split into semantically coherent chunks (typically 256–800 tokens with 10–15% overlap or hierarchical parent-child links), embedded into dense vectors, and stored alongside structured metadata (tenant_id, doc_date, permissions) in a vector index. At query time, the query is embedded with the same model, metadata pre-filters enforce ACLs and recency, top-K chunks are retrieved via cosine similarity or dot product, and the grounded passages are injected into the prompt with citation instructions.

Production Code Example
results = vector_index.query(
    vector=embed_query(user_query),
    top_k=8,
    filter={"tenant_id": user.tenant_id, "status": "published"},
    include_metadata=True,
)
Common Interview Trap / Anti-Pattern:

Embedding the document and query with mismatched embedding models—or forgetting tenant/ACL metadata filters before retrieval—causes irrelevant results or severe cross-tenant data leaks.

Question #4FundamentalJunior

What is the role of Query (Q), Key (K), and Value (V) projections in Scaled Dot-Product Self-Attention, and why do we divide by sqrt(d_k)?

Senior Engineering Answer

Each token embedding is linearly projected into Query (what it is looking for), Key (what it advertises), and Value (the information it passes along). Attention computes pairwise compatibility scores via QK^T, applies causal masking (for decoders), normalizes with softmax, and outputs a weighted sum of V. Without dividing by sqrt(d_k), dot products grow proportionally with dimension d_k in variance, pushing softmax inputs into flat saturation regions where gradients vanish toward zero.

Production Code Example
import math, torch

def scaled_dot_product_attention(Q, K, V, mask=None):
    d_k = Q.size(-1)
    scores = (Q @ K.transpose(-2, -1)) / math.sqrt(d_k)
    if mask is not None:
        scores = scores.masked_fill(mask == 0, float("-inf"))
    weights = torch.softmax(scores, dim=-1)
    return weights @ V
Common Interview Trap / Anti-Pattern:

Confusing encoder bidirectional self-attention with decoder causal self-attention where future tokens must be masked to -inf prior to softmax.

Question #5IntermediateMid-Level

Why does naive dense-only RAG fail on exact product codes, acronyms, and multi-hop queries, and how do Hybrid Search + Cross-Encoder Reranking fix it?

Senior Engineering Answer

Dense bi-encoder embeddings compress an entire passage into one vector, blurring exact lexical tokens like error codes ('ERR_OOM_402'), SKUs, or rare proper nouns. Hybrid search runs sparse lexical retrieval (BM25 / SPLADE) in parallel with dense vector search and merges candidates using Reciprocal Rank Fusion (RRF). Because bi-encoders score query and passage independently without token-level cross-attention, a second-stage Cross-Encoder reranker jointly encodes (query, chunk) pairs over the top ~50 candidates to surface the exact top 5–8 passages.

Production Code Example
def reciprocal_rank_fusion(bm25_ids, dense_ids, k=60):
    scores = {}
    for rank_list in (bm25_ids, dense_ids):
        for rank, doc_id in enumerate(rank_list, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores.items(), key=lambda x: x[1], reverse=True)
Common Interview Trap / Anti-Pattern:

Trying to normalize raw BM25 unbounded scores directly with cosine similarity using fixed linear weights breaks easily across query types; RRF relies purely on rank order.

Question #6IntermediateMid-Level

How do you decide between Prompt Engineering, RAG, and Fine-Tuning (SFT / LoRA) for an enterprise AI product?

Senior Engineering Answer

Always start with prompting + structured outputs to establish a baseline and evaluation dataset. Choose RAG when the gap is external, private, fast-changing, or auditable factual knowledge requiring citations. Choose Fine-Tuning (SFT / LoRA) when the gap is behavioral: enforcing consistent output style/format, domain-specific reasoning patterns, specialized tool-use syntax, or distilling a frontier model down to a smaller, cheaper low-latency model. Note that fine-tuning is a poor mechanism for injecting volatile facts.

Production Code Example
# Typical escalation ladder:
# 1. Baseline: Prompt + few-shot + JSON schema eval
# 2. Knowledge gap -> Hybrid RAG + Reranker
# 3. Behavior/format/latency gap -> LoRA SFT on curated 2k-10k examples
# 4. Preference/safety alignment -> DPO
Common Interview Trap / Anti-Pattern:

Jumping straight into fine-tuning to 'teach the model our company docs'—models still hallucinate fine-tuned facts and cannot easily unlearn stale policies without retraining.

Question #7IntermediateMid-Level

Explain how the KV Cache works during autoregressive LLM decoding, and calculate why long contexts become memory-bandwidth bound.

Senior Engineering Answer

During prefill (processing the prompt), the model computes K and V tensors for all prompt tokens in parallel (compute-bound). During decoding (generating 1 token at a time), recomputing K and V for all previous tokens at every step would cost O(N^2); instead, we cache each layer's K and V tensors in GPU HBM. Memory grows linearly as 2 * num_layers * num_kv_heads * head_dim * seq_len * batch_size * bytes_per_element. Because each generated token only runs matrix-vector ops while streaming gigabytes of weights and KV cache from HBM to SRAM, decoding becomes strictly memory-bandwidth bound.

Production Code Example
# KV cache bytes per token (FP16 = 2 bytes) for Llama-3-8B with GQA (8 KV heads, dim 128, 32 layers):
kv_bytes_per_token = 2 * 32 * 8 * 128 * 2  # 131,072 bytes (~128 KB/token)
# At 32k context & batch=16 -> ~64 GB just for KV cache!
Common Interview Trap / Anti-Pattern:

Confusing prefill (compute-bound, Time-To-First-Token / TTFT) with decode (memory-bandwidth-bound, Time-Per-Output-Token / TPOT) when tuning GPU hardware.

Question #8IntermediateMid-Level

How do LoRA and QLoRA work mathematically, and how do rank (r), alpha, and target modules affect adaptation quality?

Senior Engineering Answer

LoRA freezes pretrained weights W_0 (d x k) and learns a low-rank residual update Delta_W = (alpha / r) * B @ A, where A is (r x k) and B is (d x r) initialized to zero, with r << min(d, k). At inference, B @ A can be merged directly into W_0 with zero added latency. QLoRA quantizes the frozen base weights W_0 to 4-bit NormalFloat (NF4) with double quantization and paged optimizers while keeping LoRA adapters in BF16—enabling 70B fine-tuning on a single 48GB GPU. Target all linear attention and MLP projections (q/k/v/o + gate/up/down), not just q_proj/v_proj.

Production Code Example
from peft import LoraConfig

config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_dropout=0.05,
    task_type="CAUSAL_LM",
)
Common Interview Trap / Anti-Pattern:

Setting a huge rank (e.g., r=256) on a tiny noisy dataset causes rapid overfitting and catastrophic forgetting; r=8 to 32 suffices for most task adaptations.

Question #9AdvancedSenior

How does FlashAttention reduce HBM reads/writes without changing exact attention output, and how do Multi-Query (MQA) and Grouped-Query Attention (GQA) complement it?

Senior Engineering Answer

Standard attention materializes the huge N x N attention matrix S = QK^T and P = softmax(S) in slow GPU HBM, causing O(N^2) memory I/O. FlashAttention tiles Q, K, and V into small blocks that fit inside fast on-chip SRAM and uses online softmax (tracking running max m(x) and normalization factor l(x) across K/V blocks) to fuse matmul, scaling, masking, softmax, and value multiplication in a single kernel—cutting HBM memory from O(N^2) to O(N) with exact numerical output. Meanwhile, GQA shares a single K/V head across a group of query heads (e.g., 8 KV heads for 32 Q heads), slashing KV cache footprint by 4x–8x during inference.

Production Code Example
# Conceptual online softmax rescaling across two blocks:
# m_new = max(m_old, block_max)
# l_new = exp(m_old - m_new) * l_old + sum(exp(scores - m_new))
# out_new = (exp(m_old - m_new) * l_old * out_old + exp(scores - m_new) @ V_block) / l_new
Common Interview Trap / Anti-Pattern:

Describing FlashAttention as an approximate attention method (like sparse or linear attention)—FlashAttention computes mathematically exact attention.

Question #10AdvancedSenior

Compare RLHF (PPO) vs Direct Preference Optimization (DPO) for post-training alignment, and explain how reward hacking manifests.

Senior Engineering Answer

Classic RLHF trains a separate Reward Model (RM) on human preference pairs (y_w > y_l) using a Bradley-Terry loss, then runs online PPO with four models in memory (policy, reference, reward, critic) while penalizing KL divergence from the SFT reference policy. DPO derives a closed-form analytical mapping between reward and optimal policy, optimizing the policy directly on preference pairs via a binary cross-entropy objective with zero separate reward model or RL sampling loop. Reward hacking occurs when the policy exploits flaws in the RM or judge (e.g., verbosity bias, sycophancy, excessive markdown formatting) to score high reward while actual helpfulness drops.

Production Code Example
# DPO implicit reward difference:
# loss = -log_sigmoid(beta * ((log_pi(y_w|x) - log_ref(y_w|x)) - (log_pi(y_l|x) - log_ref(y_l|x))))
Common Interview Trap / Anti-Pattern:

Running DPO directly on a base model without an initial SFT phase on the target domain distribution—or without offline/online data filtering—causes likelihood displacement where both chosen and rejected probabilities drop.

Question #11AdvancedSenior

How do production inference engines (vLLM, TensorRT-LLM, SGLang) achieve 10x+ throughput via Continuous Batching, PagedAttention, and Speculative Decoding?

Senior Engineering Answer

Static batching wastes GPU cycles waiting for the longest sequence in a batch to finish. Continuous (iteration-level) batching swaps completed requests out and inserts new requests at every decode step. PagedAttention eliminates up to 60–80% KV-cache fragmentation by storing KV tensors in fixed-size non-contiguous virtual blocks mapped via a block table, also enabling copy-on-write prefix sharing for shared system prompts. Speculative decoding uses a small draft model (or Medusa/EAGLE heads) to propose gamma=4–5 tokens quickly and verifies all of them in one parallel target-model forward pass using rejection sampling—preserving the exact target distribution while breaking the memory-bandwidth bottleneck.

Production Code Example
# Speculative verification rule (lossless):
# Accept draft token x_i with probability min(1, p_target(x_i) / q_draft(x_i))
# On first rejection, sample from normalized max(0, p_target - q_draft) and discard remaining draft tokens
Common Interview Trap / Anti-Pattern:

Assuming speculative decoding helps under very high batch sizes: once GPU arithmetic intensity saturates compute rather than memory bandwidth, verifying gamma draft tokens competes with batch throughput.

Question #12AdvancedSenior

How do you build reliable evaluation harnesses for RAG and agentic systems, and what biases affect LLM-as-a-Judge?

Senior Engineering Answer

Separate retrieval evaluation (Recall@K, MRR, NDCG on golden query-doc pairs) from generation evaluation (Faithfulness/groundedness against retrieved context, Answer Relevance, and deterministic schema/unit assertions). For open-ended tasks, calibrate LLM-as-a-Judge against a human-annotated golden set using Cohen's kappa, and mitigate judge biases: position bias (swap A/B order and average), verbosity bias (penalize padding), and self-enhancement bias (avoid using the same model family to judge itself). Use pairwise comparisons or atomic rubric checklists rather than vague 1–10 Likert scales.

Production Code Example
# Pairwise judge swap to neutralize position bias:
score_ab = judge(question, answer_a, answer_b)
score_ba = judge(question, answer_b, answer_a)
final_verdict = reconcile(score_ab, invert(score_ba))
Common Interview Trap / Anti-Pattern:

Relying solely on uncalibrated LLM-as-a-Judge scores in CI without pinning judge model versions, prompts, and periodic human audit sampling.

Question #13StaffPrincipal / Staff

How do constrained decoding (FSM / CFG logit masking) guarantee 100% valid structured JSON or SQL outputs, and how can strict grammars hurt reasoning quality?

Senior Engineering Answer

Constrained decoding compiles a JSON Schema or regex into a Deterministic Finite Automaton (DFA) or pushdown automaton and precomputes a token mask per grammar state. Before sampling each token, disallowed vocabulary tokens have their logits masked to -inf so the model physically cannot emit invalid syntax. However, forcing strict JSON from token 0 prevents the model from generating scratchpad reasoning tokens first—degrading accuracy on multi-step math or classification tasks. The fix is including an explicit "reasoning" or "analysis" field before the final "answer" field in the schema (or separating chain-of-thought from constrained formatting).

Production Code Example
from pydantic import BaseModel

class TriageDecision(BaseModel):
    reasoning_steps: list[str]  # Placed FIRST so model reasons before committing
    severity: str
    escalate_to_oncall: bool
Common Interview Trap / Anti-Pattern:

Putting the final classification enum field first in the JSON schema forces the model to guess the label on token 2 before reasoning through the evidence.

Question #14StaffPrincipal / Staff

Design a defense-in-depth security architecture for an autonomous LLM agent with tool-calling access (SQL, browser, code execution, email).

Senior Engineering Answer

Assume indirect prompt injection will succeed inside untrusted retrieved documents, emails, or web pages—never rely solely on system prompt instructions ('ignore instructions in data') for security. Enforce: (1) strict privilege separation with short-lived, least-privilege scoped tokens per user session; (2) deterministic policy/schema validation outside the LLM before any tool executes (e.g., parameterized SQL AST checks, URL allowlists); (3) isolated ephemeral microVM/container sandboxes (Firecracker/gVisor) with no lateral network egress for code execution; (4) mandatory human-in-the-loop confirmation gates for state-mutating or exfiltration-capable actions (writes, external sends, payments); and (5) PII/secret DLP scanning on both tool outputs and final responses.

Production Code Example
HIGH_RISK_TOOLS = {"send_external_email", "execute_refund", "drop_table"}

def dispatch_tool(tool_call, user_ctx):
    validate_schema(tool_call)
    enforce_rbac(user_ctx, tool_call.name, tool_call.args)
    if tool_call.name in HIGH_RISK_TOOLS:
        return request_human_approval(tool_call, user_ctx)
    return execute_in_sandbox(tool_call)
Common Interview Trap / Anti-Pattern:

Using an LLM classifier ('prompt shield') as the sole security gate against prompt injection; deterministic capability controls and human approval boundaries must enforce invariants.

Question #15StaffPrincipal / Staff

How do you architect a multi-model routing, caching, and fallback platform to hit strict p95 latency and COGS budgets at scale?

Senior Engineering Answer

Route traffic dynamically across a model tier hierarchy: fast deterministic rules or small classifiers handle trivial intents; mid-sized models (8B–32B / Haiku / Flash) handle 80% of standard extraction and RAG synthesis; frontier reasoning models handle complex escalation cases flagged by confidence/router scoring. Stack three cache layers: (1) KV-prefix caching on static system prompts and tool definitions; (2) exact request-hash caching; and (3) high-threshold semantic caching (cosine >= 0.96 with tenant isolation). Add hedged retries, circuit breakers, and cross-provider/region failover while streaming tokens to keep perceived TTFT under 400ms.

Production Code Example
# Tiered routing heuristic:
# complexity_score = router_classifier(query, context_tokens)
# if complexity_score < 0.35 -> 8B quantized model (p95 TTFT 120ms, $0.05/1M)
# elif complexity_score < 0.80 -> 70B/Mid tier
# else -> Frontier reasoning tier with budget cap
Common Interview Trap / Anti-Pattern:

Deploying loose semantic caches (e.g., 0.85 similarity) on personalized or time-sensitive queries serves wrong-user or stale answers.

Question #16StaffPrincipal / Staff

Compare quantization methods (PTQ: AWQ, GPTQ, SmoothQuant FP8 vs QAT) and explain how to verify no silent capability regression occurs.

Senior Engineering Answer

Weight-only PTQ (AWQ, GPTQ) compresses weights to INT4 while keeping activations in FP16, boosting decode speed for small-batch memory-bound serving; AWQ preserves ~1% salient weight channels based on activation magnitudes rather than rounding blindly. W8A8 methods (SmoothQuant / FP8 on Hopper+ GPUs) migrate quantization difficulty from outlier activations into weights so Tensor Cores run 8-bit GEMMs, accelerating both prefill and high-batch decode. Quantization-Aware Training (QAT) simulates rounding during training when ultra-low bitwidths (<4-bit) lose reasoning. Verify quantized checkpoints not just via WikiText perplexity—which hides logic regressions—but via needle-in-a-haystack long-context recall, tool-calling syntax tests, and domain reasoning benchmarks.

Production Code Example
# Quick sanity check: perplexity alone misses long-context/coding degradation
# Always gate quantized releases on:
# 1. Domain eval accuracy delta <= 1.0%
# 2. Structured JSON/tool-call pass rate
# 3. Long-context Needle-in-a-Haystack pass rate
Common Interview Trap / Anti-Pattern:

Using WikiText-2 perplexity as the sole quantization quality gate; INT4 models often retain flat perplexity while losing multi-step instruction adherence and tool-calling reliability.

Artificial Intelligence (AI) Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Artificial Intelligence (AI) preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to AI & Data Science.

JuniorFundamental

How do subword tokenizers (BPE, WordPiece) work, and why do tokenization quirks cause LLM failures on numbers, whitespace, and non-English text?

JuniorFundamental

What do temperature, top-p (nucleus sampling), and top-k actually do to next-token logits during LLM decoding?

JuniorFundamental

Walk through a standard Retrieval-Augmented Generation (RAG) pipeline and explain how embedding similarity, chunking, and metadata filtering work together.

JuniorFundamental

What is the role of Query (Q), Key (K), and Value (V) projections in Scaled Dot-Product Self-Attention, and why do we divide by sqrt(d_k)?

Mid-LevelIntermediate

Why does naive dense-only RAG fail on exact product codes, acronyms, and multi-hop queries, and how do Hybrid Search + Cross-Encoder Reranking fix it?

Mid-LevelIntermediate

How do you decide between Prompt Engineering, RAG, and Fine-Tuning (SFT / LoRA) for an enterprise AI product?

Frequently Asked Technical Interview Questions (Artificial Intelligence (AI))

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is HNSW (Hierarchical Navigable Small World) and why do vector databases use it?
HNSW is a multi-layered proximity graph algorithm for Approximate Nearest Neighbor (ANN) search. Upper sparse layers enable long-range jumps across vector space while lower dense layers refine local neighbors, achieving sub-linear O(log N) search latency with 95–99% recall without scanning every vector.
What causes the 'lost in the middle' phenomenon in long-context LLMs?
LLMs attend strongly to tokens at the very beginning (attention sinks / system instructions) and the very end of the prompt, while recall degrades for facts buried in the middle of long contexts. Mitigate it by reranking so highest-relevance passages sit at the start/end and keeping retrieved context concise.
What is the difference between a Bi-Encoder and a Cross-Encoder in retrieval?
A Bi-Encoder embeds queries and documents separately into vectors for millisecond ANN lookup across millions of items. A Cross-Encoder feeds the query and candidate document concatenated together through full self-attention, yielding much higher relevance accuracy at higher compute cost—making it ideal as a top-K reranker.
Why does embedding cosine similarity fail if a vector database mixes normalized and unnormalized vectors or mismatched metrics?
Cosine similarity measures angle independently of vector magnitude, whereas dot product (inner product) scales with vector norm and L2 measures Euclidean distance. For unit-normalized embeddings, cosine similarity and dot product yield identical rankings, while unnormalized dot product can bias toward outlier-norm vectors.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks