Skip to content
MAMasterAI Now
3 / 1115 मिनट पठनस्तर: Intermediate5 कार्ड

बैकप्रोपेगेशन

दोष बाँटने वाला एल्गोरिद्म, जिसने डीप लर्निंग को संभव बनाया।

⚠ यह चरण हिन्दी में 3% अनूदित है; शेष कार्ड अंग्रेज़ी में दिखाए जा रहे हैं। कोई गलती दिखी? अनुवाद सुधार का स्वागत है।

पठन प्रगति0%
Card 1 — the problemकार्ड 1 / 5

Who is to blame for the mistake?

A deep network has millions of knobs. The loss is one number. Assign credit.

After a forward pass you know exactly one thing: how wrong the final answer was. But there are millions of weights, each contributing a little to that error. Backpropagation answers, for every single weight, "if I nudge you slightly, how much worse does the final loss get?"

Analogy
The factory line

A defective car rolls off the assembly line. Every station upstream demands: was it me? The blame travels backwards, station by station, each one multiplying how much it distorted what it received. That is backprop.

The maths is the chain rule from calculus, applied relentlessly. If loss depends on the output, and the output depends on an activation, and the activation depends on a weighted sum, and that depends on a weight — multiply the local sensitivities together to get the weight's share of the blame.

∂L/∂w = ∂L/∂ŷ · ∂ŷ/∂z · ∂z/∂w
Each factor is a local derivative, computed once and reused by every weight upstream of it.
अगले कार्ड से पहले एक छोटी जाँच

What exactly does backpropagation compute?

5 जाँचें

🔒

प्रयोगशाला बंद है

इस सिमुलेशन को खोलने के लिए सभी 5 कार्ड और उनकी जाँचें पूरी करें।

Read the full stage transcript (all 5 cards, no JavaScript required)
Card 1 — the problem

1. Who is to blame for the mistake?

A deep network has millions of knobs. The loss is one number. Assign credit.

After a forward pass you know exactly one thing: how wrong the final answer was. But there are millions of weights, each contributing a little to that error. Backpropagation answers, for every single weight, "if I nudge you slightly, how much worse does the final loss get?"

Analogy
The factory line

A defective car rolls off the assembly line. Every station upstream demands: was it me? The blame travels backwards, station by station, each one multiplying how much it distorted what it received. That is backprop.

The maths is the chain rule from calculus, applied relentlessly. If loss depends on the output, and the output depends on an activation, and the activation depends on a weighted sum, and that depends on a weight — multiply the local sensitivities together to get the weight's share of the blame.

∂L/∂w = ∂L/∂ŷ · ∂ŷ/∂z · ∂z/∂w
Each factor is a local derivative, computed once and reused by every weight upstream of it.

Knowledge check: What exactly does backpropagation compute?

  • a. The gradient of the loss with respect to every weight in the network← correct
  • b. The final prediction accuracy
  • c. The optimal learning rate

It is a bookkeeping algorithm for derivatives. Choosing how far to step along those gradients is a separate decision (the optimiser).

Card 2 — the mechanics

2. Forward pass, then backward pass

Every training step is two sweeps over the same graph.

  1. 1Forward pass: inputs flow through the layers, each node caching its output.
  2. 2Loss: compare the final output with the target and reduce it to one number.
  3. 3Backward pass: walk the graph in reverse, multiplying local gradients as you go.
  4. 4Store: keep ∂L/∂w for every parameter — that is the gradient vector.
  5. 5Update: the optimiser nudges all weights against their gradients.
py
# A 2-layer network: backprop by hand
# forward
h = relu(x @ W1 + b1)      # hidden activations
y_hat = h @ W2 + b2        # predictions
loss = mse(y_hat, y)

# backward (chain rule, applied in reverse)
dL_dyhat = 2 * (y_hat - y) / n
dL_dW2 = h.T @ dL_dyhat
dL_dh  = dL_dyhat @ W2.T
dL_dz1 = dL_dh * (z1 > 0)  # ReLU derivative: 1 if z>0 else 0
dL_dW1 = x.T @ dL_dz1

# update
W1 -= lr * dL_dW1
W2 -= lr * dL_dW2
NoteWhy frameworks exist

Modern libraries record every operation on the forward pass (a "tape" or autograd graph) and replay it backwards. You write only the forward pass; PyTorch and JAX derive the backward pass for you.

