From model to assistant: fine-tuning, RLHF and RAG
In the previous part we saw how a Transformer is trained: billions of sentences, a single task, predicting the next token. At the end of that training there is a model that knows the language extremely well. And yet, if we write «What is the capital of France?», it might reply «What is the capital of Germany? What is the capital of Spain?», as if it were continuing a list of quiz questions.
This is not a mistake: it is exactly what it was trained to do. A pre-trained model continues text, it does not answer. In this final part we see how we get from a model that completes sentences to an assistant that holds a conversation, which limits remain, and how retrieval-augmented generation (RAG) helps to overcome some of them.
From completion to conversation
The first step is supervised fine-tuning on instructions (instruction tuning). We take the pre-trained model and keep training it, with the same next-token objective, on tens or hundreds of thousands of carefully written examples: a request and a good answer. «Summarise this text» followed by a summary, «Translate into Italian» followed by a translation. The model does not learn new things about the world, it learns a new format: when a question arrives, what follows is an answer.
So that the model knows who is speaking, conversations are written with a chat template: special tokens that mark the start and end of each turn and the role of the writer (system, user, assistant). The first block is the system prompt, a text of general instructions the user usually does not see: «You are a polite assistant, answer in English, do not make up data». For the model it is still just text in the context, but training has taught it to give it a lot of weight.
The second step is preference alignment. It is often easier to judge an answer than to write one: so people are asked to compare two answers to the same question and pick the better one. These comparisons are used to train a reward model that scores answers, and the language model is then optimised with reinforcement learning to earn high scores. This is RLHF (reinforcement learning from human feedback), made famous by the InstructGPT work of Ouyang et al. (2022). More recent methods, such as DPO, reach a similar result without a separate reward model: they use the «preferred answer / rejected answer» pairs directly as training data.
The limits: frozen knowledge and hallucinations
Even the best assistant carries two structural limits. The first: its knowledge is frozen at the date the training data was collected. It knows nothing about what happened afterwards, nor about a company’s internal documents or articles it has never seen.
The second is hallucinations: fluent, confident and wrong answers. They are not an occasional fault but a consequence of the mechanism: the model generates the most plausible text, not verified text. If the question is about a rare detail, a quotation or a precise number, the most plausible continuation may be invented, in the same tone as a correct answer.
RAG: answering from the sources
The idea of Retrieval-Augmented Generation, proposed by Lewis et al. (2020), is simple: instead of asking the model to remember, we give it something to read. The procedure has four steps.
- Preparation: the documents are split into chunks (chunking) of a few hundred words, and for each chunk we compute an embedding, the vector that represents its meaning (we saw it in the second part of the series).
- Retrieval: the question also becomes an embedding, and we look for the k nearest chunks with cosine similarity (top-k).
- Prompt: the chunks found are pasted into the prompt, numbered, with precise instructions: answer only using these sources, cite them as [1] and [2], and if the answer is not there say «I don’t know».
- Generation: the model writes the answer by reading the sources it has in its context.
The details matter. Chunks that are too small lose context; chunks that are too large dilute the useful part and use up tokens. A low k risks leaving out the right passage, a high one fills the prompt with noise.
RAG reduces hallucinations, but it does not eliminate them. If retrieval finds the wrong chunk, the model will answer consistently with an irrelevant source; if the sources contradict each other, it may blend them; and nothing fully stops it from adding something of its own. The real advantage is that citations make the answer verifiable: the reader can open source [2] and check.
Tools, agents and responsible use
RAG is a special case of a more general idea: giving the model tools. The model is trained to produce, instead of an answer, a structured request such as «call the search with these words» or «run this code». The program hosting it executes the call, puts the result back into the context and the model carries on. A calculator avoids arithmetic mistakes, a search engine brings fresh information, a Python interpreter does the sums on the data. When the model repeats this loop several times, deciding the next step by itself, we speak of agents.
More power means more need for evaluation. An LLM-based system should be measured on test questions with known answers: are the retrieved sources the right ones? Is the answer faithful to the sources? Can it say «I don’t know»? And it should be used responsibly: check important claims, do not paste personal or confidential data without knowing where it ends up, and remember that a confident tone is no guarantee of truth.
What to try in the demo
The demo calls no external AI: it shows the retrieval part and the construction of the prompt, i.e. what a RAG system sends to the model. When it runs on the site it searches the site’s own articles; otherwise it uses a small built-in corpus. For simplicity, retrieval uses TF-IDF (shared words, weighted by rarity) instead of neural embeddings.
- Pick «What is overfitting?» and press Step several times: watch the pipeline move from question to retrieval, prompt and answer.
- Move the k slider from 1 to 5 and see how the prompt and the token estimate grow.
- Try «Who won the 1982 football championship?»: no source contains the answer and the system has to say «I don’t know».
- Ask a question with a synonym that does not appear in the texts: lexical search does not recognise it, while embeddings would. Also notice the opposite case: a source can be found just because it shares a common word with the question.
- Switch between «Site articles» and «Built-in corpus» (when the first is available) and compare the sources found for the same question.
In Python
Here is a complete mini-RAG, except for the last step: with sentence-transformers we compute the embeddings of six documents, find the two closest to the question and build the prompt.
from sentence_transformers import SentenceTransformer, util
documents = [
"Overfitting happens when a model learns the training data by heart.",
"K-means groups points into K clusters by moving centroids to the mean.",
"Gradient descent updates the weights in the direction opposite to the gradient.",
"An embedding is a vector that represents the meaning of a text.",
"In the Transformer, attention lets every token weigh the others.",
"Dropout randomly switches off some neurons during training.",
]
model = SentenceTransformer("all-MiniLM-L6-v2")
emb_docs = model.encode(documents, convert_to_tensor=True)
question = "How do I stop a network from memorising the data?"
emb_q = model.encode(question, convert_to_tensor=True)
scores = util.cos_sim(emb_q, emb_docs)[0] # similarity with every document
best = scores.topk(2).indices.tolist() # the two closest
sources = "n".join(f"[{n}] {documents[i]}" for n, i in enumerate(best, 1))
prompt = ("Answer using only the sources below and cite them as [1], [2].n"
"If the answer is not there, reply "I don't know".nn"
f"SOURCES:n{sources}nnQUESTION: {question}nANSWER:")
print(prompt)
The program prints the final prompt with the two most similar sources, probably the ones on overfitting and dropout, even though the question does not use the same words. That text can be sent to any LLM, local or through a service: the «smart» part of the retrieval we have already done ourselves.
This part brings the journey to a close. We started from tokens, the pieces text is broken into; we turned them into embeddings, vectors in which meaning becomes geometry; we saw that everything rests on next-token prediction; that attention lets every word look at the others; that the Transformer stacks these blocks and learns from enormous amounts of text; and finally how fine-tuning, alignment and source retrieval turn it into an assistant. To me, understanding these mechanisms is the best way to use LLMs well: knowing what they can do and, above all, where they can go wrong. To go deeper into recurrent networks, natural language processing and generative models, you will find it all in my book Deep Learning con Keras e Tensorflow (in Italian), and the Lab has more demos to explore.
The “Inside an LLM” series
- From text to numbers: tokenization
- Meaning as geometry: embeddings
- Predicting the next word
- Attention, explained
- The Transformer and its training
- From model to assistant: fine-tuning, RLHF and RAG