Skip to content

LLM Field Guide 01 — How an LLM Reads Text: Next-Token Prediction, Tokens, and Embeddings

An LLM is a function that takes a list of integers and returns a probability for every possible next token, then gets called in a loop. It never sees your text: a tokenizer turns it into IDs, and an embedding table turns those IDs into vectors. Those three pieces (the loop, the tokens, the vectors) decide your bill, your context budget, and a surprising number of the model's "dumb" mistakes.

In this post:

  • Next-token prediction — the one idea everything else is built on
  • What's inside the box — the pipeline from text to probabilities
  • What "large" means — parameters, data, and the memory they cost
  • Three eras of language models — why the Transformer won
  • Base model vs assistant — what post-training adds
  • "Emergent abilities" — real, or a measurement artifact?
  • What an LLM is not — four misconceptions that cause production bugs
  • API vs local — two ways to call the same loop
  • Tokens — chunks of bytes, not words
  • BPE — how a vocabulary gets built
  • Vocabulary size and the language tax — why Thai costs more than English
  • Token artifacts, special tokens, and chat templates
  • Counting tokens in production
  • Embeddings — from token IDs to vectors
  • Contextual hidden states — why bank needs the rest of the model
  • Sentence embeddings — the different model RAG uses
LLM Field Guide — all 12 posts
  1. How an LLM reads text ← you are here
  2. Inside the transformer
  3. Training and generation
  4. KV cache and long context
  5. Prompting, context, and RAG
  6. Reasoning models and agents
  7. Choosing a base model
  8. Adapting a model
  9. Making it smaller and faster
  10. Serving at scale
  11. Safety and evaluation
  12. Putting it all together

The one idea: predict the next token

Your phone keyboard suggests "home" after "I'm on my way". It learned which words tend to follow which — that's a language model. An LLM does the same thing at absurd scale. It learns one conditional probability:

P(next token | all previous tokens)

P(" mat"  | "The cat sat on the")  → high
P(" sofa" | "The cat sat on the")  → medium
P(" moon" | "The cat sat on the")  → low

There's no database of facts and no lookup table of answers. Whatever the model "knows" is encoded in the numbers that produce those probabilities.

Generation is that prediction in a loop

To write a paragraph, the model predicts one token, appends it to the input, and predicts again:

input:  "The cat sat"            → model → pick " on"
input:  "The cat sat on"         → model → pick " the"
input:  "The cat sat on the"     → model → pick " mat"
input:  "The cat sat on the mat" → model → pick "."
... until it emits an end-of-sequence token or hits max_tokens

This is autoregressive generation, and it explains three things you'll hit in practice:

  • Output is slower than input. The prompt is processed in one parallel pass; output comes one token per forward pass. That's why APIs price output tokens higher (post 04 explains the hardware reason).
  • Answers vary run to run. Each step samples from the distribution; temperature and top-p are covered in post 03.
  • Early mistakes compound. Once a wrong token is emitted, every later token is conditioned on it.

See the probabilities behind one token

Here's the whole idea in 15 lines. Qwen3-0.6B runs on a laptop CPU:

pip install "torch>=2.6" "transformers>=5.0"
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "Qwen/Qwen3-0.6B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)

ids = tok("The cat sat on the", return_tensors="pt").input_ids
with torch.no_grad():
    logits = model(ids).logits[0, -1]          # scores for the NEXT token only
probs = torch.softmax(logits, dim=-1)

top = torch.topk(probs, 5)
for p, i in zip(top.values, top.indices):
    print(f"{tok.decode(i)!r:>10}  {p.item():.3f}")

You'll see ' mat' and a few other furniture-and-floor words near the top; exact numbers depend on the model version. The output is a full distribution over ~152K vocabulary entries, not one answer7. Picking from it is a separate step.

Keep this script

Change the prompt to "The capital of Thailand is" and watch the probability mass concentrate. Change it to "My favorite color is" and watch it spread. That spread is what "uncertainty" means for an LLM.

What's inside the box

The model is a pipeline. This post covers the top two boxes; the rest of the series zooms into the others:

 "The cat sat"
      │
      ▼
 ┌──────────────┐  text → integer IDs                          this post
 │  Tokenizer   │  "The"→785  " cat"→8251  " sat"→7578  (Qwen3)
 └──────┬───────┘
        ▼
 ┌──────────────┐  each ID → a vector of 4,096 numbers         this post
 │  Embedding   │
 └──────┬───────┘
        ▼
 ┌──────────────┐  ×36 layers in Qwen3-8B                      post 02
 │ Transformer  │   ├─ Attention: tokens read each other
 │    block     │   │   (with position info, RoPE)
 │              │   └─ Feed-forward: per-token processing
 └──────┬───────┘
        ▼
 ┌──────────────┐  vector → one score per vocab entry          post 03
 │  LM head     │  → softmax → probabilities
 └──────┬───────┘
        ▼
 ┌──────────────┐  pick one token, append, repeat              post 03
 │  Sampler     │
 └──────────────┘

The weights inside those boxes come from training: showing the model trillions of tokens and nudging every number to make the true next token more likely (post 03).

What "large" actually means

"Large" counts parameters: the learned numbers in the weight matrices. More parameters means more capacity to store patterns, and more memory and compute to run.

