---
title: Deep learning fundamentals
url: https://gurkanozkan.ai/learn/topics/deep-learning/
markdown: https://gurkanozkan.ai/learn/topics/deep-learning.md
kind: topic
tracks:
  - Research
  - ML engineering
json: https://gurkanozkan.ai/api/learn/topics/deep-learning.json
---

# Deep learning fundamentals

Deep-learning fundamentals come up in research-scientist screens and ML-engineer technical rounds as derivations and "explain why" questions: backpropagation and automatic differentiation, softmax and cross-entropy gradients and their numerics, initialisation and vanishing or exploding gradients, normalisation, regularisation (dropout, weight decay), optimisers (momentum, Adam, AdamW, schedules), generalisation (bias–variance, double descent) and the inductive biases of architectures such as CNNs and vision transformers. Interviewers want crisp mechanisms, correct numbers and the practical consequences for training real models.

## Key concepts

### Automatic differentiation

Reverse mode propagates vector–Jacobian products from a scalar loss back to all parameters in one backward pass costing a small multiple (about 2×) of the forward pass, which is why it suits n inputs ≫ m outputs. Forward mode propagates Jacobian–vector products, one pass per input direction, and suits few inputs. Reverse mode must store intermediate activations, so memory is its cost; activation checkpointing recomputes them to save memory.

### Softmax and cross-entropy

