NLP embeddings from the ground up

December 18, 2025

This article works through embeddings in large language models (LLMs), from word and text vectors to training custom tokens, starting from the basics of natural language processing.


1. What is an embedding and why do we need one?

Computers operate on numbers. Human language consists of discrete symbols. Words like “apple,” “banana” and “beautiful” are strings whose semantic relationships are not immediately evident to a computer.

An embedding maps discrete items such as words, sentences or documents into a continuous vector space in which semantically related items can be close together.

"狗" → [0.2, 0.8, -0.1, ...]    (一个 d 维向量)
"猫" → [0.25, 0.75, -0.05, ...]  (与"狗"的向量很接近)
"汽车" → [-0.5, 0.1, 0.9, ...]   (与"狗"的向量较远)

A machine can then use vector operations to work with meaning.


2. Word embeddings: a static dictionary of vectors

2.1 Basic idea

A word embedding gives each item in a vocabulary a fixed vector.

In an LLM, an embedding matrix implements this mapping:

E∈RV×dE \in \mathbb{R}^{V \times d}
  • VV: vocabulary size, for example 50,000.
  • dd: embedding dimension, for example 768 or 4,096.
  • Row EiE_i: the vector representing token ii.

2.2 Looking up a vector

Given a token such as “love,” with ID 2048:

word_vector = E[2048]  # 直接取第 2048 行

This is a lookup: supply a token ID and return its vector.

2.3 A key property: independent of context

For static word embeddings, the same token always gets the same vector regardless of context.

SentenceWordEmbedding
"I went to the bank to deposit money."bankEbankE_{bank}
“I sat on the bank of the river.”bankEbankE_{bank} (identical)

The embedding layer alone cannot distinguish senses: a financial bank and a riverbank share the same input vector for “bank.”


3. How does an LLM process text input?

Now follow a piece of text through an LLM.

3.1 The complete pipeline

Suppose the input is “I love machine learning”:

Step 1: Tokenization

"I love machine learning"
→ tokens: ["I", " love", " machine", " learning"]
→ token IDs: [101, 2048, 3035, 5068]

Output shape: [N], where N is the token count.

Step 2: Look up the embedding table

token IDs: [101, 2048, 3035, 5068]
→ 从 E 中查出对应行
→ shape: [N, d_model]

Step 3: Add positional information

H₀ = X + P
shape: [N, d_model]

Positional information tells the model word order, so “dog bites man” can differ from “man bites dog.”

Step 4: Pass through the stack of Transformer layers

H₁ = Transformer_1(H₀)
H₂ = Transformer_2(H₁)
...
H_L = Transformer_L(H_{L-1})
shape: 始终是 [N, d_model]

Step 5: Use the output layer to predict the next token

logits = H_L @ W_out
shape: [N, V]  (每个位置输出词表大小的概率分布)

3.2 What determines the dimensions?

DimensionMeaningDetermined by
NSequence length in tokensText and tokenization, bounded by L_max
VVocabulary sizeTokenizer design
d_modelHidden dimensionModel architecture, e.g. 768 or 4,096
num_headsAttention head countModel architecture
LTransformer layer countModel architecture

3.3 A numerical example

Assume this configuration:

  • Batch size: B = 4
  • Sequence length: N = 100
  • Vocabulary size: V = 50,000
  • Hidden dimension: d_model = 4096
  • Attention heads: num_heads = 32

The data changes shape as follows:

token IDs:     [4, 100]
↓ embedding 查表
embedding:     [4, 100, 4096]
↓ + 位置编码
H₀:            [4, 100, 4096]
↓ Transformer 层
H_L:           [4, 100, 4096]
↓ 输出层
logits:        [4, 100, 50000]

4. Does the model read IDs or vectors?

What does a model actually “see”: integer token IDs or embedding vectors?

Answer:

  • At the API/input boundary, it receives integer token IDs.
  • Inside the computation, it uses embedding vectors.

An ID is an index directing the layer to row ii. The model does not perform arithmetic on IDs as if the word numbered 5 were larger than word 3.

One way to remember it:

The ID is the address. The embedding is the content.

Mathematically, lookup is equivalent to multiplying a one-hot encoding by the embedding matrix:

embedding=xone-hot⋅E\text{embedding} = x_{\text{one-hot}} \cdot E

Implementations directly index the table for efficiency.


5. How is the embedding table trained?

5.1 Initialization: a random matrix

When defining a model:

E = nn.Embedding(num_embeddings=V, embedding_dim=d_model)