Knowledge check: Why must the forward pass usually run before the backward pass?

  • a. Because the backward pass needs the cached activations and the loss value← correct
  • b. Because GPUs only run forward operations
  • c. It does not matter, they are independent

Each local derivative is evaluated at the values the forward pass produced. That is also why training needs far more memory than inference.

Card 3 — the killer

3. Vanishing and exploding gradients

Multiply 0.25 by itself twenty times and you get a number smaller than a grain of sand.

Backprop multiplies a chain of local derivatives. If each is smaller than 1, the product collapses toward zero: vanishing gradients. Early layers then receive almost no learning signal and effectively freeze. If each is larger than 1, the product explodes to infinity: exploding gradients, and your weights become NaN.

∂L/∂w₁ = ∂L/∂ŷ · ∏ₖ (local derivative of layer k)
The product over many layers is why scale — not correctness — is the real enemy of depth.
  • Sigmoid / tanh saturate: derivatives ≤ 0.25. Depth kills them.
  • ReLU has derivative exactly 1 when active — the modern default.
  • Careful initialisation (Xavier, He) keeps the variance of activations ~1 across layers.
  • Normalisation (BatchNorm, LayerNorm) re-centres activations at every layer.
  • Residual connections add a highway: gradients flow through the + unchanged.
  • Gradient clipping caps the update norm to stop explosions.
Analogy
Whispers down a corridor

A person whispers a sentence to the next person, twenty times over. The message arrives as mush. Residual connections are someone shouting the original message over the top: the signal survives no matter how many people stand in between.

Knowledge check: What does a residual (skip) connection do for gradients?

  • a. It adds an identity path so gradients reach early layers without being multiplied down← correct
  • b. It removes the need for a learning rate
  • c. It increases the number of parameters

Because d(a + b)/da = 1, part of the gradient always survives intact. ResNets with 100+ layers exist because of this.

Card 4 — the modern toolchain

4. Autograd: you write forward, the machine writes backward

Nobody derives gradients by hand in production.

py
import torch

x = torch.tensor([[0.5, -1.2, 3.3]])
w = torch.randn(3, 4, requires_grad=True)

# forward: every op is recorded on the autograd tape
z = x @ w
a = torch.relu(z)
loss = a.pow(2).sum()

# backward: chain rule applied over the recorded tape
loss.backward()

print(w.grad)     # dL/dw, computed for free
w.data -= 0.01 * w.grad

Frameworks build a computational graph during the forward pass, then walk it in reverse. This is why a PyTorch model costs more memory while training than while serving: the cached activations must be kept alive until the backward pass consumes them.

NoteLink to the LLM world

Activation memory — not parameter memory — is what forces gradient accumulation and checkpointing when you fine-tune a large model on one GPU. You will meet that trade-off again in Stage 9 (LoRA) and Stage 11 (inference memory).

Knowledge check: Why does training use much more GPU memory than inference?

  • a. Because cached forward activations must be kept for the backward pass← correct
  • b. Because training uses a different device
  • c. Because the model has more parameters during training

Parameters are identical; the extra memory holds activations and optimiser state (e.g. Adam keeps two extra tensors per parameter).

Card 5 — the dials

5. Batch size, learning rate and epochs

Three dials decide whether training converges, crawls or explodes.

HyperparameterWhat it doesFailure if too smallFailure if too large
Learning rateStep size along the gradientTraining crawls, stuck high on the loss curveLoss diverges or oscillates wildly
Batch sizeExamples per gradient estimateNoisy, jittery updatesSmooth but memory-hungry; can overfit verbosely
EpochsPasses over the datasetUnderfitting, model too shallow on dataOverfitting, perfect on train, poor on test
Analogy
A staircase in the dark

The learning rate is your stride. Too short and you take all night; too long and you miss the landing entirely. Batch size is how many friends you ask before deciding the direction — more opinions, steadier but slower decisions.

  • Learning-rate schedules (warmup, cosine decay) are standard: start small, grow, then shrink.
  • Adam / AdamW adapt a per-parameter step size so you worry less about a global value.
  • Early stopping watches validation loss and halts when it stops improving.
  • Weight decay adds a penalty on large weights to discourage memorisation.

Knowledge check: Training loss keeps falling but validation loss starts rising. What is happening?

  • a. Overfitting — the model is memorising the training set← correct
  • b. Underfitting — the model is too simple
  • c. The GPU is throttling

That divergence is the textbook overfitting signature. Stop early, regularise, or get more data.