Guide

AI Coding Interviews: What They Test and How to Prepare

For ML, LLM and FDE engineers: the six exercise types you'll see, how to work through them out loud, and what to practice first.

  • AI coding
  • PyTorch
  • LLM
  • Agents

TL;DR

  • AI coding rounds test whether you can turn model concepts into correct, testable code — not whether you've memorized LeetCode patterns.
  • Six exercise types cover most rounds: attention, decoding, RAG retrieval, a training/adaptation loss, an agent loop, and inference debugging.
  • Use one loop every time: Frame → Resolve → Announce → Make → Evaluate (FRAME).
  • The bugs interviewers watch for are predictable: mask polarity, softmax on the wrong dimension, unrenormalized top-p, unvalidated tool calls.
  • If AI assistants are allowed, you're graded on how you review their code, not how fast you prompt.

Picture a candidate who can explain attention on a whiteboard better than most papers. In the coding round, they write a correct-looking multi-head attention in 15 minutes — then spend the next 20 chasing NaNs. The cause: a padding mask applied after the softmax, plus an all-padding row they never tested.

That's the AI coding round in one story. The concepts are table stakes. What gets scored is shape discipline, edge cases, tests and how you reason out loud. This guide covers what these rounds look like, a method that works on any prompt, and a two-week plan.

The six AI coding exercise types and the FRAME loop
The six AI coding exercise types and the FRAME loop
Figure 1. Six exercise types, one loop. Most rounds are one full exercise plus follow-up changes.


