Shaf Lab

Tokenization and embeddings

Before a model can do anything with text, the text has to become a list of integer IDs. Subword tokenization splits language into pieces larger than letters but often smaller than words. Common words stay whole. Rare or new words are assembled from familiar chunks, so the vocabulary stays a manageable size and you rarely hit a hard unknown.

Byte-pair encoding is the usual way to build that vocabulary. Start with single symbols, count which adjacent pair appears most often, merge it into a new symbol, and repeat until you reach the target size. The byte-level version starts from raw bytes, so emoji, code, and other odd strings can be encoded without a special unknown token. The same tokenizer must be used at training and at inference. If you mix them, the model sees IDs it was not trained on.

Each ID is then looked up in a table to produce an embedding: a learned list of numbers for that token. Training pushes tokens that appear in similar contexts toward similar vectors, so meaning ends up encoded as geometry. The same word, embedding, is also used for a whole passage when you build a search index.

To compare two embeddings, cosine similarity looks at the angle between them and ignores their length. A value near 1 means they point the same way; near 0 means they are unrelated. This is the yardstick most retrieval systems use, and it is why messy tokenization or mixed embedding models quietly wreck search quality.