At creation, the table contains randomly initialized numbers without learned semantics.

5.2 Optimize it with the rest of the model

A next-token language model minimizes prediction loss:

L=−∑tlog⁡Pθ(xt∣x<t)L = -\sum_t \log P_\theta(x_t \mid x_{<t})

The parameters θ\theta include:

  • Embedding table EE
  • All Transformer-layer parameters
  • Output-layer parameters

One training step:

  1. Take a batch of text and tokenize it into input_ids.
  2. Look up embeddings using input_ids.
  3. Run the Transformer, compute logits and apply softmax to obtain probabilities.
  4. Compute cross-entropy against the actual next token.
  5. Backpropagate gradients to the embedding layer.
  6. Optimizer update: E[i] ← E[i] - η · ∂L/∂E[i]

Two observations:

  • The input lookup supplies gradients to the rows for tokens occurring in the batch.
  • Over time, words with similar semantics can move closer together.

5.3 Why can it learn meaning?

The training objective is to predict the next word:

  • If “dog” and “cat” often occur in similar contexts,
  • the model needs to make similar predictions,
  • which can encourage their embeddings to move closer.

This is the distributional hypothesis: words occurring in similar contexts tend to have similar meanings.


6. Could a hash map replace the embedding layer?

Since embedding is a lookup (E[token_id]), could we use a simple hash map or extract the table from the model?

6.1 During training the entries are trainable parameters

The embedding table is a trainable parameter matrix, optimized end to end with the Transformer:

Loss → Transformer 参数梯度 → Embedding 参数梯度

Its values are adjusted to reduce the whole network’s loss. During training it must participate in the computation graph and backpropagation.

6.2 At inference there is little to optimize separately

The embedding layer already performs a lookup:

X = E[input_ids]  # gather 操作,直接取对应行
  • No matrix multiplication or complicated computation.
  • Cost is primarily memory bandwidth rather than arithmetic.
  • It accounts for little of the model’s total compute compared with self-attention and feed-forward layers.

Switching to a hash map would not remove a costly computation: the implementation is already a lookup.


7. Word embeddings versus text embeddings

A common point of confusion:

A text embedding is not an array of word embeddings.

AspectWord embeddingText embedding
InputOne word or tokenA sentence, passage or document
OutputA vector per token, [num_tokens, d]One vector for the text, [d]
MeaningWord-level analogies such as king − man + woman ≈ queenSentence-level similarity, e.g. “I’m hungry” and “I want to eat”
ContextUsually staticGenerally context-sensitive

How they relate:

A text embedding is often a higher-level representation obtained from word embeddings by contextual encoding and pooling:

  1. Tokenize and look up word embeddings.
  2. Incorporate context through Transformer layers.
  3. Average token vectors or take the [CLS] position to obtain a text embedding.

8. Why train dedicated embedding models?

If a Transformer’s output already contains semantic information, why train dedicated models such as OpenAI’s text-embedding-3-large or Sentence-BERT?

8.1 Different training objectives

ModelObjectiveRepresentation space
Language modelPredict the next wordSuited to generation, emphasizing plausible continuations
Embedding modelContrastive learning or semantic matchingSuited to similarity, bringing related meanings closer

An LLM asks, “What is the next plausible token?” An embedding model asks, “Are A and B semantically similar?”

8.2 Differences in results

An illustrative comparison on semantic-similarity tasks:

AspectDirect LLM encoder outputDedicated embedding model
Similarity spaceDistorted, uneven distancesStructured to reflect semantic similarity
Retrieval performanceLower20–40% higher in the article’s comparison
Downstream adaptationRequires fine-tuningReady to use

For example:

S₁ = "How to learn machine learning?" S₂ = "A beginner guide to AI study"

  • Averaged GPT hidden states might give a cosine similarity of only 0.4.
  • A dedicated embedding model might give 0.9.

8.3 How are embedding models trained?

The article uses OpenAI’s text-embedding-3-large as an illustration of the general approach:

  1. Start with a Transformer backbone.
  2. Remove the next-token prediction head.
  3. Add a pooling layer.
  4. Retrain with a contrastive objective:
L=−log⁡exp⁡(sim(Ea,Eb)/τ)∑kexp⁡(sim(Ea,Ek)/τ)L = -\log \frac{\exp(\text{sim}(E_a, E_b)/\tau)}{\sum_k \exp(\text{sim}(E_a, E_k)/\tau)}

