Transformers and LLMs: how text gets generated, end to end

When you ask a chatbot something, the answer comes out a little at a time. Inside, one small job repeats hundreds of times: guess the next token. Follow the text step by step as it becomes tables of numbers, passes through layers, and turns into the probability of the next token.

Short answer. An LLM (large language model) is a neural network that gives the probability of the next token after the text so far. Its frame is the Transformer. It cuts the text into tokens → turns them into vectors and adds positions → passes them through many layers of "attention + small neural network" blocks → gives probabilities for the next token. It picks one, adds it to the end, and repeats to write text.

    Block × N layers (here 1)

1. Text → tokens. The text is cut into pieces the model knows (tokens), and each piece gets an ID number. The number is its place in the vocabulary list. The model does not get letters. It gets these numbers.

More: Tokenization

Top strip: the circles are steps 1 to 10. The orange one with the label is the current step, pale green ones are done, and the thick orange arrows are what goes into and out of the current step. The purple arrows are residual connections: the value that came into the block goes around the side and is added at the +.

A tiny toy model. 6 tokens, 8 dimensions, a vocabulary of 16, one block, one head. The weights are random numbers that were never trained, so the token picked at step 10 means nothing. Look only at the shapes and the order. The models in the GPT-2 paper have 768 to 1,600 dimensions, a vocabulary of 50,257 and 12 to 48 blocks. Cell colors: green is positive, blue is negative, and in each picture the largest value is the darkest.

Definitions

The text below explains with pictures and labs. These are the textbook definitions. x1, …, xt is a sequence of tokens, X is the n × d matrix with one token vector in each row, and d is the number of dimensions.

large language model (LLM)
A language model that, given the tokens so far, gives each token in the vocabulary the probability of being the next token. An LLM is such a neural network with a very large number of parameters, trained on a very large amount of text.

P(xt+1∣x1,…,xt)

Transformer
A neural network structure made of many stacked blocks. Each block joins attention and an MLP with residual connections and layer normalization. A block takes n × d and gives n × d, and attention is the only place where tokens pass information to each other. The block in the original paper is below. Some models move the normalization in front of each part, as x + part(norm(x)) (section 3).

H=LayerNorm(X+Attention(X))

Y=LayerNorm(H+MLP(H))

residual connection
A connection that adds the output of a layer F to that layer's input and passes the sum on.

𝐲=𝐱+F(𝐱)

layer normalization
For one vector (one row) with d entries, subtract the mean μ, divide by the standard deviation, then multiply each entry by a learned vector γ and add a learned vector β. σ² is the variance of those d entries, and ε is a small positive number added so you never divide by 0.

LayerNorm(𝐱)=γ⊙𝐱−μσ2+ϵ+β

feed-forward network (MLP)
A two-layer neural network applied to each token separately. It widens d to an inner width (4d in the original paper), passes it through an activation function φ (ReLU or GELU), and shrinks it back to d.

MLP(𝐱)=φ(𝐱W1+𝐛1)W2+𝐛2

positional encoding
A vector for each position, added to the embedding to tell the model where a token sits. The original paper uses fixed values that are not learned: the sine and cosine values below, where pos is the position and i is the number of the pair of entries (both start at 0).

PE(pos,2i)=sin(pos100002i/d)

PE(pos,2i+1)=cos(pos100002i/d)

1. LLMs and Transformers

An LLM (large language model) is a neural network that takes text and gives the probability of the next token. A token is a piece of text. It can be a whole word, part of a word, or a punctuation mark. "Large" means it has a huge number of values set by training (parameters) and was trained on a huge amount of text. You will count those values yourself in section 10.

A Transformer is the design (architecture) of that network. A 2017 paper (Vaswani and others) introduced it for translation. The core idea is a block of "attention + small neural network", stacked many times. Most LLMs are built on this design.

The original: encoder and decoder

The Transformer in the original paper has two parts.

PartWhat it doesWhat it can see
EncoderReads the whole source sentence (for example, English) and turns each token into a vectorEverything, before and after
DecoderWrites the translation one token at a time. While writing, it looks at the encoder's vectors (cross-attention)Only what it has already written

Translation has a separate source text, so it needs both parts. An LLM that only continues text has no separate source. You put the question and the answer so far in one line and guess the next token. So it uses only the decoder. With no encoder, cross-attention goes away too, and each block keeps just attention and an MLP. GPT-2 works this way, and so does the toy on this page.

