Generative AIby Dhruv Narang

1. The Goal

We have a chunk of text, "the river bank". We want one vector for it. Who turns the chunk into a vector?

We have
"the river bank"
one chunk of text
→
Embeddingmodel
→
We want
[0.9, 0.3, 0.3]
one vector, the same size every time
The answer
The embedding model turns the chunk into the vector. A company such as OpenAI or Mistral already made it. We do not build it. Next we look inside it, to see how it works.

2. Inside the Embedding Model: Four Steps

The embedding model is already made by a company. We are not building it. We only look inside to see how it works. It does four steps, one after another.

Step 1
TokenizerCut the chunk into pieces and give each piece an ID.
comes out318, 12456, 6190
Step 2
Embedding tableLook up one row of numbers for each ID, and copy it.
comes out3 rows of numbers
Step 3
AttentionEach row looks at the other rows and changes using the context.
comes out3 rows that know the context
Step 4
Average and normalizeMix the rows into one, and set its length to 1.
comes out1 vector
Steps 1 and 4 are plain programs. Steps 2 and 3 use numbers that were learned when the company trained the model.

3. Step 1: The Tokenizer Cuts the Text

The first step cuts the chunk into small pieces, and gives each piece an ID.

The chunk
the river bank
Cut into pieces
theriverbank
Each piece gets an ID
318124566190
  • The tokenizer is a normal program. It is not a neural network. It has a fixed list of pieces and cuts the text using it.
  • Pieces are not always whole words. A rare word can be split into several pieces. That is how the model can handle any word.
  • The ID is a row number. In the next step we use it to find a row in the embedding table.
  • A model needs its own tokenizer. Its IDs match the rows of its own embedding table.

4. Step 2: The Embedding Table Gives the Rows

The second step looks up one row of numbers for each ID in the embedding table.

Text
theriverbank
IDs from the tokenizer
318124566190
Rows copied from the embedding table
col 1col 2col 3
the0.500.401.60
river2.800.400.50
bank1.601.400.30
The ID is the row number in the embedding table. We copy the row. The embedding table never changes while we use it. Its numbers were learned when the model was trained. But the row for "bank" is the same in every sentence, so it does not yet know if this is a river bank or a money bank.

5. Step 3: Attention Uses the Context

Our rows are generic. Attention changes them using the other words in the sentence.

Where we are. After steps 1 and 2 we have three generic rows. "bank" has the same row in every sentence, so it does not know that this one is about a river.

col 1col 2col 3
the0.500.401.60
river2.800.400.50
bank1.601.400.30
Definition

Attention lets each word look at the other words in the sentence and take a share of their meaning, so that its row fits the sentence.

We do it for "bank" in three steps:

Step A: Compare
the1.84
river5.19
bank4.61
How related is each word to "bank"? A score for each word.
→
Step B: Make shares
the2%
river63%
bank35%
Softmax turns the scores into shares that add up to 100%.
→
Step C: Mix
col 12.33
col 20.75
col 30.45
The new "bank" row: each word's row times its share, added up.

Step A: compare. Multiply the matching numbers of two rows and add them up (a dot product). A bigger score means the rows are more alike.

"bank" withMultiply the matching numbers, and addScore
the1.6×0.5 + 1.4×0.4 + 0.3×1.61.84
river1.6×2.8 + 1.4×0.4 + 0.3×0.55.19
bank1.6×1.6 + 1.4×1.4 + 0.3×0.34.61

Step B: make shares. Softmax: raise e (about 2.718) to the power of each score, then divide each by the total. The shares add up to 1.

WordScoree to the power of the scoreShare = that number ÷ 286.2
the1.846.30.022 (2.2%)
river5.19179.50.627 (62.7%)
bank4.61100.50.351 (35.1%)
Total286.21.000 (100%)

Step C: mix. Multiply each word's row by its share, then add the three results.

