Starting Your First RAG Project? Untangle These Confusing Terms First
261205
Embeddings, tokens, tokenizers, vocabularies, encodings and chunks: what each one means, how they connect, and which ones you actually need to care about
You’ve seen the tutorials. A RAG app takes about 50 lines of Python: load some PDFs, split them, embed them, store them in a vector database, ask a question, and get an answer. Easy.
Then you start building your own, and the vocabulary trips you up. Is an “embedding” the vector in my database, or something inside the LLM? Why does my chunk count as 480 tokens in one place and 560 in another? Do I need an embedding model from the same company as my LLM? What is cl100k_base, and why does tiktoken want it?
This post is the guide I wish I’d had before my first RAG project. We’ll go through the confusing terms one at a time, with small examples, and then see how they all fit together.
RAG in 60 seconds
Retrieval-Augmented Generation (RAG) is a simple idea: before a language model answers a question, you find the relevant pieces of your data and hand them to the model along with the question.
A typical RAG app works in two phases.
Phase 1: Retrieval (finding the right text)
- Collect the documents that make up your knowledge source.
- Parse and clean them into plain, well-structured text.
- Chunk that text into smaller pieces.
- Embed each chunk: an embedding model turns it into a vector (a list of numbers).
- Store and index those vectors in a vector database.
- At question time, embed the user’s question with the same embedding model.
- Search the database for the vectors closest to the question’s vector.
- Fetch the original text of those closest chunks.
Steps 1–5 happen ahead of time (offline). This is called indexing or ingestion. Steps 6–8 happen every time a user asks something.
Phase 2: Generation (writing the answer)
- Build a prompt that contains the user’s question, the retrieved chunks, and some instructions on how to answer.
- Send it to an LLM (GPT, Claude, Llama and so on), which writes an answer grounded in those chunks.
- Return the answer to the user, ideally with citations pointing to the chunks it used.
That’s the whole loop. Now let’s look at the parts.
Step zero: what goes in decides what comes out
Before any of the confusing terms, there’s a step that gets the least attention and often matters most: choosing your documents.
The LLM can only answer from what’s in your knowledge source. If the right document is missing, or an outdated version is in there, no amount of tuning later will fix the answers. It’s the old rule: garbage in, garbage out.
This step has two parts:
- Selection: deciding which documents belong in the knowledge source.
- Collection: actually getting them in.
Next comes parsing and cleaning, which turns your PDFs, Word files and web pages into clean, well-structured text ready for chunking. The two words often travel together, but they’re different jobs:
- Parsing pulls the text and its structure (headings, lists, tables) out of each file format.
- Cleaning removes noise (headers, footers, page numbers, broken characters) and fixes problems in the extracted text.
This matters because the embedding model and the LLM only ever see this text. If parsing loses or garbles something, it’s gone for good.
The good news: these steps are rarely what confuses people. The confusion starts with embeddings, tokens, tokenizers and chunks. Let’s take them one by one.
1. Embeddings: one word, three meanings
Why the term is so confusing
“Embedding” isn’t the name of one specific thing. It’s a general mathematical idea: representing something as a list of numbers (a vector) in a space. Anything can be embedded: a token, a word, a sentence, a whole document, an image, even a user.
So the word gets used for anything turned into a vector, at any size, at any stage of a model. Three habits make it worse:
- History. The term became popular with Word2Vec (2013), where an embedding was one vector per word. Later, people started making vectors for whole sentences and documents and kept the same word.
- The same word for the container and its contents. “Embedding” can mean one vector, the table that holds all the vectors, or the model that produces them.
- Product naming. Companies sell “embedding models” (OpenAI’s
text-embedding-3, Cohere Embed) next to their LLMs. Both kinds of model have an embedding table inside, but only one of them is called an embedding model.
The three levels of embeddings
It helps to know that you can meet embeddings at three different levels.
Level 1: Token embeddings (the embedding table or embedding matrix)
A private lookup table inside a model, with one fixed row of numbers for each token in the model’s vocabulary. Every LLM has one, and so does every embedding model. It knows nothing about context: “bank” always gets the same row. You never use it directly in a RAG app.
Level 2: Contextual embeddings (also called hidden states)
After the model’s transformer layers have done their work, each token has an updated vector that reflects the words around it. There’s still one vector per token, so a 300-token chunk has 300 of them. These are internal too, and usually not exposed to you.
Level 3: Text embeddings
This is the only kind your RAG app uses. It’s one vector for a whole piece of text, such as a question or a chunk. An embedding model produces it by combining the Level 2 vectors into one (a step called pooling), and it has been trained specifically so that texts with similar meanings get similar vectors.
Here’s how Level 1 and Level 3 compare:
| LLM token embeddings (Level 1) | RAG text embeddings (Level 3) | |
|---|---|---|
| What it represents | One token (“kitten”, “ing”, “,”) | A whole question or chunk of text |
| How many vectors | One per token in the vocabulary (e.g. 150,000 rows) | One per text you embed |
| Context-aware? | No, a fixed row for each token | Yes, it reflects the whole text |
| Where it lives | Inside the model, as its first layer | Outside the model, in your vector database |
| Who uses it | The model itself | You and your RAG app |
| How it’s learned | As a side effect of training the LLM to predict the next token | Contrastive training: matching texts pulled together, unrelated texts pushed apart |
| Its size in the reference tables at the end | “Embedding dimension” in the LLM table (e.g. 7,168) | “Output dimension” in the embedding-model table (e.g. 1,024 or 3,072) |
That last row explains a lot of confusion. Both kinds of table have a column about “dimension,” but they measure different things.
Note that an embedding model has its own Level 1 table inside it too. Qwen3-Embedding, for example, contains Qwen3’s token embedding table. But what you get out of it is a Level 3 vector.
Why you can’t just use an LLM’s vectors for search
An LLM is trained to predict the next token, and its internal vectors are organized for that job. They are not organized so that “How do I reset my password?” and “Steps to recover account access” land close together. If you average an LLM’s hidden states, you get a vector that works poorly for search.
An embedding model is often built from an LLM (Qwen3-Embedding and Gemini Embedding are examples), but then it’s retrained with contrastive learning and its final step is swapped out. Instead of “predict the next token,” its job becomes “produce one vector where similar meanings sit close together.” The insides are reused; the job changes.
An analogy: The LLM and the embedding model are like two people who learned the same language (the same tokenizer, embedding table and layers). One became a writer, who produces new text. The other became a librarian, who gives every document a catalogue location so related documents end up on the same shelf. Same language skills, different job, different training.
A RAG app uses two separate models
This is where everything comes together:
- The embedding model (e.g.
text-embedding-3-large, BGE-M3) turns each chunk and each user question into a Level 3 vector. The app searches the vector database for the chunk vectors closest to the question vector, then looks up the plain text of those chunks. - The LLM (e.g. GPT, Claude, Llama) receives the question plus the retrieved chunks as plain text and writes the answer.
The vectors from the embedding model never go into the LLM. The LLM gets ordinary text, splits it with its own tokenizer, and looks up its own Level 1 token embeddings. The two models’ embeddings never meet. They’re two separate systems that only share text.
That has a very practical consequence: you can freely mix vendors. Using an embedding model from one company and an LLM from another is common and works well. You could swap your LLM from GPT to Claude to Llama tomorrow without touching your vector database.
For example, Anthropic doesn’t offer its own text embedding model, so anyone building RAG with Claude uses another vendor’s embedding model. Anthropic’s documentation points to Voyage AI and also encourages you to evaluate several embedding providers to find the best fit for your use case.
A naming cheat sheet
To avoid confusion in your own code, docs and conversations, use more precise names:
| Instead of “embedding”… | Say… |
|---|---|
| The lookup table inside a model | Token embedding table (or embedding matrix) |
| One row from that table | Token embedding |
| The per-token vectors after the layers | Hidden states / contextual token vectors |
| The single vector for a chunk or question | Text embedding (or sentence/document embedding) |
| The model that produces that vector | Embedding model (or text-embedding model) |
In short: in an LLM, “embedding” usually means the token-level lookup table inside the model. In RAG, “embedding” means one vector for a whole piece of text, produced by a separate model trained for similarity search. Same basic idea (meaning as numbers), but a different level, a different job and different training.
A closer look: the embedding table inside a model
Every model has two closely linked tables: a vocabulary (which we’ll cover in the tokens section) and an embedding table. The embedding table is a big grid of numbers with:
- one row for every token in the vocabulary, and
- one column for every embedding dimension.
With a vocabulary of 50,000 tokens and an embedding dimension of 768, the table holds 50,000 × 768 numbers, about 38 million. The token ID is simply the row number: it tells the model which row to read, and that row is the token’s embedding.
Here’s a tiny made-up example with only 4 dimensions:
| Token ID | Token | Embedding (the row) |
|---|---|---|
| 0 | <pad> | [0.00, 0.01, -0.02, 0.00] |
| … | … | … |
| 3,797 | cat | [0.61, -0.20, 0.33, 0.08] |
| 3,798 | truck | [-0.45, 0.72, -0.10, 0.29] |
| … | … | … |
| 23,102 | kitten | [0.58, -0.25, 0.30, 0.11] |
Look at the IDs. cat (3,797) and truck (3,798) are neighbours by ID but far apart in meaning, so their rows are very different. cat and kitten are far apart by ID but close in meaning, so their rows are similar.
This is the key point: a token ID carries no meaning at all. It’s just an address. All the meaning lives in the row it points to. The embedding table turns a meaningless label into a meaningful list of numbers.
How the rows get their meaning
Nobody writes these numbers by hand, and no single column has a clear human meaning on its own. The meaning comes from all the dimensions working together. The table is part of the model’s learned weights, trained like the rest of the network:
- At the start of training, every row is filled with random numbers.
- The model reads text, makes predictions and measures its mistakes.
- Training adjusts the numbers to reduce those mistakes, including the rows of the tokens that appeared in that text.
- After billions of examples, tokens used in similar ways (cat, kitten) have had their rows pushed in similar directions.
A side effect: a token that almost never appears in the training data gets very few updates, so its row stays poorly trained. That’s one reason models handle rare words and unusual spellings less well.
👉 Read more about Weights: “Model Weights Explained: From Tokens to Embeddings in a RAG App”
Things worth knowing
- The tokenizer and the embedding table are a matched pair. Row 3,797 means cat only because this tokenizer gave cat the ID 3,797. Another model’s tokenizer may give 3,797 to something completely different, and its table holds different numbers anyway. That’s why a model must always be used with its own tokenizer, and why token IDs and embeddings from different models can’t be mixed or compared.
- Vocabulary size affects model size. More tokens means more rows. Large LLMs with 100,000+ tokens and thousands of dimensions spend hundreds of millions of parameters on this table alone.
- Special tokens have rows too. Markers such as “start of text,” “end of text” or “padding” have their own IDs and rows, so the model can learn what they signal.
The row is only the starting point
The row you fetch is the token’s context-free meaning. The word “bank” means different things in “river bank” and “bank loan,” yet the table gives it the same starting numbers both times. Then:
- the model adds information about the token’s position in the sentence (the row alone doesn’t say whether it came first or tenth), and
- the network’s layers adjust each vector based on the surrounding tokens.
After those layers, “bank” next to “river” ends up closer to “shore,” and “bank” next to “loan” ends up closer to “money.” These adjusted vectors are the contextual embeddings (Level 2) from earlier.
The table also works in reverse
When an LLM generates text, its last step scores every token in the vocabulary to pick the next one. Many models reuse the same embedding table here: the model’s output vector is compared with every row, and the best-matching rows become the most likely next tokens. The winning row number is a token ID, which the tokenizer turns back into text. So token IDs and the table are used both on the way in and on the way out.
The full chain
Text → the tokenizer cuts it into tokens → each token gets an ID → the ID picks a row from the embedding table (the token embedding) → position information is added → the layers adjust it using context → (embedding models only) everything is combined into one vector for the whole text.
Or in one sentence: the token ID is an address, the embedding table is the address book, and the embedding is what’s written at that address.
The text embedding model: the one your RAG app actually uses
A text embedding model has one job: read a piece of text (a sentence, a paragraph, a chunk or a question) and turn it into a vector that describes its meaning, not its exact words.
It’s trained on huge numbers of examples of texts that belong together (a question and its answer, say) and texts that don’t. So it learns to give similar vectors to texts that mean similar things. “How do I reset my password?” and “Steps to recover access to my account” get very similar vectors even though they share almost no words, while “How do I bake bread?” lands far away from both.
Why RAG needs it. An LLM doesn’t know your company’s documents, and you can’t paste thousands of pages into every question. RAG first finds the few relevant passages and gives only those to the LLM. Plain keyword search is often poor at that, because people rarely use the exact words that appear in the documents. Embeddings let you search by meaning instead of matching words.
How it’s used, in two phases:
- Preparation: split your documents into chunks (often a paragraph or a few hundred tokens), send each chunk through the embedding model, and store the vectors in a vector database together with the original text.
- Question time: turn the user’s question into a vector with the same embedding model, find the closest stored vectors, and pass those chunks as plain text to the LLM along with the question.
The embedding model is the app’s librarian that finds the right pages; the LLM is the writer that reads them and answers.
Three rules to remember:
- Documents and questions must be embedded with the same model: same model, same version, and the same output dimension if it’s adjustable. Comparing an OpenAI question vector against Cohere document vectors gives meaningless results, because each model has its own “map of meaning.”
- Switching embedding models means re-embedding everything. Move from
text-embedding-3-largeto Voyage, and every chunk in your database has to be embedded again. - Switching the LLM costs nothing on this side. Your vector database stays exactly as it is.
What actually matters when choosing an embedding model
Since you can pick any vendor, choose on what affects retrieval quality and day-to-day operations:
- Your languages and domain: how well does it handle Swedish, legal or medical text, or code?
- Max input tokens: does it fit your chunk sizes?
- Output dimension and MRL support: these affect storage size and search speed (MRL is explained in the reference section).
- Cost per million tokens: you’ll embed your whole collection, and again if you ever switch.
- Data residency and privacy: e.g. EU hosting, or an open-weight model (BGE-M3, Qwen3-Embedding) you run yourself so documents never leave your servers.
- Measured retrieval quality on your own data: the simple test described in the chunking section below is still the best way to decide.
2. Tokens and tokenizers
What a token is
A token is the basic unit of text a language model reads and writes. Models don’t see letters or whole words. They see a sequence of tokens: small pieces of text, each mapped to an ID number in the model’s fixed vocabulary.
A token is often a whole word, but it can also be part of a word or a punctuation mark. Note that the IDs aren’t chosen by the neural network itself. They come from the tokenizer, which was built before the model was trained (more on that shortly).
For example, “The kittens played” might become:
The · kitten · s · played
Each piece is then swapped for its ID, a bit like looking a word up in a numbered dictionary:
The → 464 · kitten → 23,102 · s → 82 · played → 6,945
These IDs are just labels. Token 23,102 isn’t “closer” in meaning to 23,103 than to token 5. The ID says which token it is, not what it means.
What the model actually reads: a real example