What an AI coding round is (and isn't)

It's not a LeetCode round: you won't be graded on the clever trick for a graph problem. It's not a system design round either: the main evidence is working code, not a diagram.

It sits in between. Typically:

  • One substantial exercise plus 1–3 follow-ups ("now add a KV cache")
  • Python, usually PyTorch or NumPy; model APIs are often mocked
  • Sometimes starter code to complete, debug or speed up
  • Increasingly, an AI coding assistant is allowed — which changes what's tested

The bar rises with level. At Senior, a correct baseline with tests is the goal. At Staff, interviewers also expect you to name production concerns — memory, latency, failure modes — and make a trade-off call without being asked.

The six exercise types

1. Masked multi-head self-attention

Implement Q/K/V projections, head reshaping, scaled dot-product attention, causal and padding masks, and the output projection.

  • Follow-ups: KV cache, cross-attention, grouped-query attention, memory estimate
  • What's tested: tensor fluency, mask semantics, numerical stability, complexity

2. An LLM decoding utility

Given next-token logits: temperature, top-k and top-p filtering, sampling with injectable randomness, EOS handling and a token budget.

  • Follow-ups: repetition penalty, beam search, batched decoding, streaming
  • What's tested: probability handling, edge cases (temperature 0), testability

3. A small RAG retrieval path

Chunk documents, embed with a supplied function, cosine top-k, dedupe, assemble a token-bounded context with citations. Generation is often mocked.

  • Follow-ups: metadata filters, hybrid lexical + vector, reranking, no-result behavior, retrieval metrics
  • What's tested: end-to-end completion, schema design, ranking correctness, grounding

4. A training or adaptation loss

From a given equation: LoRA linear layer, response-only SFT loss, contrastive loss, distillation loss or DPO loss.

  • Follow-ups: gradient checks, frozen vs. trainable parameters, padding, stability
  • What's tested: equation → code, autograd reasoning, masking

5. A bounded tool-using agent loop

Given a fake model and a tool registry: validate structured tool calls, enforce permissions, execute, append results, retry transient failures safely, detect loops, return a typed stop reason.

  • Follow-ups: human approval, parallel calls, trace logging, token budgets, injected failures
  • What's tested: the engineering around models — security boundaries, reliability, deterministic tests

6. Debug and speed up an inference path

A correct but slow or memory-hungry implementation. Measure, find the bottleneck, make one targeted change, verify output parity.

  • Follow-ups: KV caching, mixed precision, batching, avoiding host–device syncs
  • What's tested: measure-first optimization, GPU and memory reasoning

If you only have time for three, practice 1, 3 and 5. They cover the most rounds for LLM and applied AI roles.

The FRAME loop: one method for every prompt

F — Frame the task

Restate input, output and success condition with shapes or schemas:

"We get hidden states of shape [B, T, D] and a padding mask [B, T] where True means valid. We return [B, T, D], and a token must never attend to future or padding positions."

Name the dimensions (B, T, H, D_h, V), mask polarity, and what happens for empty or over-budget input. Half of all bugs in these rounds come from skipping this sentence.

R — Resolve requirements and risks

Ask only questions that change the code:

  • Which libraries are allowed? Is the model local, mocked or an API?
  • Algorithm only, or a working application path?
  • What matters most: correctness, latency, memory, cost?
  • What should happen when retrieval returns nothing or a tool fails?
  • Is an AI assistant allowed?

A — Announce the approach

A short plan the interviewer can check:

  • Primitive: validate shapes → baseline → masks/normalization → test known values → complexity
  • RAG: ingest → chunk → embed → retrieve → bounded context → generate (mocked) → evaluate
  • Agent: validate model output → authorize tool → execute with bounded retries → record trace → stop with a typed result

M — Make the smallest complete baseline

Finish the core path before adding anything clever. Exact cosine search before an ANN index. Greedy decoding before beam search. One validated tool call before a multi-agent workflow. An incomplete "production" design scores lower than a complete simple one.

E — Evaluate, debug, explain

  • Test a normal case, a boundary case and the most likely failure
  • Check shapes, dtypes, devices and memory-heavy intermediates
  • Measure before optimizing
  • End with limitations and the next validation step

The bugs interviewers are waiting for

These show up again and again — in hand-written code and AI-generated code alike.

Bug Symptom Fix
Mask applied after softmax, or reversed polarity Attends to padding/future tokens Mask logits with -inf before softmax; document True = keep
All-masked row NaNs Handle explicitly (zero output or skip) and test it
Softmax over the wrong dim Rows don't sum to 1 Assert probs.sum(-1) ≈ 1
Reshape mixes sequence and head dims Silent wrong results view(B, T, H, Dh).transpose(1, 2) and shape comments
Top-p without sorting or renormalizing Wrong distribution Sort, cumulative-sum, cut, renormalize
KV cache duplicates prefill tokens Repeated or drifting output Separate prefill and decode; append-only positions
Model output trusted as a tool call Injection, crashes Parse strictly, validate against a schema, allowlist tools
Retrying a side-effecting tool Duplicate refunds/emails Idempotency key per action
No loop budget Runaway agent Max steps, tokens, time; repeated-call detection
GPU benchmark without sync Fake speedups torch.cuda.synchronize() around timing; warm up first

A useful test for causal attention: change a future token and assert earlier outputs don't change. It catches most mask bugs in one line.

If an AI assistant is allowed

More companies now allow Copilot-style tools in coding rounds. That doesn't make the round easier — it moves the grading to judgment and review.

  1. Plan before prompting. Explain the contract and approach to the interviewer first.
  2. Ask for one bounded unit. One function, one parser, one test.
  3. Put the contract in the prompt. Shapes, mask semantics, dtype/device rules, failure behavior.
  4. Read before running. Look for invented APIs, wrong dims, unsafe parsing, hidden network calls, unbounded loops.
  5. Predict, then run. Say what a tiny test should output before executing it.
  6. Own every line. Be ready to justify or rewrite anything it generated.

A prompt that works:

"Implement only scaled_dot_product_attention(q, k, v, valid_mask). Shapes are q, k, v = (B, H, T, Dh), valid_mask = (B, T) with True = valid. PyTorch, preserve dtype and device, apply a causal mask, stable softmax, define all-masked-row behavior, include two tiny deterministic tests. Don't implement a full Transformer block."

What interviewers look for

Signal Senior (L5/L6) Staff (L6+/L7)
Framing Shapes, schemas, mask semantics stated up front Also names the production constraint that matters (memory, latency, cost)
Implementation Complete, correct baseline Clean interfaces that make the follow-ups easy
Testing Normal, boundary and failure cases Property-style tests (causality, parity), deterministic fakes
Optimization Knows the standard tricks Measures first; states the quality/latency/memory trade-off
AI assistant use Reviews generated code Scopes prompts tightly; catches subtle bugs; explains ownership

A two-week prep plan

Days Focus
1–2 Tensor shapes, stable softmax, masks, scaled dot-product attention
3–4 Full multi-head attention + KV cache; memory estimates
5–6 Decoding: temperature, top-k, top-p, EOS, batching
7–8 RAG path: chunking, cosine top-k, context assembly, retrieval metrics
9–10 Agent loop: schema validation, permissions, retries with idempotency, loop detection
11 One loss: LoRA or SFT response masking or contrastive or DPO
12 Debugging drills: find-the-bug exercises
13–14 Two full mock rounds, out loud, one with an AI assistant

Practice out loud. The FRAME loop only helps if it's automatic under time pressure.

Common mistakes

  1. Coding before framing → state shapes, schemas and mask polarity first
  2. Building the "production" version → finish the simple complete path, then extend
  3. No tests until the end → test each unit as you go; predict outputs first
  4. Silent assumptions → say them out loud and write them as comments
  5. Optimizing without measuring → baseline, profile, change one thing, verify parity
  6. Accepting AI-generated code unread → review it like a pull request

Key takeaways

  1. AI coding rounds grade correct, tested code and clear reasoning — not trivia.
  2. Practice attention, RAG retrieval and a bounded agent loop first.
  3. Use FRAME on every prompt; the "Frame" sentence prevents half the bugs.

Practice prompt: Implement a bounded tool-using agent loop with a scripted fake model and two tools — one read-only, one with a side effect. Requirements: strict JSON parsing, a tool allowlist, an idempotency key on the side-effecting tool, a max of 6 steps, and a typed stop reason. Write three tests, including one where the model repeats the same call.

Cheat sheet: AI coding interview — six exercise types, FRAME loop and top bugs
Cheat sheet: AI coding interview — six exercise types, FRAME loop and top bugs


Preparing for an AI or ML coding round? I run 1:1 mock interviews and coaching for L5–L7 AI/ML engineers. Book a free 15-minute consult →

References

  1. Vaswani et al., "Attention Is All You Need," 2017. https://arxiv.org/abs/1706.03762
  2. Holtzman et al., "The Curious Case of Neural Text Degeneration" (nucleus sampling), 2019. https://arxiv.org/abs/1904.09751
  3. Hu et al., "LoRA: Low-Rank Adaptation of Large Language Models," 2021. https://arxiv.org/abs/2106.09685
  4. Rafailov et al., "Direct Preference Optimization," 2023. https://arxiv.org/abs/2305.18290
  5. PyTorch, scaled_dot_product_attention docs. https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
  6. Alireza Dirafzoon, Machine Learning Interviews (open source). https://github.com/alirezadir/machine-learning-interviews

Next step

Practice this with a realistic mock interview

Every coaching package includes a free 15-minute consultation and personalized prep materials for your target role and company.

Written by

Alireza Dirafzoon

Applied AI Scientist · author of Machine Learning Interviews. Coaches senior AI engineers, FDEs, and applied scientists through AI and ML interview loops.

More from the blog