Model Year Parameters Context window Training tokens
GPT-2 2019 1.5B2 1,024 —
GPT-3 2020 175B3 2,048 ~300B
Llama 3.1 405B 2024 405B dense4 128K 15T+5
DeepSeek-V3 2024 671B total / 37B active per token6 128K 14.8T
Qwen3-8B 2025 8.2B8 32K native —

Two trends stand out:

  • Training data grew faster than parameters. GPT-3 saw roughly 1.7 tokens per parameter; Llama 3 models saw thousands. Small models trained far longer now beat old large ones.
  • "Total" and "active" parameters split apart. DeepSeek-V3 stores 671B parameters but uses only 37B per token. That's Mixture of Experts (post 09).

Memory follows directly from the count: 8.2B parameters × 2 bytes (BF16) ≈ 16.4 GB just to hold the weights. Two-thirds of those weights sit in feed-forward layers, not attention; post 02 counts them layer by layer.

How we got here: three eras of language models

The Transformer fixed two specific problems with what came before.

Era Approach How far back it can "see" Fatal flaw
1990s–2000s n-gram counting 2–5 words Can't connect "bank" to a word 10 tokens earlier
2010s RNN / LSTM with a hidden state In theory unlimited Forgets over long ranges; processes tokens one after another, so training is slow
2017→ Transformer with attention The whole context window Cost grows with context length

The n-gram problem in one line:

"The bank where I deposited my salary last Tuesday is ____"
 needs "bank" = financial institution — 9 words back, outside any 5-gram window

The RNN squeezed everything it had read into one fixed-size hidden vector, passed left to right. The learning signal faded over long sequences (vanishing gradients), and you couldn't compute token 50 before token 49, so GPUs sat idle.

The 2017 paper "Attention Is All You Need" dropped recurrence entirely1. Every token looks directly at every other token in one parallel step. Parallel training is what made scaling to trillions of tokens practical.

From base model to the assistant you chat with

A model fresh out of pretraining is a base model. It continues text; it doesn't follow instructions. Ask it "What is the capital of France?" and it may reply with three more quiz questions, because that's how quiz text continues on the web.

Stage What it teaches Data Post
Pretraining Language, facts, patterns, code Trillions of raw web/book/code tokens 03
Continued pretraining (optional) A new language or domain Billions of domain tokens 08
Supervised fine-tuning (SFT) Follow instructions, use a chat format 10K–1M prompt→response pairs 08
Preference / RL tuning Be helpful, honest, safe; reason through problems Ranked answers, verifiable rewards 08

The alignment stages punch far above their weight. In OpenAI's InstructGPT work, human raters preferred outputs from a 1.3B model tuned this way over the 175B GPT-3 base model9.

"Emergent abilities": real, or a measurement artifact?

You'll read that abilities like multi-step arithmetic "suddenly appear" past some model size. Wei et al. (2022) documented tasks where performance sat near random for small models and then jumped at scale10.

Treat that framing with caution. Schaeffer et al. (2023) showed that many of those jumps come from the metric, not the model11. Exact-match scoring gives zero credit until every token is right, which turns smooth improvement into a cliff. With continuous metrics, most "emergent" curves become gradual.

The builder's takeaway: capability scales smoothly with compute, data, and parameters, but your pass/fail benchmark may not show it smoothly. Keep that in mind when you evaluate your own fine-tunes (post 11).

What an LLM is not

Getting these wrong causes most early production mistakes:

  • Not a database. It reconstructs facts from compressed patterns, which is why it hallucinates plausible-but-wrong details. The fix for fresh or private facts is retrieval (post 05).
  • Not stateful. Every API call starts blank. "Memory" in chat apps is the app resending the conversation into the context window (post 04, post 05).
  • Not reading words. It reads tokens, which is why it miscounts letters in "strawberry" and why Thai costs more than English (below).
  • Not acting on its own. It only emits text. Code runs and APIs get called because your code parses the output and executes it (post 06).

Two ways to call one: API vs local

Same loop, two deployment models. A hosted API call (Anthropic Python SDK):

from anthropic import Anthropic

client = Anthropic()  # reads ANTHROPIC_API_KEY
msg = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=512,
    messages=[{"role": "user", "content": "Explain next-token prediction in two sentences."}],
)
print(msg.content[0].text)
print(msg.usage.input_tokens, "in /", msg.usage.output_tokens, "out")

The same request against a local open-weight model on vLLM's OpenAI-compatible server:

pip install vllm
vllm serve Qwen/Qwen3-8B --max-model-len 32768

curl -s localhost:8000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{"model":"Qwen/Qwen3-8B",
       "messages":[{"role":"user","content":"Explain next-token prediction in two sentences."}],
       "max_tokens":512}' | jq -r '.choices[0].message.content'
Hosted API Self-hosted open weights
Quality ceiling Frontier models Strong and closing; depends on size (post 07)
Data control Leaves your network Stays on your hardware
Cost shape Per token Per GPU-hour, idle or busy
Customization Prompting, some fine-tuning Full control: fine-tune, quantize, distill (post 08, post 09)
Ops burden None Serving, scaling, monitoring (post 10)

The blog's real 30-day cost breakdown puts numbers on the right-hand column.

Tokens: chunks of bytes, not words