Pull similar texts together and push dissimilar ones apart.

8.4 Comparing word-level embeddings

For single-word similarity, how well do an LLM’s input token embeddings work?

Conclusion: they can be used, but specialized word embeddings can work better.

An additional difficulty: subwords split word meanings.

LLMs commonly use BPE tokenization:

  • "interesting" → ["interest", "ing"]
  • "unbelievable" → ["un", "believ", "able"]

Many tokens are only pieces of words and do not express their full meaning.

Approximate differences:

On classic word-similarity benchmarks such as SimLex-999 and WordSim-353:

ModelSpearman correlation
Word2Vec/GloVe0.6 ~ 0.7
LLM token embeddings (common words)0.3–0.5

8.5 Which should I use?

Dedicated word embeddings (Word2Vec/GloVe):

  • Analyze word-level semantic structure.
  • Visualize a vocabulary.
  • Solve analogies such as king − man + woman ≈ queen.

Dedicated text embedding models:

  • Semantic search.
  • Text clustering.
  • Similarity calculations.
  • Retrieval-augmented generation (RAG).

An LLM:

  • Text generation.
  • Conversation.
  • Reasoning, summarization and translation.

9. Concept map and review

Concept map

文本输入
    ↓
分词(Tokenizer)
    ↓
Token IDs: [101, 2048, 3035, ...]  ← 一维整数数组
    ↓
Embedding 查表 (E[id])
    ↓
Word Embeddings: [N, d_model]      ← 静态,上下文无关
    ↓
+ 位置编码
    ↓
Transformer 层 × L
    ↓
Hidden States: [N, d_model]         ← 动态,上下文相关
    ↓
    ├─→ 生成任务:输出层 → logits → 预测下一个词
    │
    └─→ 语义任务:Pooling → Text Embedding [d]

Main points

  1. Word embeddings are lookups. A token ID maps to a fixed, context-independent input vector.
  2. The table trains with the model. Its parameters receive gradients through backpropagation.
  3. The embedding layer is already simple. It gathers the relevant rows without extra arithmetic.
  4. A text embedding differs from a word-embedding array. It represents the whole text after contextual encoding.
  5. Dedicated embedding models optimize a space for semantic retrieval.
  6. Training custom tokens takes several steps: initialization, enough occurrences and enabling updates during LoRA training.
  7. Vocabulary reduction carries risk. Prefer starting again from the base model over manually deleting tokens.

In one sentence

Embeddings give language coordinates; the Transformer gives those coordinates contextual meaning.


10. Hands-on: adding custom tokens

Applications often need special control tokens such as <think> and <tool_response> or domain-specific vocabulary. Here is how to manage the vocabulary and embeddings.

10.1 Basic procedure

The standard Hugging Face workflow:

# 1. 添加新 token 到 tokenizer
new_tokens = ["<think>", "</think>", "<tool_response>", "</tool_response>"]
num_added = tokenizer.add_tokens(new_tokens)

# 2. 调整 embedding 矩阵大小
model.resize_token_embeddings(len(tokenizer))

What happens behind the scenes:

OperationResult
tokenizer.add_tokens()Extends the vocabulary and appends IDs for the new tokens
resize_token_embeddings()Adds rows to the embedding matrix EE and output layer WoutW_{out}
Initialize rowsRandom initialization, usually from a normal distribution 1

⚠️ Warning: New token embeddings start with random values and need training to acquire meaning.

10.2 Initialization strategies

Frameworks use different initialization methods:

Standard Hugging Face initialization as described here:

  • Sample new rows from a standard normal distribution N(0,1)\mathcal{N}(0,1).
  • Simple, but supplies no semantic prior.

Unsloth’s alternative:

# Unsloth 的词表扩展采用更智能的初始化
# 新 embedding 从现有 embedding 的多元正态分布采样
mean = E_old.mean(dim=0)
cov = torch.cov(E_old.T)
E_new ~ MVN(mean, cov)

Based on the work of Hewitt et al. 2, this places initial embeddings closer to the existing vocabulary distribution to speed convergence.

10.3 Two pitfalls when training new embeddings

Even after adding tokens and resizing the matrix, fine-tuning can yield poor results. Two common reasons follow.

Pitfall 1: new tokens appear too rarely

Input-embedding gradients from the lookup occur when the relevant token is used:

∂L∂E[i]=0if token i∉batch\frac{\partial L}{\partial E[i]} = 0 \quad \text{if token } i \notin \text{batch}