For logits z and true class y, loss = logsumexp(z) − z_y and the gradient is softmax(z) − onehot(y). Implement it stably: subtract max(z) before exponentiating and fuse softmax with the negative log-likelihood (PyTorch's CrossEntropyLoss expects raw logits). At initialisation a C-class model should score about ln C. Label smoothing replaces the one-hot target with (1 − ε) on the true class and ε/C spread across all classes.

### Initialisation and gradient flow

Backpropagation multiplies Jacobians layer by layer, so their scale compounds: below 1 gradients vanish, above 1 they explode, and saturating activations make it worse. Xavier initialisation (variance 2 / (fan_in + fan_out)) suits tanh; He initialisation (variance 2 / fan_in) suits ReLU. Residual connections add an identity path for gradients, normalisation keeps activations in range, gradient clipping caps rare explosions, and LSTM or GRU gates address the recurrent case.

### Normalisation layers

Batch normalisation normalises each feature over the batch, keeps running statistics for inference and therefore behaves differently in train and eval mode; it struggles with small or non-independent batches. Layer normalisation normalises each example over its features, so training and inference match and variable-length sequences are fine; RMSNorm drops the mean-centring and is cheaper. Pre-norm transformers (normalising before each sub-layer) train more stably than the original post-norm design.

### Regularisation

Weight decay, dropout, data augmentation, early stopping and label smoothing all reduce effective capacity or inject noise. Inverted dropout zeroes units with probability p and scales the survivors by 1/(1 − p) during training so inference needs no change; it can be read as training an implicit ensemble. Dropout before batch normalisation shifts the variance between training and inference, so it is usually placed after normalisation or used sparingly.

### Optimisers and schedules

Momentum keeps an exponential moving average of gradients to damp oscillation. Adam also tracks the squared gradient, corrects both averages for their zero initialisation and divides per parameter, at the cost of two extra fp32 tensors (8 bytes per parameter). AdamW applies weight decay directly to the weights instead of adding an L2 term that Adam would rescale. Large models use warmup then cosine or linear decay and often β2 ≈ 0.95 for stability; Muon, which orthogonalises the momentum of matrix weights with Newton–Schulz iterations, has reached frontier scale (Kimi K2's 1T-parameter run used MuonClip; DeepSeek-V4 uses Muon), with AdamW kept for embeddings, output heads and norms; AdamW is still the most common default.

### Generalisation and double descent

Classical bias–variance reasoning predicts a U-shaped test error as capacity grows. Deep networks often show double descent: error peaks near the interpolation threshold, where the model can just fit the training set, then falls again as size or training time grows. Diagnose with training and validation curves, and remember that for LLMs memorisation is driven heavily by repeated data.

### Architectural inductive biases

Convolutions build in locality, weight sharing and translation equivariance (invariance only after pooling), which makes them data-efficient. Vision transformers split images into patches and use global attention with weak priors, so they need more data, pretraining or augmentation, but scale well; hybrids mix both. On devices, convolutions and small hybrids often win on latency, memory and quantisation friendliness.

## Worked examples

### Softmax–cross-entropy: gradient, numbers and a stable implementation

For logits z = [2.0, 1.0, 0.1] with true class 0, compute the probabilities, the loss and the gradient with respect to the logits; derive the gradient; and show why the naive formula fails for z = [1000, 999].

**Solution**

**Forward.** exp(z) = [7.389, 2.718, 1.105], sum = 11.213 → p = [0.659, 0.242, 0.099].
Loss = −ln 0.659 = **0.417**.

**Gradient.** ∂L/∂z = p − y = [0.659 − 1, 0.242, 0.099] = **[−0.341, 0.242, 0.099]**. The entries sum to
zero, and the update raises the true logit and lowers the others in proportion to their probability.

**Derivation.** L = −z_y + ln Σₖ exp(zₖ), so ∂L/∂zⱼ = −1[j = y] + exp(zⱼ) / Σₖ exp(zₖ) = pⱼ − yⱼ.

**Stable form.** logsumexp(z) = m + ln Σₖ exp(zₖ − m) with m = max z:
2 + ln(1 + e^(−1) + e^(−1.9)) = 2 + ln(1.5175) = 2.4170, so loss = 2.4170 − 2.0 = 0.4170, the same.

For z = [1000, 999], exp(1000) overflows float64 (the limit is about e^709), giving inf / inf = NaN.
Subtracting the max gives exp([0, −1]) = [1, 0.368] → p = [0.731, 0.269]. In PyTorch, pass raw logits to
`F.cross_entropy`, which fuses log-softmax and the negative log-likelihood.


### Adam's bias correction and why AdamW decouples weight decay

At step 1, a parameter has gradient g = 0.2, with β1 = 0.9 and β2 = 0.999. Compute Adam's update with and without bias correction. Then compare how an L2 penalty and AdamW's decoupled decay (λ = 0.01) act on two weights of value 1.0 whose gradient scales differ: √v̂ = 1.0 for weight A and 0.01 for weight B.

**Solution**

**Moments at t = 1** (starting from zero):
- m₁ = (1 − 0.9) × 0.2 = 0.02
- v₁ = (1 − 0.999) × 0.2² = 0.00004

**With bias correction:** m̂ = 0.02 / (1 − 0.9¹) = 0.2; v̂ = 0.00004 / (1 − 0.999¹) = 0.04; √v̂ = 0.2.
Update = lr × 0.2 / 0.2 = **1.0 × lr** (ε ignored).

**Without correction:** 0.02 / √0.00004 = 0.02 / 0.00632 = **3.16 × lr**: early steps would be
about three times too large because v starts far more biased towards zero than m. Warmup also guards
against noisy early second-moment estimates.

**L2 versus decoupled decay.** With L2, λw is added to the gradient and then divided by √v̂ like any
other gradient (roughly, ignoring its own effect on v̂):
- weight A: 0.01 × 1.0 / 1.0 = 0.01 per unit learning rate
- weight B: 0.01 × 1.0 / 0.01 = 1.0 per unit learning rate, 100 times more

So weights with large gradient history are barely regularised, and the effective decay depends on
gradient statistics rather than on λ. AdamW applies w ← w − lr × λ × w separately, giving 0.01 × lr for
both. This is why "L2 regularisation" and "weight decay" are not the same thing under Adam.

**Memory.** Adam keeps m and v in fp32: 8 bytes per parameter, which dominates the training-memory
budget along with the fp32 master weights.


### Why He initialisation has a 2 in it

A 20-layer ReLU MLP has 1,024 units per layer. Compare how activation variance evolves with weights drawn at standard deviation 0.01, 0.05 and the He value.

**Solution**

For a layer z = Wa with independent zero-mean weights, Var(z) = fan_in × Var(w) × E[a²]. With ReLU,
E[a²] = Var(z_prev) / 2 because half the pre-activations are zeroed. So each layer multiplies variance by

r = fan_in × Var(w) / 2

- **std 0.01**: r = 1,024 × 0.0001 / 2 = 0.0512 → after 20 layers 0.0512²⁰ ≈ **1.5 × 10⁻²⁶**: signals
  and gradients vanish.
- **std 0.05**: r = 1,024 × 0.0025 / 2 = 1.28 → 1.28²⁰ ≈ **139**: they explode.
- **He**: Var(w) = 2 / fan_in = 2 / 1,024, std ≈ 0.0442 → r = **1**: variance is preserved.

The 2 compensates for ReLU discarding half the signal; Xavier's 1 / fan_in-style scaling suits activations
that are roughly linear near zero, such as tanh. The backward pass has the same structure with fan_out,
which is why gradient norms per layer are the first diagnostic for vanishing or exploding gradients.
Residual connections and normalisation make very deep networks far less sensitive to this choice.


## What changed recently

- **Jun 2026: DiffusionGemma: an open diffusion language model.** Google released DiffusionGemma under Apache 2.0, a 26B-total, about 3.8B-active MoE that denoises a 256-token canvas in parallel with bidirectional attention and then commits the block to the KV cache before starting the next, with Google claiming up to 1,000+ tokens/s on one H100. Non-autoregressive decoding is now a practical option, so expect questions on how it differs from next-token prediction and where it struggles (the base model scored near zero on Sudoku before fine-tuning). [Source](https://developers.googleblog.com/diffusiongemma-the-developer-guide/)
- **Feb 2026: Hybrid linear attention becomes the default layout.** Qwen3.5-397B-A17B stacks 15 blocks of three Gated DeltaNet layers and one gated-attention layer (45 linear-attention and 15 full-attention layers), with 512 experts and a native 262k context, following the same 3:1 pattern as Qwen3-Next. Interviewers ask why linear-attention layers help long context, what the remaining full-attention layers are for, and how such models are trained and served. [Source](https://huggingface.co/Qwen/Qwen3.5-397B-A17B)
- **Dec 2025: mHC: redesigning the residual connection.** DeepSeek's manifold-constrained hyper-connections widen the residual stream into several mixed streams but constrain the mixing to a manifold that preserves the identity mapping, fixing the training instability of plain hyper-connections, with infrastructure work to limit memory overhead. The residual connection, long treated as fixed, is now an active design choice in frontier architectures. [Source](https://arxiv.org/abs/2512.24880)
- **Nov 2025: Gated attention wins a NeurIPS 2025 best paper award.** The Qwen team showed that a head-specific sigmoid gate on the attention output adds non-linearity and query-dependent sparsity, mitigates attention sinks, tolerates larger learning rates and improves long-context extrapolation, across 30 variants of 15B MoE and 1.7B dense models trained on 3.5T tokens; the gate ships in Qwen3-Next. It is a compact example for questions on what attention sinks are and how small architectural changes are validated. [Source](https://blog.neurips.cc/2025/11/26/announcing-the-neurips-2025-best-paper-awards/)
- **Jul 2025: Muon trains a trillion-parameter model.** Moonshot's Kimi K2 (1T total, 32B active, 15.5T tokens) was pretrained with MuonClip, Muon plus a QK-clip step that rescales query and key projections when attention logits grow, and reported no loss spikes. Muon, which orthogonalises momentum for matrix weights, has moved from small-scale results to frontier pretraining, so 'AdamW is the only optimiser used at scale' is outdated. [Source](https://arxiv.org/abs/2507.20534)

## Pitfalls

- Treating an L2 penalty and decoupled weight decay as identical under Adam.
- Leaving dropout or batch normalisation in training mode at inference, or applying the dropout scaling twice.
- Passing probabilities to a loss that expects logits, or exponentiating without subtracting the max.
- Describing reverse-mode autodiff as numerical differentiation, or ignoring its activation-memory cost.
- Using gradient clipping instead of fixing initialisation, or confusing vanishing gradients with a learning rate that is too low.
- Calling CNNs translation-invariant without the pooling caveat, or claiming vision transformers always win.

## How interviewers probe it

- Whiteboard derivations: the softmax–cross-entropy gradient, the Adam update, why He initialisation uses 2 / fan_in, batch-norm statistics.
- 'What should the loss be at step 0?' leading into debugging follow-ups.
- 'Why do transformers use LayerNorm or RMSNorm, and why pre-norm?'
- 'Why warmup? Why β2 = 0.95 for large models? What breaks when you scale the batch?'
- Generalisation: bias–variance, double descent, and what changes for heavily over-parameterised models.
- Research labs often ask you to implement backprop for a tiny network, or attention, from scratch.

## Reading

- [Understanding Deep Learning](https://udlbook.github.io/udlbook/) (Book, 600 min, Intro): A modern, free textbook with clear chapters on backpropagation, initialisation, regularisation and transformers.
- [Neural Networks: Zero to Hero](https://karpathy.ai/zero-to-hero.html) (Course, 870 min, Intro): Builds backprop, initialisation and batch-norm intuition, and a GPT, from scratch in code.
- [Adam: A Method for Stochastic Optimization](https://arxiv.org/abs/1412.6980) (Paper, 40 min, Core): The original moment estimates and bias-correction derivation.
- [Decoupled Weight Decay Regularization](https://arxiv.org/abs/1711.05101) (Paper, 40 min, Core): Why L2 regularisation and weight decay differ under adaptive optimisers, and the AdamW fix.
- [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167) (Paper, 40 min, Core): Train versus inference statistics and the original motivation for normalisation layers.
- [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) (Paper, 40 min, Core): Residual connections, the key architectural fix for optimising very deep networks.
- [Deep Double Descent: Where Bigger Models and More Data Hurt](https://arxiv.org/abs/1912.02292) (Paper, 45 min, Deep): Evidence that test error can rise and fall again with model size, data and training time.
- [The Big LLM Architecture Comparison](https://magazine.sebastianraschka.com/p/the-big-llm-architecture-comparison) (Blog, 60 min, Core): Side-by-side tour of how recent open models differ: MoE layouts, latent attention, QK-norm, sliding windows and linear-attention hybrids.

## Practise this topic

- [Explain what dropout does during training and inference, why it regularises, and how it interacts with batch normalisation.](https://gurkanozkan.ai/learn/questions/mle-why-dropout-works-04.md)
- [Explain momentum, Adam's moment estimates and bias correction, and why AdamW decouples weight decay.](https://gurkanozkan.ai/learn/questions/mle-sgd-momentum-adam-and-adamw-10.md)
- [Why do deep or recurrent nets suffer vanishing or exploding gradients, and which architectural and training choices mitigate it?](https://gurkanozkan.ai/learn/questions/mle-vanishing-and-exploding-gradients-12.md)
- [Compare batch and layer normalisation: what they normalise over, train/inference behaviour, and why transformers use LayerNorm (or RMSNorm).](https://gurkanozkan.ai/learn/questions/mle-batchnorm-vs-layernorm-13.md)
- [Contrast forward-mode and reverse-mode automatic differentiation. For a function with n inputs and m outputs, when is each cheaper, and why does deep learning…](https://gurkanozkan.ai/learn/questions/research-forward-vs-reverse-autodiff-004.md)
- [Compare SGD, SGD with momentum and Adam. Why was AdamW introduced, and which settings (schedule, warmup, β values) matter most when training large models?](https://gurkanozkan.ai/learn/questions/research-optimisers-sgd-momentum-adam-020.md)
- [How do you tell whether a model is overfitting or underfitting, and what would you try in each case? How does "double descent" complicate the classic…](https://gurkanozkan.ai/learn/questions/research-over-and-underfitting-021.md)
- [You have just initialised a 1,000-class classifier and run one forward pass. What should the cross-entropy loss be close to, and what would you suspect if it…](https://gurkanozkan.ai/learn/questions/research-expected-loss-at-initialisation-024.md)
- [Derive the gradient of cross-entropy loss with respect to the logits when predictions come from a softmax. How do you implement the loss so it never overflows…](https://gurkanozkan.ai/learn/questions/research-softmax-cross-entropy-gradient-025.md)
- [Which inductive biases does a convolution build in, and what changes with a vision transformer? When would you expect each to win, including on-device?](https://gurkanozkan.ai/learn/questions/research-cnn-vs-vision-transformers-030.md)
- [List the knobs you would use to curb overfitting in XGBoost/LightGBM and in an MLP, and explain why each one works.](https://gurkanozkan.ai/learn/questions/mle-overfitting-controls-in-gradient-boosted-trees-vs-neural-nets-02.md)
- [Explain the Muon optimiser. What does it do to the momentum update, which parameters does it apply to, and what extra changes were needed to use it for…](https://gurkanozkan.ai/learn/questions/recent-a-dl-01.md)
- [The Qwen team's gated-attention paper won a NeurIPS 2025 best paper award. Describe the change, explain why it helps, and say how you would test whether it…](https://gurkanozkan.ai/learn/questions/recent-a-dl-02.md)
- [Several 2025–2026 open models mix linear-attention layers (for example Gated DeltaNet or Kimi Delta Attention) with a minority of full-attention layers…](https://gurkanozkan.ai/learn/questions/recent-a-dl-03.md)
- [Derive GRPO's advantage estimate and explain why it needs no value network. Then explain what DAPO and GSPO each change, and why.](https://gurkanozkan.ai/learn/questions/recent-a-ft-03.md)
- [Explain batch normalisation: what it computes at training versus inference time, and why it helps. Why do transformers use layer norm or RMSNorm instead, and…](https://gurkanozkan.ai/learn/questions/research-batch-norm-vs-layer-norm-023.md)
- [Why can gradients vanish or explode in deep networks, and how do Xavier/He initialisation, residual connections and normalisation address this?](https://gurkanozkan.ai/learn/questions/research-vanishing-exploding-gradients-026.md)
- [Your dataset is dominated by common, easy cases, and the events you care most about are rare (for example, near-misses in driving logs). How do you train and…](https://gurkanozkan.ai/learn/questions/research-long-tailed-data-rare-events-031.md)
- [You're given a training notebook where the code runs without errors but the loss barely moves. Describe, step by step, how you find the problem.](https://gurkanozkan.ai/learn/questions/research-model-that-doesnt-learn-047.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
