HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 13 of 25 — Generative AI Fundamentals
intermediate Chapter 13 of 25

Embeddings Explained: Word, Sentence and Vector Embeddings

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

What Are Embeddings in Generative AI?

Embeddings are numerical vectors that represent inputs such as tokens, sentences or documents. A model learns the coordinates during training so that the vectors can support tasks such as next-token prediction or semantic search. In a search model, texts with related meanings or relevant information often receive vectors that score highly against each other.

An embedding is usually dense: its coordinates typically contain many nonzero values, and a property can be represented across multiple coordinates. Compare this with a one-hot representation for a vocabulary of 50,000 tokens. Each one-hot vector contains one 1 and 49,999 zeros. Every pair of distinct tokens has dot product zero, so that representation gives you no reason to judge cat closer to kitten than to chair. A learned vector space can express that difference.

Two uses of the word embedding frequently come up in engineering work. Inside a language model, a token embedding is an input to the network. In a search application, a sentence or passage embedding is an output that can be stored and compared with other vectors. Both are arrays of real numbers, but their training objectives and intended uses differ. Taking a row from a language model's token table is rarely a sensible way to represent a complete support ticket.

How Does an Embedding Layer Turn Token IDs into Vectors?

Tokenization splits text into units such as whole words, subword pieces or punctuation, then maps those units to integer IDs. An ID is a lookup key. The fact that two IDs are consecutive says nothing about the meanings of their tokens. The embedding layer converts each ID into the learned vector stored at that row.

Token ID 3797 selects one row from an embedding table and returns its 768 coordinates.
The token ID selects a row, while the embedding dimension determines how many numbers that row contains.

Let E be a table of shape (V, d), where V is the vocabulary size and d is the embedding dimension. Given a token ID t, the output is E[t]. If an illustrative tokenizer emits ID 3797 and d = 768, the lookup returns all 768 coordinates of row 3797, perhaps beginning [0.23, -0.12, 0.45, ...]. Multiplying a one-hot row vector by E would produce the same numbers. An implementation can gather the row directly without creating that one-hot vector.

For a batch of 8 sequences padded to 128 token positions, the ID tensor has shape (8, 128). The embedding output has shape (8, 128, 768). This is still one vector per token position. The lookup has neither combined the sequence into one vector nor used neighbouring tokens to work out what a word means.

In a Transformer, subsequent layers compute contextual hidden states. Consider bank in “the bank approved the loan” and “the bank was eroded by the river.” If the tokenizer assigns the same ID in both cases, the raw lookup is identical. After attention and other layer operations, the representations at those positions can differ because they incorporate different surrounding tokens. Position also matters: depending on the architecture, position information may be added to inputs or incorporated inside attention.

In a next-token model, the training loss compares predictions with the actual next tokens. Backpropagation carries gradients through the network into the embedding table. If an embedding row is used several times in a batch, gradients from those lookup positions accumulate for that row. Some models share the table with the output prediction layer, in which case the output computation can also contribute gradients. At inference, the table is normally held fixed.

What Is the Difference Between Word and Sentence Embeddings?

Classic word embeddings, such as Word2Vec vectors, are static: each vocabulary word has one learned vector. In the skip-gram setup, a training example pairs a centre word with a nearby word. Learning to score observed word pairs above sampled alternatives can place words with similar usage near each other. The representation can capture semantic and syntactic patterns, but a single static vector has to serve every sense of a word.

Sentence embeddings compress a sequence into one fixed-size vector. A common design runs the token sequence through a Transformer encoder and pools its contextual token states. With masked mean pooling, v = sum(m_i * h_i) / sum(m_i), where h_i is the state at position i and m_i is 1 for included positions and 0 for excluded positions such as padding. If two included states are [2, 0] and [0, 4], and a third state belongs to padding, the mean is [1, 2]. Including the padding state would change the result.

Other models use a designated sequence token or a learned pooling method, sometimes followed by a projection that changes the final dimension. Use the pooling and preprocessing expected by the trained model. Mean pooling an arbitrary language model's token states will produce a vector of the right shape, but that alone tells you little about whether cosine similarity will rank paraphrases well.

RepresentationWhat one vector representsContext dependenceTypical use
Static word embeddingOne vocabulary wordSame vector across occurrencesWord-level features and vocabulary analysis
Token embedding lookupOne vocabulary token or subwordSame table row for the same IDInput to a language model
Contextual token stateOne token occurrence at a specific layerDepends on the available sequence contextNamed entity recognition and other token-level tasks
Sentence or passage embeddingOne sequence, after pooling or equivalent aggregationDepends on the encoded sequenceSemantic search, clustering and candidate retrieval

