Microsoft interview questions
Big tech · 11 questions reported
- junior 0
- mid 6
- senior 5
These are 11 technical questions candidates reported being asked in Microsoft interviews for AI engineer, ML engineer and applied AI engineer roles, each with a model answer you can say out loud in a minute or two. They cover embeddings, fine-tuning & alignment, sampling, hallucination, structured outputs and context selection: 0 junior, 6 mid-level and 5 senior questions. Every question comes from a public interview write-up that names Microsoft.Updated
Microsoft embeddings questions
Model answer
By vocabulary, each device owns a range of rows, looks up the tokens it owns, writes zeros for the rest, and an all-reduce sum assembles full vectors. It pairs with a tied output head sharded the same way, but popular tokens can make one shard hot.
Scroll sideways to see the whole diagram
MiniLM's tokenizer lowercases and splits “the river bank”, then adds two special tokens, [CLS] and [SEP].
Text version
- MiniLM's tokenizer lowercases and splits “the river bank”, then adds two special tokens, [CLS] and [SEP].
- Each token becomes an ID from the vocabulary. “bank” is ID 2924.
- The embedding table has one row per vocabulary entry and one column per dimension: 30,522 × 384 learned numbers.
- Embedding “bank” means reading row 2924. No arithmetic, just a lookup. The same ID always reads the same row, whatever the sentence.
Tokens, IDs, table shape and row values measured with sentence-transformers 6.1.0 (all-MiniLM-L6-v2).
By hidden dimension, every device holds all rows but a slice of the width. Lookups are local, then an all-gather concatenates the slices. Both move about batch × tokens × width numbers; choose by what the next layer wants.
Model answer
Embeddings: shortlist models on public retrieval benchmarks, then pick on your own queries; smaller dimensions or int8 vectors cut memory and latency.
Scroll sideways to see the whole diagram
The tokenizer turns the sentence into 9 token IDs, including the special tokens [CLS] and [SEP].
Text version
- The tokenizer turns the sentence into 9 token IDs, including the special tokens [CLS] and [SEP].
- Each ID reads its row of the embedding table: 9 static vectors. “bank” gets the same row here as in a sentence about money.
- Six transformer layers let every token's vector take in the others. The output is still 9 vectors, but now each depends on its context.
- Search needs one vector per text, so MiniLM averages the 9 token vectors (mean pooling) into one 384-number vector.
- Finally the vector is scaled to length 1, so cosine similarity and dot product give the same ranking.
Token count, module order (Transformer → mean Pooling → Normalize) and output length measured with sentence-transformers 6.1.0 (all-MiniLM-L6-v2).
Index: HNSW gives high recall at low latency but holds full vectors in memory; IVF with product quantisation compresses billions of vectors. Tune the recall-latency trade with ef or nprobe, then rerank a shortlist exactly.
Sharding: partition by user or tenant, since an assistant searches one person's content, which also enforces isolation; otherwise scatter-gather across shards and merge top-k. Add replicas for throughput.
Microsoft next-token prediction and sampling questions
Model answer
Keep the k best partial sentences. Each step, extend every one with its likely next tokens, score by the sum of log-probabilities, and keep the top k. A sentence's probability is the exponent of that sum.
Scroll sideways to see the whole diagram
Step 1: score the next token. With beam width 2, keep the two best, “cat” and “dog”, and drop the rest.
Text version
- Step 1: score the next token. With beam width 2, keep the two best, “cat” and “dog”, and drop the rest.
- Step 2: extend each kept sentence and multiply the probabilities. In code, add log-probabilities instead, so long products don't underflow.
- Keep the best two again. “dog barked” wins at 0.36, although “dog” was only the second-best first word.
Illustrative probabilities.
Greedy is beam width 1, so it misses sequences whose first token wasn't the best. Longer sentences collect more negative terms, so normalise by length when comparing finished beams.
Microsoft hallucination and limits questions
Model answer
Quality is task-specific: reference answers where they exist, a rubric judge, human spot checks. Hallucination against supplied context is faithfulness: split the answer into claims and check each is supported by the context.
import re
from dataclasses import dataclass, field
@dataclass
class Result:
score: float
unsupported: list = field(default_factory=list)
def claims(answer):
parts = re.split(r"(?<=[.!?])\s+", answer)
return [p.strip() for p in parts if p.strip()]
def faithfulness(answer, context, supports):
# supports(context, claim) -> bool: an NLI
# model or a judge prompt
cs = claims(answer)
if not cs:
return Result(1.0)
bad = [c for c in cs if not supports(context, c)]
return Result(1 - len(bad) / len(cs), bad)
Interviewers look for claim-level scoring, a pluggable judge validated against human labels, and the empty case handled.
Microsoft examples and structured outputs questions
Model answer
Don't ask the model for Word markup. Have it emit structured output, JSON with only allowed blocks such as heading with level, paragraph, list and table, each naming a permitted style, enforced by schema-constrained decoding.
Scroll sideways to see the whole diagram
GPT-2 scores every token in its vocabulary. Left alone, its most likely next token is “ about”, not a planet.
Text version
- GPT-2 scores every token in its vocabulary. Left alone, its most likely next token is “ about”, not a planet.
- Constrained sampling filters the scores before sampling: tokens the format doesn't allow are removed. A grammar decides what is allowed at each step.
- Only planet names can come out now, and their probabilities are rescaled to sum to 1. The output is always a valid label, but greedy decoding picks “ Earth” (24.8%) over “ Jupiter” (23.7%). The constraint fixes the form, not the content.
Real next-token logits of gpt2 (transformers 5.20.2) for “The largest planet in our solar system is”, from lib/labs/data/sampling.json; probabilities at temperature 1, computed by constrain() in lib/labs/structured.ts.
A deterministic renderer then builds the document from the template's styles. Validate rules the schema can't express, like heading order, and retry with the error. Evaluate by diffing rendered styles against the spec.
Microsoft selecting, ordering and compressing context questions
Model answer
Keep two stores per user: a small profile of stable facts and preferences, always in the prompt, and episode summaries retrieved by relevance.
Scroll sideways to see the whole diagram
The context window is finite: the prompt and the reply share it.
Text version
- The context window is finite: the prompt and the reply share it.
- Part of the prompt is fixed. The rest, such as retrieved passages, is chosen for each request, and that is where the choices are.
- In this lesson's small help centre, all 14 articles come to 299 tokens; the article that answers "how do I stop paying every month" is 25. About 12 times the input for the same answer.
- Input tokens are billed and prefilled on every request. Spend them on passages that help.
Token counts: o200k_base on the 14 help articles of lib/labs/data/search-lab.json (lib/labs/context.test.ts). Cost and latency: AI Engineering Ch. 6, "RAG".
After each conversation, a model extracts atomic facts with a timestamp and source; newer facts override conflicting ones, and duplicates merge. At query time, fit the profile plus the top retrieved memories into a fixed token budget.
The hard part is trust: users can see and delete memories, sensitive data needs consent and retention limits, stores are isolated per user, and remembered text is data, never instructions. Measure whether it helps.
Microsoft prompt versions and regression tests questions
Model answer
Start from what success means for the product, then build an eval set from real traffic: sampled, labelled, covering known failure types. Score with code checks where possible and judge models validated against human labels elsewhere.
Scroll sideways to see the whole diagram
Anything that can change the output counts as a change, not only edits to the prompt text.
Text version
- Anything that can change the output counts as a change, not only edits to the prompt text.
- Run the whole fixed suite automatically, the way unit tests run on code.
- Gate on broken cases, not only on the total: a better average can still hide a broken case you care about.
- When something slips through to users, add it as a case so it can't silently return.
Every prompt, model or retrieval change runs the suite as a gate before release. In production, log inputs and outputs, collect user feedback, and canary or A/B test changes. Triage failures into categories, fix the biggest one, and add its examples to the eval set, so each round makes the next measurement sharper.
Microsoft retrieval-augmented generation questions
Model answer
Index chunks with metadata and their source's access-control list, kept in sync. At query time, rewrite the query, run BM25 and dense retrieval with the permission filter inside both, fuse with reciprocal rank fusion, then a cross-encoder reranks the top few dozen. Measure each stage on labelled queries: recall at k for candidates, NDCG and MRR for the final order, then answer faithfulness and permission-leak tests.
Microsoft fine-tuning and alignment questions
Model answer
SFT imitates demonstrations: simple and stable, but can't exceed its data. RLHF trains a reward model on preferences and optimises against it with PPO: it can beat the demos, but is costly, unstable and prone to reward hacking. DPO-style methods learn from preference pairs directly: cheap and steady, but offline.
For checkable tasks like maths and code, RL with verifiable rewards, such as GRPO, skips the reward model. SFT usually comes first.
Model answer
Make every example executable: formulas parse, references point to real cells, and the expected output matches what a spreadsheet engine computes. Then deduplicate, check the test set doesn't overlap training, balance task types and sheet sizes, and have experts audit a sample. To decide on fine-tuning, evaluate the pretrained model with good prompts and examples on a held-out set first; fine-tune only if failures are systematic, like wrong function syntax.
Microsoft mixture of experts and parallelism questions
Model answer
Vocabulary sharding: each device holds a slice of rows and computes logits for its slice only. Softmax never needs the full vector: all-reduce the max, then the sum of exponentials. Hidden sharding: each device holds a slice of the hidden width and produces partial logits over the whole vocabulary, which must be all-reduced, a vocabulary-sized vector per token.
import torch
import torch.distributed as dist
def dist_topk(local, k, offset):
# local: [B, V_shard] logits on this rank
v, i = local.topk(k, dim=-1)
i = i + offset # to global vocabulary ids
n = dist.get_world_size()
vs = [torch.empty_like(v) for _ in range(n)]
ix = [torch.empty_like(i) for _ in range(n)]
dist.all_gather(vs, v)
dist.all_gather(ix, i)
v, i = torch.cat(vs, -1), torch.cat(ix, -1)
top, pos = v.topk(k, dim=-1)
return top, i.gather(-1, pos)
It's exact: every global top-k entry is in its own shard's top k.
Each question comes from a public interview write-up or video that names Microsoft; the answers are ours. Not affiliated with Microsoft.