Tokenization: text is split into subword chunks, each mapped to an integer ID

A tokenizer is a fixed lookup table plus a splitting algorithm. It cuts text into chunks called tokens and replaces each with its row number in the table, the token ID. Here's OpenAI's tiktoken with the o200k_base vocabulary used by GPT-4o-era models12:

# pip install tiktoken==0.14.0
import tiktoken

enc = tiktoken.get_encoding("o200k_base")
ids = enc.encode("The cat sat on the mat")
print(ids)                               # [976, 9059, 10139, 402, 290, 2450]
print([enc.decode([i]) for i in ids])    # ['The', ' cat', ' sat', ' on', ' the', ' mat']
print(enc.n_vocab)                       # 200019

Those six integers are all the model receives. Three details already matter:

  • The space belongs to the token. " cat" (leading space) is ID 9059; "cat" is a different ID.
  • Case matters. "The" is 976, " the" is 290. They start life as unrelated rows.
  • The mapping is model-specific. Qwen3's tokenizer turns "The cat sat" into [785, 8251, 7578]. Token IDs are meaningless outside their model.

Qwen3 gives every tiny variation of one word its own entry:

Input cat cat Cat Cat CAT cats
Qwen3 ID 4616 8251 26801 17358 43981 19423

Why not characters or words?

Unit Vocabulary size Sequence length Unknown words? Problem
Characters / bytes 256 (bytes) Very long Never Attention cost grows with length; each step carries little meaning
Whole words Millions Short Constantly Huge embedding table; unseen words become <UNK>
Subwords ~32K–262K Medium Never (with byte fallback) Splits are sometimes unintuitive

Subword tokenization gives you most of the compression of words with the coverage of bytes. Common words get one token; rare words split into reusable pieces. With o200k_base:

"tokenization"                    → ['token', 'ization']                            2 tokens
"antidisestablishmentarianism"    → ['ant','idis','est','ablishment','arian','ism']  6 tokens
"kubectl get pods -n kube-system" → ['kub','ectl',' get',' pods',' -','n',' kube','-system'] 8 tokens

The tiktoken README's rule of thumb: one token is about 4 bytes of English text on average12, roughly three-quarters of a word. It falls apart for code, numbers, and non-Latin scripts.

How BPE builds a vocabulary

Almost every 2026 LLM uses a variant of Byte-Pair Encoding (BPE), a 1994 compression trick adapted for neural translation by Sennrich et al. in 201513. The algorithm fits on a napkin:

  1. Start with the 256 possible byte values as your vocabulary.
  2. Count every adjacent pair of tokens in a big training corpus.
  3. Merge the most frequent pair into a new token. Record the merge.
  4. Repeat until the vocabulary hits the target size (for example, 128K).

Encoding new text later just replays the recorded merges in order. Here's a complete, dependency-free trainer:

from collections import Counter

corpus = "the cat sat on the mat. the cat ate the rat. that cat is fat."
ids = list(corpus.encode("utf-8"))          # step 1: raw bytes, vocab = 256
vocab = {i: bytes([i]) for i in range(256)}

for step in range(8):                        # steps 2-4: merge the top pair, repeat
    pairs = Counter(zip(ids, ids[1:]))
    (a, b), count = pairs.most_common(1)[0]
    new_id = 256 + step
    vocab[new_id] = vocab[a] + vocab[b]
    out, i = [], 0
    while i < len(ids):
        if i < len(ids) - 1 and (ids[i], ids[i + 1]) == (a, b):
            out.append(new_id); i += 2
        else:
            out.append(ids[i]); i += 1
    ids = out
    print(f"merge {step+1}: {vocab[a]!r} + {vocab[b]!r} -> {vocab[new_id]!r} "
          f"(seen {count}x)  sequence length now {len(ids)}")

print(f"\n{len(corpus.encode())} bytes -> {len(ids)} tokens")
merge 1: b'a' + b't' -> b'at' (seen 9x)  sequence length now 52
merge 2: b't' + b'h' -> b'th' (seen 5x)  sequence length now 47
merge 3: b'e' + b' ' -> b'e ' (seen 5x)  sequence length now 42
merge 4: b'at' + b' ' -> b'at ' (seen 5x)  sequence length now 37
merge 5: b'th' + b'e ' -> b'the ' (seen 4x)  sequence length now 33
merge 6: b'c' + b'at ' -> b'cat ' (seen 3x)  sequence length now 30
merge 7: b'at' + b'.' -> b'at.' (seen 3x)  sequence length now 27
merge 8: b'the ' + b'cat ' -> b'the cat ' (seen 2x)  sequence length now 25

61 bytes -> 25 tokens

Eight merges cut the sequence from 61 to 25 tokens. Frequent fragments (at, the) win first.

Pre-tokenization: the step the toy skips

Merge 8 made 'the cat ' one token. Production tokenizers prevent that: before BPE runs, a regex splits text into word-like chunks, and merges never cross a chunk boundary. That's why real vocabularies contain " cat" rather than "the cat ".

The regex also encodes policy. Here's "3.14159265358979" through each model's Hugging Face tokenizer:

Tokenizer Tokens Split
Llama 3.1 8B, DeepSeek-V3 7 3 . 141 592 653 589 79
Qwen3 8B, Gemma 4 E4B 16 one token per digit