A document embedding is subject to the encoder's input limit. A long policy document may get truncated before the relevant paragraph, or its single vector may combine unrelated topics. If you need to retrieve supporting evidence, encode passages separately and keep the source document ID and passage location with each vector. This also gives the application a way to show the text behind a match.

How Do Models Learn a Vector Embedding Space?

For semantic search, a common architecture is a bi-encoder: it turns the query and each candidate passage into vectors independently. The encoders may share weights. Training pairs can come from examples such as a question and its relevant help article. The aim is to assign the positive pair a higher score than irrelevant pairs, including hard negatives that share words with the query but answer a different question.

One training objective takes a batch of matched query and passage pairs. For query i, it scores every passage j with s_ij = cos(q_i, p_j) / T, where T is a positive temperature. If passage i is the only positive for query i, its loss is -log(exp(s_ii) / sum_j exp(s_ij)). In code this is typically computed using cross-entropy on the score matrix rather than explicitly taking exponentials. A relevant passage that is incorrectly treated as a negative creates a conflicting training signal, so the choice of examples matters.

The geometry reflects the training task. A retrieval model may put “UPI payment debited but order pending” near “What to do when your payment succeeds and the merchant does not receive confirmation.” This is evidence of relevance, even though the sentences are not interchangeable. A paraphrase model may favour a different ordering. Some retrieval models also expect different prefixes for queries and passages. Those prefixes are part of the model's input format.

An embedding with 768 dimensions has 768 coordinates per point. That does not imply that one axis means “animal” and another means “furniture.” Applying the same orthogonal rotation to every vector preserves all pairwise cosine scores while changing individual coordinates. To inspect groups in two dimensions, you can project sample vectors with PCA, which keeps directions of high variance. A plot may show groups of animals, furniture and fruits, but projection can hide neighbours or distort distances. Check any apparent group in the original space before drawing conclusions.

How Does Cosine Similarity Measure Semantic Similarity?

Cosine similarity compares the directions of two nonzero vectors. The dot product multiplies corresponding coordinates and sums the results. The L2 norm is the square root of the sum of squared coordinates. Dividing by both norms removes the effect of positive rescaling:

The cat and kitten vectors meet at a small angle, while the chair vector is perpendicular to the cat vector.
In this toy space, cat and kitten have cosine similarity 0.96, while cat and chair have cosine similarity 0.

cos(A, B) = (A · B) / (||A||₂ * ||B||₂)

The mathematical range is [-1, 1]. A score of 1 means the vectors point in the same direction, 0 means they are orthogonal, and -1 means they point in opposite directions. These are geometric statements. An orthogonal pair need not be semantically unrelated, and opposite directions need not represent antonyms. Words such as “enable” and “disable” can appear in very similar contexts and score highly. A cosine score is also not a probability.

Worked example: Rank three toy vectors

Suppose the query vector for cat is [3, 4, 0] and your candidates are kitten = [4, 3, 0], chair = [0, 0, 5] and cat care = [6, 8, 0]. These are hand-picked coordinates for arithmetic practice. They are not outputs from a trained model.

  1. Compute the norms. Cat, kitten and chair each have norm 5. Cat care has norm 10.
  2. Compute the dot products with cat. Kitten gives 3*4 + 4*3 = 24. Chair gives 0. Cat care gives 3*6 + 4*8 = 50.
  3. Divide each dot product by both norms. Kitten scores 24/25 = 0.96, chair scores 0/25 = 0, and cat care scores 50/50 = 1. Ranking from highest to lowest gives cat care, kitten, then chair.

The example also shows why the metric matters. By raw Euclidean distance, kitten is sqrt(2) from cat, while cat care is 5 units away. Cosine ranks cat care first because it ignores the difference in length. If both vectors are L2-normalized to unit length, cosine equals their dot product. Squared Euclidean distance then equals 2 - 2*cos(A, B), so ascending Euclidean distance and descending cosine give the same ranking. Reject or handle zero vectors explicitly because their cosine is undefined.

How Do You Build Semantic Search with Embeddings in Python?

This example uses Sentence Transformers to encode a small help centre and FAISS to rank passages. Install the packages with python -m pip install sentence-transformers faiss-cpu. The first run may download the model files. The corpus vectors are computed once; each incoming query needs only one new encoding. That separation also makes embedding search useful in retrieval-augmented generation, where the system passes selected source text to a generator.

import faiss
import numpy as np
from sentence_transformers import SentenceTransformer

passages = [
    "If your UPI payment was debited but the order is pending, "
    "check the transaction status before paying again.",
    "To change your delivery address, open Orders before dispatch.",
    "A digital invoice is available under Billing after payment.",
    "To change your account password, open Security settings.",
]

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

def encode(texts):
    vectors = model.encode(
        texts,
        normalize_embeddings=True,
        convert_to_numpy=True,
    )
    return np.ascontiguousarray(vectors, dtype=np.float32)