Remedies:

  • Give the new token enough occurrences in training, with at least 1,000 suggested here.
  • Oversample examples containing it.
  • Incorporate it into prompt templates.

Pitfall 2: LoRA/PEFT freezes the embedding layer

A default PEFT/LoRA setup:

# 默认配置
lora_config = LoraConfig(
    r=16,
    target_modules=["q_proj", "v_proj"],  # 只训练注意力层
    # embedding 层被冻结!
)

Problem:

  • New embedding rows are parameters of the base model.
  • LoRA trains adapter weights while freezing the base.
  • The new rows can remain at their random initial values.

Configuration to train the embeddings:

lora_config = LoraConfig(
    r=16,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    modules_to_save=["embed_tokens"],  # 关键:解冻 embedding 层
)

modules_to_save tells PEFT to train these modules fully and include them in the checkpoint. 3

10.4 Verify that the embeddings learned

After training, check whether the new token learned semantic relationships:

# 获取新 token 的 embedding
new_token_id = tokenizer.convert_tokens_to_ids("<think>")
new_embedding = model.get_input_embeddings().weight[new_token_id]

# 计算与相关 token 的余弦相似度
related_ids = tokenizer.convert_tokens_to_ids(["think", "reason", "analyze"])
related_embeddings = model.get_input_embeddings().weight[related_ids]

similarity = torch.cosine_similarity(
    new_embedding.unsqueeze(0),
    related_embeddings
)
print(f"Similarity with related tokens: {similarity}")
# 期望:> 0.5(如果训练充分)
# 如果 < 0.2:embedding 可能未被训练

10.5 Shrinking the vocabulary: removing unused tokens

Sometimes an experiment fails and you want to undo previously added tokens.

Support:

  • ✅ Growing the vocabulary: resize_token_embeddings(larger_size) is fully supported.
  • ⚠️ Shrinking the vocabulary: resize_token_embeddings(smaller_size) is technically possible but risky.

Limitations and risks:

  1. Only remove tokens at the end:

    # 假设原词表 50000,添加了 10 个 token 变成 50010
    # 可以缩减回 50000(删除最后 10 个)
    model.resize_token_embeddings(50000)
    
    # ❌ 不能删除中间的 token(会破坏 ID 映射)
  2. Update the tokenizer as well:

    • Resize its vocabulary along with the model.
    • Otherwise it can emit out-of-range IDs and cause a crash.
  3. Known bugs:

    • Shrinking embeddings can cause shape mismatches in some architectures, including T5 and BART. 4
    • Loading old checkpoints may require handling dimension mismatches manually.

Suggested rollback procedure:

# 方案 1:从原始模型重新开始(最安全)
# 恢复原始 tokenizer 文件
cp base_model/tokenizer.json .
cp base_model/tokenizer_config.json .

# 重新加载 base model
model = AutoModelForCausalLM.from_pretrained("base_model")

# 方案 2:手动缩减(高级,易出错)
# 1. 修改 tokenizer.json,删除新增 token
# 2. 调用 resize_token_embeddings(old_size)
# 3. 验证 lm_head 和 embedding 维度一致

💡 Tip: Instead of laboriously removing tokens, fine-tune again from the original model or keep the new tokens and control their use through the data.

10.6 Deployment considerations with vLLM

Inference engines such as vLLM rely on the Hugging Face tokenizer and model weights. 5

# vLLM 加载模型
from vllm import LLM

llm = LLM(model="your_finetuned_model")
# 内部调用:
# tokenizer = AutoTokenizer.from_pretrained(model)
# model_weights = AutoModelForCausalLM.from_pretrained(model)

Main points:

  • vLLM looks at the files, whether the model is a base or fine-tuned model.
  • If fine-tuning added tokens, deployment must:
    • ✅ Use the matching tokenizer, including the new tokens.
    • ✅ Use the trained embedding weights.
    • ❌ Avoid mixing a base tokenizer with the fine-tuned model.

Common mistake:

# ❌ 错误:用 base tokenizer 推理 fine-tuned model
tokenizer = AutoTokenizer.from_pretrained("llama-3-base")  # 词表 50000
model = LLM("llama-3-finetuned")  # 词表 50010
# 结果:生成 ID=50005 的 token → tokenizer 无法解码 → 崩溃

Correct approach:

# ✅ 保存 fine-tuned model 时同时保存 tokenizer
model.save_pretrained("my_model")
tokenizer.save_pretrained("my_model")  # 关键

