← Bytedance Interview Insights

Bytedance·Machine Learning Engineer·Technical Phone Screen·Senior

Senior
May 2026

Summary

Bytedance ML engineer interview that went deep on Transformer internals fast. They had me write pseudocode live while fielding theory questions at the same time, which was more disorienting than I expected.

Questions Asked (4)

Q1

Write pseudocode for scaled dot-product self-attention.

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

I got through the mechanics fine: compute Q, K, V projections, dot Q with K-transpose, scale, softmax, multiply by V.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by defining the inputs (Q, K, V) and their dimensions, then outline the steps: compute attention scores via dot product, scale by sqrt(d_k), apply softmax, and compute weighted sum with V. Write clear pseudocode with matrix operations, and mention masking for decoder self-attention if relevant.

Pro tip: Mention that scaling by sqrt(d_k) prevents softmax saturation and vanishing gradients, and note that efficient implementations use optimized matrix multiplication libraries or fused kernels like FlashAttention.

1. Define inputs and dimensions

Specify queries (Q), keys (K), values (V) with shapes (batch_size, seq_len, d_k) and (batch_size, seq_len, d_v). Mention that d_k is the dimension of queries and keys.

2. Compute attention scores

Compute the dot product between Q and K^T to get raw attention scores of shape (batch_size, seq_len, seq_len).

3. Scale scores

Divide the scores by sqrt(d_k) to stabilize gradients and prevent softmax saturation.

4. Apply softmax and optional masking

Apply softmax over the last dimension to get attention weights. If needed (e.g., decoder self-attention), apply a mask before softmax to prevent attending to future positions.

5. Compute weighted sum of values

Multiply the attention weights by V to produce the final output of shape (batch_size, seq_len, d_v).

Key Points to Mention

  • Scaling factor 1/sqrt(d_k) to avoid large dot products that push softmax into regions with tiny gradients.
  • Softmax is applied row-wise (over keys) to normalize attention weights.
  • Masking (e.g., causal mask) is crucial for decoder self-attention to maintain autoregressive property.
  • Computational complexity is O(n^2 * d) due to pairwise dot products, which can be a bottleneck for long sequences.
  • Batch matrix multiplication can be used for efficient parallel computation across batch and heads.
  • The output is a weighted sum of values, where weights are the attention probabilities.

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

Q2

Write pseudocode for cross-entropy loss.

Algorithms & Data Structures
Author's notes

Shorter than the attention one.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the scope: cross-entropy loss for binary vs. multi-class classification, and whether logits or probabilities are given. Then outline the mathematical formula and translate it into clear pseudocode, handling numerical stability (e.g., log-sum-exp trick) and edge cases.

Pro tip: Mention that in practice, frameworks like PyTorch combine softmax and cross-entropy for numerical stability, so pseudocode should reflect that by taking logits directly. Also, discuss how to handle class imbalance or label smoothing if relevant.

1. Clarify the problem

Ask whether the question refers to binary or multi-class cross-entropy, and whether inputs are probabilities or logits. This determines the formula and implementation details.

2. State the mathematical formula

For multi-class: L = -sum(y_i * log(p_i)). For binary: L = -(y*log(p) + (1-y)*log(1-p)). Explain that y is the true label (one-hot) and p is predicted probability.

3. Outline pseudocode structure

Define function signature, input shapes, and steps: compute softmax if logits, then compute log probabilities, then gather the log probability of the true class, then average over batch.

4. Incorporate numerical stability

Use the log-sum-exp trick: log_softmax = logits - max(logits) - log(sum(exp(logits - max(logits)))). This avoids overflow/underflow.

5. Write pseudocode and test with example

Write clear pseudocode with comments, then walk through a small example (e.g., 3 classes, batch size 2) to verify correctness.

Key Points to Mention

  • Difference between binary and multi-class cross-entropy
  • Handling logits vs. probabilities (softmax integration)
  • Numerical stability via log-sum-exp trick
  • Reduction over batch (mean vs. sum)
  • Edge cases: zero probabilities, label smoothing
  • Computational complexity and vectorization

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

Q3

What is the role of the position-wise feed-forward network inside a Transformer block?

Technical Trade-offsSystem Design
Author's notes

This is where I think I undersold myself.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by defining the position-wise feed-forward network (FFN) as a two-layer MLP applied independently to each position, then explain its role in transforming and enriching token representations. Emphasize how it complements self-attention by introducing non-linearity and increasing model capacity, and discuss trade-offs like parameter count and computational cost.

Pro tip: Highlight that the FFN is where most of the model's parameters reside, and relate its design to practical considerations like model scaling and inference latency—showing you understand both theory and engineering trade-offs.

1. Define the FFN

Describe the FFN as a position-wise two-layer MLP with a non-linear activation (e.g., ReLU, GELU) applied identically to each token independently.

2. Explain its function

Explain that it transforms each token's representation, adding non-linearity and enabling the model to learn complex features beyond what attention can capture.

3. Contrast with self-attention

Contrast the FFN with self-attention: attention mixes information across positions, while the FFN processes each position separately, providing a complementary form of computation.

4. Discuss trade-offs

Discuss trade-offs: the FFN holds most parameters, impacting memory and compute; its expansion ratio (e.g., 4x) balances capacity and efficiency.

5. Connect to system design

Connect to system design: the FFN's size affects model parallelism, inference latency, and hardware utilization, which are critical for deployment at scale.

Key Points to Mention

  • Position-wise independence: same FFN applied to each token separately.
  • Two-layer MLP with non-linear activation (e.g., ReLU, GELU).
  • Introduces non-linearity and increases model capacity.
  • Complements self-attention by processing tokens individually.
  • Contains the majority of Transformer parameters (often 2/3).
  • Expansion ratio (e.g., 4x) and its impact on compute and memory.

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

Q4

Why are attention scores scaled by 1 divided by the square root of the key dimension?

Technical Trade-offsAlgorithms & Data Structures
Author's notes

Nailed this one.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by explaining the purpose of scaling in dot-product attention: to prevent the softmax from saturating due to large dot products. Then derive the variance of the dot product under the assumption of independent components, showing that it grows with the key dimension, and explain how dividing by the square root of that dimension stabilizes the variance to 1. Conclude by discussing the practical benefits: improved gradient flow, faster convergence, and numerical stability.

Pro tip: Mention that while the scaling factor is standard, some variants use learned scaling or different normalizations; showing awareness of such alternatives demonstrates depth and practical experience.

1. Define the problem

Explain that attention scores are computed as dot products between queries and keys, and that these scores are passed through a softmax to obtain attention weights.

2. Analyze the variance

Assume query and key components are independent with zero mean and unit variance. Show that the dot product has variance equal to the key dimension, so its standard deviation is the square root of that dimension.

3. Explain the softmax saturation issue

Describe how large dot products cause the softmax to produce near-one-hot distributions, leading to vanishing gradients and poor learning.

4. Introduce the scaling factor

Show that dividing by the square root of the key dimension normalizes the variance back to 1, keeping the softmax in a well-behaved region.

5. Discuss practical implications

Highlight that this scaling improves gradient flow, accelerates convergence, and enhances numerical stability, which is crucial for training deep transformers.

Key Points to Mention

  • Dot-product attention computes similarity between queries and keys.
  • Variance of dot product grows linearly with key dimension under independence assumption.
  • Softmax saturates when inputs have large magnitude, causing vanishing gradients.
  • Scaling by 1/sqrt(d_k) normalizes variance to 1, preventing saturation.
  • This leads to better gradient flow and faster convergence.
  • Alternative scaling methods exist (e.g., learned temperature) but fixed scaling is simple and effective.

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