Multi-Head Self-Attention

One linear projection, three views, H parallel heads, one mask. The attention block as the model actually uses it.

Build 1.5 hr Python

Prerequisites: Phase 04 lessons, Phase 07 transformer lessons, Lessons 30 through 32 of this phase

#Learning Objectives

  • Implement a batched Query/Key/Value projection as a single linear layer split into H heads.
  • Compute scaled dot-product attention with the correct normalization and dtype handling.
  • Apply a causal mask that prevents a position from attending to future positions.
  • Inspect per-head attention weights for a fixed input and reason about what each head looks at.
  • Train a small attention block on a toy task and watch the loss fall as the heads specialize.
Full Access lesson

Keep going. The rest of this lesson is one step away.

Unlock all 503 lessons, video, code, quizzes and every future update. Pay in your own currency with Paystack.

The text and code of this lesson are based on AI Engineering from Scratch by Rohit Ghumare, MIT licensed.