← All posts

AI basics › How LLMs work

What are embeddings? How AI turns meaning into numbers

What embeddings are, how cosine similarity measures closeness in meaning, where they're used, and how to pick a model, with a small example I ran myself.

If you’ve read anything about building with AI lately, perhaps about RAG or vector databases, you’ve probably come across the word embeddings. It shows up in the API docs of AI companies, and many tutorials begin by telling you to embed your documents first. The word itself rarely gets explained, though, so it’s easy to come away with only a vague sense that it has something to do with vectors.

An embedding is a piece of data, such as a sentence or an image, turned into a list of numbers that captures its meaning. A trained model produces this list, and it places things with similar meanings close together. So a computer can tell how alike two pieces of text are just by measuring how close their numbers are. That’s also why you hear the word so often now. Before an AI chatbot can answer questions from documents you’ve given it, it has to find the passages that relate to each question, and embeddings are what let it search by meaning even when the words differ.

Meaning as a list of numbers

A vector is simply an ordered list of numbers. On a map, latitude and longitude are two numbers that mark a place, and places with similar numbers are close to each other. An embedding works like coordinates on a map of meaning, except that this map has hundreds of axes. The model in the example below, all-MiniLM-L6-v2, describes every sentence with 384 numbers (model card). Google’s Machine Learning Crash Course describes it the same way, as a vector in a space where similar items sit closer together.

Unlike latitude, though, none of these numbers has a name you could read, because the model works out where to put things during training. all-MiniLM-L6-v2, for instance, learned from more than a billion sentence pairs, such as a question and its answer, to bring the two halves of each pair close together. Nor is text the only thing you can embed. OpenAI’s CLIP, published in 2021, used 400 million image and caption pairs to place pictures and text in one shared space (CLIP paper).

Measuring closeness with cosine similarity

Once things are lists of numbers, you need a way to tell how close two lists are, and a common choice is cosine similarity. If you picture each vector as an arrow starting from the same point, cosine similarity looks only at the angle between two arrows. When they point the same way, the score is 1, at a right angle it’s 0, and in opposite directions it’s -1.

Sentence Transformers, the library in the example below, uses cosine similarity by default (similarity docs). According to the same page, once vectors are scaled to length 1, a simpler calculation called the dot product gives the same result, and all-MiniLM-L6-v2 ends with exactly that scaling step.

Six sentences, side by side

Explanations only go so far, so let’s look at real numbers. I embedded six sentences that form three pairs with similar meanings. The first run downloads the model, which is about 90 MB.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
sentences = [
    "How do I reset my password?",
    "I forgot my login and can't get into my account.",
    "What's a good recipe for banana bread?",
    "How do you bake a moist banana loaf?",
    "The cat is sleeping on the sofa.",
    "A kitten naps on the couch.",
]
embeddings = model.encode(sentences)
print(embeddings.shape)
print(embeddings[0][:4].round(3))
(6, 384)
[ 0.007 -0.063 -0.072 -0.032]

(6, 384) means six sentences, each turned into 384 numbers, and the second line shows the first four numbers of the first sentence. These numbers only start to mean something when you compare them with other vectors, so let’s compare every pair.

# Cosine similarity between every pair of sentences
scores = model.similarity(embeddings, embeddings)
labels = ["password", "login", "bread", "loaf", "cat", "kitten"]
print(" " * 9 + "".join(f"{name:>9}" for name in labels))
for name, row in zip(labels, scores):
    print(f"{name:>9}" + "".join(f"{s:9.2f}" for s in row))
          password    login    bread     loaf      cat   kitten
 password     1.00     0.67     0.10     0.09     0.15    -0.02
    login     0.67     1.00     0.08     0.07     0.04    -0.03
    bread     0.10     0.08     1.00     0.74    -0.01    -0.05
     loaf     0.09     0.07     0.74     1.00     0.03     0.04
      cat     0.15     0.04    -0.01     0.03     1.00     0.70
   kitten    -0.02    -0.03    -0.05     0.04     0.70     1.00

The diagonal is 1.00 because each sentence is compared with itself. The three pairs score 0.67, 0.74, and 0.70, while every other combination stays between -0.05 and 0.15. The cat and kitten sentences share only the words “on the,” yet they score 0.70. Meanwhile, the password question and the banana loaf question both begin with “How do,” and they score just 0.09.

Search is only one step further. You embed the question the same way and sort the sentences by their score.

query = model.encode("Help, I'm locked out!")
hits = model.similarity(query, embeddings)[0]
for i in hits.argsort(descending=True)[:3]:
    print(f"{hits[i]:.2f}  {sentences[i]}")
0.52  I forgot my login and can't get into my account.
0.45  How do I reset my password?
0.07  What's a good recipe for banana bread?

The question doesn’t contain password, login, or account, yet the two account sentences come first. That’s semantic search in miniature. A real service might keep millions of vectors in a vector database, but the idea stays the same.

From word vectors to sentence vectors

Turning words into vectors isn’t a new idea. In 2013, Tomas Mikolov and colleagues at Google showed a way to learn good word vectors from 1.6 billion words in less than a day, and they released the code as word2vec (word2vec paper). The paper also shows a kind of arithmetic with meaning: take Paris, subtract France, add Italy, and Rome comes out closest.