# 部署时一起加载
llm = LLM(model="my_model")  # 自动加载匹配的 tokenizer

10.7 Hands-on checklist

For the full process of adding a custom token:

  • Before adding: check whether existing token combinations can represent the term.
  • When adding: use tokenizer.add_tokens() and model.resize_token_embeddings().
  • Before training: check that the PEFT configuration includes modules_to_save=["embed_tokens"].
  • Prepare data: ensure at least 1,000 training occurrences, as suggested above.
  • During training: monitor the new token’s loss or separately measure its prediction accuracy.
  • After training: check embedding similarity as in section 10.4.
  • When saving: put the model and tokenizer in the same directory.
  • At deployment: verify that the inference engine loads the training tokenizer.

11. Summary

Concept map

文本输入
    ↓
分词(Tokenizer)
    ↓
Token IDs: [101, 2048, 3035, ...]  ← 一维整数数组
    ↓
Embedding 查表 (E[id])
    ↓
Word Embeddings: [N, d_model]      ← 静态,上下文无关
    ↓
+ 位置编码
    ↓
Transformer 层 × L
    ↓
Hidden States: [N, d_model]         ← 动态,上下文相关
    ↓
    ├─→ 生成任务:输出层 → logits → 预测下一个词
    │
    └─→ 语义任务:Pooling → Text Embedding [d]

Main points

  1. Word embeddings are lookups. A token ID maps to a fixed, context-independent input vector.
  2. The table trains with the model. Its parameters receive gradients through backpropagation.
  3. The embedding layer is already simple. It gathers the relevant rows without extra arithmetic.
  4. A text embedding differs from a word-embedding array. It represents the whole text after contextual encoding.
  5. Dedicated embedding models optimize a space for semantic retrieval.
  6. Training custom tokens takes several steps: initialization, enough occurrences and enabling updates during LoRA training.
  7. Vocabulary reduction carries risk. Prefer starting again from the base model over manually deleting tokens.

In one sentence

Embeddings give language coordinates; the Transformer gives those coordinates contextual meaning.


References

  1. Mikolov, T., et al. (2013). Efficient Estimation of Word Representations in Vector Space. arXiv:1301.3781

  2. Vaswani, A., et al. (2017). Attention Is All You Need. NeurIPS.

  3. Reimers, N., & Gurevych, I. (2019). Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. EMNLP.

  4. OpenAI. (2024). text-embedding-3 models documentation. https://platform.openai.com/docs/guides/embeddings

  5. Word embedding. In Wikipedia. Retrieved Dec 18, 2025, from https://en.wikipedia.org/wiki/Word_embedding

  6. Transformer (deep learning architecture). In Wikipedia. Retrieved Dec 18, 2025, from https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)

Footnotes

  1. PreTrainedModel.resize_token_embeddings. (n.d.). Hugging Face Transformers Documentation. Retrieved December 22, 2025, from https://huggingface.co/docs/transformers/main_classes/model#transformers.PreTrainedModel.resize_token_embeddings ↩

  2. Hewitt, J., et al. (2021). The Case for Translation-Invariant Self-Attention in Transformer-Based Language Models. arXiv:2106.01950 ↩

  3. John6666. [@John6666]. (December 1, 2024). You are basically right: if you just "add tokens + resize embeddings" and don't explicitly make those new rows trainable and well-used in the data, their embeddings can stay bad and hurt performance. Whether increasing or decreasing tokens, I often see resize_token_embeddings. In your LoRA / PEFT config, include embeddings as modules to save/train, for example: modules_to_save=["embed_tokens"]. This makes the embedding layer trainable and ensures updated embeddings are saved in your PEFT checkpoint. [Answer]. Hugging Face Discuss. https://discuss.huggingface.co/t/how-to-understand-the-special-tokens/170916 ↩

  4. Vocabulary resizing issue with T5 models. (2023). GitHub Issue. Retrieved December 22, 2025, from https://github.com/huggingface/transformers/issues/18877 ↩

  5. Tokenization. (n.d.). vLLM Documentation. Retrieved December 22, 2025, from https://docs.vllm.ai/en/latest/models/tokenization.html ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-18). NLP embeddings from the ground up. https://caiborui.com/blog/2025-12-18-zh-nlp-embeddings-from-zero-to-hero-entrans

@misc{borui2025-fc31377a,
  author = {borui},
  title = {{NLP embeddings from the ground up}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-18-zh-nlp-embeddings-from-zero-to-hero-entrans}
}