Single-digit splitting costs more tokens but gives the model a consistent view of place value, which helps arithmetic. It's a trade-off, not a bug.

Byte-level: why there's no "unknown token" anymore

GPT-2 introduced byte-level BPE: the base alphabet is the 256 bytes, so any string (emoji, Thai, binary garbage) can always be encoded, worst case one token per byte2. That's why Hugging Face tokenizers print Ġcat: Ġ is how byte-level tokenizers display the space byte. SentencePiece-style models14 print ▁cat instead. Same idea, different notation.

Family Algorithm Space marker Vocabulary entries
GPT-2 Byte-level BPE Ġ 50,2572
Llama 2 SentencePiece BPE ▁ 32,00015
Llama 3 / 3.1 Byte-level BPE (tiktoken-based) Ġ 128,25616
DeepSeek-V3 Byte-level BPE Ġ 129,280 (embedding rows)17
Qwen3 Byte-level BPE Ġ 151,66918
OpenAI o200k_base Byte-level BPE — 200,01912
Qwen3.5 Byte-level BPE Ġ 248,320 (padded)19
Gemma 4 SentencePiece-style ▁ 262K20

Why two numbers for one vocabulary?

Embedding matrices are often padded so their row count divides nicely across GPUs. Qwen3's tokenizer has 151,669 entries, but Qwen3-8B's config.json says vocab_size: 151936. The extra rows are never produced by the tokenizer.

Bigger vocabularies and the language tax

Open-model vocabularies grew 8x in three years, from 32K (Llama 2, 2023) to 262K (Gemma 4, 2026). A bigger vocabulary means fewer tokens per document. Meta reported that moving from 32K to 128K improved English compression from 3.17 to 3.94 characters per token, letting the model read more text for the same compute; the 128K vocabulary is 100K tiktoken tokens plus 28K for non-English languages4.

The cost is a bigger embedding table and a slower softmax at the output. You'll size that table in the embeddings section below. Model builders pick the point where the two balance for their target languages.

Same meaning, different bill

Tokenizers are trained mostly on English and code. Underrepresented languages get split into more, smaller pieces, so the same sentence costs more tokens. Petrov et al. found tokenized length can differ by up to 15x across languages for the same text21. That multiplies cost, latency, and context usage.

A measurement I ran, same meaning in English and Thai:

EN (105 chars): "Kubernetes schedules pods onto nodes based on resource requests, taints, tolerations, and affinity rules." TH (80 chars): "Kubernetes จัดตารางพ็อดลงบนโหนดตามคำขอทรัพยากร เทนต์ การยอมรับ และกฎความสัมพันธ์"

Tokenizer English tokens Thai tokens Thai ÷ English
Qwen3 8B 22 40 1.82x
gpt-oss-20b 21 35 1.67x
Llama 3.1 8B 22 36 1.64x
DeepSeek-V3 22 33 1.50x
Gemma 4 E4B 21 28 1.33x
Qwen3.5 9B 22 22 1.00x

The older generation was worse. "แมวนั่งอยู่บนเสื่อ" ("the cat sat on the mat") takes 17 tokens in cl100k_base (GPT-4's vocabulary, nearly one per Thai character) but 7 in o200k_base.

The 2026 fix is a bigger, more multilingual vocabulary. Qwen3.5 uses 248K entries and supports 201 languages and dialects19; Gemma 4 uses 262K and was pre-trained on 140+ languages20. If you serve a non-English market, measure token counts on your own text before you pick a model. Post 07 covers Thai-focused models.

Strange behavior that tokens explain

A lot of "LLMs are dumb" moments are tokenization artifacts.

Symptom Token-level cause What to do
Can't count the r's in "strawberry" " strawberry" is one o200k_base token (ID 101830); "strawberry" is st·raw·berry. The model never sees ten letters Ask it to spell the word out first; reasoning models do this on their own (post 06)
Odd completions after "The capital of France is " The space usually arrives glued to " Paris"; a lone trailing space is a rare state Strip trailing whitespace from completion prompts
Bizarre output on rare strings Glitch tokens like SolidGoldMagikarp: in the vocabulary but barely seen in training. Land and Bartolo found them common across open models22 Filter or test unusual strings
Code and YAML inflate counts Indentation is tokens too: Qwen3 encodes the 4-space indent in " return a + b" as ĠĠĠ plus a space glued to return Minify JSON you send as context

Special tokens and chat templates

Not every token comes from your text. Each model reserves special tokens for structure: turn boundaries, end of text, tool calls, thinking blocks. A chat template wraps your messages in them before tokenization:

# pip install "transformers>=5.0"
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
msgs = [
    {"role": "system", "content": "You are terse."},
    {"role": "user", "content": "The cat sat"},
]
text = tok.apply_chat_template(
    msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False
)
print(repr(text))
ids = tok(text, add_special_tokens=False).input_ids
print(len(ids), tok.convert_ids_to_tokens(ids))

Output (Transformers 5.22.1):

'<|im_start|>system\nYou are terse.<|im_end|>\n<|im_start|>user\nThe cat sat<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n'
24 ['<|im_start|>', 'system', 'Ċ', 'You', 'Ġare', 'Ġterse', '.', '<|im_end|>', 'Ċ',
    '<|im_start|>', 'user', 'Ċ', 'The', 'Ġcat', 'Ġsat', '<|im_end|>', 'Ċ',
    '<|im_start|>', 'assistant', 'Ċ', '<think>', 'ĊĊ', '</think>', 'ĊĊ']

Your 3-token message became 24 tokens. <|im_start|> and <|im_end|> (IDs 151644 and 151645) are single tokens the model learned to treat as turn boundaries. The empty <think></think> block is how Qwen3 switches its reasoning mode off.

Chat template mismatch is a silent quality killer

Serve a model with the wrong template, or hand-build prompts with add_special_tokens wrong, and it still answers, just worse. Always use the model's own apply_chat_template, or let your inference server apply it from tokenizer_config.json.

Counting tokens in production

You need token counts for three things: cost estimates, context-window fit, and rate limits.

Open models: use the model's own tokenizer. Never estimate Llama tokens with tiktoken or vice versa; the language-tax table shows they disagree by up to 1.8x on the same text.

from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
doc = open("runbook.md").read()
n = len(tok.encode(doc, add_special_tokens=False))
print(f"{n} tokens, {len(doc)/n:.2f} chars/token")

Hosted APIs: ask the provider. Anthropic's tokenizer isn't public, so use the free counting endpoint, which counts under the tokenizer of whatever model you pass23:

curl https://api.anthropic.com/v1/messages/count_tokens \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "content-type: application/json" \
  -H "anthropic-version: 2026-10-21" \
  -d '{
    "model": "claude-opus-5-5",
    "system": "You are a scientist",
    "messages": [{"role": "user", "content": "Hello, Claude"}]
  }'