2. The whole flow: from text to the next token

n is the number of tokens and d is the number of dimensions (how many numbers describe one token). The toy in the experiment has n = 6, d = 8 and a vocabulary of 16.

text → n token IDs
  → embedding          n × d        take rows from the vocabulary table
  → + position         n × d
  → [attention → add and normalize → MLP → add and normalize] × N layers
                       n × d        a block does not change the shape
  → final linear layer n × vocab    only the last row is used
  → softmax            one probability per vocabulary token
  → pick one, add it to the end → start again

Notice that a block does not change the shape. n × d goes in and n × d comes out. That is why you can chain as many blocks of the same design as you like. Each layer learns its own weights. Tokens share information only in attention. Everything else works on each token separately.

Try this. 1) In "4 Attention", the first row, "The", can see only itself, so its weight is 1.00. The last row, "sat", has all 6 cells open, split as 0.17, 0.09, 0.20, 0.22, 0.14, 0.18. 2) In "6 MLP", many of the 32 columns are white. 78 of the 192 cells became 0. 3) In "9 Softmax", the largest probability is "." at 42.3%. The weights are random, so this means nothing. Training is what makes these probabilities sensible (section 7).

3. The four parts of a block: attention, MLP, residual connection, layer normalization

Each block has four parts. Here is why each one is there.

PartWhat it doesWhy it is there
AttentionFor each token, picks useful information from earlier tokens and mixes it inThis is the only place where tokens exchange information. Things you can only know by looking at other tokens, like what "it" refers to, are handled here. Attention
MLP (small neural network)For each token separately, widens to 4 times the dimensions and narrows backProcesses the mixed-in information inside each token. Two thirds of each layer's parameters are here (section 10)
Residual connectionAdds the part's output to what came in: x + part(x)The part only has to produce a correction. Even with many layers, the training signal flows well along this addition path. It was first used in image networks (ResNet)
Layer normalizationSets each row to mean 0 and size (standard deviation) 1, then stretches and shifts it by learned amountsKeeps values from growing too big or too small layer after layer. Training becomes more stable

The original paper normalizes after each part: normalize(x + part(x)). GPT-2 moved the normalization to the input of each part and added one more at the very end: x + part(normalize(x)). The toy in the experiment follows the original order. Either way, the four parts are the same.

In both the original paper and GPT-2, the MLP's inner width is 4 times the dimensions (512 → 2,048 in the original). The original uses a function that turns negative values into 0 (ReLU). GPT-2 uses GELU, a smooth version of it.

One block drawn top to bottom. The dashed purple lines are the residual connections. On the left (the original paper) layer normalization comes after the result of attention or the MLP is added; on the right (GPT-2) it comes before attention and before the MLP. The four parts are the same and only the order differs.

4. The causal mask: looking only backward

An LLM's attention looks only at earlier tokens. Later tokens are hidden. This is called the causal mask: the name comes from the idea that only earlier things can affect later things. With 4 tokens, it hides these cells.

1234
Token 1✓···
Token 2✓✓··
Token 3✓✓✓·
Token 4✓✓✓✓

The reason is training. During training, a whole chunk of text goes in at once, and the model guesses the next token at every position at the same time. If position 3 could see token 4, it would just copy the answer. With the mask, one chunk gives many guessing problems at once. When writing, the later tokens do not exist yet anyway, so the same design fits.

Hiding is simple. In the attention score table, set the hidden cells to −∞ before softmax, and their weights become 0. The gray cells in "4 Attention" in experiment 1 are hidden this way.

5. Writing one token at a time

Each time a Transformer runs, it gives only the probabilities for one next token. Text is written like this.

  1. Cut the prompt into tokens.
  2. Run the model to get the probabilities for the next token.
  3. Pick one by its probability and add it to the end.
  4. Repeat steps 2 and 3 until an end token comes out or a length limit is reached.

Because the model takes its own output as the next input, this is called autoregressive generation.

A tiny toy model. The probabilities come from a small made-up table. The table looks only at the one token right before and lists two or three candidates with fixed probabilities. A real model looks at every earlier token and computes a probability for every one of tens of thousands of candidates. The random numbers come from the seed, so the same seed always writes the same text.