Here’s the question “Can I get a refund after 30 days?” as seen by all-MiniLM-L6-v2, a small, popular embedding model that uses BERT’s WordPiece tokenizer. A few things to notice:
- Common words are one token each:
can,get,after,days. - Less common words are split into pieces: “refund” becomes
ref+##und, so one word costs two tokens. “refundable” becomes three:ref+##unda+##ble. These are pieces the tokenizer learned from its training text. ##marks a piece that continues the word before it. That’s WordPiece’s convention; other tokenizers mark word boundaries differently (for example, by attaching the space to the start of the next token).- This tokenizer is uncased, so “Can” and “I” become
canandi. Many other tokenizers keep capital letters. - The model only ever works with the numbers: 2064, 1045, 2131 and so on.
- Behind the scenes, the tokenizer also adds two special tokens,
[CLS]at the start and[SEP]at the end, so the model actually receives 12 IDs, not 10.
And the part that matters for your app: chunk sizes, this model’s 256-token input limit and LLM pricing are all counted in tokens, not words, and every model counts with its own tokenizer.
Rule of thumb for English: 1 token ≈ ¾ of a word, or about 4 characters. So 1,000 tokens is roughly 750 words. Other languages, code and unusual text usually need more tokens per word.
Why not just use words or characters?
| Approach | Problem |
|---|---|
| Whole words | The vocabulary would be huge, and any new or misspelled word (“ChatGPTish”, “teh”) would be unknown. |
| Single characters | The vocabulary is tiny, but sequences get very long, which makes models slower and meaning harder to learn. |
| Subword tokens | A middle ground: a manageable vocabulary (often 30k–260k entries) that can still represent any text by combining pieces. |
Tokenizers
A tokenizer is the component that turns text into tokens and token IDs before the model sees them, and turns IDs back into text after the model generates them. It’s separate from the neural network: it’s built before the model is trained, and it stays fixed afterwards.
Encode: "Hello world" → ["Hello", " world"] → [9906, 1917] → model Decode: model → [40, 1093, 433] → ["I", " love", " it"] → "I love it"
A tokenizer is essentially a set of rules plus a lookup table:
- Vocabulary: every token it knows, each with an ID (e.g.
" the"→ 279). - Merge rules or a scoring model: how to split new text into those tokens.
- Pre-tokenization rules: how text is first roughly broken up, e.g. on spaces and punctuation, or by separating digits.
- Normalization (optional): clean-up like Unicode normalization or lowercasing.
- Special tokens: reserved markers with a structural meaning, such as:
<bos>/<eos>: beginning and end of a sequence<pad>: filler to make sequences the same length in a batch<unk>: unknown token (used by older tokenizers)- chat markers that separate system, user and assistant turns
The main tokenizer algorithms
| Algorithm | How it works | Used by (examples) |
|---|---|---|
| BPE (Byte-Pair Encoding) | Starts from characters or bytes and repeatedly merges the most frequent pair. | GPT models, Llama, many modern LLMs |
| Byte-level BPE | BPE run on raw bytes, so any text (emoji, any language, code) can be encoded and there’s never an “unknown” token. | GPT-2 onwards, most current LLMs |
| WordPiece | Like BPE, but picks the merges that most increase the likelihood of the training data. Marks word continuations with ## (e.g. play, ##ing). | BERT, all-MiniLM |
| Unigram LM | Works the other way round: starts with a large vocabulary and removes the least useful tokens, keeping a probabilistic model to pick the best split. | T5, ALBERT (via SentencePiece) |
| SentencePiece | A library rather than one algorithm. It treats text as a raw stream with spaces marked as ▁, so it works for languages without spaces (Japanese, Chinese). Supports BPE or Unigram. | T5, Llama 1–2, many multilingual models |
How a tokenizer is trained
Training a tokenizer is statistical counting, not neural-network training:
- Collect a large, representative text corpus. The language mix matters a lot.
- Choose a target vocabulary size (e.g. 32k, 50k, 128k, 200k).
- Run the algorithm (e.g. BPE merges) until that size is reached.
- Save the vocabulary and the rules.
Then the model is trained using that tokenizer, and the two are tied together for good.
Key design trade-offs
Vocabulary size
- Larger: fewer tokens per text, so more text fits in the context window and generation is faster, but the embedding table is bigger and rare tokens get little training.
- Smaller: a lighter model, but longer token sequences.
Training data mix
- A tokenizer trained mostly on English splits other languages into many more tokens. In Chinese, for instance, one character may be split into several tokens, while a common group of characters may become a single token. More tokens means higher cost and less room in the context window. This is often called the “token tax” on non-English languages.
- Including code in the training data gives efficient tokens for indentation and common keywords.
Number handling
- Some tokenizers split numbers into single digits (2026 → 2, 0, 2, 6), others group them (2026 → “202”, “6”). This affects how well models do arithmetic.
Practical points to remember
- A model and its tokenizer must match. Another model’s tokenizer produces the wrong IDs, and the output is garbage.
- Token counts differ between models. The same sentence can be 10 tokens in one model and 13 in another, so cost and context estimates aren’t directly comparable.
- Your LLM and your embedding model each have their own tokenizer (more on this below).
- Whitespace and capitalization matter. “Hello”, ” Hello” and “HELLO” are often different tokens.
- Count tokens with the provider’s tools (e.g. tiktoken for OpenAI models, Hugging Face
AutoTokenizerfor open models, or a token-counting API) before you send text.
The vocabulary: the model’s dictionary
We’ve mentioned the vocabulary several times. It’s the full, fixed list of tokens a model knows. With 50,000 tokens, they’re numbered 0 to 49,999, and that number is the token ID. Each entry pairs a token string with a unique integer ID. If a piece of text isn’t in the vocabulary, the model can’t represent it directly and has to build it from smaller entries.
A typical vocabulary of 32k–260k entries is a mix of:
- Base units: all 256 possible bytes (in byte-level tokenizers) or individual characters. These guarantee that any text can be encoded, at worst one byte at a time.
- Subword pieces: prefixes, suffixes and stems (
un,ing,tion,pre). - Whole words: frequent words, often in several forms (
the,▁the,The,▁The). - Formatting chunks: runs of spaces for code indentation,
\n\n,://,.com. - Numbers: single digits or small groups, depending on the design.
- Pieces from other languages: how many depends on the training mix.
- Special tokens:
<bos>,<eos>,<pad>, chat-role markers, tool-call markers. Ordinary text never produces these; the tokenizer inserts them on purpose.
In BPE, the order often reflects how the vocabulary was built: lower IDs tend to be base units and the earliest (most frequent) merges, higher IDs are later, rarer merges.
Here’s what a vocabulary might look like:
| ID | Token | Notes |
|---|---|---|
| 0 | <pad> | Special: padding |
| 1 | <bos> | Special: beginning of sequence |
| 2 | <eos> | Special: end of sequence |
| 3 | <unk> | Special: unknown (older tokenizers) |
| … | … | |
| 65 | a | Single character |
| 256 | th | Early merge |
| 1,820 | ▁the | Common word with a leading space |
| 4,512 | ing | Common suffix |
| 9,906 | Hello | Capitalized word |
| 23,401 | ▁Hello | The same word with a leading space is a different token |
| 31,999 | ▁photosynthesis | A rarer word that still earned its own entry |
How the vocabulary shapes the model
The vocabulary is more than a lookup file. Its size directly sets the shape of two layers in the model: the first one and the last one.
Input side: the embedding matrix. Each ID points to one row of a learned matrix:
Embedding matrix E (shape: V × d)
V = vocabulary size (e.g. 50,000)
d = embedding dimension (e.g. 4,096)
ID 1820 ("▁the") → row 1820 → [0.12, -0.83, 0.05, … 4,096 numbers]
ID 9906 ("Hello") → row 9906 → [-0.44, 0.31, 0.77, …]
Output side: the prediction layer. At every step, the model gives a score (a logit) to every entry in the vocabulary, and softmax turns those scores into probabilities:
Output layer W_out (shape: d × V)
hidden state (4,096 numbers) → 50,000 scores → softmax → probabilities
P("▁cat") = 0.31
P("▁dog") = 0.22
P("▁car") = 0.04
… one probability per vocabulary entry
The chosen ID is decoded back to text with the vocabulary. So the vocabulary defines everything the model can possibly say at each step.
Weight tying: many models reuse the same matrix for input and output (the output layer is the transpose of E). This saves parameters and links “how a token is understood” with “how it’s predicted.”
Text → [vocab: token → ID] → ID → [embedding row] → Transformer layers
→ [output layer: a score for every vocab entry] → softmax → chosen ID
→ [vocab: ID → token] → Text
Why vocabulary size matters
| Smaller vocab (e.g. 32k) | Larger vocab (e.g. 128k–256k) | |
|---|---|---|
| Tokens per sentence | More | Fewer, so the context window holds more text |
| Embedding + output parameters | Fewer | More (2 × V × d if not tied) |
| Output softmax cost per step | Lower | Higher |
| Multilingual / code efficiency | Weaker | Better |
| Rare-token training | Each token seen often | Some tokens seen rarely, so their embeddings are weaker |
A worked example with V = 128,000 and d = 4,096: 128,000 × 4,096 ≈ 524 million parameters for the embedding matrix alone. That’s a big part of a small model.
The trend in recent LLMs has been toward larger vocabularies (100k+), mainly to handle many languages and code more efficiently.
Important properties
- Fixed after training. You can’t freely swap or reorder entries, because each ID is tied to a learned row. Adding tokens (e.g. for fine-tuning) means adding new rows that start out untrained.
- Model-specific. ID 1820 means one thing in one model and something completely different in another.
- No true “unknown” in byte-level vocabularies. All 256 bytes are included, so any input can be encoded.
- “Glitch tokens.” Sometimes a vocabulary contains strings that were common in the tokenizer’s training data but rare in the model’s. Their embeddings stay barely trained, which can make the model behave strangely when it sees them.
In one line: the vocabulary is a fixed mapping between every token string and an integer ID; each ID points to a learned row on the input side and one output score on the prediction side, so it defines everything the model can read and say.
Is my LLM’s tokenizer related to my embedding model’s tokenizer?
Short answer: they’re separate and independent, though not always different.
Separate and independent: always true in a RAG app. The embedding model and the LLM each run their own tokenizer, at different stages. Nothing passes between them except plain text. The embedding model’s token IDs never reach the LLM, and the LLM never uses the embedding model’s tokenizer. Choosing one doesn’t limit your choice of the other.
Different: usually, but not always. If the two models come from different families (Voyage embeddings with Claude, or OpenAI embeddings with Llama), their tokenizers have different vocabularies and different IDs. But some embedding models are built from an LLM and keep its tokenizer: Qwen3-Embedding uses the Qwen3 tokenizer, and EmbeddingGemma uses the Gemma tokenizer. Pair Qwen3-Embedding with a Qwen3 LLM, and both split text the same way with the same IDs.
Even then, nothing changes in how RAG works. Each model still tokenizes the text on its own, the stored vectors contain no token IDs, and the LLM still only receives plain text. A shared tokenizer is a family resemblance, not a connection between the two models in your app.
The one practical effect is token counting: if the tokenizers differ, the same chunk can count as a different number of tokens against the embedding model’s input limit and the LLM’s context window.
3. Chunks and chunking
Where chunking fits
For text documents, the retrieval side of RAG looks like this:
- Documents are split into chunks (chunking).
- Each chunk is embedded and stored in a vector database such as Qdrant, which indexes the vectors for fast approximate nearest-neighbour search (commonly with an index called HNSW).
- At question time, the question is embedded with the same model. Vectors from different models live in different spaces and can’t be compared.
- The top-k most similar chunks are retrieved and passed to the LLM with the question, so the answer is grounded in your data.
Steps 1 and 2 together are the offline indexing (or ingestion) process.
👉 Read more about Similarity Check: “Cosine similarity explained for RAG developers”
What chunking is, and why we need it
Chunking is splitting large content (documents, PDFs, web pages and so on) into smaller, meaningful, manageable pieces, so they can be embedded, stored and retrieved efficiently. Chunks are created before they’re turned into embeddings.
Why not embed whole documents? Because a real document is rarely about one thing. It’s a sequence of different meanings. A product manual might contain:
- an introduction (what the product is),
- installation steps (how to set it up),
- a troubleshooting section (what to do when it fails),
- warranty terms (legal conditions), and
- a pricing table (numbers).
Each part answers its own kind of question. A user asking “Why does the device keep restarting?” needs the troubleshooting section, not the warranty terms, even though both live in the same file. Chunking separates those parts so each can be found on its own.
On top of that, a knowledge base holds many documents (manuals, policies, FAQs, emails, reports), and chunks from different documents can have the same meaning, different meanings with similar words, complementary meanings, or conflicting meanings. Chunking turns all of them into comparable units that compete in one index and can be combined from many sources to answer one question.
Key idea: A RAG app never retrieves a whole document. It retrieves chunks. Think of a chunk as the unit of retrieval.
Boundaries and size
The quality of your chunks largely sets the ceiling on how good your RAG system can be. Two things matter most: where a chunk starts and ends, and how big it is.
Chunk boundaries
Cuts should fall where the meaning changes: at section, paragraph or topic boundaries. They should not break sentences, list items, tables, code blocks, or separate a question from its answer.
Overlap between neighbouring chunks can soften bad boundaries, but it also creates near-duplicates. It’s a patch, not a substitute for good boundaries.
Chunk size
If one document is split into small, focused chunks and another into big, mixed ones, the small chunks usually score higher (their meaning is sharper), and the big ones tend to lose, even when they hold the answer.
- Too small: precise but missing context, so the answer is often spread across several chunks.
- Too large: plenty of context but imprecise, with several meanings squeezed into one vector and more noise for the LLM.
The right size depends on:
- Content type: FAQ answers are naturally short; a legal clause or a procedure is longer.
- Document structure: headings, sections, paragraphs, topics.
- The embedding model’s input limit and the length it handles best.
Size matters, but mostly as a consequence of meaning, not as a goal in itself.
Chunking strategies
- Fixed size: split every N tokens. A simple baseline that’s easy to implement.
- Fixed size with overlap: repeat part of the previous chunk to reduce lost context. Often called naive chunking.
- Structure-aware (hierarchical): respect headings, sections, paragraphs, tables and code blocks (classes or functions). Often the best choice for technical docs and documents with code.
- Recursive: try splitting by sections, then paragraphs, then sentences, then words. Good for general structured documents.
- Semantic: split where the topic changes, typically by embedding sentences or paragraphs and cutting where similarity drops. Useful for mixed-topic content, but it needs more processing and tuning.
- Sentence window: retrieve one sentence, then add its neighbours. Good for precise facts that need a little context; the window size needs tuning.
How to choose: test, don’t guess
There’s no universal best chunk size. It depends on your documents and your questions, and the way to find out is to measure:
- Write 20 to 30 real questions whose answers you know, and note which document and section holds each answer.
- Chunk your documents two or three ways: say 150, 300 and 500 tokens, or fixed-size versus heading-based.
- For each question, check whether the right passage shows up in the top few results (the top k), and count how often it does. This measure is called recall@k, and it’s cheap to compute.
- Look at the failures. Is the answer split across two chunks? Is the chunk missing its heading? Is it buried in a very long chunk?
- Then check the final answers, to confirm that better retrieval really produced better responses.
Keep your test questions and rerun them whenever you change the chunking or add new kinds of documents. The same test works for comparing embedding models.
Common mistakes
- Using the default chunk size and never testing it. Defaults are reasonable, not tuned to your documents.
- Chunks with no context. A fragment that doesn’t say what it’s about can’t be found.
- Splitting tables and lists down the middle.
- Ignoring document structure that’s already there.
- Making chunks so large that they hold several topics.
- Changing the chunking without re-embedding. Chunks and their embeddings must match, so re-index everything after any change.
- Judging only the final answer and never looking at which chunks were retrieved.
Token vs chunk: A token is a unit of text a model processes, and a word isn’t always exactly one token. A chunk is a retrieval unit you create, and it normally holds many tokens plus metadata (source, page, section heading and so on).
4. How chunks, tokens and budgets fit together
Chunk size is measured in tokens. Here’s why.
Both your LLM and your embedding model work with tokens, each with its own tokenizer and its own IDs. Token 3,797 in your embedding model has nothing to do with token 3,797 in your LLM (unless, as we saw, they come from the same family, like Qwen3-Embedding and a Qwen3 LLM).
A chunk is turned into a vector using the embedding model’s own tokens, and chunk sizes are usually measured in tokens for two reasons:
- The embedding model has an input limit counted in tokens. If a chunk is longer than that limit, it’s often silently cut off before the vector is made, so the end of the chunk is never represented. (Some APIs return an error instead, which is better than silent truncation.)
- Cost. API embedding models charge per token, counted by their own tokenizer.
The LLM’s context window is a token budget too
An LLM’s context window also has a limit counted in tokens, and the retrieved chunks are pasted straight into the prompt. Everything has to fit:
Context window (e.g. 128,000 tokens) must hold: System instructions ~500 tokens + User question ~50 tokens + Retrieved chunks 5 × 800 = 4,000 tokens + Room for the answer ~1,000 tokens
And it isn’t only about fitting: more chunk tokens in the prompt means you pay more and wait longer for every query.
Counting characters or words isn’t precise enough for any of this, because the token count for the same text varies with language, code and formatting. That’s why chunkers usually count tokens with the same tokenizer as the embedding model.
A real-world setup
Here’s the setup I use for proof-of-concept projects:
- Embedding model:
text-embedding-3-small(1,536 numbers per vector). It’s a good balance of quality and very low cost. I use it both for embedding document chunks offline (stored in a Qdrant vector database) and for embedding users’ questions at query time. - LLM:
gpt-4o-mini. A small, cheap model that’s good enough for short, structured tasks. The model name is set in the app’s configuration, so I can switch to a stronger model for answer-writing later without changing any code.
Counting tokens
Since token counts drive limits and cost, you need a reliable way to count them. Counting tokens means running your text through the same tokenizer the model uses and counting the IDs it produces. Every model has its own tokenizer, so a count only means something for a specific model: the same chunk can be 480 tokens for one model and 560 for another.
There are two ways to get the count:
- Locally, before sending: load the model’s tokenizer and take the length of the encoded output. Fast, free, and ideal for sizing chunks during preprocessing.
- From the provider: use a dedicated counting endpoint before the call, or read the usage field that comes back with every response.
When you count, remember that the limit covers everything the model receives, not just your chunk text:
- special tokens such as
[CLS],<s>or end-of-sequence markers, - instruction prefixes (e.g.
"query: "or a task instruction), and - for an LLM: the system prompt, the user question, all retrieved chunks, and the room reserved for the answer.
If you can’t get the exact tokenizer, estimate (about 4 characters, or ¾ of a word, per English token), but treat that as a rough guide and leave a safety margin. Code, numbers and non-English text often produce many more tokens.
Tools for counting
- OpenAI models:
tiktoken, OpenAI’s open-source tokenizer library (encodings such ascl100k_baseando200k_base). - Open-weight models (BGE, Jina, Qwen, Llama, Mistral, Sentence-Transformers…): the Hugging Face
transformers/tokenizerslibraries, which load the exact tokenizer withAutoTokenizer.from_pretrained(...). SentencePiece and Mistral’smistral-commoncover models built on those formats. - Hosted providers: Voyage’s
count_tokens()in its Python client, Cohere’s Tokenize endpoint, Google’scountTokensin the Gemini/Vertex SDKs, and Anthropic’s token-counting endpoint for Claude models. - Usage metadata: almost every API reports the actual token count in its response. That’s the authoritative number for billing.
- RAG frameworks wrap these tools in their text splitters: LangChain’s
TokenTextSplitterandRecursiveCharacterTextSplitter.from_tiktoken_encoder(...), LlamaIndex’sTokenTextSplitterandSentenceSplitter, and similar options in Haystack and Semantic Kernel. You setchunk_sizeandchunk_overlapdirectly in tokens. Just make sure the splitter uses the same tokenizer as the model you’ll feed the chunks to.
Gotcha: even one vendor uses different tokenizers
Using a single vendor doesn’t mean a single tokenizer. tiktoken contains several encodings, and OpenAI maps them to models like this:
o200k_base→ gpt-4o, gpt-4o-mini, and newer models such as GPT-4.1 and the o-seriescl100k_base→ gpt-4-turbo, gpt-4, gpt-3.5-turbo, text-embedding-ada-002, text-embedding-3-small, text-embedding-3-large
So even an “all-OpenAI” RAG app needs two different encodings. You can check it yourself:
import tiktoken
embed_enc = tiktoken.encoding_for_model("text-embedding-3-large") # cl100k_base
llm_enc = tiktoken.encoding_for_model("gpt-4o") # o200k_base
chunk = "Your chunk text here..."
print(len(embed_enc.encode(chunk))) # count against the embedding model's 8,191-token limit
print(len(llm_enc.encode(chunk))) # count against the LLM's context window
The two numbers will usually be a little different for the same text. That’s “two tokenizers, two token budgets” in practice.
5. Encodings vs embeddings: the last confusing pair
What an “encoding” is
In tiktoken’s terms, an encoding (like cl100k_base or o200k_base) is a specific trained rulebook for splitting text into tokens. The tokenizer is the program that follows the rulebook. Tokens and token IDs are what come out.
Other libraries call the same thing a “tokenizer model,” a “vocabulary” or simply a “tokenizer file” (e.g. tokenizer.json on Hugging Face). When people say “GPT-4o’s tokenizer,” they usually mean both the rulebook and the program, e.g. tiktoken running o200k_base.
An analogy: BPE is the method of looking words up in a dictionary, tiktoken is the person doing the lookup, and
cl100k_baseando200k_baseare two different editions of the dictionary. Give the same person the same sentence and a different edition, and you get different results.
What’s inside an encoding
An encoding like o200k_base contains three things:
- A splitting pattern: a rule that first cuts text into rough pieces (words, numbers, punctuation, spaces). It decides things like whether a space stays attached to the following word, or how long runs of digits are handled.
- The vocabulary with its IDs, in merge order: the vocabulary we discussed above. For BPE, the order also tells the tokenizer which pieces to merge first.
- Special tokens: reserved markers that never come from normal text, like
<|endoftext|>, used to mark the end of a document or the structure of a chat.
The names roughly describe the vocabulary size: cl100k_base has about 100,000 tokens and o200k_base about 200,000. (“o200k” arrived with GPT-4o; “base” means the core set before extra special tokens are added. That’s how o200k_harmony extends o200k_base for gpt-oss.)
How an encoding is made
An encoding is learned from data before the model is trained, using BPE:
- Start with the smallest building blocks: the 256 possible bytes, so any text in any language can be represented.
- Scan a huge sample of text and find the pair of pieces that appears together most often (say
t+h). Merge them into a new token,th. - Repeat:
th+e→the, then +the→the, and so on. - Stop when the vocabulary reaches the target size (100k, 200k).
Common words end up as a single token; rare words get split into several pieces. That’s why the encoding’s training text matters. o200k_base was built with much more non-English text than cl100k_base, so it usually needs fewer tokens for languages like Swedish, Arabic or Hindi.
Two lookup tables, one handover point
Encodings and embeddings sound alike but are different things: two separate lookup tables, used one after the other, connected only by the token ID.
Table 1: the encoding (e.g. o200k_base). It answers “Which number is this piece of text?”
- Input: a piece of text, e.g.
" cat" - Output: a number, e.g.
1 - Contains no meaning, just text pieces and their numbers, like a phone book.
- It’s a file used by the tokenizer, outside the neural network.
Table 2: the embedding table. It answers “What does number 1 mean?”
- Input: a number, e.g.
1 - Output: a list of numbers describing meaning, e.g.
[0.8, 0.1, -0.3] - Contains no text at all, just rows of numbers.
- It’s inside the model, as its first layer.
The token ID is the handover point: the encoding produces it, and the embedding table uses it as a row number.
A tiny worked example
Imagine a toy model with only 6 tokens.
The encoding (text → ID):
| Text piece | Token ID |
|---|---|
the | 0 |
cat | 1 |
sat | 2 |
kit | 3 |
ten | 4 |
. | 5 |
The embedding table (ID → meaning vector), 3 numbers per row:
| Row (= token ID) | Embedding |
|---|---|
| 0 | [0.0, 0.2, 0.1] |
| 1 | [0.8, 0.1, -0.3] |
| 2 | [-0.2, 0.7, 0.4] |
| 3 | [0.6, 0.0, -0.1] |
| 4 | [0.5, 0.2, -0.4] |
| 5 | [0.0, 0.0, 0.9] |
Processing “the cat sat.”:
Step 1 – Tokenizer splits: "the" | " cat" | " sat" | "." Step 2 – Encoding gives IDs: 0 1 2 5 Step 3 – Table rows: row 0, row 1, row 2, row 5 Step 4 – Result: [0.0, 0.2, 0.1], [0.8, 0.1, -0.3], [-0.2, 0.7, 0.4], [0.0, 0.0, 0.9]
Steps 1–2 use only the encoding. Steps 3–4 use only the embedding table. The IDs (0, 1, 2, 5) are all that passes between them.
Separate, but they must match
The two tables must agree in two ways:
- Same size. The embedding table has exactly one row per token in the encoding. Our toy encoding has 6 tokens, so the table has 6 rows.
o200k_basehas about 200,000 tokens, so GPT-4o’s embedding table has about 200,000 rows. - Same numbering. Row 1 only means “cat” because the encoding gave
" cat"the ID 1. The row itself has no idea what text it belongs to.
And they’re made at different times, in different ways:
- The encoding comes first, before the model exists, by counting which text pieces occur most often. Pure statistics, no meaning involved.
- The embedding table comes second, during model training. It starts as random numbers, and training gradually adjusts each row so tokens used in similar ways get similar vectors.
The encoding decides which rows exist and how they’re numbered. Training decides what numbers go in each row.
This is also why GPT-4o, whose embedding table was trained with o200k_base IDs, would read nonsense if you fed it cl100k_base IDs: every ID would point to the wrong row. And it’s why you must count text-embedding-3-large tokens with cl100k_base, even if your LLM uses o200k_base.
Same first steps, different final step
This encoding-to-table step happens at the very start of every model, LLM or text embedding model. What differs is what happens afterwards:
| LLM | Text embedding model | |
|---|---|---|
| Step 1: encoding → IDs | Same | Same |
| Step 2: IDs → rows of the embedding table | Same | Same |
| Step 3: transformer layers add context | Same idea | Same idea |
| Step 4: final step | Predicts the next token, using the vocabulary again to pick what to output | Combines all the token vectors into one vector for the whole text |
| What you get | Generated text | One vector, usually stored in a vector database |
So the vector in your database is not a row from the embedding table. It’s built from those rows, after the layers have processed them and they’ve been combined into one. That’s also why the final vector’s length can differ from the table’s row width: some models add a final projection, and models with MRL let you shorten the output (e.g. from 3,072 to 1,024 numbers).
Two smaller differences:
- The tokenizer method varies. OpenAI models use BPE with tiktoken encodings. Other embedding models use other methods: all-MiniLM uses WordPiece (BERT’s 30,522-token vocabulary), while BGE-M3 and jina-v3 use SentencePiece (XLM-RoBERTa’s vocabulary of about 250,000 tokens). “Encoding” is tiktoken’s word, but the idea is the same everywhere: a fixed vocabulary that turns text into IDs, matched to the model’s embedding table.
- The output side. An LLM uses its vocabulary at the end too, to turn its prediction back into text. A text embedding model uses the vocabulary only at the start; its output is a vector, not tokens.
The whole chain
BPE (the method) → trained on lots of text → produces an encoding like
o200k_base(the rulebook) → tiktoken (the program) applies it to your text → tokens and token IDs → the IDs pick rows from the model’s embedding table.
In short: an encoding is one specific, trained tokenizer vocabulary plus its splitting rules. The tokenizer library runs it, tokens and IDs are its output, and each model is permanently tied to the encoding it was trained with.
TL;DR: a glossary for your first RAG project
- Token: a small piece of text (word, part of a word, punctuation) with an ID. Limits and prices are counted in tokens.
- Tokenizer: the program that turns text into token IDs and back. Every model has its own.
- Encoding: tiktoken’s name for a tokenizer’s trained rulebook (
cl100k_base,o200k_base). - Vocabulary: the fixed list of every token a model knows, each with an ID.
- Token embedding table: a grid inside every model with one learned vector per vocabulary entry. The token ID is the row number.
- Hidden states / contextual embeddings: per-token vectors after the model’s layers have added context.
- Text embedding: one vector for a whole chunk or question. The only “embedding” your RAG app stores and searches.
- Embedding model: the model that produces text embeddings. Separate from your LLM, and can come from any vendor.
- Chunk: a piece of a document you create; the unit of retrieval. Sized in tokens.
- Top-k / recall@k: retrieving the k closest chunks / how often the right chunk is among them.
Three rules that save the most pain:
- Same embedding model for documents and questions, always. Switching means re-embedding everything.
- Your LLM never sees your vectors, only text. So mix vendors freely.
- Count tokens with the right tokenizer for each model, and test your chunking with real questions.
Reference: the numbers behind the models
If you want to see real figures for the concepts above, here they are. Treat them as a snapshot: vendors update models often, so check the official docs before you rely on a number.
LLM token embedding tables
Open-weight models
| Model (lab) | Vocabulary size | Tokenizer | Embedding dimension | Training approach | Embedding table size |
|---|---|---|---|---|---|
| DeepSeek-V3 / R1 (DeepSeek) | 129,280 | Byte-level BPE | 7,168 | Next-token pre-training → SFT → RL with GRPO (R1) | ≈ 0.93 B |
| DeepSeek-V4-Pro / Flash (DeepSeek, 2026) | 129,280 | Byte-level BPE (same as V3) | 7,168 / 4,096 | Pre-training → expert models trained with SFT + GRPO → merged by distillation | ≈ 0.93 B / 0.53 B |
| gpt-oss-120b / 20b (OpenAI) | 201,088 | o200k_harmony (BPE, tiktoken) | 2,880 | Next-token pre-training → reasoning post-training (SFT + RL) | ≈ 0.58 B |
| Llama 4 Scout / Maverick (Meta) | 202,048 | BPE (tiktoken-style) | 5,120 | Next-token pre-training (multimodal) → SFT → RL → DPO | ≈ 1.03 B |
| Qwen3 (Alibaba), e.g. 235B-A22B | 151,936 | Byte-level BPE | 4,096 (235B MoE); varies by size | Next-token pre-training → SFT + reasoning RL + general RL | ≈ 0.62 B |
| Gemma 3 (Google), e.g. 27B | 262,144 | SentencePiece (same as Gemini) | 5,376 (27B) | Pre-training with distillation from a larger teacher → SFT + RL | ≈ 1.41 B |
| Kimi K2 (Moonshot AI) | 163,840 (“160K”) | BPE (tiktoken-style) | 7,168 | Pre-training with the MuonClip optimizer → SFT + RL | ≈ 1.17 B |
| Mistral (Mistral AI): Small/Medium 3 · Large 4 | 131,072 · 204,800 | Tekken (BPE, tiktoken-based) | 5,120 (Small 3) · 6,144 (Large 4) | Next-token pre-training → SFT + preference/RL tuning | ≈ 0.67 B · 1.26 B |
Closed frontier models
| Model (lab) | Vocabulary size | Tokenizer | Embedding dimension | Training approach |
|---|---|---|---|---|
| GPT-4o / o-series / GPT-5 (OpenAI) | ~200k (o200k family) | BPE (tiktoken) | Not disclosed | Pre-training → SFT → RLHF and large-scale RL for reasoning |
| Claude (Anthropic) | Not disclosed | Not disclosed | Not disclosed | Pre-training → SFT → RLHF + Constitutional AI (RL from AI feedback) |
| Gemini (Google) | ~262k (shared with Gemma 3) | SentencePiece | Not disclosed | Pre-training → SFT → RLHF |
How to read these tables
- Exact numbers are public only for open-weight models, which publish their configuration files. The big closed models don’t disclose vocabulary size, embedding dimension or full training details.
- “Embedding dimension” here means the model’s hidden size, i.e. the length of each row in the embedding table. The last column multiplies vocabulary size by embedding dimension to show how many numbers the table holds.
Where the figures come from
- DeepSeek: V3’s reference config lists
vocab_size129,280 andhidden_size7,168; GRPO is the RL algorithm used for R1-Zero and R1. V4-Pro reuses V3’s backbone shape (hidden size 7,168, 61 layers, 128 attention heads), while V4-Flash uses 4,096. In V4’s post-training, domain experts get SFT and GRPO (with verifiers and generative rewards) and are then combined through on-policy distillation. - gpt-oss: OpenAI’s model card describes
o200k_harmonyas a BPE tokenizer that extends the o200k tokenizer used by GPT-4o and o4-mini, with 201,088 tokens in total, and a residual stream dimension of 2,880. - Llama 4: the Transformers config lists
vocab_size202,048 andhidden_size5,120. - Qwen3: published configs show
hidden_size4,096 andvocab_size151,936. The tokenizer goes back to the first Qwen report, which used BPE starting from tiktoken. - Gemma 3 / Gemini: the Gemma 3 report says it shares Gemini 2.0’s tokenizer (a redesigned 262k vocabulary) and that the models are trained with distillation. The 27B hidden size of 5,376 is from its published config.
- Kimi K2: 160K vocabulary, hidden dimension 7,168, pre-trained on 15.5 trillion tokens with the MuonClip optimizer.
- Mistral: Mistral 3-family configs show
hidden_size5,120 andvocab_size131,072; NVIDIA’s config for Mistral Large 4 lists 6,144 and 204,800. - OpenAI closed models:
o200k_baseis used by GPT-4o, o3-mini, o4-mini and many other recent OpenAI models. OpenAI hasn’t formally documented which tokenizer each GPT-5 version uses.
Patterns worth noticing
- The training recipe is broadly the same everywhere. Pre-training on trillions of tokens to predict the next token, then post-training with SFT (supervised fine-tuning on example answers) and reinforcement learning: RLHF (human preferences), DPO (a simpler preference method), or GRPO / RLVR (RL with automatically checkable rewards, used for reasoning). The embedding table is learned during pre-training along with everything else.
- Vocabularies have grown. Early LLMs used 32k–50k tokens; today’s use roughly 130k–260k, mainly for many languages and code.
- The embedding table is a meaningful share of the model, around 0.5–1.4 billion numbers. That’s a lot for a small model, but a small fraction of one with hundreds of billions of parameters.
- Embedding dimension doesn’t grow with total size in MoE models. DeepSeek-V4-Pro has 1.6 trillion parameters but the same 7,168 embedding dimension as V3; most of the growth goes into the expert layers.
Remember: these are LLM embedding tables (token embeddings inside generative models). The text-embedding models used for RAG are separate models with their own output dimensions, covered next.
Text embedding models for RAG
These models turn a whole chunk of text into one vector; they don’t generate text.
Commercial (API) embedding models
| Model (provider) | Tokenizer / vocabulary | Output dimension | Max input tokens | Training approach |
|---|---|---|---|---|
| text-embedding-3-large / -small (OpenAI) | cl100k_base BPE (~100k) | 3,072 / 1,536 (MRL, can shorten) | 8,191 | Not published in detail; contrastive training, MRL |
| Embed v4 (Cohere) | Cohere’s own BPE (size not disclosed) | 1,536 default; 256 / 512 / 1,024 (MRL) | ~128,000 | Not published in detail; multimodal (text + images) |
| voyage-4 / -4-large / -4-lite (Voyage AI, now MongoDB) | Voyage’s own (published on Hugging Face) | 1,024 default; 256 / 512 / 2,048 (MRL) | 32,000 | Matryoshka + quantization-aware training |
| gemini-embedding-001 (Google) | Gemini SentencePiece (size not published) | 3,072 default (MRL) | 2,048 | Built from Gemini; contrastive fine-tuning, MRL |
| Gemini Embedding 2 (Google, 2026) | Gemini tokenizer | Up to 3,072 (MRL, 128–3,072) | 8,192 | Multimodal (text, image, video, audio, PDF), MRL |
| Titan Text Embeddings V2 (Amazon Bedrock) | Amazon’s own (not published) | — | 8,192 tokens or 50,000 characters | Not published |
| mistral-embed (Mistral AI) | Mixtral SentencePiece BPE (32k) | 1,024 | 8,192 | Not published |
Open-weight embedding models
| Model (lab) | Tokenizer / vocabulary | Output dimension | Max input tokens | Training approach |
|---|---|---|---|---|
| Qwen3-Embedding 0.6B / 4B / 8B (Alibaba) | Qwen3 byte-level BPE (~152k) | 1,024 / 2,560 / 4,096 (adjustable) | 32,768 | Built on the Qwen3 LLM: weakly supervised contrastive pre-training on LLM-generated synthetic pairs → supervised fine-tuning → model merging |
| BGE-M3 (BAAI) | XLM-RoBERTa SentencePiece (~250k) | 1,024 (+ sparse and multi-vector outputs) | 8,192 | RetroMAE pre-training → contrastive learning → unified fine-tuning with self-knowledge distillation |
| jina-embeddings-v3 (Jina AI) | XLM-RoBERTa SentencePiece (~250k) | 1,024 (MRL down to 32) | 8,192 | Contrastive training with task-specific LoRA adapters |
| EmbeddingGemma (Google) | Gemma 3 SentencePiece (~262k) | 768 (MRL down to 128) | 2,048 | Built on Gemma 3; contrastive training, MRL |
| EmbeddingGemma 2 (Google) | Gemma tokenizer | 768 (MRL 128–768) | 8,192 (text) | Built on Gemma 4; multimodal |
| all-MiniLM-L6-v2 (Sentence-Transformers) | BERT WordPiece, uncased (~30.5k) | 384 | 256 (default truncation) | Contrastive fine-tuning on ~1B sentence pairs |
Model notes
- OpenAI: text-embedding-3-small produces 1,536 dimensions and -large 3,072. Both date from 2024.
- Cohere: Embed v4 supports Matryoshka dimensions of 256, 512, 1,024 and 1,536.
- Voyage: voyage-4 supports 256–2,048 dimensions with several quantization options. Unusually, all 4-series models produce compatible embeddings.
- Google: gemini-embedding-001 uses MRL to scale down from 3,072 dimensions. Gemini Embedding 2 raises the input limit to 8,192 tokens, with 768, 1,536 and 3,072 recommended as output sizes.
- Mistral: mistral-embed returns a 1,024-dimension vector regardless of text length.
- Qwen3-Embedding: comes in 0.6B, 4B and 8B sizes. The Qwen3 LLMs serve both as backbones and as generators of synthetic training data. The 0.6B model supports custom output sizes from 32 to 1,024.
- BGE-M3: does dense, sparse and multi-vector retrieval in one model, and was further pre-trained with RetroMAE.
- jina-embeddings-v3: 570 million parameters; MRL lets you go from 1,024 down to 32 dimensions with little loss. It also supports late chunking.
- EmbeddingGemma: a 308M-parameter multilingual model based on Gemma 3, with a 2K context. EmbeddingGemma 2 (740M parameters, built on Gemma 4) maps text, images, audio and video into one 768-dimension space.
- all-MiniLM-L6-v2: maps text to 384 dimensions; it was fine-tuned with a contrastive objective on about 1 billion sentence pairs.
Input limits and tokenizer details for each model are in the next table.
Text embedding models: tokenizers, limits and token counting
This table brings together what you need when sizing chunks: which tokenizer each model uses, its input limit, and how to count tokens for it.
| Model (provider) | Tokenizer | Max input tokens | How to count tokens |
|---|---|---|---|
| text-embedding-3-small / -3-large (OpenAI) | cl100k_base (byte-level BPE, ~100k vocab) | 8,191 | tiktoken: tiktoken.get_encoding("cl100k_base") |
| Embed v4 (Cohere) | Cohere’s own BPE tokenizer | 128k | Cohere Tokenize API: co.tokenize(text=..., model=...) |
| voyage-4 / voyage-4-large / voyage-code-4 (Voyage AI) | Voyage’s own tokenizer (published on Hugging Face) | 32,000 | voyageai.Client().count_tokens(texts, model=...), or AutoTokenizer.from_pretrained("voyageai/voyage-4-large") |
| gemini-embedding-001 (Google) | Gemini SentencePiece tokenizer | 2,048 per text | countTokens in the Gemini SDK; Vertex AI also returns statistics.token_count in each embedding response |
| Titan Text Embeddings V2 (Amazon Bedrock) | Amazon’s own (not published) | 8,192 tokens or 50,000 characters | No public tokenizer: read inputTextTokenCount from the response after the call, and estimate beforehand from characters |
| mistral-embed (Mistral) | Mistral/Mixtral SentencePiece BPE (32k vocab) | 8,192 | mistral-common, or Hugging Face tokenizers with mistralai/Mixtral-8x7B-v0.1 |
| jina-embeddings-v3 (Jina AI, open weights) | XLM-RoBERTa SentencePiece (~250k vocab) | 8,192 | AutoTokenizer.from_pretrained("jinaai/jina-embeddings-v3") |
| BGE-M3 (BAAI, open weights) | XLM-RoBERTa SentencePiece (~250k vocab) | 8,192 | AutoTokenizer.from_pretrained("BAAI/bge-m3") |
| Qwen3-Embedding 0.6B / 4B / 8B (Alibaba, open weights) | Qwen byte-level BPE (~151k vocab) | 32,768 | AutoTokenizer.from_pretrained("Qwen/Qwen3-Embedding-0.6B") |
| all-MiniLM-L6-v2 (Sentence-Transformers, open weights) | BERT WordPiece, uncased (~30.5k vocab) | 256 (default truncation) | AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2"), or model.tokenizer |
Notes behind the numbers
- OpenAI: text-embedding-3-small and -large accept 8,191 tokens counted with
cl100k_base, and going over that limit returns an error rather than truncating. OpenAI’s help center confirms thatcl100k_baseis the encoding to use for its third-generation embedding models. - Cohere: Embed v4 accepts up to 128k tokens, and its Tokenize endpoint splits text with byte-pair encoding (BPE). Even so, smaller chunks usually give better retrieval and lower cost in RAG.
- Voyage: the voyage-4 family accepts 32,000 tokens. Its tokenizer isn’t tiktoken: on average it produces 1.1–1.2× as many tokens, so don’t use tiktoken to size Voyage chunks.
- Google: gemini-embedding-001 limits each input text to 2,048 tokens and silently truncates anything longer, unless you set
autoTruncateto false. With the smallest limit in the table, Gemini embeddings need fairly small chunks. - Amazon Titan V2: takes up to 8,192 tokens or 50,000 characters. AWS gives about 4.7 characters per token for English, which helps you estimate before sending.
- Mistral: mistral-embed accepts 8,192 tokens and uses the same tokenizer as the first Mixtral model.
- Jina v3: built on XLM-RoBERTa, it uses Rotary Position Embeddings (RoPE) to handle inputs of up to 8,192 tokens.
- BGE-M3: handles anything from short sentences to documents of 8,192 tokens, after extending XLM-RoBERTa’s maximum length to 8,192.
- Qwen3-Embedding: all three sizes (0.6B, 4B, 8B) have a 32K sequence length.
- all-MiniLM-L6-v2: truncates input beyond 256 word pieces by default. Raising the limit doesn’t help: in a maintainer’s benchmark, going to 512 took almost twice as long and scored slightly worse, because the model was trained on shorter inputs.
Code to count tokens for each type of model
# 1) OpenAI → tiktoken
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
n = len(enc.encode(chunk))
# 2) Open-weight models (BGE-M3, Jina, Qwen3, MiniLM, Voyage's HF tokenizer...) → Hugging Face
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("BAAI/bge-m3")
n = len(tok.encode(chunk, add_special_tokens=True)) # include special tokens: they count toward the limit
# 3) Voyage → official client
import voyageai
n = voyageai.Client().count_tokens([chunk], model="voyage-4-large")
# 4) Cohere → Tokenize API
import cohere
n = len(cohere.ClientV2().tokenize(text=chunk, model="embed-v4.0").tokens)
Practical takeaways for token counting
- Count with the model’s own tokenizer. The same chunk gives different counts across models (cl100k vs XLM-RoBERTa vs Voyage), so a 500-token chunk for OpenAI isn’t 500 tokens for BGE-M3.
- Watch out for silent truncation. Gemini, MiniLM and Hugging Face pipelines with
truncation=Truedrop the excess without an error, so the end of your chunk is simply ignored. OpenAI returns an error instead. - Leave a safety margin. Special tokens (
[CLS],<s>,<|endoftext|>) and any instruction prefix count toward the limit. Aim for about 90% of the limit at most. - A big limit isn’t a target chunk size. A model that accepts 32k or 128k tokens can still retrieve better with chunks of a few hundred tokens, for the reasons covered in the chunking section.
Five takeaways from these tables
- Almost all of them are trained with contrastive learning. The model sees a question with the passage that answers it (a positive) and many unrelated passages (negatives), and learns to pull the matching pair together and push the rest apart. Modern models do this in stages: first on huge amounts of loosely matched pairs, then on a smaller, high-quality set with hard negatives (passages that look relevant but aren’t).
- Many modern embedding models are built from LLMs. Qwen3-Embedding from Qwen3, EmbeddingGemma from Gemma, Gemini Embedding from Gemini. They inherit the LLM’s tokenizer and token embedding table, and contrastive training teaches them to produce one good vector per text. Older models like BGE-M3 and jina-v3 are built on encoder models (XLM-RoBERTa) instead.
- MRL (Matryoshka Representation Learning) makes the dimension flexible. Like Russian nesting dolls, the model is trained so the first numbers in the vector carry the most important meaning. You can keep only the first 256 or 768 of 3,072 numbers and still get good results with much less storage.
- “Max input tokens” is your chunk-size ceiling, from 256 (all-MiniLM) to about 128,000 (Cohere Embed v4). A high limit doesn’t mean huge chunks work best, and since each model has its own tokenizer, the same chunk counts differently in each.
- Vectors from different models can’t be mixed. You can’t compare an OpenAI vector with a Cohere vector, or even a 3,072-dimension vector with a 1,536-dimension one. Switch embedding models and you re-embed everything. Voyage’s 4-series is the rare exception.
Wrapping up
Most of the confusion around RAG comes from a handful of words doing double duty. Once you see that your app has two separate models (a librarian and a writer) that share nothing but plain text, and that everything in between is measured in tokens counted by each model’s own tokenizer, the pieces fall into place.
From there, the real work is the unglamorous part: choosing the right documents, parsing them cleanly, chunking them along their natural boundaries, and testing retrieval with real questions before you tune anything else.
Happy building!
That’s it for now! I hope you enjoyed it!
Thanks for reading and stay tuned!
