Inside a Transformer
A Transformer is the neural network design behind every modern large language model. It turns a list of tokens into a list of vectors, passes them through a stack of identical blocks, and at the end gives a score to every token in its vocabulary for what comes next. Each block has two parts: self-attention, where tokens share information with each other, and a feed-forward network, which processes each token on its own.
"Transformers and Attention, Simply" explained the idea in plain words. This chapter opens a real model and looks at the numbers inside.
The Parts of a Transformer
| Part | Description |
|---|---|
| Tokenizer | It is used to split text into tokens and give each one an ID number |
| Token embedding | It is used to turn each token ID into a vector of numbers; see "What Are Embeddings" |
| Position information | It is used to tell the model the order of the tokens |
| Self-attention | It is used to let each token gather information from the tokens before it |
| Feed-forward network | A small neural network applied to each token separately, after attention |
| Normalization | It is used to keep the numbers in a steady range so training is stable |
| Output layer | It is used to turn the final vector into a score for every token in the vocabulary |
Each block also uses residual connections: its input is added back to its output, so information can pass straight through many layers. Training deep networks would be much harder without them.
Example: Opening a Real Model
The programs in this chapter need pip install torch transformers. They use SmolLM2-135M, a small open language model from Hugging Face (Apache 2.0 license, about 270 MB), which runs on an ordinary laptop. The first run downloads it; the download and loading messages are left out of the output shown.
SmolLM2-135M has 135 million parameters and was pretrained on 2 trillion tokens of web pages, educational text and code, using 64 H100 GPUs, according to its model card. This program reads its settings and counts where its parameters are.
from transformers import AutoModelForCausalLM
# SmolLM2-135M: a small open language model (Apache 2.0) from Hugging Face
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M")
c = model.config
print("Layers (Transformer blocks):", c.num_hidden_layers)
print("Hidden size (numbers per token):", c.hidden_size)
print("Attention heads per layer:", c.num_attention_heads)
print("Vocabulary (different tokens):", f"{c.vocab_size:,}")
print("Longest context (tokens):", f"{c.max_position_embeddings:,}")
total = sum(p.numel() for p in model.parameters())
embed = model.model.embed_tokens.weight.numel()
block = model.model.layers[0]
attn = sum(p.numel() for p in block.self_attn.parameters())
mlp = sum(p.numel() for p in block.mlp.parameters())
norms = sum(p.numel() for p in block.parameters()) - attn - mlp
print(f"\nToken embeddings: {embed:>12,}")
print(f"One block: attention {attn:,} + feed-forward {mlp:,} + norms {norms:,} = {attn + mlp + norms:,}")
print(f"All 30 blocks: {(attn + mlp + norms) * c.num_hidden_layers:>12,}")
print(f"Total parameters: {total:>12,}")
print("\nOne block:")
print(block)Layers (Transformer blocks): 30
Hidden size (numbers per token): 576
Attention heads per layer: 9
Vocabulary (different tokens): 49,152
Longest context (tokens): 8,192
Token embeddings: 28,311,552
One block: attention 884,736 + feed-forward 2,654,208 + norms 1,152 = 3,540,096
All 30 blocks: 106,202,880
Total parameters: 134,515,008
One block:
LlamaDecoderLayer(
(self_attn): LlamaAttention(
(q_proj): Linear(in_features=576, out_features=576, bias=False)
(k_proj): Linear(in_features=576, out_features=192, bias=False)
(v_proj): Linear(in_features=576, out_features=192, bias=False)
(o_proj): Linear(in_features=576, out_features=576, bias=False)
)
(mlp): LlamaMLP(
(gate_proj): Linear(in_features=576, out_features=1536, bias=False)
(up_proj): Linear(in_features=576, out_features=1536, bias=False)
(down_proj): Linear(in_features=1536, out_features=576, bias=False)
(act_fn): SiLUActivation()
)
(input_layernorm): LlamaRMSNorm((576,), eps=1e-05)
(post_attention_layernorm): LlamaRMSNorm((576,), eps=1e-05)
)Explanation:
- 30 layers, each 576 numbers wide. Every token is represented by 576 numbers as it moves through the model, and there are 30 identical blocks.
- The token embeddings are a table of 49,152 rows (one per token) by 576 numbers: 28.3 million parameters. The same table is reused for the output layer, which is why the total doesn't count it twice.
- One block has about 3.5 million parameters: a quarter in attention (
q_proj,k_proj,v_proj,o_proj, explained in "Self-Attention") and three quarters in the feed-forward network (gate_proj,up_proj,down_proj), which widens each token's vector to 1,536 numbers and back. LlamaRMSNormis the normalization step, before attention and before the feed-forward network. SmolLM2 uses the same design as Meta's Llama models.- All the pieces add up exactly: 28,311,552 + 106,202,880 + 576 for a final normalization = 134,515,008.
Example: Following One Prompt Through the Model
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M")
model.eval()
prompt = "The school library opens at eight in the"
ids = tokenizer(prompt, return_tensors="pt").input_ids
print("Tokens:", tokenizer.convert_ids_to_tokens(ids[0]))
print("Token IDs:", ids[0].tolist())
with torch.no_grad():
out = model(ids, output_hidden_states=True)
states = out.hidden_states # the embeddings, then the output of each block
print("\nAfter the embedding layer:", tuple(states[0].shape))
print("After block 1: ", tuple(states[1].shape))
print("After all 30 blocks: ", tuple(states[30].shape))
print("Scores for the next token:", tuple(out.logits.shape))
probs = out.logits[0, -1].softmax(dim=0) # only the last position predicts what comes next
top = probs.topk(5)
print("\nMost likely next tokens:")
for p, i in zip(top.values, top.indices):
print(f"{p:6.1%} {tokenizer.decode(i)!r}")Tokens: ['The', 'Ġschool', 'Ġlibrary', 'Ġopens', 'Ġat', 'Ġeight', 'Ġin', 'Ġthe']
Token IDs: [504, 1125, 4971, 10573, 418, 4475, 281, 260]
After the embedding layer: (1, 8, 576)
After block 1: (1, 8, 576)
After all 30 blocks: (1, 8, 576)
Scores for the next token: (1, 8, 49152)
Most likely next tokens:
63.3% ' morning'
20.5% ' afternoon'
14.1% ' evening'
0.3% ' early'
0.2% '\n'Explanation:
- The prompt becomes 8 tokens. The
Ġat the start of a token stands for a space, soĠschoolis " school". Each token has an ID, such as 1125 for " school". - The shape
(1, 8, 576)stays the same through every block: 1 prompt, 8 tokens, 576 numbers each. Blocks change the numbers, not the shape, which is what lets them stack. - The output has 49,152 scores for each of the 8 positions. Every position predicts the token after it, which matters for training. For generating text, only the last position is used.
- The model's best guesses for the next word are "morning" (63.3%), "afternoon" (20.5%) and "evening" (14.1%), all sensible. To generate a sentence, the model adds the chosen token to the prompt and runs again, as in "How an LLM Generates Text".
How the Lessons in This Chapter Fit Together
| Lesson | Question it answers |
|---|---|
| Tokenization | How is text split into tokens? |
| Self-Attention | How do tokens share information? |
| Pretraining | How does the model learn from trillions of tokens? |
| Instruction Tuning and RLHF | How does a text predictor become a helpful assistant? |
| Sampling and Decoding | How is one token chosen from 49,152 scores? |
| Scaling and Context Windows | What changes as models and prompts grow? |
Common Mistakes
Thinking each layer does one clear job. Researchers can find some patterns, but most of what the layers do is spread across millions of numbers and is still being studied.
Thinking the model reads whole words. It reads tokens, which can be parts of words; see "Tokenization".
Forgetting that only the last position is used to generate. The model computes predictions for every position, but each new token comes from the last one.
Confusing parameters with knowledge stored as text. The model holds no list of facts; it has numbers that make some continuations likely. See "Parameters: What a Model Learns".
Interview Corner
What are the main parts of a Transformer block?
Self-attention, which lets tokens share information, and a feed-forward network, which processes each token, each with normalization and a residual connection. Language models stack many identical blocks between a token embedding layer and an output layer.
What does a language model output?
A score (logit) for every token in its vocabulary, at every position. Softmax turns the scores into probabilities for the next token; generation picks one, appends it and repeats.
Practice
Exercise: a different prompt. Change the prompt in the second program to "The capital of France is" and to "My favorite color is". Which prompt gives one very likely next token, and which spreads the probability over many?
Check your understanding:
- How many numbers represent each token inside SmolLM2-135M?
- Why does the shape stay
(1, 8, 576)from block to block? - Which part of a block holds most of its parameters?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Load a model | AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M") |
| Load its tokenizer | AutoTokenizer.from_pretrained(...) |
| Settings | model.config.num_hidden_layers, .hidden_size, .vocab_size |
| Count parameters | sum(p.numel() for p in model.parameters()) |
| Hidden states of every block | model(ids, output_hidden_states=True).hidden_states |
| Next-token probabilities | model(ids).logits[0, -1].softmax(dim=0) |
Was this tutorial helpful?