Try this. 1) With seed 1, press "Next token" five times. It writes "The cat by the window lay dozing quietly." and then the end token comes out. The first random number is 0.63, which falls in the 0.55 to 0.85 range of "lay". The most likely token, "sat" (55%), is not always picked. 2) Change the seed to 6. The first number is 0.53, so "sat" is added, and it ends with "sat watching birds." 3) Seed 7 gives "sat watching outside." and seed 4 gives "hid watching birds." 4) After ".", the only candidate is the end token (100%), so any number ends the text.

How to pick (always the largest, by probability, or flatter or sharper with temperature) is in the next topic, Softmax, temperature and sampling.

Do not redo earlier work: the KV cache

Running the whole model from the start for every new token would be wasteful. Thanks to the causal mask, the work for earlier tokens does not change no matter what comes after. So each layer saves the keys (K) and values (V) of earlier tokens and computes only the new token. This is called the KV cache. It is in GPT-2's public code too (past, present).

6. Positional encoding

Here are the numbers added in "3 + Position" in experiment 1. The original paper computes sine and cosine values for each position. It is a fixed table with nothing to learn.

PE(pos, 2i)   = sin(pos ÷ 10000^(2i/d))
PE(pos, 2i+1) = cos(pos ÷ 10000^(2i/d))

pos is the position (starting at 0), d is the number of dimensions, and i numbers the pairs of columns (starting at 0). Columns go in pairs: sin and cos of the same angle. In the left pairs the angle grows fast (for i = 0 it is just pos). Further right, the angle is divided by bigger powers of 10000, so it grows slowly. Like the second, minute and hour hands of a clock, fast and slow columns mix to give each position its own pattern.

Example: d = 8, position 1. The first pair has angle 1, so sin(1) = 0.841 and cos(1) = 0.540. The second pair has angle 1 ÷ 10000^(2/8) = 1 ÷ 10 = 0.1, so sin(0.1) = 0.100 and cos(0.1) = 0.995. The third pair has angle 0.01 and the fourth 0.001. So the eight values for position 1 are 0.841, 0.540, 0.100, 0.995, 0.010, 1.000, 0.001, 1.000.

Each row of the top picture is the set of numbers added at one position. The bottom picture joins the values of rows A and B across the dimensions. Similarity is the cosine similarity of the two rows taken as vectors.

Try this. 1) With the starting values (16 positions, 16 dimensions, A = 3, B = 5), the similarity is 0.80. Move B to 4 and it goes up to 0.94. 2) Move to A = 10, B = 12. The distance is still 2, so it stays 0.80. 3) In the top picture, the left columns change color quickly from row to row, and the right columns barely change. Even with 64 positions, the rightmost column hardly changes. 4) Farther does not always mean less similar. With A = 3, B = 13 gives 0.46 and B = 15 gives 0.67.

PropertyIn plain words
Values are always between −1 and 1They can be added without shaking the embedding values too much
Every position has a different rowFast and slow columns mix, so the same pattern rarely comes back
Similarity depends only on the distance between two positionsPositions 3 and 5 are as similar as positions 10 and 12
The row k places later comes from the current row by a fixed calculation (a linear map)The original paper expected this to make it easy for the model to learn relative positions like "k tokens back"
It is computed, not learnedYou can compute it for texts longer than those seen in training. The original paper chose it because this may help with longer texts

Many newer models use other methods too. GPT-2 uses a learned table with one vector per position (context length × dimensions). The original paper also tried this and reported nearly the same results. Another widely used method, rotary position embedding (RoPE), does not add positions at all. It rotates the query (Q) and key (K) vectors by an amount set by the position, so the distance between two tokens shows up in their score.

7. Training: guess the next token

What gets learned is every table (the weights). At first they are random, like in experiment 1, so the probabilities mean nothing. Training nudges these numbers, little by little, so that the token that actually came next in real text gets a higher probability.

  1. Take a chunk from a huge amount of text. For example: "The cat by the window sat".
  2. Guess the next token at every position. After "The" comes "cat", after "The cat" comes "by", and so on. Thanks to the causal mask, one 6-token chunk gives 5 guessing problems.
  3. At each position, take the probability p the model gave the correct token and score a penalty of −log p (natural log). A confident right guess scores close to 0. A small probability for the right answer scores high. This penalty is cross-entropy.
  4. Change all the weights a little in the direction that lowers the average penalty (gradient descent). Repeat this a huge number of times.

