Transformers
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.
- 1Tokens → IDs"Toshkentdan Samarqandga poyezd" → [ID, ID, ID, ...]
- 2Embedding tableone vector per token
- 3Position: RoPEword order enters the attention scores
- 4N identical blocks36 in qwen3:8bSelf-attentiontokens look at earlier tokens and mix in what is relevantFeed-forwardeach token processed alone (SwiGLU)Residual + RMSNormkeeps 36 layers trainable
- 5lm_head → logits → softmaxa probability for each of about 151,000 tokens
- 6Pick the next tokentemperature, top-p
Tokens and the embedding table
Position: RoPE
Self-attention
Causal mask
Feed-forward network
Residual connection and normalization
Output and generation
| Type | Sees | Good for | Examples |
|---|---|---|---|
| Encoder-only | all tokens, both directions | understanding: classification, cross-encoder rerankers | BERT, bge-reranker |
| Decoder-only | only earlier tokens | generation; also embeddings with last-token pooling | GPT, Qwen, Llama |
| Encoder-decoder | encoder reads the input, decoder writes the output | translation, speech-to-text | T5, 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_ctxto 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.