Word Embeddings and Language Models
How documents and words become vectors (vector space model, one-hot encodings, word embeddings) that are compared by dot product or cosine similarity, and how language models from n-gram counts to LLMs predict the next token, combined in retrieval-augmented generation.
Concepts#
- Vector Space Modeldocuments as term-score vectors in a term-document matrix ; retrieval as start here
- Cosine Similaritylength-normalized dot product; ranks documents, words and chunks by direction
- Sparse Matrixstores only the non-zero entries of ; row-major = inverted index
- One-Hot Encodingwords as orthogonal unit vectors; a VSM column is their sum
- Embeddingdense low-dimensional word/text vectors whose cos-sim reflects meaning
- Language Modeldistribution over the next token given the previous tokens
- N-Gram Modelcount-based language model (unigram, bigram, trigram), sampling via cumulative counts
- Large Language Modelvery large neural language model; base vs. instruct, system prompt, API
- Retrieval-Augmented Generationchunk, embed, retrieve top- by cos-sim, prompt the LLM
- Softmaxturns a score vector into a probability distribution (exam: relation to sigmoid)
- Sigmoidtwo-class special case of softmax (WS 23/24 Task 5.3)
How it fits together#
From text to vectors#
Every representation in this topic is a vector over a vocabulary , and a document vector is a sum of word vectors:
| Representation | Word vector | Document vector | Dimension | Related words | Word order |
|---|---|---|---|---|---|
| VSM / one-hot | , orthogonal | sum of one-hot encodings = column of (tf), or BM25 scores | , sparse | cos-sim | lost (bag of words) |
| word embedding (ES11) | learned, dense | sum of word embeddings | (ES11: 300) | high cos-sim | lost (bag of words) |
| embedding model/API (ES12) | — | one vector per text from the model | high cos-sim | not covered (see the Beyond-the-lecture note in Embedding) |
Queries are encoded exactly like documents, so query and documents live in the same space.
Comparing vectors: three ways to score documents#
With (rows = terms, columns = documents) and query , all scores come from one product :
| Score | Matrix entries | Long documents | Result | Used in |
|---|---|---|---|---|
| dot product | tf | favoured (more and higher entries) | tf score sum of Lecture 2 | VL11 example |
| dot product | BM25 | handled by BM25’s length normalization | exactly the BM25 ranking of the Inverted Index (Lecture 2) | ES11, Ex. 1 |
| cos-sim | any; normalize the columns of and once | length removed entirely (direction only) | ES11, Ex. 2 |
The DBIS use of the normalization trick: computing norms per query is costly, so normalize all document vectors once in advance; afterwards cos-sim with every document is again a single product . The same holds for embeddings: ranking words by cos-sim to emb["internet"] (ES11) and ranking chunks by cos-sim to the query embedding (RAG) are the same operation.
Storing the matrix#
is mostly zeros, so it is kept as a sparse matrix of (value, row, column) triples. Row-major order groups the entries per term, which is literally an Inverted Index with scores; column-major order groups them per document. So “VSM with a sparse matrix” and “inverted index with BM25” are the same retrieval, written as linear algebra vs. as list processing. PyTorch: torch.sparse_coo_tensor, and q @ A_sparse computes all scores.
From counts to LLMs#
All language models here compute ; they differ in how. Tokens can be words, subwords (modern LLMs) or characters (lecture n-gram code).
- Unigram → bigram → trigram: condition on , , previous tokens; learn by counting and normalizing; generate by sampling via cumulative counts.
- Why counting stops working: possible n-grams ( trigrams for ), and most long contexts never occur (smoothing = random next token).
- Neural language model: same distribution, computed by a network forward pass; allows context sizes up to tokens.
- LLM: a very large neural LM. A base model only continues text; an instruct model is trained to converse and is steered by a system prompt. Services return tokens per request (
max_completion_tokens,temperature).
| n-gram model | LLM | |
|---|---|---|
| Distribution from | counts | neural network |
| Context size | tokens, small | up to tokens |
| Unseen context | smoothing (random token) | always a distribution |
| Prompt longer than context | only the last tokens count | only the last tokens, or RAG |
RAG: where the two halves meet#
When the text exceeds even an LLM’s context size (ES12: all lecture transcripts), RAG uses the first half of the topic to choose the input for the second: split the text into sentence-complete chunks, embed them, embed the query with the same model, take the chunks with the highest cos-sim (linear scan in ES12), and give their text plus a system prompt to the LLM. Knobs: chunk size, overlap, embedding model, , system prompt.
Softmax and sigmoid#
Not lectured in WS 25/26, but asked in WS 23/24 Task 5.3 under this topic: softmax maps a score vector to a distribution, , and the sigmoid is its two-class case: . Sigmoid is the output of logistic regression (Linear Classifiers and Logistic Regression).
Key Formulas#
- Scores of all documents: (Vector Space Model)
- with (Cosine Similarity)
- Document vector (one-hot, One-Hot Encoding) or (Embedding)
- (N-Gram Model)
- (Softmax, Sigmoid)
Exercises & Exam Questions#
SuccessSolution
import math
def cos_sim(emb1: list[float], emb2: list[float]) -> float:
dot = sum(a * b for a, b in zip(emb1, emb2))
norm1 = math.sqrt(sum(a * a for a in emb1))
norm2 = math.sqrt(sum(b * b for b in emb2))
return dot / (norm1 * norm2)
The official solution accumulates the three sums in one loop and returns sum_products / math.sqrt(sum_squares_emb1 * sum_squares_emb2) (DBIS Exam WS2324 (not published)).
SuccessSolution
(divide numerator and denominator by ). Likewise
so , consistent with . The sigmoid is the two-class special case of softmax.
SuccessSolution
class SimplisticLanguageModel(torch.nn.Module):
def __init__(self, n: int, d: int):
super().__init__()
self.linear = torch.nn.Linear(n * d, d)
def forward(self, X: torch.Tensor):
# X has shape (batch_size, n * d)
return self.linear(X)
Concatenate the input embeddings into one vector of dimension and apply one linear layer; it has parameters (weights + bias). A (very small) neural language model with context size .
SuccessSolution
def sample(tokens: list[str], probs: list[float], k: int) -> str:
top_k_indices = argsort(probs)[len(probs) - k:]
top_k_probs = [probs[i] for i in top_k_indices]
top_k_tokens = [tokens[i] for i in top_k_indices]
top_k_probs_normalized = [p / sum(top_k_probs) for p in top_k_probs]
return top_k_tokens[sample_from_dist(top_k_probs_normalized)]
The last indices of the ascending sort are the most likely tokens; renormalize their probabilities to sum to and sample. Same idea as sampling from an n-gram distribution, restricted to the top .
SuccessSolution
Column of is , a linear combination of the document columns of with the weights in : for documents 1–3, resp. for documents 4–7 (Vector Space Model).
| Exam | Task | Points | Subtopics |
|---|---|---|---|
| DBIS Exam WS2324 (not published) | Task 5 | 20 (12 here) | 5.1 cos_sim implementation, 5.3 softmax–sigmoid proof (5.2 logistic regression epoch: Linear Classifiers and Logistic Regression) |
| DBIS Exam WS2324-2 (not published) | Task 5 | 20 (15 here) | 5.2 simplistic language model on embeddings, 5.3 top- sampling (5.1 logistic regression model: Linear Classifiers and Logistic Regression) |
| DBIS Exam WS1920 (not published) | Task 4.1 | 5 | term-document matrix, averaging documents via |
Lectures#
- DBIS_VL11 — vector space model, retrieval as , dot product vs. BM25 vs. cosine similarity, sparse matrices in PyTorch, one-hot encodings, word embeddings
- DBIS_VL12 — tokens, unigram/bigram/trigram models and sampling, neural language models and LLMs (base vs. instruct, API), retrieval-augmented generation
Related Topics#
- Inverted Index and Ranking — tf and BM25 scores; the sparse row-major term-document matrix is an inverted index
- Latent Semantic Indexing — works on the same term-document matrix, factorized by SVD
- Linear Classifiers and Logistic Regression — sigmoid, softmax and logistic regression (the other parts of the exam tasks above)
- Inner Products and Norms — foundation: dot product, norms, angles behind cosine similarity