Example: the right token after "window" is "sat". If the model gave "sat" a probability of 0.55, the penalty is −log 0.55 = 0.598. If it gave 0.15, the penalty grows to −log 0.15 = 1.897. If it gave 1, the penalty is 0.

Pre-training and fine-tuning

Pre-training is doing the above for a long time on a huge amount of text. It costs the most money and time. A model that has only been pre-trained is good at continuing text, but it is not tuned to answer questions. After a question, it might just write more similar questions.

Fine-tuning trains the finished model a bit more on a smaller set of data, such as pairs of questions and good answers, or chat logs. The design stays the same and the weights change a little. Methods like LoRA, which train only a small add-on instead of all the weights, cut the cost a lot. Some models add another step that tunes them to give the answers people preferred more often.

8. The context window, and what the model knows

The context window is the limit on how many tokens the model can see at once. For GPT-2 it is 1,024 tokens. If the prompt plus the answer so far goes over the limit, the start has to be cut off, and for the model, the cut part no longer exists. In a model with a learned position table, the number of rows in that table is the limit.

A longer context window costs much more work. The attention score table is context length × context length, so twice the length means 4 times the cells (see the calculator in section 10).

What the model knows lives in the weights

Once training ends, the weights are fixed. The facts, style and grammar the model "knows" are all spread across these numbers. There is no separate list it can look things up in, like a database.

So it does not know things that happened after training, documents inside your company, or a price that changed yesterday. To use them, you have to put them in the prompt so they are inside the context window. Finding documents related to the question and adding them to the prompt is called RAG (retrieval-augmented generation). When a chatbot seems to "remember" the conversation, it is usually because the earlier messages are sent again in the prompt every time.

9. Why hallucinations happen

A hallucination is when the model says something false in a way that sounds true. Here are the reasons in plain words. Research has not fully settled this. This is an explanation that follows from the design we have seen.

Ways to reduce it: put source documents in the prompt and ask for answers only from them (RAG), and ask for sources and have a person check them. None of these brings hallucinations down to zero.

10. Size: counting parameters

Parameters are the values set by training, that is, the cells of all the tables. If you count the tables in one block, the number depends almost only on the dimension d.

TableSizeCells
Attention's query (Q), key (K), value (V) and output tablesfour of d × d4 × d²
MLP's widening table and narrowing tabled × 4d, 4d × d8 × d²
One block12 × d²
Embedding (vocabulary table). The final linear layer reuses itvocab × dvocab × d
parameters ≈ vocab × d + layers × 12 × d²

Biases and layer normalization add only a few times d per layer, which is tiny next to d², so they are left out. The number of heads is not in the formula. Several heads just split d between them (one head's width = d ÷ heads), so the total table size stays the same. The context length is not in the formula either. A model with learned positions adds context × d.

PartFormulaWith these settings
Embeddingvocab × dimensions
Attention, one layer4 × dimensions²
MLP, one layer8 × dimensions²
All layerslayers × (attention + MLP)
Total (estimate)embedding + all layers
Counting everythingThe GPT-2 code's design: add a position table context × dimensions, biases and normalization 13 × dimensions per layer, and a final normalization 2 × dimensions

Share of the estimate: embedding · attention in all layers · MLP in all layers =

The sliders use a log scale, so one slider can reach both small and large numbers. Type exact numbers in the boxes. The estimate leaves out biases and normalization, so the smaller the settings, the bigger the gap to the full count.

Try this. 1) The starting values are the toy from experiment 1. The estimate is 896. 2) Press "Smallest model in the GPT-2 paper". The estimate is 123,532,032 (about 124 million), 0.7% lower than the 124,439,808 you get by counting everything with the public code's design. 3) Change the heads from 12 to 1 or to 64. The parameter count stays the same. Only one head's width changes (768 with 1 head, 12 with 64). 4) Raise the context length from 1,024 to 2,048. One layer's attention score table goes from 12,582,912 cells to 50,331,648 cells, 4 times as many. 5) In "Largest model", the MLP is 63.2% and the embedding 5.2%. In the smallest model the embedding is 31.2%. The bigger the model, the more d² takes over and the blocks become almost everything.

Counting by hand: the toy from experiment 1

