← TikTok Interview Insights

TikTok·Machine Learning Engineer·Technical Phone Screen·Senior

SeniorPrefer not to say
May 2026

Summary

TikTok ML engineer interview that leaned hard into transformer internals and sampling methods. Two meaty coding questions back to back, both with follow-ups that required actual understanding rather than just pattern matching. Left feeling like I'd studied the right stuff but maybe not deeply enough.

Questions Asked (2)

Q1

Implement multi-head attention from scratch given query, key, and value tensors, the number of heads, and an optional mask. Your output should match the input sequence shape and include linear projections, scaled dot-product attention with softmax, masking, dropout, head concatenation, and a final output projection. Follow-up: why do we scale by the square root of the head dimension?

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

I got the structure right but fumbled the reshape logic for splitting heads.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the input shapes and the expected output shape, then outline the multi-head attention computation step by step: linear projections, splitting into heads, scaled dot-product attention with masking and dropout, concatenation, and final projection. Emphasize the importance of matching the input sequence shape and handling the optional mask correctly.

Pro tip: Mention that you would use efficient tensor operations (e.g., einsum or reshape/transpose) to avoid explicit loops, and discuss the trade-offs between clarity and performance. Also, note that the scaling factor prevents softmax saturation, which is crucial for stable gradients.

1. Clarify inputs and outputs

Confirm the shapes of query, key, and value tensors (batch_size, seq_len, d_model) and the number of heads. Ensure the output should have the same shape as the input.

2. Linear projections and head splitting

Apply linear projections to query, key, and value to obtain d_model-dimensional representations. Then split each into h heads of dimension d_k = d_model / h, reshaping to (batch_size, h, seq_len, d_k).

3. Scaled dot-product attention with mask and dropout

Compute attention scores as Q @ K^T / sqrt(d_k). Apply the mask (if provided) by setting masked positions to -inf before softmax. Apply softmax to get attention weights, then apply dropout. Multiply by V to get head outputs.

4. Concatenate heads and final projection

Concatenate the outputs from all heads along the feature dimension, resulting in (batch_size, seq_len, d_model). Apply a final linear projection to produce the output.

5. Explain the scaling factor

Discuss why scaling by sqrt(d_k) is necessary: it prevents the dot products from growing too large in magnitude, which would push the softmax into regions with tiny gradients, hindering learning.

Key Points to Mention

  • Linear projections for Q, K, V and output
  • Splitting into multiple heads and reshaping
  • Scaled dot-product attention formula
  • Masking with -inf before softmax
  • Dropout on attention weights
  • Concatenation of heads and final linear layer
  • Scaling by sqrt(d_k) to stabilize gradients

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q2

Implement nucleus (top-p) sampling for a language model: given a vocabulary's logit scores and a threshold p between 0 and 1, find the smallest set of tokens whose cumulative probability meets or exceeds p, renormalize over that set, and sample the next token. Follow-up: how does this compare to top-k sampling in terms of advantages and disadvantages?

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

Sorting the probabilities descending and doing a cumsum felt natural, but I initially forgot to handle the edge case where p equals 1.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by outlining the algorithm: compute softmax probabilities from logits, sort tokens by probability descending, find the smallest set where cumulative probability >= p, then renormalize and sample. For the follow-up, compare top-p and top-k in terms of adaptivity, computational cost, and practical performance.

Pro tip: Mention that top-p sampling is often preferred for open-ended generation because it adapts to the model's confidence, but top-k can be more stable for tasks requiring diversity control. Also, note that both can be combined in practice.

1. Understand the problem

Clarify that nucleus sampling selects the smallest set of tokens whose cumulative probability exceeds p, ensuring a dynamic vocabulary size based on the distribution.

2. Outline the algorithm

Describe steps: compute softmax, sort probabilities, compute cumulative sum, find cutoff index where cumsum >= p, zero out others, renormalize, and sample from the filtered distribution.

3. Discuss implementation details

Mention handling edge cases (e.g., p=0 or p=1), efficiency considerations (sorting O(V log V)), and potential optimizations like using a heap for large vocabularies.

4. Compare with top-k sampling

Explain that top-k uses a fixed number of tokens, while top-p adapts to the distribution's shape. Discuss advantages (top-p: dynamic, avoids including unlikely tokens; top-k: simpler, consistent diversity) and disadvantages (top-p: can include too many tokens if distribution is flat; top-k: may cut off plausible tokens or include implausible ones).

5. Conclude with practical insights

Summarize when to use each method, mention that top-p is common in state-of-the-art LLMs like GPT, and note that hyperparameter tuning is often needed.

Key Points to Mention

  • Softmax computation and numerical stability (e.g., subtracting max logit)
  • Sorting and cumulative sum to determine the nucleus
  • Renormalization to ensure probabilities sum to 1
  • Adaptive vocabulary size in top-p vs fixed size in top-k
  • Trade-offs: diversity, coherence, and computational cost
  • Edge cases: p=0 (greedy), p=1 (full sampling), and handling ties

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.