TinyLanguageBuilder / The Tiny Textbook

Chapter 2: Embeddings

Chapter 1 turned text into token numbers. But the number 437 says nothing about the token it names. This chapter shows how a model gives every token a list of numbers it can learn, and what that list ends up meaning.

1. Token ids are only labels

Token 437 is not "bigger" than token 436 in any useful way, and nothing about the numbers says ·dog and ·cat are alike. If the model did arithmetic on raw ids it would learn nonsense.

So the first layer of the model is a look-up table: one row per token, each row a short list of numbers (a vector). The model reads the token id, fetches that row, and works with the row from then on. The rows start out random. Training nudges them, a little at a time, so that tokens which behave alike end up with similar rows. The table is called the embedding table, and nobody writes its contents by hand.

Below, a tiny model starts with a random table. Press Train and the real training code runs in your browser. Every few hundred steps it keeps a snapshot of the table, so afterwards you can scrub back through the training and watch meaning appear.

2. Train a tiny model

Loading the engine…

3. One token, one vector

Its vector at this snapshot (32 numbers; blue above zero, orange below)

4. Similar rows, similar tokens

How do we say that two vectors are alike? By the angle between them. Cosine similarity is 1 when two vectors point the same way, 0 when they are unrelated, and −1 when they are opposite. Nobody told the model that ·dog and ·cat are related. They end up pointing the same way because the model predicts the next token better when it treats them alike: they tend to follow the same words and be followed by the same words.

5. Nearest neighbours: before and after

At the start (random)

    At this snapshot

      Left: the random table you started with. Right: the snapshot chosen by the slider above. Bars show cosine similarity (0 to 1). Neighbours are chosen from the 512-token vocabulary only.

      6. A map of the whole table

      Each dot is one token. Hover a dot to read it, click to select it.

      7. What to take from this, and what not to

      "Similar" means "used in similar places", not "means the same". ·happy and ·sad can end up close because they fill the same slots in a sentence. This model trains on only about a million characters of children's stories, so some neighbours are good and some are noise. Try several tokens.

      The map is a squeezed picture. The real vectors have many dimensions; the map keeps the two directions along which the table varies most and throws the rest away. Dots that look close on the map may be far apart in the full table, so trust the neighbour lists more than the picture.

      Position needs its own table. The model also learns an embedding for where a token sits in the window, and adds it in. Next chapter: how tokens look at each other through attention.