Implement Multi-Head Transformer Attention with Masks

Asked at Apple · Coding Questions · Difficulty: Medium · Last asked Jun 16, 2026

Implement multi-head scaled dot-product self-attention, the core layer of a transformer, using only the Python standard library. Each token is projected into a query, a key and a value vector. Every head compares queries with keys to decide how much of each value to mix into its output, and the heads are then concatenated and projected back to the model width.

Loading the problem…