Let us count the toy: vocabulary 16, dimension 8, one block, MLP inner width 32 (= 4 × 8).

  1. Embedding. 16 × 8 = 128.
  2. Attention. The Q, K, V and output tables each have 8 × 8 = 64 cells. Four of them make 4 × 64 = 256.
  3. MLP. Widening table 8 × 32 = 256, narrowing table 32 × 8 = 256. Together 512 (= 8 × 8²).
  4. Total. One block, so 256 + 512 = 768. Add the embedding: 128 + 768 = 896.
  5. What was left out. Counting the GPT-2 way adds a position table 6 × 8 = 48, biases 9 × 8 = 72, two normalizations in the block 4 × 8 = 32 and a final normalization 2 × 8 = 16. That is 168 more, for 1,064. In a model this small, the left-out part is a big 15.8%. As the dimension grows, d² races far ahead of d and the left-out part shrinks.

Checking against published numbers

The GPT-2 paper released four models of different sizes. All four have a vocabulary of 50,257 and a context of 1,024 (section 2.3 of the paper).

LayersDimensionsPaper's tableThis page's estimateFull count with the public code's design
12768117M123,532,032124,439,808
241,024345M353,453,056354,823,168
361,280762M772,117,760774,030,080
481,6001542M1,554,971,2001,557,611,200

M means million. The estimate is within 1% of the full count. The numbers in the paper's table are 1% to 6% smaller than the counts from the public code. This page could not confirm why.

The base model of the original paper (6 encoder layers + 6 decoder layers, 512 dimensions, 8 heads, 65 million parameters in the paper's table) is not checked with this calculator. Each decoder block has an extra cross-attention, and the encoder blocks are built differently, so they do not fit this calculator's decoder-only formula.

11. Key properties

PropertyIn plain words
The output is always "the probabilities for one next token"Long text comes from picking and adding one token over and over
A block takes n × d and gives n × dSo the same design can be stacked as many times as you like
Tokens mix only in attentionThe MLP, normalization and residual connections work on each token separately
It looks only backward (causal mask)Training practices every position of a chunk at once, and writing saves and reuses earlier work
parameters ≈ vocab × d + layers × 12 × d²The number of heads and the context length hardly change it. The context length changes the amount of work (with its square)

Where it is used

Frequently asked questions

Are an LLM and a Transformer the same thing?

No. A Transformer is a way to build a neural network (an architecture). An LLM is a large model built that way and trained on a huge amount of text. Most LLMs use only the decoder part of the Transformer.

Does the model write the whole answer at once?

No. Each run gives only the probabilities for the one next token. The model picks one, adds it to the end, and runs again, until an end token comes out.

Why do I get a different answer to the same question each time?

Because the next token is picked at random, following the probabilities. If an early token is different, everything after it changes too. If you always take the most likely token, you get almost the same answer every time.

Why doesn't the model know recent events or my company's documents?

What the model knows lives in the weights that were set during training, and they do not change after training ends. To use new information, you have to put it in the prompt so it is inside the context window. Finding related documents and adding them to the prompt is called RAG.

Why do hallucinations happen?

The model learned to produce a likely next token. There is no separate step that checks facts. Even when it does not know something, it still gives probabilities, so it can produce wrong content that looks right.

Words

Word used hereTerm in books
large language modelLLM
token, token IDtoken, token ID
vocabularyvocabulary, vocab
a token's vector, vocabulary tableembedding, embedding matrix
dimensionsmodel dimension, hidden size (d_model)
position numberspositional encoding. Learned ones: learned positional embedding. Rotating ones: RoPE (rotary position embedding)
block, layerTransformer block, layer
small neural networkMLP, feed-forward network (FFN)
addition pathresidual connection, skip connection
setting each row to mean 0 and size 1layer normalization
hiding later tokenscausal mask
the reading part / the writing partencoder / decoder
attention from the decoder to the encodercross-attention
scores from the final linear layerlogits
adding one token at a timeautoregressive generation
saving the K and V of earlier tokensKV cache
how many tokens it can see at oncecontext window, context length
values set by trainingparameters, weights
the penalty for guessing the next tokencross-entropy loss
big first training / extra trainingpre-training / fine-tuning
wrong content that sounds righthallucination

Sources

← AttentionEncoders and decoders: three kinds of transformer →