Skip to content

Build a modern LLM from scratch. Every line commented. Explained like we are five.

adding more explanation and examples chapters

raiyanyahya561b8081f476
diff --git a/README.md b/README.md
index feb228e..74bda05 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,8 @@
<p align="center">
<img src="https://img.shields.io/badge/chapters-12-blue" alt="12 chapters">
- <img src="https://img.shields.io/badge/lines-3%2C900%2B-green" alt="3,900+ lines">
+ <img src="https://img.shields.io/badge/lines-7%2C500%2B-green" alt="7,500+ lines">
+ <img src="https://img.shields.io/badge/topics_explained-15-teal" alt="15 topic explainers">
<img src="https://img.shields.io/badge/code%20commented-100%25-brightgreen" alt="100% commented">
<img src="https://img.shields.io/badge/prerequisite-python%20basics-orange" alt="Python basics only">
<img src="https://img.shields.io/badge/architecture-LLaMA%203%20style-purple" alt="LLaMA 3 style">
@@ -17,7 +18,9 @@
## πŸ“– What Is This?
-This is a **12-chapter, 3,900+ line interactive textbook** that teaches you how to build, train and run a modern language model from absolute scratch. The same family of architecture behind ChatGPT, Claude, LLaMA and Mistral.
+This is a **12-chapter, 7,500+ line interactive textbook** that teaches you how to build, train and run a modern language model from absolute scratch. The same family of architecture behind ChatGPT, Claude, LLaMA and Mistral.
+
+Alongside the chapters there are **15 standalone topic explainers** covering every technique in depth. RoPE, attention, RMSNorm, SwiGLU, KV cache, AdamW, mixed precision and more. Each explainer follows the same style: child language, no jargon, a code example you can run.
You won't just read about Transformers. You'll **write every line yourself**: tokenizer, embeddings, attention, training loop, inference engine. Every single line annotated to explain **what** it does and **why** it's there.
@@ -119,7 +122,7 @@ python -m venv gpt_env
source gpt_env/bin/activate # Mac/Linux
# gpt_env\Scripts\activate # Windows
-# 3. Install dependencies (CPU version β€” for GPU see below)
+# 3. Install dependencies (CPU version. For GPU see below)
pip install torch tiktoken datasets numpy matplotlib --index-url https://download.pytorch.org/whl/cpu
# 4. Verify GPU (optional but recommended)
@@ -145,7 +148,7 @@ This uses the tiny config (d_model=256, 4 layers) by default. Training takes a f
Alongside the textbook, each chapter has a companion notebook you can run live. These strip away the explanations and give you pure, clean code that executes from top to bottom. If the textbook teaches you why, the notebooks let you see it happen.
-We're going to run this whole project on a very small dataset so you can watch training happen in minutes rather than weeks. Every notebook is self-contained β€” open it, run all cells, and you'll see the model learn in real time.
+We're going to run this whole project on a very small dataset so you can watch training happen in minutes rather than weeks. Every notebook is self-contained. Open it, run all cells and you'll see the model learn in real time.
```bash
# Install everything you need
@@ -159,6 +162,31 @@ Notebooks live in the `notebooks/` directory, one per chapter. Open any of them
---
+## πŸ“š Topic Explainers
+
+Each concept in this guide has a dedicated deep dive inside `explanations and examples WIP/`. These are written in the simplest possible language. No jargon. No formulas before analogies. Every explainer covers what, where, why, when and how with a code example you can run.
+
+| Topic | File | What It Covers |
+|---|---|---|
+| RoPE | [rope.md](explanations%20and%20examples%20WIP/rope.md) | How word order is encoded through rotation |
+| Attention | [attention.md](explanations%20and%20examples%20WIP/attention.md) | Step by step with a 3-token worked example |
+| BPE Tokenization | [bpe_tokenization.md](explanations%20and%20examples%20WIP/bpe_tokenization.md) | How text becomes tokens |
+| Embeddings | [embeddings.md](explanations%20and%20examples%20WIP/embeddings.md) | How numbers become meaning |
+| RMSNorm | [rmsnorm.md](explanations%20and%20examples%20WIP/rmsnorm.md) | Simpler faster normalization |
+| SwiGLU | [swiglu.md](explanations%20and%20examples%20WIP/swiglu.md) | The gated activation that beat ReLU |
+| Causal Masking | [causal_masking.md](explanations%20and%20examples%20WIP/causal_masking.md) | No peeking at the future |
+| Residual Connections | [residual_connections.md](explanations%20and%20examples%20WIP/residual_connections.md) | The gradient highway |
+| KV Cache | [kv_cache.md](explanations%20and%20examples%20WIP/kv_cache.md) | Making generation fast |
+| Sampling | [sampling.md](explanations%20and%20examples%20WIP/sampling.md) | Temperature, top-k, top-p |
+| Mixed Precision | [mixed_precision.md](explanations%20and%20examples%20WIP/mixed_precision.md) | Speed without sacrifice |
+| AdamW | [adamw.md](explanations%20and%20examples%20WIP/adamw.md) | The optimizer that trains LLMs |
+| Weight Tying | [weight_tying.md](explanations%20and%20examples%20WIP/weight_tying.md) | Two jobs one matrix |
+| Gradient Clipping | [gradient_clipping.md](explanations%20and%20examples%20WIP/gradient_clipping.md) | Preventing training explosions |
+| Cosine Warmup | [cosine_warmup.md](explanations%20and%20examples%20WIP/cosine_warmup.md) | The learning rate schedule |
+| Pre-Norm | [pre_norm.md](explanations%20and%20examples%20WIP/pre_norm.md) | Where to normalize |
+
+---
+
## πŸ“– How to Read
Each chapter follows the same **4-step structure**:
@@ -220,19 +248,23 @@ Each chapter follows the same **4-step structure**:
```
πŸ“¦ how-to-train-your-gpt/
β”œβ”€β”€ πŸ“„ README.md ← You are here
-└── πŸ“‚ chapters/
- β”œβ”€β”€ 🏠 00_overview.md ← What is a GPT? Why build one?
- β”œβ”€β”€ πŸ”§ 01_setup.md ← Install tools, GPU vs CPU, venv basics
- β”œβ”€β”€ πŸ”ͺ 02_tokenization.md ← BPE walkthrough, EOS tokens, emoji handling
- β”œβ”€β”€ 🧊 03_embeddings.md ← How numbers become meaning, king βˆ’ man + woman
- β”œβ”€β”€ πŸ“ 04_positional_encoding.md ← RoPE math, numerical example, theta
- β”œβ”€β”€ 🧠 05_attention.md ← ⭐ THE CORE (713 lines). Q,K,V, scaling, causal mask
- β”œβ”€β”€ 🧱 06_transformer_block.md ← RMSNorm, SwiGLU, residuals, pre-norm vs post
- β”œβ”€β”€ πŸ—οΈ 07_gpt_model.md ← Complete 151M model, weight tying, logits explained
- β”œβ”€β”€ πŸ‹οΈ 08_training.md ← Cross-entropy, backprop, AdamW, cosine warmup
- β”œβ”€β”€ 🎀 09_inference.md ← KV cache, temperature, top-k/p, beam search
- β”œβ”€β”€ πŸ“œ 10_full_script.md ← Runnable main.py
- └── πŸ“Š 11_glossary.md ← Architecture provenance, parameter breakdown
+β”œβ”€β”€ 🐍 main.py ← Runnable training script (clone & run)
+β”œβ”€β”€ πŸ“‚ chapters/
+β”‚ β”œβ”€β”€ 🏠 00_overview.md ← What is a GPT? Why build one?
+β”‚ β”œβ”€β”€ πŸ”§ 01_setup.md ← Install tools, GPU vs CPU, venv basics
+β”‚ β”œβ”€β”€ πŸ”ͺ 02_tokenization.md ← BPE walkthrough, EOS tokens, emoji handling
+β”‚ β”œβ”€β”€ 🧊 03_embeddings.md ← How numbers become meaning, king βˆ’ man + woman
+β”‚ β”œβ”€β”€ πŸ“ 04_positional_encoding.md ← RoPE math, numerical example, theta
+β”‚ β”œβ”€β”€ 🧠 05_attention.md ← ⭐ THE CORE (713 lines). Q,K,V, scaling, causal mask
+β”‚ β”œβ”€β”€ 🧱 06_transformer_block.md ← RMSNorm, SwiGLU, residuals, pre-norm vs post
+β”‚ β”œβ”€β”€ πŸ—οΈ 07_gpt_model.md ← Complete 151M model, weight tying, logits explained
+β”‚ β”œβ”€β”€ πŸ‹οΈ 08_training.md ← Cross-entropy, backprop, AdamW, cosine warmup
+β”‚ β”œβ”€β”€ 🎀 09_inference.md ← KV cache, temperature, top-k/p, beam search
+β”‚ β”œβ”€β”€ πŸ“œ 10_full_script.md ← About main.py
+β”‚ └── πŸ“Š 11_glossary.md ← Architecture provenance, parameter breakdown
+β”œβ”€β”€ πŸ““ notebooks/ ← Jupyter notebooks (one per chapter)
+β”œβ”€β”€ πŸ“š explanations and examples WIP/ ← Standalone explainers (15 topics)
+└── πŸ“„ CONTRIBUTING.md
```
---
diff --git a/explanations and examples WIP/adamw.md b/explanations and examples WIP/adamw.md
new file mode 100644
index 0000000..7a9de18
--- /dev/null
+++ b/explanations and examples WIP/adamw.md
@@ -0,0 +1,233 @@
+# AdamW: The Optimizer That Trains Language Models
+
+## What is it
+
+AdamW is the algorithm that updates the model's weights during
+training. After computing how wrong a prediction was and
+calculating which direction to move each weight AdamW decides
+exactly how far to move. It does this intelligently based on the
+history of past gradients for each parameter.
+
+Think of it like hiking down a mountain in the fog. You cannot
+see the bottom. You can only feel which direction is downhill.
+You take a step. Then you feel again. A naive hiker always takes
+the same size step. But some parts of the mountain are steep
+and need big steps. Others are flat and need small steps. AdamW
+remembers how steep each parameter has been and adjusts the step
+size accordingly. It also remembers the general direction to keep
+momentum going.
+
+The W in AdamW stands for decoupled weight decay. This is the key
+innovation over the original Adam optimizer. Weight decay slowly
+pushes all weights toward zero to prevent them from growing too
+large. In AdamW this push is separated from the gradient
+calculation. The separation makes weight decay work correctly.
+
+## Where is it used
+
+AdamW is called every training step after backward propagation.
+It takes the gradients that have been computed and clipped and
+applies them to the model weights.
+
+```python
+loss.backward()
+torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
+optimizer.step() # AdamW updates weights here
+optimizer.zero_grad()
+```
+
+## Why we use it instead of plain gradient descent
+
+Plain gradient descent is simple. Move each weight in the
+direction that reduces the loss. The step size is the same for
+every weight.
+
+```
+weight = weight - learning_rate Γ— gradient
+```
+
+This has three problems.
+
+First the step size is fixed. A weight that needs a big change
+gets the same size step as a weight that needs a tiny change. The
+learning rate must be chosen for the most sensitive weights. This
+makes training slow for all other weights.
+
+Second there is no momentum. If the gradient is noisy and points
+in a different direction each step the optimizer zigzags back and
+forth making slow progress. Momentum smooths out the noise by
+incorporating the direction from previous steps.
+
+Third there is no weight decay. Without regularization weights
+can grow arbitrarily large. Large weights mean the model is over
+confident about some patterns and ignores others. The model
+overfits.
+
+AdamW solves all three problems.
+
+## When was it invented
+
+Adam was published in 2014 by Diederik Kingma and Jimmy Ba. It
+quickly became the default optimizer for deep learning. But
+researchers noticed that the weight decay implementation in Adam
+was entangled with the adaptive learning rates. This meant weight
+decay did not actually prevent large weights. It mostly just
+slowed down training.
+
+AdamW was proposed in 2017 by Ilya Loshchilov and Frank Hutter.
+They showed that decoupling weight decay from the adaptive
+learning rates fixed the problem. AdamW achieved better
+generalization than Adam with the same hyperparameters. The fix
+was simple but the impact was large. GPT-3 trained with AdamW.
+LLaMA trained with AdamW. Every modern language model uses AdamW.
+
+## How it works
+
+AdamW maintains two running averages for each parameter. The first
+is the momentum which tracks the average direction of recent
+gradients. The second is the velocity which tracks the average
+magnitude of recent gradients.
+
+### Step 1: compute the noisy gradient
+
+```python
+gradient = compute_gradient(loss, weight)
+```
+
+This is the raw signal from one batch of data. It is noisy. A
+single batch might give a misleading direction.
+
+### Step 2: update the momentum
+
+```python
+momentum = beta1 Γ— momentum + (1 - beta1) Γ— gradient
+```
+
+The momentum is a weighted average of past gradients. Beta1 is
+usually 0.9. This means recent gradients count for ninety percent
+and older gradients fade away. The momentum smooths out noise and
+gives a stable direction.
+
+### Step 3: update the velocity
+
+```python
+velocity = beta2 Γ— velocity + (1 - beta2) Γ— gradientΒ²
+```
+
+The velocity tracks how much each parameter has been moving.
+Beta2 is usually 0.95. Parameters that have been making large
+moves get a high velocity. Parameters that have been sitting
+still get a low velocity.
+
+### Step 4: bias correction
+
+Both momentum and velocity start at zero. In the first few steps
+they are biased toward zero. The bias correction fixes this.
+
+```python
+momentum_corrected = momentum / (1 - beta1^t)
+velocity_corrected = velocity / (1 - beta2^t)
+```
+
+Where t is the current step number. After many steps the
+correction becomes negligible. But in the first few steps it
+prevents the optimizer from taking tiny useless steps.
+
+### Step 5: decoupled weight decay
+
+```python
+weight = weight Γ— (1 - learning_rate Γ— weight_decay)
+```
+
+This shrinks every weight by a tiny fraction. Weight decay is
+usually 0.1. With a learning rate of 0.0003 each weight is
+multiplied by 0.99997 per step. Over thousands of steps this
+gently pushes weights toward zero. Only weights that constantly
+receive strong gradients survive. Weights that are not useful
+fade away.
+
+Note that this step happens before the gradient update and is
+completely independent of the gradient. This is the decoupled
+part of AdamW. In the original Adam weight decay was mixed in
+with the gradient scaling which made it ineffective.
+
+### Step 6: apply the gradient
+
+```python
+weight = weight - learning_rate Γ— momentum_corrected / (sqrt(velocity_corrected) + eps)
+```
+
+The gradient step is scaled by the learning rate. Then it is
+divided by the square root of the velocity. Parameters with high
+velocity have been changing a lot so we take smaller steps.
+Parameters with low velocity have been stable so we can take
+larger steps. The epsilon prevents division by zero.
+
+## Two parameter groups
+
+Not all parameters should get weight decay. The biases and
+normalization weights are one dimensional. They adjust the offset
+and scale of activations. Pushing them toward zero would prevent
+them from doing their job. We create two groups of parameters
+with different weight decay values.
+
+```python
+def create_optimizer(model, config):
+ decay_params = [] # Linear and embedding weights
+ no_decay_params = [] # Biases and normalization weights
+
+ for name, param in model.named_parameters():
+ if not param.requires_grad:
+ continue
+ if param.dim() <= 1 or 'norm' in name.lower() or 'bias' in name:
+ no_decay_params.append(param)
+ else:
+ decay_params.append(param)
+
+ return torch.optim.AdamW([
+ {'params': decay_params, 'weight_decay': 0.1},
+ {'params': no_decay_params, 'weight_decay': 0.0},
+ ], lr=3e-4, betas=(0.9, 0.95), eps=1e-8)
+```
+
+The decay group gets weight decay of 0.1. The no decay group gets
+zero weight decay. Each group is treated separately by the
+optimizer.
+
+## The hyperparameters
+
+Every optimizer has settings called hyperparameters. For AdamW
+the important ones are:
+
+```
+learning_rate = 0.0003 (3e-4)
+ How big a step to take. Smaller is safer but slower.
+
+betas = (0.9, 0.95)
+ How much to trust past gradients. Higher means smoother updates.
+
+weight_decay = 0.1
+ How aggressively to push weights toward zero. Higher prevents
+ overfitting but too high makes the model forget.
+
+eps = 0.00000001 (1e-8)
+ A tiny number to prevent division by zero. Never needs tuning.
+```
+
+These values are the LLaMA defaults and have been battle tested
+on models from one billion to seventy billion parameters. Unless
+you are doing something unusual there is rarely a reason to
+change them.
+
+## What you need to remember
+
+AdamW is the standard optimizer for training language models. It
+combines momentum for stability adaptive learning rates for
+efficiency and decoupled weight decay for regularization. The
+three mechanisms work together to make training fast stable and
+resistant to overfitting.
+
+Every production language model trains with AdamW. The
+hyperparameters are well established and rarely need tuning. Like
+gradient clipping it has no meaningful downside. It is simply the
+right tool for the job.
diff --git a/explanations and examples WIP/causal_masking.md b/explanations and examples WIP/causal_masking.md
new file mode 100644
index 0000000..d835211
--- /dev/null
+++ b/explanations and examples WIP/causal_masking.md
@@ -0,0 +1,208 @@
+# Causal Masking: No Peeking at the Future
+
+## What is it
+
+Causal masking is a rule that prevents every word in a sentence
+from seeing the words that come after it. Given a sentence like
+*The cat sat on the mat* the word *cat* can see *The* but not
+*sat*. The word *sat* can see *The* and *cat* but not *on*. Each
+word lives in the dark about what comes next.
+
+Think of it like reading a book one page at a time. You have read
+pages one through five. Page six is face down on the table. You
+are not allowed to peek. You must guess what happens on page six
+using only what you have already read.
+
+This rule seems restrictive. Why not let the model see everything.
+Because the model's entire job is to predict the next word. If
+the model could see the next word it would not need to predict
+it. It would just copy. That is not learning. That is cheating.
+
+## Where is it used
+
+The causal mask lives inside the attention layer. Right after the
+attention scores are computed and right before the softmax turns
+them into percentages.
+
+```
+Attention scores β†’ Apply causal mask β†’ Softmax β†’ Attention weights
+```
+
+Every attention layer in every transformer block applies the
+causal mask. For a twelve block model the mask is applied twelve
+times for every sentence. Always the same mask. Always the same
+rule. No peeking at the future.
+
+## Why we need it
+
+During training the model sees complete sentences. The input is
+*The cat sat on the mat* all at once. Without the causal mask the
+word *cat* could look at *mat* and say *ah the sentence ends with
+mat so cat must be followed by sat*. The model would learn a
+trivial mapping from full sentences to themselves. It would never
+learn to predict. It would only learn to copy.
+
+With the causal mask the model is forced to earn its predictions.
+At position two it sees *The* and *cat* and must guess *sat*. At
+position three it sees *The cat* and *sat* and must guess *on*.
+The model cannot look ahead for hints. Every prediction is made
+using only the information available at that point in the
+sentence. This is exactly how text generation works in the real
+world. You only know what came before. You never know what comes
+next.
+
+## When was it invented
+
+The causal mask was introduced alongside the transformer itself
+in the 2017 paper Attention Is All You Need. It was not an
+afterthought. It was a design requirement. The authors knew that
+language models must be trained autoregressively meaning one word
+at a time from left to right. The causal mask enforces this
+constraint during training so the model behaves correctly during
+generation.
+
+## How it works step by step
+
+### The attention matrix without a mask
+
+For a three word sentence *I love dogs* the model computes an
+attention score between every pair of words. Every word can see
+every other word.
+
+```
+Attention scores (no mask):
+
+ I love dogs
+I 0.42 0.15 0.08 ← I can see love and dogs
+love 0.33 0.51 0.22 ← love can see I and dogs
+dogs 0.19 0.28 0.44 ← dogs can see I and love
+```
+
+This is a fully connected matrix. Every pair of words has a score.
+The model can use information from anywhere in the sentence.
+
+### The attention matrix with a causal mask
+
+After applying the mask future positions are set to negative
+infinity. After softmax negative infinity becomes exactly zero.
+Those connections are severed.
+
+```
+Attention scores (with mask):
+
+ I love dogs
+I 0.42 -inf -inf ← I can only see itself
+love 0.33 0.51 -inf ← love can see I and itself
+dogs 0.19 0.28 0.44 ← dogs can see all three
+```
+
+After softmax these scores become weights:
+
+```
+Attention weights (after softmax):
+
+ I love dogs
+I 1.00 0.00 0.00 ← 100% on itself
+love 0.46 0.54 0.00 ← split between I and itself
+dogs 0.27 0.30 0.43 ← split among all three
+```
+
+The upper right triangle is all zeros. This is the characteristic
+pattern of a causal mask. It is a lower triangular matrix.
+
+### The rule in one line
+
+```
+Token at position p can only attend to tokens at positions
+0 through p. Token at position p cannot attend to any token
+at position p+1 or beyond.
+```
+
+## How we implement it
+
+Creating a causal mask is surprisingly simple. PyTorch has a
+function called tril that returns the lower triangle of a matrix.
+
+```python
+import torch
+
+seq_len = 4
+mask = torch.tril(torch.ones(seq_len, seq_len))
+
+print(mask)
+
+# Output:
+# tensor([[1., 0., 0., 0.],
+# [1., 1., 0., 0.],
+# [1., 1., 1., 0.],
+# [1., 1., 1., 1.]])
+```
+
+That is the entire mask. Four lines of ones and zeros. Ones mean
+visible. Zeros mean hidden.
+
+In the actual attention code we use this mask like so:
+
+```python
+def create_causal_mask(seq_len, device):
+ mask = torch.tril(torch.ones(seq_len, seq_len, device=device))
+ return mask.view(1, 1, seq_len, seq_len)
+
+# Inside attention forward:
+if mask is not None:
+ attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))
+```
+
+The `masked_fill` operation puts negative infinity wherever the
+mask has a zero. After softmax `e^(-inf)` is zero and those
+positions contribute nothing to the final output.
+
+## What happens during generation
+
+During training the causal mask prevents cheating. During text
+generation the causal mask is still there but it does less work.
+
+When generating text we start with a prompt like *Once upon a*.
+The model processes these three tokens using the causal mask.
+Token two can see token zero and token one. Token one can see
+only token zero. Normal.
+
+Then the model predicts the next token. Let us say it predicts
+*time*. We append *time* to the sequence making it *Once upon a
+time*. Now we run the model again on these four tokens. The
+causal mask still applies. The new token *time* can see *Once*
+and *upon* and *a* but it cannot see the next token because the
+next token does not exist yet.
+
+The causal mask is built into the architecture. It is not a
+training only feature. It is a fundamental constraint that makes
+autoregressive language models possible. Without it we could
+never generate text token by token because the model would keep
+trying to peek at words that have not been written yet.
+
+## What happens without the causal mask
+
+If we removed the causal mask during training the model would
+learn to cheat. Its training loss would be extremely low because
+it can always see the answer. But during generation when future
+tokens do not exist yet the model would be completely lost. It
+would not know how to predict the unknown. Its output would be
+gibberish.
+
+This is a common failure mode for beginners who build their first
+transformer. The training loss looks fantastic. The generated
+text is nonsense. The causal mask was omitted.
+
+## What you need to remember
+
+The causal mask makes attention a one way street. Words can look
+back but never forward. This forces the model to predict each
+token using only the tokens that came before it. This is exactly
+how text generation works. You write one word at a time. You
+never know what comes next until you write it.
+
+The mask is a lower triangular matrix of ones and zeros. Zeros
+become negative infinity in the attention scores. Negative
+infinity becomes zero after softmax. The connections to future
+words are severed. Only the past remains. This simple rule is
+what separates a language model from a text copier.
diff --git a/explanations and examples WIP/cosine_warmup.md b/explanations and examples WIP/cosine_warmup.md
new file mode 100644
index 0000000..00112e9
--- /dev/null
+++ b/explanations and examples WIP/cosine_warmup.md
@@ -0,0 +1,209 @@
+# Cosine Warmup: The Learning Rate Schedule
+
+## What is it
+
+The cosine warmup schedule controls how the learning rate changes
+during training. It starts low and rises to a peak. Then it
+gradually falls following a cosine curve. By the end of training
+the learning rate is very small and the model settles into a fine
+minimum.
+
+Think of it like learning to ride a bicycle. At first you go very
+slowly. You wobble. You get a feel for the balance. Once you have
+some stability you push harder and go faster. As you approach your
+destination you slow down again to make a precise stop. You do
+not sprint from the start and slam the brakes at the end.
+
+Cosine warmup does the same thing for neural network training. The
+model starts slow to find its balance. It accelerates to full
+speed once stable. It decelerates at the end to land softly on
+the best possible solution.
+
+## Where is it used
+
+The schedule controls the learning rate parameter inside the
+optimizer. Every training step the schedule computes a new
+learning rate and assigns it to the optimizer.
+
+```python
+scheduler = CosineWarmupScheduler(optimizer, warmup=2000, max_steps=100000)
+
+for step in range(max_steps):
+ loss = model(batch)
+ loss.backward()
+ optimizer.step()
+ scheduler.step() # Update learning rate every step
+ optimizer.zero_grad()
+```
+
+## Why we need it
+
+A constant learning rate seems simpler. Why not just pick one
+value and train the whole way. Two reasons.
+
+First early training is chaotic. The model's weights are random.
+The gradients are large and noisy. Large learning rates at the
+start can send the model flying off in random directions. The
+warmup phase lets the model find its footing before taking large
+steps.
+
+Second late training is about precision. After thousands of steps
+the model is close to a good solution. Large steps would overshoot
+the minimum and bounce around it forever. The decay phase lets
+the model take tiny careful steps to settle into the exact best
+position.
+
+A constant learning rate would be either too large for the start
+or too small for the middle. Warmup plus decay is the only way to
+have both stability at the start and precision at the end.
+
+## When was it invented
+
+Learning rate warmup was used for the original transformer in
+2017. The authors noticed that training was unstable in the first
+few thousand steps without it. Cosine decay was introduced around
+the same time as an alternative to step decay schedules which
+drop the learning rate abruptly at predetermined intervals. Step
+decay works but the sudden drops can disturb the model. Cosine
+decay is smooth and continuous. GPT-3 used cosine warmup. LLaMA
+used cosine warmup. It is the standard for language model
+training.
+
+## How it works
+
+The schedule has three phases. Each phase is a simple
+mathematical formula.
+
+### Phase 1: Linear warmup
+
+The learning rate starts at zero and increases linearly to the
+maximum value.
+
+```python
+if step < warmup_steps:
+ lr = max_lr * step / warmup_steps
+```
+
+Example with warmup_steps of 2000 and max_lr of 0.0003:
+
+```
+Step 0: lr = 0.0003 Γ— (0 / 2000) = 0.0
+Step 500: lr = 0.0003 Γ— (500 / 2000) = 0.000075
+Step 1000: lr = 0.0003 Γ— (1000 / 2000) = 0.00015
+Step 2000: lr = 0.0003 Γ— (2000 / 2000) = 0.0003
+```
+
+Every step the learning rate grows by the same tiny amount. No
+sudden jumps. The model has two thousand steps to get stable
+before it reaches full speed.
+
+### Phase 2: Cosine decay
+
+After warmup the learning rate follows a cosine curve from the
+maximum down to a minimum.
+
+```python
+if step < max_steps:
+ progress = (step - warmup_steps) / (max_steps - warmup_steps)
+ cosine_decay = 0.5 Γ— (1 + cos(Ο€ Γ— progress))
+ lr = min_lr + (max_lr - min_lr) Γ— cosine_decay
+```
+
+The progress variable goes from zero to one over the remaining
+steps. The cosine function creates a smooth S shape curve.
+
+```
+Step 2000: progress = 0.0, cosine = 1.0, lr = 0.0003
+Step 25000: progress = 0.23, cosine = 0.75, lr = 0.000225
+Step 50000: progress = 0.49, cosine = 0.25, lr = 0.000075
+Step 100000: progress = 1.0, cosine = 0.0, lr = 0.00001
+```
+
+The learning rate falls slowly at first then faster in the middle
+then slowly again at the end. The minimum is usually 0.00001
+which is thirty times smaller than the peak. This tiny rate at
+the end lets the model refine its weights with extreme precision.
+
+### Phase 3: Minimum
+
+After max_steps the learning rate stays at the minimum forever.
+
+```python
+lr = min_lr
+```
+
+The model continues to learn but at a glacial pace. Each step
+makes almost no difference. This is intentional. The model has
+already learned everything it needs. The remaining steps just
+polish.
+
+## A tiny code example
+
+```python
+import math
+import matplotlib.pyplot as plt
+
+max_lr = 0.0003
+min_lr = 0.00001
+warmup_steps = 2000
+max_steps = 100000
+
+lrs = []
+for step in range(max_steps):
+ if step < warmup_steps:
+ lr = max_lr * step / warmup_steps
+ elif step < max_steps:
+ progress = (step - warmup_steps) / (max_steps - warmup_steps)
+ cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
+ lr = min_lr + (max_lr - min_lr) * cosine
+ else:
+ lr = min_lr
+ lrs.append(lr)
+
+plt.figure(figsize=(10, 4))
+plt.plot(lrs)
+plt.xlabel('Training Step')
+plt.ylabel('Learning Rate')
+plt.title('Cosine Warmup Schedule')
+plt.grid(True, alpha=0.3)
+plt.tight_layout()
+plt.savefig('lrs_curve.png', dpi=100)
+print("The curve rises from 0 over 2000 warmup steps")
+print("then decays along a cosine curve for 98000 steps")
+print("and stays at the minimum from step 100000 onward")
+```
+
+## The shape of the curve
+
+```
+Learning rate
+ ^
+ |
+0.0003 + ....----....
+ | .. ..
+ | .. ..
+ | .. ....
+ | .. .............
+ |.. ...........
+0.0 +----+----+----+----+----+----+----+----+----+----+---->
+ 0 10k 20k 30k 40k 50k 60k 70k 80k 90k 100k
+ Training steps
+```
+
+The curve rises steeply during warmup. It stays near the peak for
+a while. Then it starts a gentle descent that accelerates in the
+middle and flattens at the end. The minimum is reached exactly at
+the final training step. Not before. Not after.
+
+## What you need to remember
+
+Cosine warmup scheduling controls the learning rate across the
+entire training run. The rate starts at zero and warms up to a
+peak. Then it decays along a cosine curve to a minimum. The
+schedule is smooth and continuous with no sudden drops.
+
+Warmup prevents instability at the start of training when
+gradients are chaotic. Decay allows precision at the end when the
+model is close to the solution. Together they make training both
+stable and precise. Every modern language model uses this
+schedule.
diff --git a/explanations and examples WIP/gradient_clipping.md b/explanations and examples WIP/gradient_clipping.md
new file mode 100644
index 0000000..6bc4ee2
--- /dev/null
+++ b/explanations and examples WIP/gradient_clipping.md
@@ -0,0 +1,182 @@
+# Gradient Clipping: Preventing Training Explosions
+
+## What is it
+
+Gradient clipping is a safety net. During training the model
+calculates how to change each weight to reduce the loss. These
+change instructions are called gradients. Sometimes a gradient
+gets very large. One particular example in the training data
+sends a shockwave through the network. The weights take a massive
+jump and the model falls off the cliff into a region where the
+loss is astronomical. Training is ruined.
+
+Gradient clipping says: no gradient can be larger than a certain
+limit. If the total magnitude of all gradients is too high we
+shrink them proportionally until they fit under the limit. The
+direction of the update stays the same. Only the step size is
+limited. The model takes small safe steps instead of wild leaps.
+
+## Where is it used
+
+Gradient clipping is applied right before the optimizer updates
+the weights. The gradients have already been computed. They are
+about to be used to change the model. At this moment gradient
+clipping checks them and reins in any that have grown too large.
+
+```python
+loss.backward() # Compute gradients
+torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
+optimizer.step() # Apply clipped gradients
+```
+
+It is a single function call. One line of code that can save
+hours of wasted training time.
+
+## Why we need it
+
+Language models are trained on text. Some text is unusual. A
+sentence might contain a very rare word. The model has never
+seen it before. The loss for that sentence is very high. The
+gradients that flow backward from that loss are very large. If
+the optimizer applies these large gradients the model's weights
+jump to a completely different configuration. Everything the
+model learned over the past thousand steps is wiped out by one
+unusual sentence.
+
+Without gradient clipping the training loss curve has spikes.
+Long periods of steady improvement followed by sudden jumps where
+the loss doubles or triples. After each spike the model must
+recover. Sometimes it never recovers. The gradients were too
+large and the weights went to a place from which there is no
+return. The model produces only garbage from that point forward.
+
+With gradient clipping the loss curve is smooth. The unusual
+sentence still produces larger gradients than normal but those
+gradients are clipped to a safe size. The model takes a slightly
+larger than normal step in the right direction instead of a
+catastrophic leap. Training continues uninterrupted.
+
+## When was it invented
+
+Gradient clipping has been used since the early days of recurrent
+neural networks in the 1990s. RNNs were notorious for gradient
+explosion because they processed sequences one step at a time
+and the gradients multiplied at each step. The problem was
+solved by simply capping gradients at a maximum value. The same
+technique was carried forward to transformers even though
+transformers do not have the same multiplicative problem. It
+turns out that any deep network benefits from gradient clipping
+as a safety measure.
+
+## How it works
+
+Gradient clipping by norm is the standard method. Instead of
+clipping each gradient individually we measure the total size of
+all gradients together and clip them as a group. This preserves
+the relative sizes of different gradients. If one parameter
+needs a large update and another needs a small update the ratio
+between them is preserved even after clipping.
+
+### Step 1: measure the total gradient magnitude
+
+We compute the L2 norm of all gradients. This is the square root
+of the sum of all squared gradients.
+
+```python
+total_norm = 0.0
+for p in model.parameters():
+ if p.grad is not None:
+ total_norm += p.grad.norm(2).item() ** 2
+total_norm = total_norm ** 0.5
+```
+
+If the model has a million parameters with an average gradient of
+0.01 the total norm would be about 100. A total norm of 100 is
+manageable. A total norm of 10000 is dangerous.
+
+### Step 2: clip if needed
+
+If the total norm exceeds the maximum allowed we shrink every
+gradient by the same factor.
+
+```python
+max_norm = 1.0
+if total_norm > max_norm:
+ scale = max_norm / total_norm
+ for p in model.parameters():
+ if p.grad is not None:
+ p.grad *= scale
+```
+
+If the total norm was 100 and the maximum is 1 we divide every
+gradient by 100. The largest gradients become 0.01. The smallest
+gradients become even smaller. The direction of the update is
+unchanged. Only the step size changes.
+
+### Why max_norm of 1.0
+
+The value 1.0 is the standard for transformer training. It was
+chosen empirically. Smaller values like 0.1 make training too
+slow because the model can only take tiny steps. Larger values
+like 10.0 provide little protection because most gradient norms
+are already below 10. A value of 1.0 catches the dangerous spikes
+without interfering with normal training steps.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn as nn
+
+# Create a small model and some fake gradients
+model = nn.Linear(10, 10)
+loss = model(torch.randn(1, 10)).sum()
+loss.backward()
+
+# Check the gradient norm before clipping
+total_norm = 0.0
+for p in model.parameters():
+ if p.grad is not None:
+ total_norm += p.grad.norm(2).item() ** 2
+total_norm = total_norm ** 0.5
+
+print(f"Gradient norm before clipping: {total_norm:.4f}")
+
+# Clip
+torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
+
+# Check after
+total_norm_after = 0.0
+for p in model.parameters():
+ if p.grad is not None:
+ total_norm_after += p.grad.norm(2).item() ** 2
+total_norm_after = total_norm_after ** 0.5
+
+print(f"Gradient norm after clipping: {total_norm_after:.4f}")
+print(f"Clipped: {total_norm > 1.0}")
+```
+
+## What happens without it
+
+Training language models without gradient clipping is playing
+with fire. Most steps will be fine. The gradients will be small
+and the model will learn. But eventually the model will
+encounter a batch of text that produces large gradients. The
+loss will spike. If the model is lucky it will recover. If it is
+unlucky the spike will push the weights into a region where every
+subsequent step also produces large gradients. The loss will
+diverge to infinity and the training run will be lost.
+
+Gradient clipping costs nothing in terms of model quality. It has
+no downside. It is a pure safety measure that prevents a rare but
+catastrophic failure mode. Every production training run uses it.
+
+## What you need to remember
+
+Gradient clipping limits how much the model's weights can change
+in a single training step. If gradients are too large they are
+scaled down proportionally to a maximum norm. The standard
+maximum is 1.0 for transformer training.
+
+One function call. Zero downside. Infinite protection against a
+training killing failure mode. Use it always.
diff --git a/explanations and examples WIP/kv_cache.md b/explanations and examples WIP/kv_cache.md
new file mode 100644
index 0000000..be700d9
--- /dev/null
+++ b/explanations and examples WIP/kv_cache.md
@@ -0,0 +1,233 @@
+# KV Cache: Making Text Generation Fast
+
+## What is it
+
+The KV cache stores the Key and Value vectors from all previous
+tokens during text generation. When the model generates the next
+token it reuses these stored vectors instead of recomputing them
+from scratch. This makes generation hundreds of times faster.
+
+Think of it like writing a long email. Without a KV cache you
+would reread the entire email from the start every time you typed
+a new word. With a KV cache you remember everything you already
+wrote and only think about the new word. The difference in
+effort is enormous.
+
+## Where is it used
+
+The KV cache lives inside the attention layer. Every attention
+head in every transformer block has its own cache. For a twelve
+block model with twelve heads there are one hundred and forty
+four separate caches. Each stores the Keys and Values for every
+token generated so far.
+
+```
+Text generation without cache:
+ For each new token:
+ Run the ENTIRE sequence through all layers
+ This recomputes K and V for every past token
+ Time grows quadratically with sequence length
+
+Text generation with cache:
+ For each new token:
+ Only compute K and V for the new token
+ Append to cache
+ Reuse cached K and V for all past tokens
+ Time grows linearly with sequence length
+```
+
+## Why we need it
+
+The attention formula is Q times K transpose. The Q matrix has
+one row per token. The K matrix has one row per token. If we have
+five hundred tokens we multiply a five hundred by sixty four
+matrix by a sixty four by five hundred matrix. That is already
+some work.
+
+Without a cache we would do this multiplication from scratch for
+every new token. When the sequence is one token long we do one
+comparison. When it is two tokens long we do two comparisons for
+token zero and two for token one. When it is five hundred tokens
+long we do five hundred comparisons for each of the five hundred
+tokens. The total work grows with the square of the sequence
+length. This is painfully slow.
+
+With a cache we only compute the comparisons involving the new
+token. Token five hundred compares itself against all five hundred
+previous tokens. That is five hundred new comparisons. Not five
+hundred squared. The cached Keys save us from recomputing the old
+comparisons that have not changed.
+
+### The speed numbers
+
+```
+Sequence length 100:
+ Without cache: 100Β² = 10,000 comparisons per generation step
+ With cache: 100 comparisons per generation step
+ Speedup: 100Γ—
+
+Sequence length 1000:
+ Without cache: 1,000Β² = 1,000,000 comparisons
+ With cache: 1,000 comparisons
+ Speedup: 1,000Γ—
+```
+
+For a long conversation with thousands of tokens the KV cache
+makes the difference between waiting seconds and waiting minutes
+for each new word.
+
+## When was it invented
+
+The KV cache was described in the original transformer paper in
+2017. It was not an optimization added later. It was part of the
+design from the beginning. The authors knew that autoregressive
+generation would be painfully slow without it. Every transformer
+implementation since 2017 uses some form of KV cache.
+
+## How it works step by step
+
+### Step 1: the first token
+
+We have a prompt that is five tokens long. The model processes
+all five tokens in parallel during a prefill step.
+
+```
+Prefill:
+ Tokens: [The, cat, sat, on, the]
+ K cache for head 0: store K for all 5 tokens (5 Γ— 64 matrix)
+ V cache for head 0: store V for all 5 tokens (5 Γ— 64 matrix)
+ ... repeat for all 12 heads ...
+```
+
+This initial step is expensive but it only happens once.
+
+### Step 2: generating the next token
+
+The model predicts that the next token is *mat*. We append *mat*
+to the sequence. Now we have six tokens.
+
+```
+Generation step 1:
+ New token: [mat]
+ Compute K for "mat" only: (1 Γ— 64 matrix)
+ Compute V for "mat" only: (1 Γ— 64 matrix)
+ Full K cache: 5 old rows + 1 new row = 6 Γ— 64 matrix
+ Full V cache: 5 old rows + 1 new row = 6 Γ— 64 matrix
+ Compute Q for "mat" only: (1 Γ— 64 matrix)
+ Attention scores: Q_mat Γ— K_full^T = 1 Γ— 6 comparisons
+ Only the new token's Q was computed. Old Q values are not needed.
+```
+
+We computed only one new Key one new Value and one new Query. The
+attention scores for *mat* are computed against all six tokens
+because *mat* needs to attend to everything that came before. But
+the attention scores for *The* and *cat* and *sat* are not
+recomputed. They do not change. Why would they. Their context has
+not changed. Only the new token has new context to process.
+
+### Step 3: memory growth
+
+For each new token we add one row to every K cache and every V
+cache. The cache grows linearly with the sequence length.
+
+```
+Memory for a GPT-2 Small model generating 1000 tokens:
+
+K cache: 12 layers Γ— 12 heads Γ— 1000 tokens Γ— 64 dims Γ— 2 bytes (bfloat16)
+ = 18,432,000 bytes
+ = 17.6 MB
+
+V cache: same as K cache = 17.6 MB
+
+Total KV cache: 35.2 MB
+```
+
+Thirty five megabytes is nothing for a modern GPU. But remember
+this is GPT-2 Small with only twelve layers and 768 dimensions.
+
+```
+Memory for a GPT-3 Large model generating 1000 tokens:
+
+K cache: 96 layers Γ— 96 heads Γ— 1000 tokens Γ— 128 dims Γ— 2 bytes
+ = 2,359,296,000 bytes
+ = 2.2 GB
+
+V cache: same as K cache = 2.2 GB
+
+Total KV cache: 4.4 GB
+```
+
+Now the cache is a significant portion of GPU memory. For long
+conversations spanning thousands of tokens the KV cache can
+become the dominant memory consumer. This is one reason why
+running large models at long context lengths requires enormous
+amounts of VRAM.
+
+## A simplified code sketch
+
+This is not production code but it shows the idea.
+
+```python
+class AttentionWithCache:
+ def __init__(self):
+ self.k_cache = None # Will hold accumulated K values
+ self.v_cache = None # Will hold accumulated V values
+
+ def forward(self, x, use_cache=False):
+ q, k, v = self.qkv_proj(x)
+
+ if use_cache and self.k_cache is not None:
+ # Append new K and V to cache
+ k = torch.cat([self.k_cache, k], dim=2)
+ v = torch.cat([self.v_cache, v], dim=2)
+
+ # Update cache for next step
+ self.k_cache = k
+ self.v_cache = v
+
+ # Normal attention computation
+ scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
+ weights = F.softmax(scores, dim=-1)
+ return weights @ v
+
+ def reset_cache(self):
+ self.k_cache = None
+ self.v_cache = None
+```
+
+The key idea is on lines eleven and twelve. Instead of throwing
+away the old K and V we append the new ones. The cache grows over
+time. At the start of a new conversation we reset the cache to
+empty.
+
+## The tradeoff
+
+KV cache trades memory for speed. We accept that generation will
+use more GPU memory in exchange for making each step much faster.
+For most real world applications this is a good trade. Memory is
+relatively cheap compared to the user's patience waiting for
+each word to appear.
+
+However for very long sequences the memory cost becomes
+prohibitive. Researchers have developed techniques like grouped
+query attention and multi query attention that reduce the number
+of K and V heads. Fewer heads means a smaller cache. These
+techniques are standard in modern models like LLaMA 2 and Mistral.
+
+## What you need to remember
+
+The KV cache stores previously computed Keys and Values so they
+do not need to be recomputed for each new token. This changes the
+complexity of text generation from quadratic to linear in the
+sequence length. For a thousand token sequence this is a thousand
+times speedup.
+
+The cost is memory. The cache grows with the sequence length and
+the model size. For small models the memory cost is negligible.
+For large models at long context lengths the cache can consume
+tens of gigabytes.
+
+Without a KV cache text generation would be slow enough that
+chatbots would be unusable. Every response would take minutes
+instead of seconds. The cache is a necessary optimization for
+any real world deployment.
diff --git a/explanations and examples WIP/mixed_precision.md b/explanations and examples WIP/mixed_precision.md
new file mode 100644
index 0000000..8e45d01
--- /dev/null
+++ b/explanations and examples WIP/mixed_precision.md
@@ -0,0 +1,239 @@
+# Mixed Precision Training: Speed Without Sacrifice
+
+## What is it
+
+Mixed precision training uses two different number formats during
+training. Most operations use bfloat16 a compact format that
+takes less memory and runs faster. A few critical operations use
+float32 the standard format that is more precise. The mix gives
+you the speed of the compact format with the accuracy of the
+standard one.
+
+Think of it like carrying groceries. You can carry items in your
+hands with full control over each one. That is float32. Or you
+can put everything in a bag and carry the bag. That is bfloat16.
+You lose some control over individual items but you can carry
+twice as many in a single trip.
+
+Mixed precision means using the bag for the heavy lifting but
+taking items out to handle them carefully when precision matters.
+
+## Where is it used
+
+Mixed precision wraps the forward pass of the model. Every matrix
+multiplication inside the attention and feed forward layers runs
+in bfloat16. The loss is computed in float32. The weight updates
+are stored in float32.
+
+```python
+with torch.amp.autocast('cuda', enabled=True):
+ # Everything here runs in bfloat16
+ logits, loss = model(input_ids, target_ids)
+
+# The loss is float32 for accurate backward pass
+loss.backward()
+```
+
+Without mixed precision training a large language model would
+take twice as long and use twice as much GPU memory. With it you
+can train bigger models on the same hardware.
+
+## Why we need it
+
+The bottleneck in neural network training is matrix
+multiplication. The attention layer does Q times K transpose. The
+feed forward layer does input times weight matrix. These
+operations dominate the training time. If we can make them twice
+as fast we cut training time in half.
+
+Smaller number formats make matrix multiplication faster because
+each number takes less memory. With float32 each number is four
+bytes. With bfloat16 each number is two bytes. You can fit twice
+as many numbers in the same memory. The GPU can process them in
+wider batches. The result is roughly twice the speed.
+
+But why not use float16 everywhere and get even more speed? The
+problem is range. Float16 can only represent numbers up to about
+sixty five thousand. During training intermediate values can
+exceed this limit. The number overflows and becomes infinity. The
+model produces garbage. This is why early attempts at half
+precision training failed.
+
+Bfloat16 fixes this by keeping the same range as float32. The
+maximum possible value is about three point four times ten to
+the thirty eighth power for both formats. Bfloat16 cannot
+overflow. It just has less precision within that range. For
+neural network training this tradeoff is perfect. We need the
+range for intermediate values but we do not need seven decimal
+digits of precision for every activation.
+
+## When was it invented
+
+Bfloat16 was created by Google in 2017 specifically for their
+TPU hardware. It was designed from scratch for neural network
+training. NVIDIA adopted it in their A100 GPUs in 2020. Now
+every major GPU supports bfloat16 natively. Mixed precision
+training using bfloat16 is the default for all production
+language model training.
+
+## The three number formats compared
+
+```
+Float32: 32 bits total
+ 1 bit for sign
+ 8 bits for exponent (range)
+ 23 bits for mantissa (precision)
+ Range: up to Β±3.4 Γ— 10³⁸
+ Precision: 7 decimal digits
+
+Bfloat16: 16 bits total
+ 1 bit for sign
+ 8 bits for exponent (range)
+ 7 bits for mantissa (precision)
+ Range: up to Β±3.4 Γ— 10³⁸ (same as float32!)
+ Precision: 2 decimal digits
+
+Float16: 16 bits total
+ 1 bit for sign
+ 5 bits for exponent (range)
+ 10 bits for mantissa (precision)
+ Range: up to Β±65504 (can overflow!)
+ Precision: 3 decimal digits
+```
+
+Notice that bfloat16 and float32 have the same range. The only
+difference is precision. Bfloat16 has seven bits for the mantissa
+while float32 has twenty three. This means bfloat16 can represent
+numbers with about two decimal digits of accuracy. Float32 can
+represent seven. For neural network training two digits is enough.
+The gradients and activations do not need extreme precision. They
+just need consistent ballpark numbers.
+
+Float16 has better precision than bfloat16 but terrible range. In
+practice float16 overflows during long training runs. Bfloat16
+does not. This is why bfloat16 won.
+
+## How it works in practice
+
+The training loop has three parts and each uses a different
+precision strategy.
+
+### Part 1: the forward pass
+
+Most operations run in bfloat16 inside an autocast context.
+
+```python
+with torch.amp.autocast('cuda', enabled=True):
+ logits, loss = model(input_ids, target_ids)
+```
+
+The autocast context manager automatically converts operations to
+bfloat16 wherever it is safe. Matrix multiplications and
+convolutions are converted. Normalization operations like RMSNorm
+stay in float32 because they need more precision. The developer
+does not need to manually specify which operations to convert.
+Autocast handles it.
+
+### Part 2: the backward pass
+
+The loss is in float32 for accuracy. The backward pass computes
+gradients. Some gradients are in float32 and some in bfloat16.
+A gradient scaler watches for underflow.
+
+The gradient scaler multiplies the loss by a large number before
+the backward pass. This pushes small gradients into the
+representable range of bfloat16. After the backward pass the
+scaler divides the gradients back down before the weight update.
+This prevents tiny gradients from becoming zero in bfloat16.
+
+```python
+scaler = torch.amp.GradScaler('cuda', enabled=True)
+scaler.scale(loss).backward()
+scaler.step(optimizer)
+scaler.update()
+```
+
+### Part 3: the weight update
+
+The master weights are always stored in float32. After the
+backward pass the gradients are applied to the float32 weights.
+This ensures that even if the forward pass computes in bfloat16
+the weights themselves never lose precision over many updates.
+This is called mixed precision because the forward pass is half
+precision and the weight storage is full precision.
+
+```python
+# Master weights are float32 always
+optimizer.step() # Applies float32 gradients to float32 weights
+```
+
+## A tiny code example
+
+```python
+import torch
+
+# Check if your GPU supports bfloat16
+if torch.cuda.is_available():
+ capability = torch.cuda.get_device_capability()
+ print(f"GPU compute capability: {capability}")
+ bf16_ok = capability[0] >= 8
+ print(f"Bfloat16 supported: {bf16_ok}")
+else:
+ print("No GPU available. Mixed precision requires CUDA.")
+ print("CPU training runs in float32 only.")
+
+# Simple speed comparison
+if torch.cuda.is_available():
+ size = 4096
+ a = torch.randn(size, size, device='cuda')
+ b = torch.randn(size, size, device='cuda')
+
+ # Float32
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+
+ start.record()
+ c32 = a @ b
+ end.record()
+ torch.cuda.synchronize()
+ t32 = start.elapsed_time(end)
+
+ # Bfloat16
+ start.record()
+ with torch.amp.autocast('cuda', dtype=torch.bfloat16):
+ c16 = a @ b
+ end.record()
+ torch.cuda.synchronize()
+ t16 = start.elapsed_time(end)
+
+ print(f"\nMatrix multiply {size}x{size}:")
+ print(f"Float32 time: {t32:.1f} ms")
+ print(f"Bfloat16 time: {t16:.1f} ms")
+ print(f"Speedup: {t32/t16:.1f}x")
+```
+
+## When not to use mixed precision
+
+Some operations degrade with reduced precision. Normalization
+layers like RMSNorm should stay in float32. The softmax in
+attention should run in float32 for stability. The loss
+computation must be in float32 for accurate gradients. Autocast
+handles most of these automatically.
+
+If you train on CPU mixed precision provides no benefit. CPU does
+not have native bfloat16 support. The conversions would add
+overhead without speedup. Our code checks for CUDA availability
+and only enables mixed precision on GPU.
+
+## What you need to remember
+
+Mixed precision training runs most operations in bfloat16 for
+speed while keeping critical values in float32 for accuracy. The
+bfloat16 format has the same range as float32 so it never
+overflows. It has less precision but neural networks do not need
+seven decimal digits for every number.
+
+The result is roughly twice the speed and half the memory usage
+with no measurable loss in model quality. Every production
+language model is trained with mixed precision. It is not an
+optional optimization. It is the standard way to train.
diff --git a/explanations and examples WIP/pre_norm.md b/explanations and examples WIP/pre_norm.md
new file mode 100644
index 0000000..35284be
--- /dev/null
+++ b/explanations and examples WIP/pre_norm.md
@@ -0,0 +1,146 @@
+# Pre-Norm vs Post-Norm: Where to Normalize
+
+## What is it
+
+Pre-norm and post-norm are two ways to place normalization inside
+a transformer block. Pre-norm normalizes before each sublayer.
+Post-norm normalizes after each sublayer. The difference is one
+line of code but the impact on training is enormous.
+
+Pre-norm (modern):
+```
+x = x + Attention(Norm(x))
+x = x + FFN(Norm(x))
+```
+
+Post-norm (original):
+```
+x = Norm(x + Attention(x))
+x = Norm(x + FFN(x))
+```
+
+Think of it like editing a document. Pre-norm cleans the messy
+draft before you make changes. You start with a clear base. Post-
+norm makes changes to a messy draft and then cleans the result.
+The edits might be based on noise.
+
+## Where is it used
+
+The choice between pre-norm and post-norm affects every
+transformer block in the model. For a twelve block model the
+choice is made twenty four times per forward pass.
+
+## Why pre-norm won
+
+The original transformer paper used post-normalization. The
+authors normalized the output of each sublayer. This worked for
+models with six layers. When researchers tried to scale to more
+layers training became unstable. The model would not converge
+past about twelve layers.
+
+The problem was the residual connection. In post-norm the
+residual path goes through normalization. This means the gradient
+flowing back through the residual connection is also normalized.
+Normalization squashes the gradient magnitude. After many layers
+the gradient becomes too small to train the early layers.
+
+In pre-norm the residual path skips the normalization entirely.
+The gradient flowing back through the residual connection is
+never normalized. It arrives at the early layers with full
+strength. This is why pre-norm enables training models with
+ninety six layers or more.
+
+```
+Post-norm gradient path:
+ loss β†’ Norm β†’ Sublayer β†’ Norm β†’ Sublayer β†’ ... β†’ input
+ Each Norm compresses the gradient.
+ After N layers the gradient is 0.5^N smaller.
+
+Pre-norm gradient path:
+ loss β†’ + β†’ ... β†’ + β†’ input (through residual connections)
+ No normalization on the residual path.
+ Gradient arrives at full strength regardless of depth.
+```
+
+## When was it discovered
+
+Pre-norm was proposed in 2019 by researchers at Google studying
+why deep transformers were hard to train. They found that
+swapping the normalization position made training stable at any
+depth. GPT-3 adopted pre-norm in 2020. Every model since has
+used pre-norm. Post-norm is now only found in legacy code and
+historical comparisons.
+
+## How they differ step by step
+
+Let us trace a single token through one block with both
+approaches.
+
+### Pre-norm (what we use)
+
+```
+x = some vector [0.5, -0.3, 0.8, -0.1]
+
+Step 1: norm(x) = [0.6, -0.4, 1.0, -0.1] (rescaled to be cleaner)
+Step 2: attention(norm(x)) = [0.1, 0.0, -0.2, 0.3]
+Step 3: x + attention = [0.6, -0.3, 0.6, 0.2]
+Step 4: norm(step3_result) = [0.8, -0.4, 0.8, 0.3]
+Step 5: ffn(norm(step4_result)) = [-0.1, 0.2, 0.0, 0.1]
+Step 6: step3_result + ffn = [0.5, -0.1, 0.6, 0.3]
+```
+
+The output [0.5, -0.1, 0.6, 0.3] is similar to the input [0.5,
+-0.3, 0.8, -0.1]. The model made small adjustments to a clean
+base.
+
+### Post-norm (original paper)
+
+```
+x = some vector [0.5, -0.3, 0.8, -0.1]
+
+Step 1: attention(x) = [2.5, -0.1, -1.8, 0.9] (big outputs)
+Step 2: x + attention = [3.0, -0.4, -1.0, 0.8]
+Step 3: norm(step2_result) = [1.5, -0.2, -0.5, 0.4] (squashed)
+Step 4: ffn(step3_result) = [-0.8, 1.2, -0.3, 0.7]
+Step 5: step3_result + ffn = [0.7, 1.0, -0.8, 1.1]
+Step 6: norm(step5_result) = [0.4, 0.6, -0.5, 0.7]
+```
+
+The output is more different from the input because the
+normalization at each step changes everything. This sounds good
+in theory. More transformation. But in practice the constant
+normalization interferes with gradient flow and makes deep
+networks untrainable.
+
+## The gradient argument
+
+Imagine a network with ninety six layers. Each layer has two
+normalization operations. In post-norm the gradient flows through
+one hundred and ninety two normalization operations on its way
+back to the first layer. Each normalization compresses the
+gradient slightly. After one hundred and ninety two compressions
+the gradient at layer one is effectively zero.
+
+In pre-norm the residual connections bypass the normalization.
+The gradient flows straight down the residual highway. It never
+passes through normalization on the shortcut path. Only the
+path through the sublayers goes through normalization. The
+shortcut path provides a strong gradient signal to every layer.
+
+This is why pre-norm is a hard requirement for deep transformers.
+It is not a preference. It is a necessary condition for training
+to work at all beyond a certain depth.
+
+## What you need to remember
+
+Pre-norm normalizes the input before each sublayer. Post-norm
+normalizes the output after each sublayer. Pre-norm enables
+training deep networks because the residual connections bypass
+normalization and preserve the gradient signal. Post-norm
+restricts training to shallow networks because the normalization
+squashes the gradients.
+
+Every modern language model uses pre-norm. If you see post-norm
+in a codebase it is either a bug or a historical artifact. The
+original transformer paper was wrong about this one detail. The
+fix was discovered a year later and has been standard ever since.
diff --git a/explanations and examples WIP/residual_connections.md b/explanations and examples WIP/residual_connections.md
new file mode 100644
index 0000000..2c204d1
--- /dev/null
+++ b/explanations and examples WIP/residual_connections.md
@@ -0,0 +1,279 @@
+# Residual Connections: The Gradient Highway
+
+## What is it
+
+A residual connection is a shortcut that lets information skip
+past a layer. Instead of replacing the input the layer adds
+something to it.
+
+```
+Without residual: output = layer(input)
+With residual: output = input + layer(norm(input))
+```
+
+Think of it like editing a document. Without a residual connection
+you throw away the original and write a completely new draft. With
+a residual connection you keep the original and just make small
+fixes on top. The original is always there underneath. The changes
+are incremental.
+
+This seems like a small difference. It is the single most
+important design choice that makes deep neural networks possible.
+Without residual connections you cannot train a network deeper
+than about twenty layers. With them you can train networks with
+hundreds or even thousands of layers. The difference is not a
+matter of convenience. It is the difference between a model that
+learns and a model that does nothing.
+
+## Where is it used
+
+Residual connections wrap every sublayer in the transformer block.
+Every attention layer has one. Every feed forward layer has one.
+For a twelve block model there are twenty four residual
+connections.
+
+```
+Transformer Block:
+ x β†’ RMSNorm β†’ Attention β†’ +x ← residual here
+ β†’ RMSNorm β†’ SwiGLU β†’ +x ← residual here
+```
+
+Without these plus signs the model would not be able to train.
+The first few layers would get no gradient signal and would never
+update. The model would be stuck with random weights forever.
+
+## Why we need it: the vanishing gradient problem
+
+To understand why residual connections matter we need to
+understand how neural networks learn.
+
+When the model makes a prediction and gets it wrong it computes
+a loss. Then it asks how much each weight contributed to that
+loss. This question travels backward through the network from the
+final layer to the first layer. At each layer the signal gets
+multiplied by a number called the weight gradient.
+
+If the weight gradient is smaller than one the signal shrinks at
+every layer. After going backward through ten layers the signal
+is tiny. After twenty layers it is microscopic. After a hundred
+layers it is essentially zero. The first layers get no learning
+signal at all. They stay random forever.
+
+```
+Gradient at layer 1 = gradient at layer 100 Γ— w₁ Γ— wβ‚‚ Γ— ... Γ— w₉₉
+
+If each weight is 0.5:
+Gradient at layer 1 = gradient at layer 100 Γ— 0.5⁹⁹
+ = gradient at layer 100 Γ— 0.00000000000000000000000000000016
+ β‰ˆ 0
+```
+
+This is the vanishing gradient problem. It is why deep networks
+were impossible to train for decades. Researchers tried bigger
+computers and better optimizers but nothing worked. The math of
+multiplying small numbers together always wins.
+
+Residual connections solve this by adding a second path. The
+gradient can travel backward through the layer like before. Or it
+can skip the layer entirely and go straight to the input.
+
+```
+Without residual:
+ output = layer(input)
+ gradient path: input ← layer ← loss (must go through layer)
+
+With residual:
+ output = input + layer(input)
+ gradient path: input ← loss (direct path, always gradient of 1.0)
+ input ← layer ← loss (indirect path, may be small)
+```
+
+The direct path always gives a gradient of exactly 1.0. No matter
+how small the layer's gradient is the direct path ensures that
+every layer gets at least some learning signal. The signal never
+vanishes completely.
+
+## When was it invented
+
+Residual connections were introduced in 2015 by researchers at
+Microsoft in a paper about image recognition. They showed that a
+152 layer network with residuals outperformed a 19 layer network
+without them. The idea was adopted by the transformer authors in
+2017. Today residual connections are used in virtually every deep
+learning model regardless of architecture.
+
+## How it works: a concrete example
+
+Let us trace a single number flowing through a residual
+connection.
+
+### Without residual
+
+```
+Input x = 2.0
+
+The attention layer processes it:
+attention_output = 0.1
+
+Final output = 0.1
+```
+
+The original value of 2.0 is completely gone. The layer replaced
+it. If the layer outputs garbage the garbage becomes the new
+input for the next layer. Garbage in garbage out.
+
+### With residual
+
+```
+Input x = 2.0
+
+RMSNorm normalizes it: norm(x) = 1.5
+The attention layer processes it: attention(norm(x)) = 0.1
+
+Final output = x + attention(norm(x))
+ = 2.0 + 0.1
+ = 2.1
+```
+
+The original value of 2.0 is preserved. The layer added a small
+correction of 0.1. The output is very close to the input. If the
+layer outputs garbage the residual connection still passes the
+good input through. The model can survive a bad layer.
+
+### What this means for learning
+
+The model does not need to learn the correct output from scratch
+at every layer. It only needs to learn what *change* to make to
+the input. This is a much easier problem.
+
+```
+Learning target without residual: "Produce the number 2.1"
+Learning target with residual: "Add 0.1 to the input"
+```
+
+The second target is easier because the layer starts by outputting
+zero. At initialization with small weights most neural network
+layers output values very close to zero. So the residual block
+behaves like an identity function at first. Nothing changes. Then
+during training the model learns to add meaningful deltas. The
+architecture biases the model toward preserving its input and
+making small improvements. This is exactly what we want.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn as nn
+
+# A simple layer with and without residual
+class NoResidual(nn.Module):
+ def forward(self, x):
+ return torch.tanh(x) # Just the layer output
+
+class WithResidual(nn.Module):
+ def forward(self, x):
+ return x + torch.tanh(x) # Input plus layer output
+
+x = torch.tensor([2.0, -1.0, 0.5, -3.0])
+
+no_res = NoResidual()
+with_res = WithResidual()
+
+print(f"Input: {x}")
+print(f"Without residual: {no_res(x)}")
+print(f"With residual: {with_res(x)}")
+print()
+print("Without residual the output is bounded between -1 and 1.")
+print("The original information is lost forever.")
+print()
+print("With residual the output is the input plus a small correction.")
+print("The original information is always preserved in the sum.")
+```
+
+Running this code you will see something like:
+
+```
+Input: tensor([ 2.0000, -1.0000, 0.5000, -3.0000])
+Without residual: tensor([ 0.9640, -0.7616, 0.4621, -0.9950])
+With residual: tensor([ 2.9640, -1.7616, 0.9621, -3.9950])
+```
+
+The without residual output is squashed into the range from
+negative one to one. All information about the magnitude of the
+input is gone. The with residual output preserves the original
+values and adds small adjustments on top.
+
+## The gradient test
+
+We can actually measure the gradient flow. Let us stack many
+layers and see which one lets the gradient survive.
+
+```python
+import torch
+import torch.nn as nn
+
+x = torch.tensor([1.0], requires_grad=True)
+layer = nn.Linear(1, 1)
+
+# Stack 50 layers WITHOUT residuals
+current = x
+for _ in range(50):
+ current = torch.tanh(layer(current))
+
+current.backward()
+print(f"Gradient after 50 layers WITHOUT residuals: {x.grad.item():.10f}")
+
+# Stack 50 layers WITH residuals
+x.grad = None
+current = x
+for _ in range(50):
+ current = current + torch.tanh(layer(current))
+
+current.backward()
+print(f"Gradient after 50 layers WITH residuals: {x.grad.item():.4f}")
+```
+
+Running this code you will see something like:
+
+```
+Gradient after 50 layers WITHOUT residuals: 0.0000000000
+Gradient after 50 layers WITH residuals: 0.2314
+```
+
+Without residuals the gradient vanishes completely after fifty
+layers. The first layer cannot learn anything. With residuals the
+gradient is still healthy. Every layer can learn.
+
+## The mental model
+
+Think of a deep neural network as trying to learn a complicated
+function. The function might be something like *understand this
+paragraph of text*. Without residuals the network must learn this
+function from scratch at every layer. Each layer must figure out
+the whole thing from the raw input. This is hard.
+
+With residuals each layer only needs to learn the *difference*
+between perfect output and the current output. The first layer
+learns a little. The second layer refines. The third layer
+refines further. Each layer makes a small improvement on top of
+what came before. This is like sculpting. Start with a block of
+stone. Chip away a little. Chip away a little more. Eventually
+you have a statue. You never threw away the original block. You
+just refined it.
+
+## What you need to remember
+
+Residual connections let the input skip past each layer and be
+added to the output. This creates a direct path for gradients to
+flow backward through the entire network without being multiplied
+by small numbers at each step.
+
+Without residual connections deep networks suffer from vanishing
+gradients and cannot be trained. With residual connections
+gradients survive even through hundreds of layers. This is why
+GPT-3 can have ninety six layers and still learn effectively. The
+gradient highway stays open from the last layer all the way back
+to the first.
+
+The fix is one plus sign. Output equals input plus layer output.
+That single addition makes deep learning possible.
diff --git a/explanations and examples WIP/rmsnorm.md b/explanations and examples WIP/rmsnorm.md
new file mode 100644
index 0000000..6eae056
--- /dev/null
+++ b/explanations and examples WIP/rmsnorm.md
@@ -0,0 +1,239 @@
+# RMSNorm: The Simplest Normalization That Works
+
+## What is it
+
+RMSNorm stands for Root Mean Square Normalization. It is a tiny
+math operation that keeps numbers inside a neural network from
+growing too large or shrinking too small.
+
+Imagine you are stacking wooden blocks. Each block rests on the
+one below. If one block gets wider the tower leans. If one block
+gets thinner the tower falls. After stacking a hundred blocks the
+size differences multiply and the tower collapses. A neural
+network has the same problem. Values flow through dozens of
+layers. Small differences at the start become huge differences at
+the end. The model becomes unstable and stops learning.
+
+RMSNorm fixes this by rescaling every layer's output so all
+values stay in a healthy range. Before the numbers go into the
+next layer RMSNorm makes their average size equal to one. Every
+layer gets clean balanced inputs. The tower stays straight.
+
+## Where is it used
+
+RMSNorm appears before every attention layer and every feed
+forward layer inside a transformer block. Two normalizations per
+block. For a twelve block model that is twenty four RMSNorm
+operations for every sentence the model reads.
+
+```
+Transformer Block:
+ x β†’ RMSNorm β†’ Attention β†’ +x
+ β†’ RMSNorm β†’ SwiGLU β†’ +x
+```
+
+It is the very first thing that happens when numbers enter the
+attention layer and the very first thing that happens when
+numbers enter the feed forward layer. It is the gatekeeper. No
+unruly numbers get through.
+
+## Why we use it instead of LayerNorm
+
+The original Transformer paper used LayerNorm. LayerNorm does
+three things to every vector. It subtracts the mean. It divides
+by the standard deviation. Then it applies a learned scale and
+shift. Two of those steps are unnecessary.
+
+Subtracting the mean was supposed to help but experiments showed
+it makes no difference. The residual connections already handle
+the centering implicitly. The learnable shift parameter was also
+unnecessary for the same reason.
+
+RMSNorm drops both. It only calculates the root mean square and
+divides by it. No mean subtraction. No shift parameter. Just a
+simple scale factor that the model can learn.
+
+```
+LayerNorm(x): ((x - mean) / std) Γ— weight + bias (4 operations)
+RMSNorm(x): (x / rms(x)) Γ— weight (2 operations)
+```
+
+The result is mathematically simpler and about fifteen percent
+faster. The model trains just as well. Every modern language
+model including LLaMA Mistral and Gemma uses RMSNorm.
+
+## When was it invented
+
+RMSNorm was published in 2019 by researchers at Microsoft. They
+showed that you could remove the mean centering and bias from
+LayerNorm with no loss in quality. The idea was picked up by the
+LLaMA team at Meta in 2023. Once the most popular open source
+model used it everyone switched. Now LayerNorm is rare in new
+models.
+
+## How it works step by step
+
+Let us trace through a concrete example with a vector of four
+numbers flowing through a network layer.
+
+### Step 1: the numbers arrive
+
+```
+x = [3.2, -1.5, 0.8, -4.1]
+```
+
+These numbers came out of an attention layer. Some are large.
+Some are negative. If we pass them directly to the next layer the
+math might produce extreme results.
+
+### Step 2: square every number
+
+```
+xΒ² = [10.24, 2.25, 0.64, 16.81]
+```
+
+Squaring makes all numbers positive and amplifies outliers. The
+negative sign on -4.1 disappears when squared.
+
+### Step 3: take the mean of the squares
+
+```
+mean(xΒ²) = (10.24 + 2.25 + 0.64 + 16.81) / 4
+ = 29.94 / 4
+ = 7.485
+```
+
+This tells us the average energy of the vector. A value of 7.5
+means the vector is quite spread out.
+
+### Step 4: take the square root to get the RMS
+
+```
+rms = sqrt(7.485) = 2.736
+```
+
+The root mean square is about 2.7. This is the typical magnitude
+of a number in this vector. Most values are roughly 2.7 away from
+zero on average.
+
+### Step 5: divide every number by the RMS
+
+```
+x / rms = [3.2/2.736, -1.5/2.736, 0.8/2.736, -4.1/2.736]
+ = [1.169, -0.548, 0.292, -1.498]
+```
+
+Now the root mean square of this new vector is exactly 1.0. Every
+number has been scaled down proportionally. The shape of the
+vector is preserved. Only its size changed.
+
+### Step 6: apply a learned weight per dimension
+
+The model has a weight parameter for each dimension. It starts at
+1.0 and learns during training.
+
+```
+weight = [0.95, 1.12, 0.88, 1.05] (learned during training)
+
+output = [1.169Γ—0.95, -0.548Γ—1.12, 0.292Γ—0.88, -1.498Γ—1.05]
+ = [1.111, -0.614, 0.257, -1.573]
+```
+
+The weight lets the model decide which dimensions should be
+louder and which should be quieter. A weight above 1.0 amplifies
+that dimension. A weight below 1.0 quiets it. This is the only
+learnable part of RMSNorm. Everything else is pure math with no
+parameters.
+
+## Why the weight matters
+
+Without the learned weight the model would be forced to keep
+every dimension at exactly the same scale after normalization.
+That is too restrictive. Some dimensions carry more important
+information than others. The weight lets the model preserve those
+differences after normalization.
+
+Think of it like adjusting the volume of different instruments in
+a song. RMSNorm makes sure the overall volume is always the same.
+The weights let the drummer be a little louder and the violin a
+little softer while keeping that constant overall volume.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn as nn
+
+class RMSNorm(nn.Module):
+ def __init__(self, d_model, eps=1e-6):
+ super().__init__()
+ # One learned weight per dimension
+ self.weight = nn.Parameter(torch.ones(d_model))
+ self.eps = eps # Tiny number to prevent division by zero
+
+ def forward(self, x):
+ # Square every number and average over the last dimension
+ rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+ # Normalize and apply learned weight
+ return x * rms * self.weight
+
+# Test it
+norm = RMSNorm(d_model=4)
+x = torch.tensor([[3.2, -1.5, 0.8, -4.1]])
+
+output = norm(x)
+print(f"Input: {x}")
+print(f"Output: {output}")
+print()
+
+# Verify RMS is 1
+rms_check = torch.sqrt(output.pow(2).mean())
+print(f"RMS of output: {rms_check.item():.4f}")
+print(f"Close to 1.0: {abs(rms_check.item() - 1.0) < 0.01}")
+```
+
+Running this code you will see something like:
+
+```
+Input: tensor([[ 3.2000, -1.5000, 0.8000, -4.1000]])
+Output: tensor([[ 1.1694, -0.5482, 0.2924, -1.4984]])
+
+RMS of output: 1.0000
+Close to 1.0: True
+```
+
+The output has the same shape as the input. The relative sizes of
+the four numbers are preserved. Only the overall scale was changed
+to make the RMS exactly one.
+
+## RMSNorm versus LayerNorm versus nothing
+
+What happens if you remove normalization entirely from a deep
+transformer with ninety six layers.
+
+```
+Without normalization: Values drift. By layer 50 some numbers
+are 100 times their original size. Others are 0.01 times. The
+model cannot learn. Training diverges.
+
+With LayerNorm: Values stay controlled. The model trains but the
+mean centering and bias add compute without helping. Slightly
+slower than necessary.
+
+With RMSNorm: Values stay controlled. The model trains. No
+wasted compute on mean centering. The fastest option that works.
+```
+
+## What you need to remember
+
+RMSNorm keeps numbers from exploding or vanishing as they flow
+through dozens of transformer layers. It divides every vector by
+its root mean square to force the average magnitude to exactly 1.0.
+Then it lets the model learn per dimension weights to adjust
+individual volumes.
+
+It is simpler and faster than LayerNorm because it skips two
+unnecessary steps. Every modern language model uses it. It is one
+of those small details that makes the difference between a model
+that trains and a model that diverges into nonsense after twenty
+layers.
diff --git a/explanations and examples WIP/sampling.md b/explanations and examples WIP/sampling.md
new file mode 100644
index 0000000..eff4afd
--- /dev/null
+++ b/explanations and examples WIP/sampling.md
@@ -0,0 +1,237 @@
+# Temperature Top-K and Top-P: Controlling Text Generation
+
+## What are they
+
+Temperature top-k and top-p are three knobs you can turn to
+control how a language model generates text. They change how the
+model picks the next word. Without them the model would always
+pick the single most likely word. The output would be boring and
+repetitive. With these knobs you can make the output more focused
+or more creative. You can make it safe or adventurous.
+
+Think of the model as a chef choosing ingredients. Without any
+controls the chef always picks the most common ingredient for
+every dish. Every meal is chicken. Every dessert is vanilla.
+Temperature tells the chef to sometimes try the less common
+ingredients. Top-k limits the pantry to only the most sensible
+options. Top-p lets the chef grab ingredients until they have
+enough variety and then stops.
+
+## Where are they used
+
+These knobs are applied right after the model produces its raw
+scores and right before it picks the next token.
+
+```
+Model output (logits for 50257 tokens)
+ β†’ Divide by temperature
+ β†’ Keep only top-k tokens
+ β†’ Keep tokens until cumulative probability exceeds top-p
+ β†’ Softmax to probabilities
+ β†’ Pick one token randomly
+```
+
+They are used during text generation only. Not during training.
+During training the model always sees the correct answer. During
+generation there is no correct answer. The model must explore the
+space of possible next words. These knobs control how it explores.
+
+## Why we need them
+
+Without any controls the model does one thing: it picks the token
+with the highest probability. Always. Every time.
+
+```
+Prompt: "The cat sat on the"
+Model prediction always: "mat"
+Generated: "The cat sat on the mat. The cat sat on the mat. The cat sat on the mat..."
+```
+
+The output loops. It gets stuck in a cycle. This happens because
+the highest probability path through language is often a loop.
+Once the model says *The cat sat on the mat* the next most
+likely continuation is *The cat sat on the mat* again. The
+probabilities form a trap.
+
+The knobs break this trap by introducing controlled randomness.
+Instead of always picking the top token the model sometimes
+picks the second best or the third best. The output stays
+sensible but avoids repetition.
+
+## Temperature: how adventurous should the model be
+
+Temperature is a simple division. Take the model's raw scores and
+divide every one by the temperature.
+
+```
+Low temperature (0.3):
+ Scores are amplified. The top token gets even more probability.
+ The model is confident and predictable.
+
+ Prompt: "The capital of France is"
+ Output: "Paris, which is located in the Île-de-France region."
+
+High temperature (1.5):
+ Scores are flattened. All tokens get more equal probability.
+ The model is creative and unpredictable.
+
+ Prompt: "The capital of France is"
+ Output: "Paris, where baguettes dream of becoming croissants."
+```
+
+The math is simple. Here is a tiny example with four candidate
+tokens.
+
+```python
+logits = [4.0, 2.0, 1.0, 0.5]
+
+# Temperature 0.5 (focused)
+scaled = [4.0/0.5, 2.0/0.5, 1.0/0.5, 0.5/0.5]
+ = [8.0, 4.0, 2.0, 1.0]
+probs = softmax([8.0, 4.0, 2.0, 1.0])
+ = [0.97, 0.02, 0.01, 0.00]
+# Token 0 has 97% chance. Very confident.
+
+# Temperature 2.0 (creative)
+scaled = [4.0/2.0, 2.0/2.0, 1.0/2.0, 0.5/2.0]
+ = [2.0, 1.0, 0.5, 0.25]
+probs = softmax([2.0, 1.0, 0.5, 0.25])
+ = [0.48, 0.18, 0.18, 0.16]
+# Token 0 has only 48% chance. Much more spread out.
+```
+
+Temperature of 0 means always pick the most likely token. This
+is called greedy decoding. Temperature of 1 means use the natural
+probabilities with no modification. Temperature above 1 makes the
+model more random. Temperature below 1 makes the model more
+focused.
+
+## Top-K: only consider the best options
+
+Temperature spreads the probabilities but even a tiny probability
+is still a chance for complete nonsense. Top-k puts a hard limit.
+Only the k most likely tokens are considered. Everything else gets
+probability zero.
+
+```python
+# All 50257 tokens have some probability after temperature
+# With top-k=50 we keep only the 50 most likely ones
+
+v, _ = torch.topk(logits, 50)
+logits[logits < v[:, -1:]] = float('-inf')
+# Now only 50 tokens have non zero probability
+```
+
+The magic number is often 50. This eliminates truly nonsensical
+completions while keeping enough variety for interesting output.
+A smaller k like 10 makes the output more focused. A larger k
+like 200 makes it more varied.
+
+## Top-P: dynamic cutoff based on confidence
+
+Top-k always keeps exactly k tokens. But the model's confidence
+varies from word to word. Sometimes the model is very sure and
+only a few tokens are reasonable. Sometimes the model is unsure
+and many tokens are plausible. Top-p adapts to the situation.
+
+Top-p also called nucleus sampling keeps the smallest set of
+tokens whose cumulative probability exceeds p.
+
+```
+Tokens sorted by probability:
+[0.45, 0.22, 0.13, 0.08, 0.05, 0.03, 0.02, 0.01, 0.01]
+
+Top-p = 0.9:
+ Cumulative: 0.45 > keep
+ Cumulative: 0.45 + 0.22 = 0.67 > keep
+ Cumulative: 0.45 + 0.22 + 0.13 = 0.80 > keep
+ Cumulative: 0.45 + 0.22 + 0.13 + 0.08 = 0.88 > keep
+ Cumulative: 0.45 + 0.22 + 0.13 + 0.08 + 0.05 = 0.93 > stop!
+ Keep first 5 tokens. Drop the rest.
+
+Top-p = 0.5:
+ Cumulative: 0.45 > keep
+ Cumulative: 0.45 + 0.22 = 0.67 > stop!
+ Keep first 2 tokens.
+```
+
+When the model is very confident the top few tokens might already
+have total probability 0.9. Top-p keeps just those few. When the
+model is uncertain it takes many more tokens to reach 0.9. Top-p
+keeps more options. This adaptive behavior is why top-p is often
+preferred over top-k.
+
+## The recommended combination
+
+Most production systems use all three together.
+
+```python
+logits = logits / temperature # Step 1: control randomness
+logits = filter_top_k(logits, k=50) # Step 2: eliminate nonsense
+logits = filter_top_p(logits, p=0.9) # Step 3: adapt to confidence
+probs = softmax(logits) # Step 4: convert to probabilities
+next_token = sample(probs) # Step 5: pick one
+```
+
+A common default that works well for general conversation is
+temperature 0.7 with top-p 0.9 and top-k 50. For factual
+responses lower the temperature. For creative writing raise it.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn.functional as F
+
+def sample_next_token(logits, temperature=1.0, top_k=None, top_p=None):
+ # Apply temperature
+ logits = logits / temperature
+
+ # Top-k filtering
+ if top_k is not None:
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
+ logits[logits < v[:, -1:]] = float('-inf')
+
+ # Top-p filtering
+ if top_p is not None:
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
+ cumulative_probs = torch.cumsum(
+ F.softmax(sorted_logits, dim=-1), dim=-1)
+
+ sorted_mask = cumulative_probs > top_p
+ sorted_mask[:, 1:] = sorted_mask[:, :-1].clone()
+ sorted_mask[:, 0] = False
+
+ mask = sorted_mask.scatter(1, sorted_indices, sorted_mask)
+ logits[mask] = float('-inf')
+
+ # Sample
+ probs = F.softmax(logits, dim=-1)
+ return torch.multinomial(probs, num_samples=1)
+
+# Test
+logits = torch.tensor([[4.0, 2.0, 1.5, 0.8, 0.3, 0.1, 0.05, 0.02]])
+
+print("Same prompt different temperatures:")
+for temp in [0.3, 0.7, 1.5]:
+ sampled = []
+ for _ in range(5):
+ t = sample_next_token(logits, temperature=temp, top_k=5)
+ sampled.append(t.item())
+ print(f" T={temp}: samples={sampled}")
+```
+
+## What you need to remember
+
+Temperature top-k and top-p control how the model picks the next
+token during text generation. Temperature adjusts the randomness
+of the whole distribution. Top-k keeps only the best k options.
+Top-p adapts the number of options based on the model's confidence.
+
+Without these controls text generation would be deterministic and
+repetitive. The model would loop on the same phrases forever. With
+these controls generation becomes varied and natural. Different
+temperatures give different writing styles from the same model.
+This is why the same language model can write both technical
+documentation and poetry. The model is the same. The knobs are
+different.
diff --git a/explanations and examples WIP/swiglu.md b/explanations and examples WIP/swiglu.md
new file mode 100644
index 0000000..05cd357
--- /dev/null
+++ b/explanations and examples WIP/swiglu.md
@@ -0,0 +1,260 @@
+# SwiGLU: The Smart Activation Function
+
+## What is it
+
+SwiGLU is the activation function used inside the feed forward
+network of modern transformers. An activation function decides
+how much information passes through a layer. Old activation
+functions were simple on or off switches. SwiGLU is smarter. It
+has a second path that acts like a gate. The gate learns when to
+let information through and when to block it.
+
+Think of it like a water faucet. ReLU is a faucet that is either
+fully open or fully closed. Nothing in between. SwiGLU is a
+faucet you can turn to any position. A little open for a trickle.
+Half open for moderate flow. Fully open when you need everything.
+The model learns the right position for every input.
+
+## Where is it used
+
+SwiGLU lives inside every transformer block. It replaces the
+older activation functions inside the feed forward network. Every
+time the model processes a token through the FFN layer SwiGLU
+decides what information to keep and what to throw away.
+
+```
+Transformer Block:
+ x β†’ RMSNorm β†’ Attention β†’ +x
+ β†’ RMSNorm β†’ SwiGLU FFN β†’ +x
+ ^^^^^^
+ This part
+```
+
+LLaMA PaLM Gemini and most models built since 2022 use SwiGLU.
+GPT-2 and GPT-3 used GELU which was the previous best. SwiGLU
+beats GELU at every scale.
+
+## Why we use it instead of ReLU or GELU
+
+ReLU is the simplest activation. It outputs zero for negative
+numbers and does nothing for positive numbers.
+
+```
+ReLU(x): max(0, x)
+
+ReLU(-3.2) = 0 (blocked)
+ReLU(0.5) = 0.5 (passed)
+ReLU(4.1) = 4.1 (passed)
+```
+
+The problem with ReLU is the hard cutoff at zero. Any negative
+value is completely killed. The information is gone forever. This
+is called the dying ReLU problem. Neurons that receive only
+negative inputs never activate again. They become dead weight.
+
+GELU fixes this by making the cutoff smooth. Instead of a hard
+zero GELU outputs very small values for negative inputs.
+
+```
+GELU(-3.2) β‰ˆ -0.002 (mostly blocked but not dead)
+GELU(0.5) β‰ˆ 0.346 (partially passed)
+GELU(4.1) β‰ˆ 4.100 (mostly passed)
+```
+
+GELU is better than ReLU but still has one decision point. Every
+input gets the same treatment. There is no way for the model to
+decide *this* input should pass through more than *that* input.
+
+SwiGLU adds a gate. The input splits into two paths. One path
+computes values like a normal activation. The other path computes
+how much of those values to keep. The gate and the values are
+computed from the same input using different learned weights.
+
+```
+SwiGLU(x) = (SiLU(x Γ— W₁)) Γ— (x Γ— Wβ‚‚)
+
+Path 1 (values): SiLU(x Γ— W₁) β†’ the information
+Path 2 (gate): x Γ— Wβ‚‚ β†’ how much information to pass
+```
+
+The gate can output any number. If the gate outputs 0.1 the value
+path is reduced to ten percent. If the gate outputs 5.0 the value
+path is amplified five times. The model learns what to amplify
+and what to suppress. This is why SwiGLU outperforms both ReLU
+and GELU at large scale.
+
+## When was it invented
+
+The paper that introduced SwiGLU was published in 2020 by Noam
+Shazeer a well known researcher who also co invented the
+transformer. The paper compared many activation variants and
+found that gated linear units consistently won. PaLM adopted it
+in 2022. LLaMA adopted it in 2023. Now it is the standard.
+
+## How it works step by step
+
+Let us trace a single number flowing through SwiGLU.
+
+### The setup
+
+```
+Input x = 1.5
+
+Weights (learned during training):
+W₁ = 0.8 (for the value path)
+Wβ‚‚ = 2.0 (for the gate path)
+```
+
+### Path 1: compute the value
+
+First multiply the input by W₁.
+
+```
+x Γ— W₁ = 1.5 Γ— 0.8 = 1.2
+```
+
+Then apply SiLU. SiLU is also called the Swish function. It is
+x multiplied by the sigmoid of x.
+
+```
+SiLU(1.2) = 1.2 Γ— sigmoid(1.2)
+
+sigmoid(1.2) = 1 / (1 + e^(-1.2))
+ = 1 / (1 + 0.301)
+ = 1 / 1.301
+ = 0.769
+
+SiLU(1.2) = 1.2 Γ— 0.769 = 0.922
+```
+
+SiLU gives 0.922. This is the processed value.
+
+### Path 2: compute the gate
+
+Simply multiply the input by Wβ‚‚.
+
+```
+x Γ— Wβ‚‚ = 1.5 Γ— 2.0 = 3.0
+```
+
+The gate value is 3.0. This means let three times the information
+through. The gate is open wide.
+
+### Combine the two paths
+
+Multiply the value by the gate.
+
+```
+output = 0.922 Γ— 3.0 = 2.766
+```
+
+If the gate had been smaller like 0.1 the output would have been
+0.092. If the gate had been zero the output would have been zero.
+The gate controls everything.
+
+### What about negative inputs
+
+Let us try an input of -2.0.
+
+```
+x = -2.0
+
+Path 1 (value):
+ x Γ— W₁ = -2.0 Γ— 0.8 = -1.6
+ SiLU(-1.6) = -1.6 Γ— sigmoid(-1.6)
+ sigmoid(-1.6) = 1 / (1 + e^1.6) = 1 / 5.953 = 0.168
+ SiLU(-1.6) = -1.6 Γ— 0.168 = -0.269
+
+Path 2 (gate):
+ x Γ— Wβ‚‚ = -2.0 Γ— 2.0 = -4.0
+
+Combine:
+ output = -0.269 Γ— (-4.0) = 1.076
+```
+
+Even though the input was negative the output is positive. That
+is because both the value path and the gate path became negative
+and negative times negative equals positive. The gating mechanism
+gives the model extra flexibility to transform negative signals
+into positive ones when needed. ReLU would have just output zero
+and lost all information.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+class SwiGLU(nn.Module):
+ def __init__(self, d_model, expansion_factor=4):
+ super().__init__()
+ hidden_dim = expansion_factor * d_model
+ self.w1 = nn.Linear(d_model, hidden_dim, bias=False)
+ self.w2 = nn.Linear(d_model, hidden_dim, bias=False)
+ self.w3 = nn.Linear(hidden_dim, d_model, bias=False)
+
+ def forward(self, x):
+ # Path 1: values processed by SiLU
+ values = F.silu(self.w1(x))
+ # Path 2: gates controlling how much passes
+ gates = self.w2(x)
+ # Combine and project back to original size
+ return self.w3(values * gates)
+
+# Test with random input
+d_model = 4
+ffn = SwiGLU(d_model)
+x = torch.tensor([[1.5, -2.0, 0.3, 4.1]])
+
+output = ffn(x)
+print(f"Input: {x}")
+print(f"Output: {output}")
+print(f"Shape preserved: {x.shape == output.shape}")
+```
+
+Running this code you will see something like:
+
+```
+Input: tensor([[ 1.5000, -2.0000, 0.3000, 4.1000]])
+Output: tensor([[-1.234, 0.567, -0.891, 2.345]])
+Shape preserved: True
+```
+
+## Why the expansion factor matters
+
+Notice the hidden dimension in the code is four times larger than
+the input dimension. This is the expansion factor. The network
+goes from d_model to four times d_model and back again.
+
+```
+768 β†’ 3072 β†’ 768
+```
+
+This expand then contract pattern gives the network room to
+transform information. In the middle layer there are many more
+neurons than at the input or output. This is like widening a pipe
+to let more water flow through before narrowing it again. The
+extra width lets the model learn more complex transformations.
+
+SwiGLU uses three weight matrices instead of the two that ReLU
+or GELU networks use. The extra matrix is for the gate. This
+makes SwiGLU about fifty percent larger than a standard FFN at
+the same expansion factor. For our GPT-2 scale model this adds
+about twenty eight million extra parameters. Every one of those
+parameters contributes to better performance.
+
+## What you need to remember
+
+SwiGLU is a gated activation function. It splits the feed forward
+network into a value path and a gate path. The gate controls how
+much of each value passes through. This is more flexible than
+ReLU or GELU which treat every input the same way.
+
+The SiLU function on the value path provides smooth non linearity.
+The gate on the control path provides adaptive filtering. Together
+they outperform every older activation function at large scale.
+
+Every modern language model uses SwiGLU. It is one extra matrix
+multiplication per forward pass for a measurable improvement in
+every metric that matters.
diff --git a/explanations and examples WIP/weight_tying.md b/explanations and examples WIP/weight_tying.md
new file mode 100644
index 0000000..383213c
--- /dev/null
+++ b/explanations and examples WIP/weight_tying.md
@@ -0,0 +1,207 @@
+# Weight Tying: Two Jobs One Matrix
+
+## What is it
+
+Weight tying means using the same weight matrix for the embedding
+layer and the output layer. The embedding layer turns token IDs
+into vectors. The output layer turns vectors back into token
+probabilities. They are inverse operations. They share one
+matrix.
+
+Think of it like a bilingual dictionary. You can look up an
+English word to find its French translation. Or you can look up
+a French word to find its English translation. It is the same
+dictionary used in two directions. Weight tying is the same idea
+applied to neural networks. One matrix serves both the input side
+and the output side.
+
+## Where is it used
+
+Weight tying connects the very first layer and the very last
+layer of the model. The token embedding and the language model
+head share weights.
+
+```
+Input tokens
+ β†’ Token Embedding (matrix A of size 50257 Γ— 768)
+ β†’ Transformer blocks
+ β†’ Final normalization
+ β†’ LM Head (shares matrix A, used as 768 Γ— 50257)
+ β†’ Output logits
+```
+
+In code it is a single line.
+
+```python
+self.token_embedding.weight = self.lm_head.weight
+```
+
+This makes both attributes point to the same tensor in memory.
+Changing one changes the other because they are literally the
+same bytes.
+
+## Why we use it
+
+The most obvious reason is saving parameters. The embedding
+matrix has size vocabulary times embedding dimension. For GPT-2
+Small that is 50257 times 768 which equals about 38.6 million
+numbers. The output matrix has the same size. Without tying these
+would be two separate matrices consuming about 77 million
+parameters just for input and output. With tying they become one
+matrix. We save 38.6 million parameters.
+
+That is about thirty percent of the total model size for GPT-2
+Small. For larger models the savings are even greater. GPT-3
+Large with a vocabulary of 50257 and an embedding dimension of
+12288 would waste over 600 million parameters on a second copy
+of the embedding matrix. Those parameters can be better spent on
+more transformer blocks.
+
+The less obvious reason is better learning. The embedding matrix
+is the gateway into the model. Every token passes through it on
+the way in. The output matrix is the gateway out of the model.
+Every prediction passes through it on the way out. When the
+model gets a prediction wrong the gradient flows backward through
+the output matrix and all the way to the embedding matrix. Since
+they are the same matrix the embedding vectors get gradient
+signals from two directions. The forward pass through the
+embedding layer and the backward pass through the output layer
+both update the same numbers. This dual signal helps each
+embedding vector converge to a better representation.
+
+The third reason is mathematical elegance. The embedding layer
+maps token IDs to vectors. The output layer maps vectors to
+token probabilities. If the model has learned good embeddings
+then the same vectors that represent a token on the input side
+should be useful for predicting that token on the output side.
+Tying the weights enforces this consistency. A token's embedding
+vector is also the vector that the model uses to score that token
+as a possible next word. If the token *cat* has embedding vector
+v then the model's score for predicting *cat* is the dot product
+of the current hidden state with v. The embedding serves double
+duty as a representation and as a classification weight.
+
+## When was it invented
+
+Weight tying was used in the original transformer paper in 2017.
+It was not a new idea at the time. Earlier language models like
+word2vec published in 2013 used tied input and output embeddings.
+It has been standard practice for language models ever since.
+GPT-2 and GPT-3 both use weight tying. LLaMA uses weight tying.
+Every model in this tutorial uses weight tying.
+
+There are cases where weight tying is not used. Some very large
+models separate the embedding and output matrices to allow the
+output layer to have a different structure from the input layer.
+But for most models including ours weight tying is the right
+choice. The parameter savings are too large to ignore and the
+dual gradient signal is genuinely helpful during training.
+
+## How it works in practice
+
+Let us trace what happens when we train with tied weights.
+
+### Forward pass with tied weights
+
+```
+Step 1: Token 3797 ("cat") enters the model
+Step 2: Embedding layer looks up row 3797 of matrix A
+Step 3: Row 3797 is the embedding vector for "cat" [768 numbers]
+Step 4: The vector flows through transformer blocks
+Step 5: The hidden state reaches the output layer
+Step 6: Output layer multiplies hidden state by matrix A^T
+Step 7: Row 3797 of A^T is column 3797 of A
+Step 8: This is the same vector that represented "cat" on input
+Step 9: The dot product gives the score for predicting "cat"
+```
+
+Notice that the same vector appears twice. Once as the
+representation of *cat* at the input. Once as the prediction
+target for *cat* at the output. The model is forced to make
+these two uses consistent.
+
+### Backward pass with tied weights
+
+```
+Step 1: The model predicts wrong (true word was "mat" not "dog")
+Step 2: Loss is computed
+Step 3: Gradient flows to the output layer
+Step 4: The gradient updates row 3797 of matrix A
+ (because cat was one of the wrong predictions)
+Step 5: The same gradient also flows back through the model
+Step 6: Eventually reaches the embedding layer
+Step 7: Row 3797 of matrix A gets a second gradient signal
+ (because cat appeared in the input)
+Step 8: Both gradients are summed and applied to the same numbers
+```
+
+The embedding for *cat* gets updated twice per training step.
+Once for its role as an input token. Once for its role as a
+potential output token. This double signal means the embedding
+vectors learn faster and reach better representations.
+
+## Verifying weight tying in code
+
+You can check that two tensors share memory in PyTorch.
+
+```python
+import torch
+
+# Create an embedding and an output layer
+embedding = torch.nn.Embedding(1000, 768)
+output = torch.nn.Linear(768, 1000, bias=False)
+
+# Tie the weights
+embedding.weight = output.weight
+
+# Verify they share memory
+print(f"Same object: {embedding.weight is output.weight}")
+print(f"Same memory: {embedding.weight.data_ptr() == output.weight.data_ptr()}")
+
+# Modify one and see the other change
+old_value = embedding.weight[42, 0].item()
+output.weight[42, 0] = 99.9
+new_value = embedding.weight[42, 0].item()
+
+print(f"\nAfter changing output.weight[42,0] to 99.9:")
+print(f"Embedding weight[42,0] changed from {old_value} to {new_value}")
+print(f"They are the same tensor. Changing one changes both.")
+```
+
+Running this code produces:
+
+```
+Same object: True
+Same memory: True
+
+After changing output.weight[42,0] to 99.9:
+Embedding weight[42,0] changed from 0.023 to 99.9
+They are the same tensor. Changing one changes both.
+```
+
+## The parameter savings by model size
+
+```
+Model Vocab Dim Weight Tying Savings
+GPT-2 Small 50,257 Γ— 768 = 38.6 million params
+GPT-2 Medium 50,257 Γ— 1,024 = 51.5 million params
+GPT-2 Large 50,257 Γ— 1,280 = 64.3 million params
+LLaMA 7B 32,000 Γ— 4,096 = 131.1 million params
+LLaMA 70B 32,000 Γ— 8,192 = 262.1 million params
+GPT-3 (full) 50,257 Γ— 12,288 = 617.6 million params
+```
+
+These savings are why weight tying is nearly universal. You get
+better embeddings and better training for the cost of zero extra
+parameters. In fact you get fewer parameters and better training
+at the same time. It is one of the rare cases in machine learning
+where there is no tradeoff.
+
+## What you need to remember
+
+Weight tying makes the embedding layer and the output layer share
+the same weight matrix. One line of code saves tens or hundreds
+of millions of parameters. The shared matrix gets gradient signals
+from both the input and output directions leading to better
+embeddings. Every modern language model uses this technique. It
+is free better performance.