WordShareIts rowShare × its row
the0.022[0.5, 0.4, 1.6][0.011, 0.009, 0.035]
river0.627[2.8, 0.4, 0.5][1.756, 0.251, 0.313]
bank0.351[1.6, 1.4, 0.3][0.562, 0.491, 0.105]
Add them up[2.328, 0.751, 0.454]
Before
[1.6, 1.4, 0.3]   closeness to the “river” row: 0.84
After (river sentence)
[2.328, 0.751, 0.454]   closeness to the “river” row: 0.99

In "the money bank" the same steps use the "money" row, [0.3, 2.7, 0.6], instead of "river". The scores become 1.84, 4.44 and 4.61, and the new "bank" row is [0.989, 1.942, 0.475]: it moves toward "money" (closeness 0.74 to 0.94). The embedding table does not change. Only the copies change, for this sentence.

It is called attention because each word pays attention to the other words and decides how much each one matters. A real model does this for every word at once, and repeats it in many layers.


6. Step 4: Average and Normalize

The last step turns many rows into one vector.

Where we are. After attention we have three rows, one for each word. We need one vector for the whole chunk, so we average them and then normalize. Three steps:

Step A: Average
col 12.143
col 20.590
col 30.668
Add the three rows and divide by 3. One row for the whole chunk.
→
Step B: Magnitude
sum of squares5.385
magnitude2.321
Square each number and add them. The square root is the magnitude.
→
Step C: Divide
col 10.923
col 20.254
col 30.288
Divide each number by the magnitude. This is the embedding.

Step A: average. Add the three rows column by column, then divide by 3.

col 1col 2col 3
the1.3600.5731.055
river2.7400.4450.494
bank2.3280.7510.454
Add the three rows6.4281.7692.003
Divide by 3 (the average)2.1430.5900.668

The last line is one row of numbers for the whole chunk.

Step B and Step C: normalize. Normalizing means scaling the row so its magnitude becomes 1, without changing its direction. The magnitude is the length of the row as an arrow: square each number, add the squares, take the square root (Step B). Then divide every number by it (Step C).

What we docol 1col 2col 3All three
The average row2.1430.5900.668
Square each number4.5920.3480.446add them: 5.385
Square root of that sum = the magnitude2.321
Divide each number by 2.321 = the embedding0.9230.2540.288

This final row, [0.923, 0.254, 0.288], is the embedding of "the river bank". Its magnitude is 1.

Why divide by the magnitude? A long chunk and a short chunk about the same topic give arrows of different lengths, but the same direction. The direction carries the meaning. Dividing by the magnitude keeps only the direction, so comparisons between vectors are fair. Here is the idea with a small example.

112233445[3, 4]length 5[0.6, 0.8]length 1SAME DIRECTION, DIFFERENT LENGTH
The example
The row [3, 4]
Its magnitude
√(3×3 + 4×4) = √25 = 5
Divide by 5
[3 ÷ 5, 4 ÷ 5] = [0.6, 0.8]
The new magnitude
√(0.6×0.6 + 0.8×0.8) = √1 = 1

The red arrow is [3, 4], the green arrow is [0.6, 0.8]. They point the same way. Only the length changed, from 5 to 1.


7. Does the Length Carry Meaning?

We divided by the magnitude and kept only the direction. Is the length really worth nothing?

Why do we throw the length away? It depends on how the model was trained. It is not a law of maths that length means nothing. Most text embedding models are trained so that texts with the same meaning point the same way. Only the direction is rewarded, so the model has no reason to put anything useful into the length. The length is what is left over.

What is the difference between [3, 4] and [6, 8]? They point the same way, and the second is twice as long. It depends on the model:

A model trained on direction
(most text embedding models)
A model trained for the dot product
(a few models)
What the length meansNothing useful. It can come from things like the length of the text, or how the words were averaged.It can carry a signal, such as how important or popular something is.
Are [3, 4] and [6, 8] the same?Yes, the same meaning.No. The longer one can score higher for every question.
What we doNormalize. Compare by direction (cosine).Do not normalize. Use the metric the docs say, the dot product.

