Study Vault Search notes, aliases and full text
Graph
TopicDBISAI-written · not yet proofread

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#

  1. Vector Space Modeldocuments as term-score vectors in a term-document matrix AA; retrieval as q⊤Aq^\top A start here
  2. Cosine Similaritylength-normalized dot product; ranks documents, words and chunks by direction
  3. Sparse Matrixstores only the non-zero entries of AA; row-major = inverted index
  4. One-Hot Encodingwords as orthogonal unit vectors; a VSM column is their sum
  5. Embeddingdense low-dimensional word/text vectors whose cos-sim reflects meaning
  6. Language Modeldistribution over the next token given the previous tokens
  7. N-Gram Modelcount-based language model (unigram, bigram, trigram), sampling via cumulative counts
  8. Large Language Modelvery large neural language model; base vs. instruct, system prompt, API
  9. Retrieval-Augmented Generationchunk, embed, retrieve top-kk by cos-sim, prompt the LLM
  10. Softmaxturns a score vector into a probability distribution (exam: relation to sigmoid)
  11. 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 VV, and a document vector is a sum of word vectors:

RepresentationWord vectorDocument vectorDimensionRelated wordsWord order
VSM / one-hoteie_i, orthogonalsum of one-hot encodings = column of AA (tf), or BM25 scores∣V∣\lvert V \rvert, sparsecos-sim 00lost (bag of words)
word embedding (ES11)learned, densesum of word embeddingsd≪∣V∣d \ll \lvert V \rvert (ES11: 300)high cos-simlost (bag of words)
embedding model/API (ES12)—one vector per text from the modelddhigh cos-simnot 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 A∈R∣V∣×nA \in \mathbb{R}^{|V| \times n} (rows = terms, columns = documents) and query q∈{0,1}∣V∣q \in \{0,1\}^{|V|}, all nn scores come from one product q⊤A∈R1×nq^\top A \in \mathbb{R}^{1 \times n}:

ScoreMatrix entriesLong documentsResultUsed in
dot producttffavoured (more and higher entries)tf score sum of Lecture 2VL11 example
dot productBM25handled by BM25’s length normalizationexactly the BM25 ranking of the Inverted Index (Lecture 2)ES11, Ex. 1
cos-simany; normalize the columns of AA and qq oncelength removed entirely (direction only)q′⊤A′q'^\top A'ES11, Ex. 2

The DBIS use of the normalization trick: computing n+1n + 1 norms per query is costly, so normalize all document vectors once in advance; afterwards cos-sim with every document is again a single product q′⊤A′q'^\top A'. 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#

AA 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 Pr⁡(next token∣previous tokens)\Pr(\text{next token} \mid \text{previous tokens}); they differ in how. Tokens can be words, subwords (modern LLMs) or characters (lecture n-gram code).

  1. Unigram → bigram → trigram: condition on 00, 11, 22 previous tokens; learn by counting and normalizing; generate by sampling via cumulative counts.
  2. Why counting stops working: ∣V∣n|V|^n possible n-grams (1003=106100^3 = 10^6 trigrams for ∣V∣=100|V| = 100), and most long contexts never occur (smoothing = random next token).
  3. Neural language model: same distribution, computed by a network forward pass; allows context sizes up to 10610^6 tokens.
  4. 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 kk tokens per request (max_completion_tokens, temperature).
n-gram modelLLM
Distribution fromcountsneural network
Context sizen−1n - 1 tokens, smallup to 10610^6 tokens
Unseen contextsmoothing (random token)always a distribution
Prompt longer than contextonly the last tokens countonly the last nn 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 kk 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, kk, 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 z∈Rkz \in \mathbb{R}^k to a distribution, softmax(z)i=ezi/∑jezj\text{softmax}(z)_i = e^{z_i} / \sum_j e^{z_j}, and the sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}) is its two-class case: softmax([x,0])=(σ(x),σ(−x))\text{softmax}([x, 0]) = (\sigma(x), \sigma(-x)). Sigmoid is the output of logistic regression (Linear Classifiers and Logistic Regression).

Key Formulas#

  • Scores of all documents: q⊤A∈R1×nq^\top A \in \mathbb{R}^{1 \times n} (Vector Space Model)
  • cos-sim(x,y)=x∙y∣x∣⋅∣y∣=x′∙y′\text{cos-sim}(x, y) = \dfrac{x \bullet y}{|x| \cdot |y|} = x' \bullet y' with x′=x/∣x∣x' = x / |x| (Cosine Similarity)
  • Document vector =∑w∈docew= \sum_{w \in \text{doc}} e_w (one-hot, One-Hot Encoding) or ∑w∈docemb(w)\sum_{w \in \text{doc}} \text{emb}(w) (Embedding)
  • Pr⁡(v∣v1…vn−1)=#v1…vn−1v / ∑u∈V#v1…vn−1u\Pr(v \mid v_1 \dots v_{n-1}) = \#v_1 \dots v_{n-1} v \,/\, \sum_{u \in V} \#v_1 \dots v_{n-1} u (N-Gram Model)
  • softmax([x,0])=(σ(x),σ(−x))\text{softmax}([x, 0]) = (\sigma(x), \sigma(-x)) (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

softmax([x,0])1=exex+e0=exex+1=11+e−x=σ(x)\text{softmax}([x, 0])_1 = \frac{e^x}{e^x + e^0} = \frac{e^x}{e^x + 1} = \frac{1}{1 + e^{-x}} = \sigma(x)

(divide numerator and denominator by exe^x). Likewise

softmax([x,0])2=1ex+1=11+e−(−x)=σ(−x),\text{softmax}([x, 0])_2 = \frac{1}{e^x + 1} = \frac{1}{1 + e^{-(-x)}} = \sigma(-x),

so softmax([x,0])=(σ(x),σ(−x))\text{softmax}([x, 0]) = (\sigma(x), \sigma(-x)), consistent with σ(x)+σ(−x)=1\sigma(x) + \sigma(-x) = 1. 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 nn input embeddings into one vector of dimension n⋅dn \cdot d and apply one linear layer; it has (n⋅d)⋅d+d(n \cdot d) \cdot d + d parameters (weights + bias). A (very small) neural language model with context size nn.

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 kk indices of the ascending sort are the kk most likely tokens; renormalize their probabilities to sum to 11 and sample. Same idea as sampling from an n-gram distribution, restricted to the top kk.

SuccessSolution

B=(1/301/301/3001/401/401/401/4)∈R7×2B = \begin{pmatrix} 1/3 & 0 \\ 1/3 & 0 \\ 1/3 & 0 \\ 0 & 1/4 \\ 0 & 1/4 \\ 0 & 1/4 \\ 0 & 1/4 \end{pmatrix} \in \mathbb{R}^{7 \times 2}

Column jj of ABAB is AbjA b_j, a linear combination of the document columns of AA with the weights in bjb_j: 1/31/3 for documents 1–3, resp. 1/41/4 for documents 4–7 (Vector Space Model).

ExamTaskPointsSubtopics
DBIS Exam WS2324 (not published)Task 520 (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 520 (15 here)5.2 simplistic language model on embeddings, 5.3 top-kk sampling (5.1 logistic regression model: Linear Classifiers and Logistic Regression)
DBIS Exam WS1920 (not published)Task 4.15term-document matrix, averaging documents via A⋅BA \cdot B

Lectures#

  • DBIS_VL11 — vector space model, retrieval as q⊤Aq^\top A, 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

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only