Skip to content

Transformers

Chapter 15 0 code blocks 1299 words

How a transformer works

Say this

A transformer is a stack of identical blocks. Text becomes tokens, each token becomes a vector, and every block does two things: self-attention, where each token looks at the other tokens and takes in what is relevant, and a feed-forward network, which processes each token on its own. Residual connections and normalization keep the deep stack trainable. An LLM like Qwen is decoder-only: a causal mask lets each token see only the tokens before it, and the last layer turns the final vector into a probability for every word in the vocabulary, so the model predicts the next token, appends it, and repeats. It replaced RNNs because all positions are processed in parallel during training and any token can reach any other token in one step.

One forward pass
decoder-only LLM such as qwen3:8b
  1. 1
    Tokens → IDs
    "Toshkentdan Samarqandga poyezd" → [ID, ID, ID, ...]
  2. 2
    Embedding table
    one vector per token
  3. 3
    Position: RoPE
    word order enters the attention scores
  4. 4
    N identical blocks
    36 in qwen3:8b
    Self-attention
    tokens look at earlier tokens and mix in what is relevant
    softmax(QK⊤dk)V
    Feed-forward
    each token processed alone (SwiGLU)
    Residual + RMSNorm
    keeps 36 layers trainable
  5. 5
    lm_head → logits → softmax
    a probability for each of about 151,000 tokens
  6. 6
    Pick the next token
    temperature, top-p
append the token and run again; the KV cache keeps earlier keys and values
1

Tokens and the embedding table

What
Text is split into subword tokens, and each token ID picks a row from a learned table.
How
Qwen's vocabulary has about 151,000 tokens. The row is the token's starting vector; in qwen3:8b it has 4096 numbers.
Why
The model can only do math on numbers. The ID itself means nothing; the learned row is where meaning starts.
2

Position: RoPE

What
Attention by itself does not know word order, so position is added.
How
RoPE rotates the query and key vectors by an angle that depends on the position, so the attention score depends on how far apart two tokens are.
Why
"Ali Valini urdi" and "Vali Alini urdi" have the same tokens and different meanings. Older models added fixed sine waves or learned position vectors instead.
3

Self-attention

What
Every token decides which other tokens matter to it and mixes in their information.
How
Each token's vector is multiplied by three learned matrices to get a query Q, a key K and a value V. The score between two tokens is Q·K, divided by √d so softmax does not saturate, then softmax turns scores into weights, and the output is the weighted sum of V: Attention(Q,K,V)=softmax(QK⊤dk)V. Multi-head attention runs this many times in parallel with smaller vectors, so different heads can follow different relations.
Attention(Q,K,V)=softmax(QK⊤dk)V
Qquery: what this token is looking for
Kkey: what each token offers to be matched on
Vvalue: the information that gets mixed in
dkscaling by the vector size so softmax does not saturate
softmaxturns scores into weights that sum to 1
Example
In "bank foiz stavkasini oshirdi", the token "oshirdi" gives high weight to "stavkasini" and "bank", so its vector now carries "the bank raised the rate".
Weakness
Every token is compared with every other token, so the cost grows with the square of the context length. That is why a long context is slow and needs memory.
4

Causal mask

What
In a decoder (GPT, Qwen, Llama) a token may only look at tokens before it.
How
Scores for future positions are set to minus infinity before softmax, so their weight is zero.
Why
The model is trained to predict the next token; seeing the future would be cheating. It is also why my embedding model takes the LAST token's vector: only the last token has seen the whole text.
5

Feed-forward network

What
After attention, each token's vector goes through a small two-layer network on its own.
How
It expands the vector to a bigger size, applies a non-linearity (SwiGLU in Qwen and Llama), and projects back. Most of the parameters live here.
Why
Attention moves information between tokens; the feed-forward layer transforms it, and is where much of the stored knowledge is.
6

Residual connection and normalization

What
Each sub-layer adds its output to its input instead of replacing it, and vectors are normalized before each sub-layer.
How
x←x+Attention(Norm(x)), then x←x+FFN(Norm(x)). Qwen uses RMSNorm.
Why
The gradient can flow straight through the additions, so a stack of 36 layers still trains. Without it, deep networks stop learning.
7

Output and generation

What
The final vector of the last token becomes a score for every token in the vocabulary.
How
The lm_head multiplies it into about 151,000 logits; softmax gives probabilities; temperature and top-p choose one token; it is appended and the model runs again.
Why
Generation is one token at a time. The KV cache stores the keys and values of earlier tokens, so each new token only computes its own, not the whole text again.
Passes on
Text, one token per step, until a stop token or the length limit.
TypeSeesGood forExamples
Encoder-onlyall tokens, both directionsunderstanding: classification, cross-encoder rerankersBERT, bge-reranker
Decoder-onlyonly earlier tokensgeneration; also embeddings with last-token poolingGPT, Qwen, Llama
Encoder-decoderencoder reads the input, decoder writes the outputtranslation, speech-to-textT5, Whisper

Example project

  • Embeddings: qwen3-embedding:4b is a decoder transformer with 36 layers; I take the last token's vector (2560 numbers) because of the causal mask, and normalize it.
  • Context length is a real cost: 6 chunks of up to 1800 tokens could go past Ollama's 16,384-token default window, and the overflow is cut silently, so I set num_ctx to 24576 (qwen3:8b supports 40,960). A longer window means a bigger KV cache in GPU memory.
  • Fine-tuning: in Tez I trained LoRA adapters on the attention projections of Qwen3.5-4B, not the whole model.

If they push

  • Why divide by √d? Dot products of long vectors get large, softmax then puts almost all weight on one token and gradients vanish. Scaling keeps the scores in a useful range.
  • Grouped-query attention: several query heads share one key/value head (qwen3:8b has 32 query heads and 8 key/value heads), so the KV cache is 4 times smaller.
  • Long context: attention is quadratic; FlashAttention computes the same result in blocks without storing the full score matrix, so it is faster and uses less memory.
  • Mixture of experts: the feed-forward layer is split into many experts and a router sends each token to a few of them, so a big model costs less per token.
  • Temperature: logits are divided by it before softmax; low is more deterministic (I use 0 for RAG), high is more varied.

Trap questions

  • "Does attention mean the model understands?" No. Attention is learned weighting of other tokens. Whatever the model "knows" comes from training on data.
  • "Why can't an LLM count the letters in a word?" It sees tokens, not letters; "strawberry" may be two or three tokens.
  • "Are parameters and context the same memory?" No. Parameters are fixed after training; the context is the text of this request, held in the KV cache while it runs.

Be honest

"I haven't trained a transformer from scratch. I use them every day: embeddings, generation, LoRA fine-tuning, and I tune context length and KV cache memory. The from-scratch training loop I know well is my CRNN OCR model."

Questions about this chapter?

The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.

Write on Telegram Contents