The exception is the second column. The dot product uses the angle and the length together, so a model trained for it can use the length. If you used cosine on such a model, or normalized its vectors, you would throw that signal away.

What this means for us. For the models in this course, the direction is the meaning. Many text embedding models already return vectors of length 1, or normalize inside, so this step costs nothing. Check your model's docs for which metric it was trained for. If it says dot product, follow it.


8. In Code

One call does all four steps for you. Which model you call depends on your app.

Which embedding model do I use? It depends on the provider of your app. Every provider has its own LangChain class. You change only the import and the model name, because all of them have the same two methods: embed_query for one text and embed_documents for a list of chunks. The code below is the one from your file.

Pick onean embedding class for each provider
install: pip install langchain-mistralailangchain-openailangchain-google-genailangchain-huggingface sentence-transformers
from langchain_mistralai import MistralAIEmbeddings

embedding_model = MistralAIEmbeddings(model="mistral-embed")

query = "What is the capital of France?"
query_vec = embedding_model.embed_query(query)

print(f"Vector Dimensions: {len(query_vec)}")
print(f"Sample First 5 Floats: {query_vec[:5]}")from langchain_openai import OpenAIEmbeddings

embedding_model = OpenAIEmbeddings(model="text-embedding-3-small")

query = "What is the capital of France?"
query_vec = embedding_model.embed_query(query)

print(f"Vector Dimensions: {len(query_vec)}")
print(f"Sample First 5 Floats: {query_vec[:5]}")from langchain_google_genai import GoogleGenerativeAIEmbeddings

embedding_model = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")

query = "What is the capital of France?"
query_vec = embedding_model.embed_query(query)

print(f"Vector Dimensions: {len(query_vec)}")
print(f"Sample First 5 Floats: {query_vec[:5]}")from langchain_huggingface import HuggingFaceEmbeddings

embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

query = "What is the capital of France?"
query_vec = embedding_model.embed_query(query)

print(f"Vector Dimensions: {len(query_vec)}")
print(f"Sample First 5 Floats: {query_vec[:5]}")
Output (example)
Vector Dimensions: 1024
Sample First 5 Floats: [-0.0069, -0.053, 0.040, 0.218, -0.031]Vector Dimensions: 1536
Sample First 5 Floats: [0.012, -0.034, 0.057, -0.008, 0.021]Vector Dimensions: 3072
Sample First 5 Floats: [0.004, -0.021, 0.018, 0.033, -0.009]Vector Dimensions: 384
Sample First 5 Floats: [-0.045, 0.012, 0.087, -0.003, 0.031]
  • Only two lines change from tab to tab: the import and the model line. The query and the two prints stay the same.
  • Import the embedding class from the provider's own package: langchain_mistralailangchain_openailangchain_google_genailangchain_huggingface. Create the model with the class MistralAIEmbeddingsOpenAIEmbeddingsGoogleGenerativeAIEmbeddingsHuggingFaceEmbeddings, and put the model name inside the brackets.
  • The size of the vector depends on the model: 1,0241,5363,072384 numbers here.
  • Put its API key in your .env file. This is the one used in this course.Put its API key in your .env file. Put its API key in your .env file. No API key is needed. The model is downloaded the first time you run it.
  • The embedding model and the chat model are separate choices. You can embed with Mistral and answer with Gemini. Pick the embedding model by quality, cost and size, and the chat model by what you want to say.
  • Use the same embedding model for the chunks and the question. The vectors of two models do not match.
  • The vector database must match the size. A collection fixed at 1,024 numbers cannot take a 1,536-number vector. If you change the model, embed all the chunks again into a new collection.
  • Some models let you shorten the vector. OpenAI has a dimensions setting, and Google has output_dimensionality. A shorter vector saves space but keeps less detail.
  • Model names and sizes change. These are examples, so check the provider's docs for the current names.

The output numbers are examples. Yours will differ, but the size is fixed for each model.