Those were static embeddings, though, with one vector per word, so a word with several meanings had to share a single point. Transformer models such as BERT produce contextual embeddings instead, giving the same word a different vector in each sentence (Obtaining embeddings). But comparing two sentences with BERT meant feeding both into the model together, so finding the most similar pair among 10,000 sentences took about 65 hours. The 2019 Sentence-BERT paper brought that down to about 5 seconds by embedding each sentence once and comparing the vectors with cosine similarity. The sentence-transformers library I used above grew out of the work of its authors, Nils Reimers and Iryna Gurevych.

How embeddings differ from tokens and keywords

Tokens are often mixed up with embeddings. A token is a piece of text, a word or part of one, that a model reads, and each token has an ID number. The ID is only a position in the model’s vocabulary, so neighboring IDs don’t mean neighboring meanings. Inside the model, each token is first turned into a vector, which the Transformer paper calls learned embeddings (Attention Is All You Need). all-MiniLM-L6-v2 passes those vectors through its layers and then averages them into the single 384-number vector you saw above.

Keyword search finds documents that contain the same words as the query, which makes it fast and exact with names, error codes, and product numbers. Semantic search, as the Sentence Transformers semantic search docs explain, can also find synonyms, even when the words themselves don’t match. Because their strengths differ, some systems run both and merge the results, which is often called hybrid search.

Where embeddings are used

OpenAI’s embeddings guide lists search, clustering, recommendations, anomaly detection, diversity measurement, and classification as common uses. In more concrete terms, that means work like this.

  • Finding the help article that answers a question, even when the wording differs
  • Recommending products or posts close to the ones a person liked
  • Grouping reviews or support tickets by topic, which is called clustering
  • Spotting questions that were already asked in other words
  • Fetching related documents for an LLM before it answers, which is RAG

RAG stands for retrieval-augmented generation. In the 2020 RAG paper, Patrick Lewis and colleagues gave a language model a dense vector index of Wikipedia as its memory, searched by a neural retriever (RAG paper). It’s the same pattern as the six-sentence search above, only much bigger.

How to choose an embedding model

Here’s what to check first when picking a model, with the values for the model above.

What to check Why it matters all-MiniLM-L6-v2
Language Models handle the languages they learned best English
Dimensions More numbers take more storage and search time 384
Maximum input Anything longer gets cut off 256 word pieces
Where it runs Your own machine, or a paid API Locally, about 90 MB

If your text is in Korean or mixes languages, you’ll need a multilingual model. Dimensions vary a lot as well. OpenAI’s text-embedding-3-small, for example, returns 1,536 numbers by default, though the dimensions parameter can shorten them to save cost and storage (checked on October 27, 2026). And documents longer than the limit are often split into chunks before embedding.

To compare quality, a public benchmark called MTEB (Massive Text Embedding Benchmark) helps. Its 2022 paper evaluated models on 8 kinds of tasks across 58 datasets and 112 languages, and it found that no single method dominates across all tasks (MTEB paper). So on the MTEB leaderboard, I’d look at the scores for your own task and language before the overall average, and then check whether the right answers come back for a few dozen real questions from your own data.

Limits to keep in mind

Embeddings tend to capture what a sentence is about better than exactly what it says. With this small model, at least, that’s easy to see.

pairs = [
    ("The movie was good.", "The movie was not good."),
    ("Error E1042 on startup", "Error E2210 on startup"),
]
for a, b in pairs:
    score = model.similarity(model.encode(a), model.encode(b)).item()
    print(f"{score:.2f}  {a} / {b}")
0.80  The movie was good. / The movie was not good.
0.85  Error E1042 on startup / Error E2210 on startup

Even though the meanings are opposite or the codes differ, both pairs score higher than any pair in the table above, since each pair talks about the same subject. That’s why, when negation, numbers, or exact codes matter, it’s safer to add keyword search or a separate check.

The other limit is that every model has its own space. Here are the same six sentences, embedded by BAAI’s bge-small-en-v1.5, another model that also outputs 384 numbers.

other = SentenceTransformer("BAAI/bge-small-en-v1.5")
other_embeddings = other.encode(sentences)
print(other_embeddings.shape)
# Each sentence compared with itself, across the two models
print(model.similarity_pairwise(embeddings, other_embeddings).numpy().round(2))
(6, 384)
[0.29 0.32 0.33 0.31 0.15 0.23]

The sizes match, so the code runs without an error. Yet each sentence scores only 0.15 to 0.33 against its own vector from the other model, lower even than the 0.67 that the password and login sentences got inside one model. The same coordinates point to different places on each model’s map. So documents and questions must be embedded by the same model, and switching models means embedding every stored document again. The score you treat as similar has to be set for each model too, and the bge model card advises choosing a threshold from the score distribution on the data you actually work with.

Where to start

If you’d like to try it, install the library with pip install -U sentence-transformers (installation guide) and run the examples above with sentences you pick yourself. A short FAQ or a few product descriptions is enough to get a feel for what a model treats as close. The official quickstart covers the next step, searching a list of documents with a query. I ran these examples on October 27, 2026, on macOS with Python 3.13.12, sentence-transformers 6.2.0, and PyTorch 2.14.1.

AI tools helped with the research for this post.