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.
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:
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.causal_mask(n): annbynarray of booleans,Trueabove the diagonal, where a query would look ahead.attention(Q, K, V, mask=None): the scoresQ @ K.T, divided by the square root of the key size; scores wheremaskisTrueset to minus infinity; softmax along each row into weights. Returns(weights @ V, weights).self_attention(X, Wq, Wk, Wv, causal=True): queries, keys and values all made fromX, with the causal mask unlesscausalisFalse. 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.
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
- Questions, labels and contents
- A little from every pigeonhole
- Every character asks at once
- How Paul would do it
- No looking ahead
- No looking ahead
- Queries, keys and values from the same rows
- Fix Aaesha's version
- Everyone asks at once
- Several heads at once
- Two heads, side by side
- Layer norm
- One block
- One block
- Hot and cold writing
- Hot and cold
- Where each character sits
- A tiny GPT
- Ship it