# {"input_tokens": 14}

Tokenizers change between model versions, and so does your bill. Anthropic documents that Claude 4.7 and later models produce roughly 30% more tokens for the same input than earlier models, and says to recount rather than reuse old numbers23. A prompt that fit under a limit can overflow after an upgrade with zero changes on your side.

  • Count tokens with the exact tokenizer of the model you deploy, not a proxy
  • Count the templated prompt (system + chat template + tool schemas), not just user text
  • Re-measure on every model version upgrade
  • Benchmark your real non-English traffic: tokens per request per candidate model
  • Strip trailing whitespace from completion prompts; minify JSON context
  • Budget output tokens separately: they're priced higher and generated one at a time

Embeddings: a token ID is a row number

Embedding lookup: each token ID selects one row of the embedding matrix

Integers carry no meaning. ID 9059 isn't "bigger" than ID 976 in any useful sense. The fix is a learned table, the embedding matrix E, with one row per vocabulary entry and d columns. The notation E ∈ ℝ^(V×d) reads: a matrix of real numbers with V rows (vocabulary size) and d columns (hidden size). For Llama 3.1 8B that's 128,256 × 4,09616.

A toy version with d = 4, using the real o200k_base IDs from above:

E  (real: 128K–262K rows × 4,096 cols; shown: 6 rows × 4 dims)
           d₁    d₂    d₃    d₄
   976 | 1.0   0.0   0.5   0.2 |  ← "The"
  9059 | 0.5   1.0   0.2   0.8 |  ← " cat"
 10139 | 0.2   0.5   1.0   0.3 |  ← " sat"
   402 | 0.7   0.1   0.4   0.6 |  ← " on"
   290 | 0.9   0.1   0.5   0.2 |  ← " the"   (ID 290 ≠ ID 976)
  2450 | 0.4   0.9   0.1   0.7 |  ← " mat"

The lookup is pure indexing, no multiplication. Stack the rows for "The cat sat" and you get the input matrix X, shape T × d with T = 3:

X =
| 1.0   0.0   0.5   0.2 |  ← "The"
| 0.5   1.0   0.2   0.8 |  ← " cat"
| 0.2   0.5   1.0   0.3 |  ← " sat"

These 12 numbers are the model's entire input; in a real 8B model it's 3 × 4,096 = 12,288 floats. Post 02 carries this exact X through attention and the feed-forward layer.

Mathematically, a lookup equals multiplying a one-hot vector by E. Frameworks skip the multiply:

# pip install torch
import torch

V, d = 200_019, 4
emb = torch.nn.Embedding(V, d)          # E: 200,019 × 4, randomly initialized
ids = torch.tensor([976, 9059, 10139])  # "The cat sat"
X = emb(ids)                            # shape (3, 4)

one_hot = torch.nn.functional.one_hot(ids, V).float()   # (3, 200019)
assert torch.allclose(X, one_hot @ emb.weight)          # identical result

The one-hot version builds a 3 × 200,019 matrix to select three rows. That's why nobody does it that way.

Similar meaning, nearby vectors

Distance in vector space stands in for similarity in meaning, and distance is cheap to compute. The standard measure is cosine similarity: 1 for same direction, 0 for unrelated, −1 for opposite. It ignores length:

cos(a, b) = (a · b) / (‖a‖ × ‖b‖)

Toy numbers prove nothing, so I pulled the real embedding matrix out of Qwen3-0.6B (151,936 × 1,024) and measured single-token words:

Pair Cosine Pair Cosine
king / queen 0.562 cat / dog 0.398
Paris / France 0.463 car / truck 0.312
man / woman 0.442 cat / car 0.188
cat / kitten 0.429 cat / Paris 0.066