corpus = encode(passages)                 # shape: (4, d)
index = faiss.IndexFlatIP(corpus.shape[1])
index.add(corpus)

query = encode(["Money left my bank account but my order is not confirmed."])
scores, row_ids = index.search(query, k=2)

for score, row_id in zip(scores[0], row_ids[0]):
    print(f"{float(score):.3f}  {passages[int(row_id)]}")

The model handles tokenization, contextual encoding and its configured pooling. The explicit normalization means that IndexFlatIP, an exact inner-product index, returns cosine scores. With a single query and k=2, the score and ID arrays both have shape (1, 2). The IDs refer to insertion order because this example uses a flat index without custom IDs. The first passage is the intended match; inspect the returned ranking rather than assuming the model gets it right.

A flat index compares the query with every stored vector, which costs roughly O(N*d) for N vectors of dimension d. It is a useful baseline. If exact scanning becomes too slow, vector indexes such as HNSW and IVF can reduce search work, with trade-offs in recall, memory and index construction. Compare their results against exact search to separate indexing errors from mistakes made by the embedding model.

How Do You Evaluate and Deploy Vector Embeddings?

Start with real queries and label the passages that answer them. Use Recall@k to measure how many labelled relevant passages appear in the first k results. If a query has four relevant passages and the top five contain three of them, its Recall@5 is 3/4 = 0.75. Average the per-query values over a test set with relevance labels. Also inspect the first few ranks: two systems with the same recall can place the first usable answer at very different positions.

Include examples where dense retrieval can fail: nearly identical product codes, policy exceptions, negated statements and questions with no answer in the corpus. For an Indian support application, test the languages and mixed-language queries that users actually submit. A model that ranks English help articles well may struggle with Roman-script Hindi or regional-language variants. Compare with a lexical baseline, especially for IDs and exact phrases, and consider combining lexical and dense results when their errors differ.

Keep query and corpus encoding compatible. Record the model revision, pooling, normalization and any required prefixes alongside the index configuration. Equal dimensions do not make vectors from different models comparable. If you change the model, plan to re-encode the corpus, rebuild the index and rerun the same evaluation. For capacity planning, one million 768-dimensional vectors stored as float32 take 1,000,000 * 768 * 4 = 3,072,000,000 bytes, about 3.07 GB for the vectors alone. Index structures, IDs and passage metadata add to that figure.

Choose thresholds on labelled examples from your own task. A top match always exists in a nonempty corpus, even for an unanswerable query. If the system feeds passages to a generator, evaluate retrieval and answer quality separately: a correct source may be retrieved and still be misread, or the source may never reach the generator. Those failure modes need different fixes.

Key Takeaways

  • A token ID selects a row in a learned table. Its integer value carries no similarity information.
  • Static word vectors, contextual token states and sentence embeddings represent different units and serve different tasks.
  • A sentence encoder combines token information into one vector using the pooling and preprocessing it was trained to use.
  • Cosine similarity measures direction, with no universal score that means two texts are semantically equivalent.
  • Unit-normalized vectors can be ranked by inner product to obtain cosine similarity rankings.
  • Evaluate on labelled queries and re-encode the corpus when switching to an incompatible embedding model.

Frequently Asked Questions

Are embeddings and tokens the same thing?

No. A token is a unit produced by a tokenizer, and a token ID is the integer assigned to that unit. A token embedding is the vector selected by that integer. A contextual token representation is computed later by the network. A sentence embedding is another kind of vector that represents an entire encoded sequence.

Why do antonyms sometimes have high cosine similarity?

Antonyms often occur around the same words. For example, instructions to enable and disable a setting may mention the same menus and controls. A model trained on contextual usage or retrieval relevance may place those instructions close together. For applications where polarity matters, test negated and reversed examples and verify the selected passage before acting on it.

Is a higher embedding dimension always better?

No. A larger vector uses more storage and generally increases the cost of scoring each candidate, but quality also depends on training data, the objective and your query distribution. Compare candidate models on the same labelled queries and hardware. Use reduced dimensions only when the model supports that option or when evaluation shows that your reduction preserves acceptable retrieval quality.

Can I compare embeddings from two different models?

Generally, avoid direct comparison. Two encoders can output vectors of the same length while assigning different coordinates to the same text. Use a single model with its prescribed query and passage formatting, or a pair of encoders trained to share a space. Rebuild your stored vectors when moving to an incompatible model.

When should I use cosine similarity instead of dot product?

Use the metric expected by the model or recommended for its retrieval setup. Cosine removes vector magnitude, which is helpful when direction is the intended signal. Raw dot product keeps magnitude in the score, so longer vectors can rank higher. With unit-normalized vectors, cosine and dot product are numerically equivalent up to floating-point rounding.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course