This is the kind of question where you think you know Transformers until you have to actually write them line by line under pressure.
Start by outlining the overall architecture and data flow, then implement each component modularly with clear function signatures. Emphasize the purpose of each part and how they interact, and be ready to discuss complexity and design choices.
Pro tip: Write clean, vectorized code and mention that you would use PyTorch's built-in functions for efficiency, but you can also implement from scratch to demonstrate understanding. Also, proactively discuss numerical stability and masking.
Confirm the input/output shapes, batch size, sequence length, and model dimensions. Sketch the encoder block: input -> positional encoding -> multi-head attention -> add & norm -> feed-forward -> add & norm.
Write a function that takes Q, K, V and optional mask, computes attention scores, scales by sqrt(d_k), applies softmax, and returns weighted sum. Discuss complexity O(n^2 d).
Split Q, K, V into multiple heads, apply scaled dot-product attention in parallel, concatenate heads, and apply output projection. Explain how this allows attending to different representation subspaces.
Implement sinusoidal positional encoding and add to input embeddings. For each sublayer, apply residual connection followed by LayerNorm (post-norm or pre-norm). Explain their roles in stabilizing training and enabling deep networks.
Create a two-layer MLP with ReLU/GELU activation and dropout. Combine all components into a single encoder block class/function. Discuss parameter count and computational complexity.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.