Related words score 0.3–0.6; unrelated words land near zero. Nobody labeled these. The structure emerged because words used in similar contexts get similar gradient updates.

Two surprises worth knowing:

  • The nearest neighbors of cat are spelling variants, not animals: Cat (0.79), cat (0.77), Cat (0.74). The model's first job is learning these separate IDs are one word.
  • king − man + woman ≈ queen only half-works. The nearest vector to that sum is king itself (0.670), with queen second (0.582). Word2vec-era demos24 usually exclude the input words from results.

The code downloads the 1.5 GB checkpoint once and touches only the embedding tensor:

# pip install "transformers>=5.0" safetensors huggingface_hub torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from safetensors import safe_open
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
path = hf_hub_download("Qwen/Qwen3-0.6B", "model.safetensors")
with safe_open(path, "pt") as f:
    E = f.get_tensor("model.embed_tokens.weight").float()   # (151936, 1024)

def row(word):
    ids = tok.encode(word, add_special_tokens=False)
    assert len(ids) == 1, f"{word!r} is {len(ids)} tokens"
    return E[ids[0]]

print(F.cosine_similarity(row(" king"), row(" queen"), dim=0))   # 0.562
q = row(" king") - row(" man") + row(" woman")
top = F.cosine_similarity(q.unsqueeze(0), E, dim=1).topk(5)
print([tok.decode([i]) for i in top.indices])
# [' king', ' queen', ' King', ' kings', 'King']

Where the numbers come from, and what the table costs

Embedding values start random and are learned by backpropagation, like every other weight (post 03). Two consequences:

  • Only rows that appear in training get updated. A token that almost never occurs keeps a near-random vector. That's the root cause of glitch tokens22.
  • Adding tokens means adding untrained rows. When you extend a model to a new language, new rows are typically initialized from the average of existing ones and need continued pretraining to become useful (post 08).

Sizing the table

The embedding table is V × d parameters, and with 128K–262K vocabularies it's a big share of a small model. From each model's config.json:

Model V d Embedding params BF16 size Tied?
Qwen3-0.6B 151,936 1,024 156M (~26% of the model) 0.31 GB Yes25
Llama 3.1 8B 128,256 4,096 525M 1.05 GB No16
Qwen3-8B 151,936 4,096 622M 1.24 GB No7
gpt-oss-20b 201,088 2,880 579M 1.16 GB No26
Gemma 4 E4B 262,144 2,560 671M (+2.8B per-layer embeddings) 1.34 GB Yes20
Qwen3.5-9B 248,320 4,096 1.02B 2.03 GB No19

Llama 3.1 8B: 128,256 × 4,096 = 525,336,576 parameters, 1.05 GB in BF16. Its untied output layer adds another 525M, so 13% of the 8.03B total is embedding and un-embedding. Qwen3-0.6B's card lists 0.44B non-embedding parameters out of 0.6B25: a quarter of the model is a lookup table.

Gemma 4's per-layer embeddings

Gemma 4's small "E" models give each decoder layer its own small per-token embedding (256 dims × 262,144 rows × 42 layers ≈ 2.8B parameters for E4B). That's why E4B is marketed as 4.5B "effective" parameters, 8B with embeddings20. Lookups are cheap, and the tables can live in slower memory.

Weight tying: one matrix, two jobs

At the end of the model, the final hidden vector becomes one score per vocabulary token through another V × d matrix, the LM head. Weight tying reuses the input embedding as the LM head. Press and Wolf showed in 2016 that tying lowers perplexity and can cut translation models to less than half their size27.

Tied Untied
Parameters V × d once V × d twice
Typical users (2026) Small models: Qwen3-0.6B, Gemma 4 7B+: Llama 3.1 8B, Qwen3-8B, gpt-oss
Why Embedding is a big fraction, so savings are large Embedding is small; separate matrices give more freedom

Check any model with one field: tie_word_embeddings in config.json.

Token embeddings are context-free; hidden states are not

The embedding row for bank is identical whether the sentence is about rivers or money. The transformer layers fix that: each one mixes in other tokens and transforms the result (post 02). The vector flowing through the layers, the hidden state, becomes contextual.

You can measure it. Three sentences through Qwen3-0.6B, comparing bank at each layer:

import torch, torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "Qwen/Qwen3-0.6B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32).eval()

def bank_states(text):
    ids = tok(text, return_tensors="pt").input_ids
    idx = tok.convert_ids_to_tokens(ids[0]).index("Ġbank")
    with torch.no_grad():
        out = model(ids, output_hidden_states=True)
    return [h[0, idx] for h in out.hidden_states]   # 29 entries: embeddings + 28 layers

river = bank_states("I sat on the river bank")
cash  = bank_states("I deposited cash at the bank")
muddy = bank_states("We walked along the muddy bank")
for L in [0, 1, 4, 8, 14, 27]:
    print(L, F.cosine_similarity(river[L], cash[L], dim=0).item(),
             F.cosine_similarity(river[L], muddy[L], dim=0).item())
Layer river vs cash river vs muddy
0 (embedding) 1.000 1.000
1 0.843 0.915
4 0.653 0.839
8 0.539 0.819
14 0.743 0.901
27 0.841 0.947

