insideout Get Pro
Learn
AI engineering · Module 03

Tokens and Embeddings

How text becomes numbers a model can learn from.

Start here · Lesson 01

Text as bytes, bytes as tokens

How text becomes a list of integer IDs a model can read.

Start lesson

LessonsAll lessons

  1. 01 Text as bytes, bytes as tokensHow text becomes a list of integer IDs a model can read. Free
  2. 02 Training a BPE tokenizerMerge the most common pair again and again until the vocabulary is full. Free
  3. 03 Tokenizer quirks: numbers, spelling, languagesWhy models miscount letters, split numbers oddly and charge more for some languages. Free
  4. 04 Looking up a token's vectorAn embedding table turns each token ID into a learned vector. Pro
  5. 05 Cosine similarity and the dot productTwo ways to score how close two vectors are, and when they disagree. Pro
  6. 06 The distributional hypothesisWords used in the same contexts end up with similar vectors. Pro
  7. 07 A tour of trained embedding spacesNeighbours, analogies and clusters in vectors a real model learned. Pro
  8. 08 Blind spots of cosine similarityOpposites, negation and rare words that similarity scores get wrong. Pro
  9. 09 Semantic search and clusteringUse embeddings to search, group and label text. Pro
  10. 10 A bigram language modelPredict the next character by counting, then by training, and compare the two. Pro
  11. 11 Bits per byteA loss you can compare across models with different tokenizers. Pro
  12. 12 How embedding models are trainedTrain a model to rank each query's passage above the rest of its batch. Pro

Build it yourself · on your own machine

A tokenizer and a bigram model on one book

Your own BPE tokenizer and a bigram model on its tokens, scored in bits per byte so every vocabulary size, and gzip, compare fairly.
  1. Download two public-domain novels by one author from Project Gutenberg as plain text (Pride and Prejudice and Emma work), then train on one and hold out the other.
  2. Write byte-level BPE yourself: split the text into words, count them, and merge the most common pair until you have 256 + 1,000 tokens.
  3. Check that encoding then decoding gives back every held-out line exactly, and compare bytes per token on the held-out book with GPT-2's tokenizer in tiktoken.
  4. Build a bigram model over your tokens by counting, choosing the smoothing on a slice of the training book.
  5. Train the same bigram in PyTorch as a 64-wide embedding table plus an output layer, and list the nearest neighbours of five tokens by cosine.
  6. Turn each held-out loss into bits per byte at vocabularies of 256, 512 and 1,256, and put gzip's figure beside them.

How you'll know it worksA table of bytes per token and held-out bits per byte for each vocabulary, counted and trained, with gzip as a row, and a round trip that's exact on every held-out line.

Python, tiktoken and PyTorch on a laptop CPU. The books are free plain-text downloads from Project Gutenberg. Uses lessons 01 to 11.