Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

LLM: understanding language models (Transformer, GPT, Llama)

21 min read
Improve this page

An LLM (Large Language Model) is a program that predicts the next word in a sentence, trained on billions of texts. This simple ability, repeated at large scale, makes it possible to generate coherent text, answer questions, summarize documents or write code. This guide explains how an LLM works, from tokenization to generation, through the Transformer architecture, which appeared in 2017.

What you will learn

  • Tokenization: how text is split into units the model can process (BPE, vocabulary)
  • Transformer architecture: the core of modern LLMs (embeddings, layers, attention)
  • Attention mechanism: how the model understands the relations between words (Query, Key, Value)
  • Training: the three phases that give the model its abilities (pre-training, fine-tuning, RLHF)
  • Text generation: decoding strategies (temperature, top-k, top-p)
  • Limits: hallucinations, biases, context window and solutions (RAG, agents)

History and evolution of language models

The history of language models did not begin with ChatGPT. It is a long quest to let machines understand human language, which has sped up in recent years.

At the start, between the 1950s and the 1990s, the approaches were statistical. Computers tried to predict the next word based only on the 2 or 3 previous words ("n-grams"). It was very limited: the models had no real understanding of what a sentence meant.

In the 2000s, neural networks brought a first revolution. Models such as RNNs (Recurrent Neural Networks) and later LSTMs became able to process whole sentences and to keep context better. However, they remained slow and struggled with dependencies over long texts.

The real turning point came in 2017 with the invention of the Transformer architecture by Google. Instead of reading the text word by word, the Transformer could analyze all the words of a sentence at the same time thanks to the attention mechanism. This innovation made it possible to process far larger amounts of text and to understand complex relations between words, even very distant ones.

This architecture is the basis of all modern LLMs. It opened the way to a race for size and performance, with models such as OpenAI's GPT, which went from a few billion to several hundred billion parameters in just a few years.

Three factors explain this recent explosion:

  1. The Transformer architecture, far more efficient.
  2. Access to massive amounts of data (a large part of the Internet).
  3. The increase in computing power (notably thanks to GPUs).

This combination allowed emergent abilities to appear: complex skills that even their creators had not foreseen.

Fundamental architecture of Large Language Models

To understand how an LLM works, picture a complex machine made of several stages that gradually turn raw text into an intelligent answer. A Large Language Model is fundamentally a gigantic computer program that has learned to predict the next word in a sentence from billions of examples of text it saw during training.

The layered structure of an LLM

A modern LLM looks like a language-processing factory. At the input, an embedding layer turns the text into a series of numbers that the computer can handle.

The core of the model is made of dozens of stacked Transformer blocks. Each block analyzes the text to understand the relations between words. For example, in "The dog barks because it is hungry", the model must understand that "it" refers to "the dog". To do so, it uses the attention mechanism, which evaluates the importance of words relative to one another.

Unlike older systems that analyzed words one by one, the Transformer architecture processes the whole text in parallel. This ability to take the whole previous context into account, as long as it fits in the model's context window (the maximum number of tokens it reads at once), keeps long passages coherent.

Finally, the output layer computes the probability of each possible word to continue the sentence and picks the most relevant one, repeating this process to generate a complete answer.

Tokenization and handling variable-length sequences

Tokenization is the first processing step: it splits the text into standardized units called tokens. This step answers the question: "how can a model compare texts of different sizes?".

A token is not always a whole word. The most common technique, BPE (Byte Pair Encoding), merges frequent pairs of characters to build a vocabulary. A common word like "hello" can become a single token, while a rare word is split into several sub-units. This approach makes it possible to handle unknown words by breaking them into known parts.

The diagram reads from top to bottom. It starts from an example sentence in French, "Le chat mange ses croquettes" (The cat eats its kibble), applies "BPE tokenisation" to it, then adds the positions. Look at the split: "Le", "chat", "mange" and "ses" stay whole, but "croquettes" is cut into three tokens, "cro", "quet" and "tes". This split is illustrative: the real one depends on the vocabulary of the tokenizer, the component that splits the text, which is specific to each model. The last step ("Adding positions") gives each token its position in the sentence, from 1 to 7.