At layer 0 every bank is the same vector. By layer 8 the money bank has drifted far from the river bank (0.54), while the two riverbank senses stay close (0.82). Similarity creeps back up in late layers as representations converge toward predicting the next token, but the river senses always stay closer to each other.

Sentence embeddings: a different model for a different job

When people say "embeddings" in a RAG or vector-database context, they mean something else: one vector for a whole sentence or document, produced by a dedicated embedding model.

Token embeddings (inside an LLM) Sentence embeddings (embedding model)
Unit One vector per token One vector per text (sentence, chunk, document)
Context None at the input layer Full text, via a whole transformer
Produced by A lookup table A forward pass, then pooling
Trained for Next-token prediction Similar texts close, dissimilar far (contrastive)
You use it for Nothing directly Semantic search, RAG retrieval, clustering, dedup
Example model.embed_tokens in Qwen3-8B Qwen3-Embedding-0.6B

Modern embedding models are often built from a decoder LLM: run the text through every layer, take the final hidden state (often of the last token), and normalize it. Qwen3-Embedding-0.6B is a 28-layer model with 1,024-dim output and a 32K-token context28. With sentence-transformers 6.2.0:

# pip install "sentence-transformers>=6.0" "transformers>=5.0"
from sentence_transformers import SentenceTransformer

m = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B")
docs = [
    "The cat sat on the mat.",
    "A kitten was resting on the rug.",
    "แมวนั่งอยู่บนเสื่อ",                     # Thai: "the cat sat on the mat"
    "kubectl get pods -n kube-system",
    "The stock market fell sharply today.",
]
E = m.encode(docs, normalize_embeddings=True)   # shape (5, 1024)
print(m.similarity(E, E))
cat/mat kitten/rug Thai cat kubectl stocks
The cat sat on the mat. 1.000 0.688 0.525 0.227 0.315
A kitten was resting on the rug. 0.688 1.000 0.435 0.221 0.242
แมวนั่งอยู่บนเสื่อ 0.525 0.435 1.000 0.239 0.408

"A kitten was resting on the rug" shares zero content words with "The cat sat on the mat" and still scores 0.688, the highest in the row. That's what keyword search can't do.

The Thai row is a warning. It matches its English twin at 0.525, but also scores 0.408 against the unrelated stock-market sentence. Cross-lingual similarity is weaker and noisier than same-language similarity, especially in small models. Evaluate retrieval on your languages before trusting the scores (post 05).

Matryoshka embeddings: shrink vectors without retraining

One million 1,024-dim float32 vectors take 4.1 GB; at 256 dims, 1.0 GB. Models trained with Matryoshka Representation Learning (MRL)29 pack the most important information into the first dimensions, so you can truncate. Qwen3-Embedding-0.6B supports any size from 32 to 1,02428:

E256 = m.encode(docs, truncate_dim=256, normalize_embeddings=True)   # shape (5, 256)

On the same five sentences, cat/kitten went from 0.688 at 1,024 dims to 0.710 at 256, and the English rankings held. Four times less storage, same ordering on this toy set — five sentences prove nothing about recall, so validate on your own queries.

  • Use the same embedding model and version for documents and queries; vectors from different models can't be compared
  • Re-embed everything when you change models; plan a dual-index cutover
  • L2-normalize vectors so dot product equals cosine similarity
  • Use the model's query prompt if it has one (Qwen3-Embedding: prompt_name="query")
  • Size dimensions from a storage budget (vectors × dims × 4 bytes), then test MRL truncation
  • Measure retrieval on your languages and domain, not a leaderboard average
  • Don't use an LLM's raw embed_tokens rows as sentence embeddings; they're context-free

Summary

Concept Rule Number to remember
What an LLM is A next-token probability distribution, called in a loop ~152K probabilities per step for Qwen3
Scale Parameters are learned numbers; data grew faster than size 8.2B params × 2 bytes ≈ 16.4 GB of weights
Base vs assistant SFT + preference/RL turn a text-continuer into an instruction-follower 1.3B InstructGPT beat 175B GPT-3 base
Emergence Often a metric artifact; check for all-or-nothing scoring —
Not a database, not stateful Retrieval, context management, and tool calling fill the gaps —
Tokens Subword byte chunks from BPE; IDs are model-specific ~4 bytes of English per token
Vocabulary size Bigger vocab = fewer tokens, bigger embedding table 32K → 262K in three years
Language tax Underrepresented languages cost more tokens Thai 1.0x–1.8x English across six 2026 tokenizers
Chat templates Special tokens wrap every turn 3-token message → 24 templated tokens
Tokenizer upgrades Recount on every model change Claude 4.7+: ~30% more tokens
Embedding lookup Token ID → row of E; pure indexing 128,256 × 4,096 for Llama 3.1 8B (525M params)
Weight tying Reuse E as the LM head Small models tie; 7B+ usually don't
Contextual states Layers turn context-free rows into context-aware vectors bank river vs money: 1.00 → 0.54 by layer 8
Sentence embeddings A separate model, one vector per text, built for search MRL: 1,024 → 256 dims = 4x less storage

Next: Post 02 — Inside the Transformer: the matrix X has no idea "cat" comes before "sat". Next we add position, then run it through attention and the feed-forward layers.

