Model Weights Explained: From Tokens to Embeddings in a RAG App
261206
What weights are
Weights are the adjustable numbers inside a machine learning model, and they hold everything the model has learned. If you build apps on top of LLMs or a RAG pipeline, knowing what weights are will help you understand why models behave the way they do, and what you can and can’t change.
A model is just a function: input goes in, output comes out. Inside that function are numbers that decide exactly how the input becomes the output. Those numbers are the weights, also called parameters.
The simplest model you can write is a straight line:
y = w * x + b
Say you want to predict pizza delivery time from distance:
delivery_minutes = 3 * distance_km + 10
Here w = 3 (each extra kilometre adds 3 minutes) and b = 10 (10 minutes to bake and pack, even at distance zero). b is called the bias, and it counts as a parameter too.
You didn’t write these numbers by hand. A training process found them by looking at hundreds of past deliveries. Change the numbers and you get a different model, with different predictions.
An LLM works on the same idea. The only difference is scale: instead of 2 numbers, it has billions of them.
How weights shape a prediction
A weight tells the model how much one input should count. Neural networks are made of small units called neurons, and each one does this calculation:
output = activation(w1*x1 + w2*x2 + w3*x3 + b)
Each input x is multiplied by its own weight w, the results are added up with the bias b, and an activation function decides what to pass on to the next layer.
Here’s a worked example. Imagine a tiny model that predicts a house price from three inputs, and training has given it these weights:
| Input | Value for our house | Learned weight | Contribution |
|---|---|---|---|
| Size (m²) | 80 | 3,000 | +240,000 |
| Age (years) | 10 | −500 | −5,000 |
| Distance to centre (km) | 5 | −2,000 | −10,000 |
| Bias | – | 50,000 | +50,000 |
| Predicted price | 275,000 |
Notice what the weights tell you:
- Large positive weight (size): this input pushes the prediction up a lot.
- Negative weight (age, distance): this input pushes the prediction down.
- Weight near zero: the model has learned to mostly ignore that input.
In a real neural network, neurons are stacked in many layers, and each layer’s output is the next layer’s input. You can’t read a single weight in an LLM and say what it means like we did here. Meaning is spread across millions of weights working together. The principle is still the same: weights decide how strongly each signal flows through the network.
How weights are learned
Nobody sets weights by hand. The model learns them from data in a repeating loop called training:
- Initialise: start every weight as a small random number.
- Forward pass: run a batch of examples through the model and get predictions.
- Loss: measure how wrong the predictions are with a loss function (for example, mean squared error).
- Backpropagation: for every weight, calculate its gradient, which says how the loss would change if that weight moved a little.
- Update: nudge every weight a small step in the direction that lowers the loss.
- Repeat thousands or millions of times.
The update rule in step 5 looks like this:
w_new = w_old - learning_rate * gradient
A quick example with real numbers: a weight is currently 0.8, its gradient is 2.0 (increasing it would make the error worse), and the learning rate is 0.01. The new weight is 0.8 - 0.01 * 2.0 = 0.78. That’s a tiny step in the right direction. Every weight in the model gets a step like this at the same time.
A useful picture: you’re on a foggy hillside trying to reach the valley floor. You can’t see the valley, but you can feel which way the ground slopes under your feet. The slope is the gradient, and the size of your step is the learning rate.
Here’s what that loop looks like in PyTorch:
import torch
model = torch.nn.Linear(3, 1) # 3 weights + 1 bias, like our house example
loss_fn = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(100):
for inputs, targets in data_loader: # one mini-batch at a time
predictions = model(inputs) # forward pass
loss = loss_fn(predictions, targets)
optimizer.zero_grad() # clear old gradients
loss.backward() # backpropagation
optimizer.step() # weights are updated HERE
Two terms you’ll see everywhere:
- Mini-batch: the small group of examples processed before each update (e.g. 32 or 256). One mini-batch means one update, also called one step.
- Epoch: one full pass through the whole training dataset. With 10,000 examples and a batch size of 100, one epoch is 100 updates.
You never write the derivatives yourself. Frameworks like PyTorch compute the gradients automatically when you call loss.backward().
When weights change and when they stay frozen
Weights only change during training. Once a model is deployed and answering requests, its weights are frozen.
There are a few kinds of training you’ll hear about:
| Process | Starts from | What changes |
|---|---|---|
| Pretraining | Random weights | All weights; the model learns general language from huge amounts of text |
| Fine-tuning | Pretrained weights | All or some weights; the model adapts to a task, domain or style using a smaller dataset and a smaller learning rate |
| LoRA (Low-Rank Adaptation) – parameter-efficient fine-tuning | Pretrained weights | Only small new adapter weights; the original weights stay frozen |
Fine-Tuning and How It Relates to Weights and model Training
Fine-tuning changes a model’s weights, but it isn’t a separate mechanism and it isn’t the only process that changes them. It uses the same steps as any training: forward pass, loss, backpropagation, optimizer.step(). Only the starting point and the goal differ.
“Training” is the umbrella term for any process that updates weights with gradient descent. Pretraining and fine-tuning are two stages of it:
– Random weights go through pretraining on huge, general data.
– The result is pretrained weights (a “base model”).
– These go through fine-tuning on small, specific data, and the result is fine-tuned weights (a specialised model).
Fine-tuning means continuing training from weights that are already trained. So, fine-tuning updates weights, using the same mechanism as all training. It is a later stage of training that starts from pretrained weights and uses smaller, targeted data and a smaller learning rate.
LoRa – Low-Rank Adaptation
LoRA stands for Low-Rank Adaptation. It was introduced in 2021 by researchers at Microsoft (Hu et al.) in the paper “LoRA: Low-Rank Adaptation of Large Language Models.” – It’s written LoRA, with a capital “A” at the end. LoRa, with a lowercase “a”, is a different thing: a long-range wireless radio technology for IoT devices.
What the name means
Adaptation: the method adapts (fine-tunes) a pretrained model to a new task or domain.
Low-Rank: it does that with small, low-rank matrices instead of changing the big weight matrices directly.
In LoRA and similar methods, the original weights stay frozen and only small added weights are trained.
Note 👉: when you chat with an AI assistant, your conversation does NOT change its weights. The model doesn’t learn from your messages. So, prompting, few-shot examples and RAG change the model’s input, not its weights. Its weights change only when someone deliberately runs training, such as the model provider releasing a new version or your team running a fine-tuning job.
Tokens, token IDs and the embedding matrix
Models can’t read text directly; they need numbers. Getting from text to numbers takes two steps, and only the second one involves weights.
Step 1: the tokenizer (no weights). A tokenizer splits text into tokens (whole words or pieces of words) and replaces each token with an ID from a fixed vocabulary:
"Weights matter" -> ["Weight", "s", " matter"] -> [4371, 82, 5030]
The exact split and IDs depend on the tokenizer; these are made up for illustration. The vocabulary is a lookup list built before training. It’s not learned by gradient descent, and the IDs are just labels: ID 5030 isn’t “bigger” than ID 82.
Step 2: the embedding matrix (weights). The embedding matrix is a table with one row per token in the vocabulary. Each row is a vector of numbers, and every number in it is a weight. Turning a token ID into a vector just means looking up its row.
Here’s a toy version with a 4-token vocabulary and 3-dimensional vectors:
| Token ID | Token | Embedding (a row of weights) |
|---|---|---|
| 0 | “cat” | [0.21, −0.84, 0.33] |
| 1 | “dog” | [0.19, −0.79, 0.41] |
| 2 | “bank” | [−0.62, 0.15, 0.90] |
| 3 | “the” | [0.02, 0.05, −0.11] |
In a real LLM, the table is huge. With a vocabulary of 128,000 tokens and 4,096 numbers per row, the embedding matrix alone has about 524 million weights.
These rows start out random and are trained like every other weight. Over millions of training steps, tokens used in similar ways drift towards similar vectors. Notice how “cat” and “dog” have similar numbers in the toy table. Nobody programs that; it comes from training.
One detail to keep in mind: an embedding-matrix vector is static. The token “bank” always gets the same row, whether the sentence is about a river or about money. The model’s later layers (more weights) mix in the surrounding words to produce contextual vectors, where the two meanings of “bank” end up different.
Embedding models: weights that turn text into vectors
A text embedding model is a separate neural network whose job is to turn a whole piece of text into one vector that captures its meaning. It’s the engine behind semantic search, and it’s at the heart of every RAG app.
It has weights just like an LLM, and the inside looks similar:
- Its own tokenizer splits the text into token IDs.
- Its own embedding matrix turns each ID into a vector (weights).
- Transformer layers turn those into contextual vectors (more weights).
- A pooling step, often averaging, combines them into one vector for the whole text.
The main difference is in how it’s trained. An LLM learns to predict the next word. An embedding model is usually trained with a contrastive loss: it sees pairs of texts that belong together (a question and its answer, two paraphrases) and adjusts its weights so matching texts land close together and unrelated texts land far apart.
Here’s what using one looks like with the sentence-transformers library:
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
sentences = [
"How do I reset my password?",
"Steps to change your login password",
"Best pizza places in town",
]
vectors = model.encode(sentences)
print(vectors.shape) # (3, 384): one 384-number vector per sentence
print(util.cos_sim(vectors[0], vectors[1])) # high score: similar meaning
print(util.cos_sim(vectors[0], vectors[2])) # low score: unrelated
The first two sentences share almost no words, but they get similar vectors because they mean similar things. That’s the model’s weights at work.
Keep one rule in mind: the vectors are outputs, not weights. The weights live inside the model. The vectors are what the model produces when you run text through it, the way a calculator’s answers aren’t part of the calculator.
Where weights sit in a RAG app
A RAG (Retrieval-Augmented Generation) app uses two separate models, each with its own tokenizer, embedding matrix and weights: an embedding model to find relevant text, and an LLM to write the answer.
The work happens in two paths.
Indexing path (runs when you add documents):
- Split your documents into chunks, e.g. a few paragraphs each.
- The embedding model turns each chunk into a vector. Inside, its tokenizer creates token IDs, its embedding matrix looks up their rows, and its layers and pooling produce the final vector.
- Store each vector, together with the chunk’s text, in a vector database.
Query path (runs on every user question):
- The user asks a question.
- The same embedding model turns the question into a vector.
- The vector database finds the stored vectors closest to it, which are the most relevant chunks.
- Your code puts the text of those chunks and the question into a prompt.
- The LLM tokenizes the prompt with its own tokenizer, runs it through its own weights, and generates the answer.
Here’s where weights live, and when they change:
| Component | Has weights? | When it changes |
|---|---|---|
| Tokenizer / vocabulary | No (a fixed lookup list) | Only when a new model version is built |
| Embedding model | Yes | Only when you fine-tune it or switch to another model |
| Vector database | No (it stores the embedding model’s outputs) | Every time you add, delete or re-embed documents |
| Retrieved chunks and prompt | No (just text) | On every request |
| LLM | Yes | Only when the provider releases a new version or you fine-tune it |
Two things in this picture often surprise developers:
- The LLM never sees your stored vectors. The vectors are only used for searching. The LLM receives the chunks as plain text in the prompt and turns them into its own tokens and embeddings.
- Nothing in a RAG app trains anything. Adding documents, asking questions and generating answers are all inference. Every weight in both models stays exactly the same. RAG gives the model new information by putting it in the prompt, not by changing its weights.
Rules of thumb for RAG developers
Knowing where the weights sit leads straight to a few practical rules:
- Use the same embedding model for documents and queries. Different weights produce different vector spaces. A query vector from model B compared with document vectors from model A gives meaningless similarity scores, like measuring some things in centimetres and others in inches.
- If you change the embedding model, re-embed everything. Fine-tuning it or upgrading to a new version changes its weights, so every vector already in your database is out of date. Re-run all your chunks through the new model and replace the old vectors. This is called re-indexing, and it’s why teams change embedding models carefully.
- Store the model name with your vectors. Save which embedding model and version produced each index, so you always know whether a re-index is needed.
- Switching the LLM is cheap. The LLM only reads text, so you can swap it for a newer version without touching your vector database.
- Pick the right tool: use RAG when the model needs new or private knowledge (your docs, your data). Consider fine-tuning when you need to change behaviour: a style, a format, a specialised task. Many apps use both.
Wrapping up
Weights are the learned numbers that decide how a model turns input into output. Training finds them by repeatedly nudging each one to make the model less wrong, and after that they stay frozen while the model is in use.
In a RAG app, weights live in two places: the embedding model, which turns text into vectors for search, and the LLM, which writes the answer. Tokenizers, vector databases and prompts have no weights. If you remember that vectors are outputs and weights are the model, most RAG design decisions become much easier to reason about.
That’s it for now! I hope you enjoyed it!
Thanks for reading and stay tuned!