From top to bottom: the French sentence Le chat mange ses croquettes goes through BPE tokenization, which gives, as an example, the tokens Le, chat, mange, ses, cro, quet, tes, then each token receives its position from 1 to 7.Sentence (French)Le chat mange ses croquettesBPE tokenisationTokensLe, chat, mange, ses, cro, quet, tesAdding positionsPositioned tokens1:Le, 2:chat … 7:tesstarting sentenceprocessing stepresult: tokensmove to the next step
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

So a text of any length is turned into a sequence of tokens that the model can process. To keep the order of the words, the model adds to each token position information (a positional encoding), which is crucial to tell "Paul calls Marie" from "Marie calls Paul". No token is added: it is each token's vector that carries its place in the sequence.

However, each LLM has a context limit, a maximum number of tokens it can process at once. For longer texts, techniques such as the sliding window are used to process the document in segments while keeping part of the previous context.

Attention mechanism and contextual relations in transformers

The attention mechanism is the key innovation of modern LLMs. It lets the model weigh the importance of each word in a sentence to understand its context. For example, in the French sentence "Le chat que j'ai adopté hier mange ses croquettes" (The cat I adopted yesterday eats its kibble), attention helps the model understand that "ses" (its) refers to "chat" (cat).

Technically, attention computes relevance scores between words. For each word, the model evaluates how important the words it can look at are for defining its meaning in this precise context.

Query, Key and Value: the three vectors of each token

To compute these scores, the model does not compare tokens directly. From each token's vector (the series of numbers given by the embedding layer), it produces three new vectors, each with a precise role:

  • the Query (Q) expresses what this token is looking for in the other tokens;
  • the Key (K) describes what this token offers, so that it can be compared to a Query;
  • the Value (V) holds the information this token passes on when it is attended to.

These three vectors are computed by three transformations learned during training. A given token therefore has a different Query, Key and Value.

Take the sentence "Le chat que j'ai adopté hier mange ses croquettes". When the model processes the token "ses", its Query looks for the noun this possessive refers to. It is compared with the Key of each of the previous tokens and with its own. The Key of "chat" matches this search well, the Key of "hier" (yesterday) much less. The token "ses" then mostly picks up the Value of "chat", and its representation is enriched with that information.

The computation takes four steps, for each token:

  1. The model computes a score between the Query of the current token and the Key of each token it can look at. This score is a dot product: the more the two vectors point in the same direction, the higher it is. In an LLM that generates text, a token looks at those that precede it and at itself, never at those that follow it.
  2. The scores are divided by the square root of the dimension of the Keys (the number of values in each Key vector). Without this division, the scores grow with the size of the vectors and the softmax of the next step becomes too sharp.
  3. The softmax function turns the scores into attention weights: numbers between 0 and 1 whose sum is 1 for a given token.
  4. The token's output is the sum of the Values weighted by these weights. A token with a high weight contributes a lot to the output, a token with a weight close to 0 hardly at all.

As a formula, this is the scaled dot-product attention of the paper "Attention Is All You Need" (Vaswani et al., 2017), where Q, K and V gather the vectors of all the tokens and d_k is the dimension of the Keys:

Attention(Q, K, V) = softmax(Q · K^T / sqrt(d_k)) · V

The attention weights are not fixed once and for all: they are recomputed for each sentence, from the Query and Key of its tokens. This is what lets "ses" refer to "chat" in this sentence and to another word in another sentence.

LLMs run several attention mechanisms in parallel: this is multi-head attention. Each "head" has its own Q, K and V transformations, and can specialize in one type of relation: one follows grammatical links, another pronoun references, a third associations of meaning.

By stacking many attention layers, the model builds an increasingly fine understanding of the text, from simple syntactic structures to complex abstract concepts.

Training phases: pre-training, fine-tuning and human alignment

Training an LLM takes place in three distinct phases, each with a precise goal.

The diagram reads from top to bottom. The arrows of the "phase sequence" legend link the blank neural network, the three phases and the usable assistant. Coming from the right, the "data fed to the phase" arrows show what feeds each phase: billions of texts (Internet, books) for pre-training, question-answer examples for fine-tuning, human evaluations for alignment. The model thus learns the language, then to follow instructions, then human preferences.