Go deeper:


  1. Vaswani et al., Attention Is All You Need, NeurIPS 2017. ↩

  2. Radford et al., Language Models are Unsupervised Multitask Learners (2019) — GPT-2, 1,542M parameters, 1,024-token context; byte-level BPE with a 50,257-token vocabulary. ↩↩↩

  3. Brown et al., Language Models are Few-Shot Learners (2020) — 175B parameters; Table 2.1 lists a 2,048-token context, and §2.2 reports ~300B training tokens. ↩

  4. Llama Team, Meta, The Llama 3 Herd of Models (2024) — "a dense Transformer with 405B parameters and a context window of up to 128K tokens"; §3.2: 128K vocabulary = 100K tiktoken tokens + 28K non-English, English compression 3.17 → 3.94 characters per token. ↩↩

  5. Meta, Introducing Meta Llama 3 — "pretrained on over 15T tokens"; 128K-token vocabulary. ↩

  6. DeepSeek-AI, DeepSeek-V3 Technical Report — 671B total parameters, 37B activated per token, pretrained on 14.8T tokens. ↩

  7. Qwen, Qwen3-8B config.json — hidden_size: 4096, 36 layers, vocab_size: 151936, tie_word_embeddings: false. ↩↩

  8. Qwen, Qwen3-8B model card — 8.2B parameters (6.95B non-embedding), 32,768 native context (131,072 with YaRN). ↩

  9. Ouyang et al., Training language models to follow instructions with human feedback (2022) — 1.3B InstructGPT outputs preferred over 175B GPT-3. ↩

  10. Wei et al., Emergent Abilities of Large Language Models (2022). ↩

  11. Schaeffer, Miranda, Koyejo, Are Emergent Abilities of Large Language Models a Mirage? (2023) — "alleged emergent abilities evaporate with different metrics or with better statistics." ↩

  12. OpenAI, tiktoken README — BPE is "reversible and lossless"; "each token corresponds to about 4 bytes" on average; o200k_base usage example. n_vocab of 200,019 measured with tiktoken 0.14.0. ↩↩↩

  13. Sennrich, Haddow, Birch, Neural Machine Translation of Rare Words with Subword Units (2015) — adapts byte-pair encoding to subword segmentation. ↩

  14. Kudo, Richardson, SentencePiece: A simple and language independent subword tokenizer (2018). ↩

  15. Touvron et al., Llama 2: Open Foundation and Fine-Tuned Chat Models (2023) — 32K-token vocabulary. ↩

  16. Llama 3.1 8B config.json: vocab_size: 128256, hidden_size: 4096, tie_word_embeddings: false (mirror of meta-llama/Llama-3.1-8B; the official repo is gated). Total of 8,030,261,248 parameters counted by instantiating the config in Transformers 5.22.1. ↩↩↩

  17. DeepSeek, DeepSeek-V3 config.json — vocab_size: 129280; the tokenizer itself loads 128,815 entries. ↩

  18. Qwen Team, Qwen3 Technical Report (2025) — byte-level BPE, vocabulary size 151,669; pre-training on 119 languages and dialects. ↩

  19. Qwen, Qwen3.5-9B model card — token embedding 248,320 (padded), hidden dimension 4,096; "Expanded support to 201 languages and dialects"; tie_word_embeddings: false in config.json. ↩↩↩

  20. Google, Gemma 4 E4B model card — 262K vocabulary for all sizes; pre-trained on 140+ languages; Per-Layer Embeddings; 4.5B effective parameters (8B with embeddings). config.json: vocab_size: 262144, hidden_size: 2560, hidden_size_per_layer_input: 256, num_hidden_layers: 42, tie_word_embeddings: true. ↩↩↩↩

  21. Petrov et al., Language Model Tokenizers Introduce Unfairness Between Languages (NeurIPS 2023) — tokenized length differs "up to 15 times" across languages. ↩

  22. Land, Bartolo, Fishing for Magikarp: Automatically Detecting Under-trained Tokens in Large Language Models (2024). ↩↩

  23. Anthropic, Token counting — POST /v1/messages/count_tokens, free with RPM limits; Claude 4.7 and later produce "approximately 30 percent more tokens" for the same input. Re-checked 2026-11-06. ↩↩

  24. Mikolov et al., Distributed Representations of Words and Phrases and their Compositionality (2013) and Efficient Estimation of Word Representations in Vector Space (2013). ↩

  25. Qwen, Qwen3-0.6B model card — 0.6B parameters, 0.44B non-embedding, 28 layers; config.json lists vocab_size: 151936, hidden_size: 1024, tie_word_embeddings: true. ↩↩

  26. OpenAI, gpt-oss-20b config.json — vocab_size: 201088, hidden_size: 2880, tie_word_embeddings: false. ↩

  27. Press, Wolf, Using the Output Embedding to Improve Language Models (2016) — tying lowers perplexity and can "reduce the size of neural translation models to less than half of their original size." ↩

  28. Qwen, Qwen3-Embedding-0.6B model card — 28 layers, 32K context, embedding dimension up to 1,024, MRL output dims 32–1,024, instruction-aware, 100+ languages. ↩↩

  29. Kusupati et al., Matryoshka Representation Learning (NeurIPS 2022). ↩

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.