Paul's Python CoursePPC

Project 11 of 14, for Aaesha

Tiny GPT

A character-level GPT from scratch, where attention means what it says: self-attention with a causal mask, several heads, a transformer block checked number by number, then two trained blocks that write in the style of Three Men in a Boat.

About 4 hours, in 20 steps.

Sign up free to open itLog in

Act 7 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • AaeshaIn psychology, attention is choosing what to notice, like hearing one voice across a noisy room and not the rest.
  • YahyaThe forecast model looked one letter back, and this one looks at all of them?
  • AaeshaAll of them, and it decides how much each one counts, which is literally what attention is.

In attention.py:

  1. softmax(scores): chances along the last axis, so each row adds up to 1. It must cope with very large scores and with minus infinity.
  2. causal_mask(n): an n by n array of booleans, True above the diagonal, where a query would look ahead.
  3. attention(Q, K, V, mask=None): the scores Q @ K.T, divided by the square root of the key size; scores where mask is True set to minus infinity; softmax along each row into weights. Returns (weights @ V, weights).
  4. self_attention(X, Wq, Wk, Wv, causal=True): queries, keys and values all made from X, with the causal mask unless causal is False. Returns (output, weights).

Then in block.py, one transformer block: multi_head, layer_norm (row by row), feed_forward and transformer_block, checked against a reference with Neil's test weights.

Then in gpt.py, the whole model, with weights trained on Jerome K. Jerome's Three Men in a Boat: embed, next_scores through both blocks, sample_next with a temperature, and generate, which writes a character at a time.

What it prints
the river to day, and the strange of the work the busin't so a morning from before on the
george said, and a not a sing to much as real the partice, and the man who had the sland wa
montmorency would have stopped half a man on the back that it was a since to be in a methin

What you learn

What's in it

  1. Questions, labels and contents
  2. A little from every pigeonhole
  3. Every character asks at once
  4. How Paul would do it
  5. No looking ahead
  6. No looking ahead
  7. Queries, keys and values from the same rows
  8. Fix Aaesha's version
  9. Everyone asks at once
  10. Several heads at once
  11. Two heads, side by side
  12. Layer norm
  13. One block
  14. One block
  15. Hot and cold writing
  16. Hot and cold
  17. Where each character sits
  18. A tiny GPT
  19. Ship it