Three training phases, from top to bottom: a blank network is pre-trained on billions of texts, fine-tuned on question-and-answer examples, then aligned by RLHF from human ratings to become a usable assistant.Blank neuralnetworkPhase 1pre-trainingPre-trainedmodelPhase 2fine-tuningFine-tuned modelPhase 3RLHF alignmentUsable AIassistantBillions of textsInternet, books…Question-answerexamplesHumanevaluationsstarting pointtraining phasemodel or dataphase sequencedata fed to the phase
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

Pre-training: the fundamental learning

Pre-training is the longest phase. The model analyzes billions of texts (books, websites) with a simple goal: predict the next word. This task, repeated at large scale, lets it acquire a deep understanding of grammar, of facts about the world and of reasoning structures. It is during this step that emergent abilities appear: complex skills that were not explicitly programmed.

Fine-tuning: specializing on tasks

After pre-training, the model is "cultured" but does not know how to be useful. Fine-tuning consists in training it on thousands of high-quality question-and-answer examples. It thus learns to follow instructions, summarize, translate or write code.

Human alignment: learning preferences

Finally, alignment with human preferences refines the model's behavior to make it safer and more relevant. Through techniques such as RLHF (Reinforcement Learning from Human Feedback), human evaluators compare and rate the model's answers. The model learns from these preferences to avoid toxic content, reduce AI hallucinations (incorrect information) and give more useful answers.

Text generation: probabilities, sampling and decoding strategies

When an LLM generates text, it does not "think": it computes the probability of each possible word to continue the sentence and picks the next one according to a strategy.

At each step, the model examines its vocabulary (tens of thousands of tokens, sometimes more than 100,000) and assigns a probability to each one depending on the context. For example, after "Il fait chaud, j'aimerais boire quelque chose de" (It's hot, I'd like to drink something...), "frais" (cool) will have a high probability, while "chaud" (hot) will have a very low one.

The diagram shows this computation on that example. On the left, the text to complete enters the "Probability computation" step. It gives a percentage to each candidate word, stacked in the middle, from 45% for "frais" to 0.001% for "bleu" (blue). On the right, the most probable word, "frais", becomes the "Selected word". The diagram draws only some of the possible words: the percentages shown therefore do not add up to 100%.

After the French context Il fait chaud, j'aimerais boire quelque chose de, the model computes one probability per word: frais (cool) 45%, froid (cold) 35%, glacé (iced) 15%, chaud (hot) 0.1%, bleu (blue) 0.001%; frais is selected.Context (French):Il fait chaud,j'aimerais boirequelque chose deProbabilitycomputationfrais (cool): 45%froid (cold): 35%glacé (iced): 15%chaud (hot): 0.1%bleu (blue): 0.001%Selectedwordtext to completemodel computationcandidate wordchosen wordnext stepword pick
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

Token selection strategies

Several strategies exist to choose the next word:

StrategyDescriptionUse case
GreedyAlways the most probable wordFactual answers
TemperatureControlled randomness (low = coherent, high = creative)Creative generation
Top-kChoice among the k most probable wordsBalance
Top-p (nucleus)Choice among the words covering p% of the probabilityMore flexible
Beam searchExplores several branches in parallelTranslation, summarization

To keep long texts coherent, more advanced methods such as beam search explore several possible sentences in parallel before choosing the best one.

Handling long contexts and memory limits

An LLM's ability to handle long texts is defined by its context window, that is, the maximum number of tokens it can process at the same time. The size of this window varies from one model to another: the note above says where to read it.

The cost of attention computations grows quadratically with the length of the sequence, since each token is compared with all those it can look at: doubling the length multiplies the number of comparisons by four. The limit chosen for a model depends on this cost, on the length of the texts seen during training, on how the model encodes the position of tokens and on the memory available to run it.

To work around this limitation, several strategies exist:

  • Simple truncation cuts the beginning of the text, at the risk of losing information.
  • The sliding window processes the text in overlapping segments, keeping part of the previous context.
  • More advanced approaches such as context compression or alternative architectures (Mamba, hierarchical models) try to optimize this processing.

RAG (Retrieval-Augmented Generation) is another solution: it connects the LLM to an external database. Instead of storing everything in memory, the model looks up the relevant information when it needs it, which gives it access to knowledge that can be updated without retraining it.

Technical limitations and biases of language models

Despite their performance, LLMs have limits inherent in their design:

  • Hallucinations: inventing information. AI hallucinations are the tendency of models to invent facts convincingly. This happens because an LLM predicts the most probable next word, even when it does not have the correct information. It has no notion of "truth" and merely reproduces learned linguistic patterns, which can lead it to generate information that is plausible but false.
  • Biases and distorted representations. LLMs reproduce and amplify the biases present in their training data. They can thus associate professions with specific genders or reflect dominant cultural perspectives. Correcting these biases is a major challenge, because they are deeply rooted in the billions of texts analyzed.
  • Reasoning limitations. An LLM's "understanding" is statistical, not semantic. It excels at recognizing patterns but struggles with tasks that require deep logical or causal reasoning. It can solve a math problem by imitating a solution it has seen before, yet fail on a variant that requires a real understanding of the principles.
  • Dependence on training data. An LLM is frozen in time: its knowledge stops at the end of its training. A model trained in 2023 knows nothing about 2024. It will also reproduce the factual errors present in its source data. RAG is one solution to this obsolescence, but the intrinsic quality of the model still depends on the quality of its initial corpus.

Where things are heading: RAG, agents and multimodality

The future of LLMs points toward more complex and more capable systems, combining several technologies to get past their current limits.

The diagram starts from a root on the left, "Future developments", which splits into three branches. To the right of each one is what it brings: RAG adds an external database and up-to-date information, agents use tools and act in the real world, multimodality combines text, images, audio and video for a broader understanding.

Three evolutions: RAG brings an external base and up-to-date information, agents use tools and act in the real world, multimodality combines text, image, audio and video.Future developmentsRAGIntelligent agentsMultimodalityExternaldatabaseUp-to-date informationTool useActions inthe real worldText + images + audio + videoMultimodalunderstandingtopicevolution and what it bringsbreaks down into
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %
  • RAG: connecting LLMs to up-to-date knowledge. The RAG (Retrieval-Augmented Generation) technique answers the problem of outdated knowledge and limits hallucinations. When a question is asked, the system first looks up the relevant information in the external database and gives it to the LLM along with the question. The model thus relies on verified, up-to-date sources to build its answer.
  • Intelligent agents. Here, LLM agents are the next step: systems able not only to generate text but also to act. An agent can use tools, browse the Internet, run code or call APIs to accomplish complex tasks. It breaks a request down into steps, runs each action, analyzes the result and adjusts its plan accordingly. This autonomy makes it possible to entrust whole processes to the agent, such as analyzing data and then creating a report.
  • Multimodality. Here, multimodal models are not limited to text: they also process images, audio and video. They can describe an image, generate an illustration from a description or even create short videos. This ability opens new applications, such as troubleshooting assistants that understand screenshots or creation tools that automatically generate visual presentations.

These evolutions converge toward more versatile and autonomous systems, but they also raise significant ethical and security challenges. The future of LLMs will depend as much on technical advances as on our ability to oversee their development responsibly.

Key takeaways

  1. An LLM predicts the next word: it is this simple task, repeated billions of times, that gives rise to the observed abilities
  2. The Transformer architecture processes text in parallel thanks to the attention mechanism: a token's Query is compared with the Keys of the other tokens, and the resulting scores weight their Values
  3. BPE tokenization splits text into sub-units to handle any word, even an unknown one
  4. Three training phases: pre-training (language), fine-tuning (instructions), RLHF (human preferences)
  5. Hallucinations are inherent to how it works: the model generates what is probable, not what is true
  6. The context window limits how much text can be processed at once; its size is read in the model's page
  7. RAG works around the limits by connecting the LLM to external, up-to-date sources
  8. LLM agents can use tools and act in the real world

FAQ - Frequently Asked Questions