Deep Learning Fundamentals, Efficient Architectures & Learning Paradigms
Primary references:
- Analytics Vidhya - Momentum in Neural Networks
- Paperspace - Popular Deep Learning Architectures: AlexNet, VGG, GoogleNet
- WandB - Implementing Dropout in PyTorch
- Analytics Vidhya - Introduction to Batch Normalization
- Chip Huyen - A Friendly Introduction to Machine Learning Compilers and Optimizers
- NVIDIA Developer - Mixed Precision Training Deep Neural Networks
Overview
Deep learning systems are shaped by four interacting concerns:
- Optimization: How model weights are updated efficiently and stably.
- Regularization and normalization: How overfitting and unstable activations are controlled.
- Architecture: How parameters, compute, memory, and accuracy are balanced.
- Learning paradigm: How models learn from labeled, unlabeled, shifted, or self-generated data.
This document covers stochastic gradient descent with momentum, regularization, normalization, efficient convolutional architectures, mixed-precision training, distributed training, model compression, semi-supervised learning, domain adaptation, and self-supervised learning.
The practical goal is not merely to train a model that performs well offline. It is to train a model that remains accurate, efficient, robust, and deployable on the target hardware.
Module 1: Optimization and Foundations
Stochastic Gradient Descent
Stochastic Gradient Descent, or SGD, updates model weights using gradients estimated from a mini-batch rather than the entire dataset. It converges more quickly than full-batch gradient descent, but its optimization trajectory is noisy and oscillatory. blog.paperspace
Standard SGD updates parameters as:
\[w_{t+1} = w_t - \eta \nabla L(w_t)\]where:
- $w_t$ is the parameter vector at step $t$.
- $\eta$ is the learning rate.
- $\nabla L(w_t)$ is the gradient of the loss with respect to the parameters.
Momentum
Momentum accumulates an exponentially decaying moving average of past gradients. It stabilizes updates and accelerates convergence along directions where gradients consistently point toward the minimum. blog.paperspace
\[v_{t+1} = \gamma v_t + \eta \nabla L(w_t)\] \[w_{t+1} = w_t - v_{t+1}\]where:
- $v_t$ is the velocity term.
- $\gamma$ is the momentum coefficient, commonly around 0.9.
- $\eta$ is the learning rate.
Momentum dampens oscillations across steep, high-curvature dimensions, where gradients alternate signs, while accumulating velocity along gentle, consistent directions.
No momentum:
Gradient zig-zags across steep dimensions.
With momentum:
Past gradients smooth the trajectory.
Movement accelerates along consistent directions.
Regularization
Overfitting occurs when a model has excessive degrees of freedom and memorizes training noise. It often assigns disproportionately large weights to specific input features. blog.paperspace
L1 regularization
L1 regularization, also called LASSO, adds a penalty proportional to the sum of absolute weight values:
\[\mathcal{L}_{total} = \mathcal{L}_{data} + \lambda \sum_{i,j} |w_{ij}|\]where:
- $\mathcal{L}_{data}$ is the task loss.
- $\lambda$ is the regularization strength.
- $w_{ij}$ is a model weight.
L1 regularization encourages sparsity because it can drive weights exactly to zero.
L2 regularization
L2 regularization, also called Ridge regularization or weight decay, adds a penalty proportional to the sum of squared weights:
\[\mathcal{L}_{total} = \mathcal{L}_{data} + \frac{\lambda}{2} \sum_{i,j} w_{ij}^2\]L2 regularization penalizes large weights and keeps the parameter vector smooth. Unlike L1, it usually shrinks weights toward zero without forcing them exactly to zero.
In PyTorch, weight decay can be integrated directly into the optimizer:
optimizer = torch.optim.SGD(
model.parameters(),
lr=1e-3,
weight_decay=1e-4,
)
Dropout
Dropout randomly deactivates neurons with probability $p$ during training using Bernoulli trials. This prevents units from co-adapting and forces the network to learn redundant, robust representations. blog.paperspace
During training:
Neuron active with probability: 1 - p
Neuron dropped with probability: p
During evaluation, inverted dropout scales remaining activations by:
\[\frac{1}{1-p}\]This makes the evaluation forward pass approximately equivalent to an ensemble of trained subnetworks without requiring multiple forward passes.
import torch.nn as nn
dropout = nn.Dropout(p=0.5)
Module 2: Normalization and Training Stability
Internal covariate shift
Deep neural networks can suffer from internal covariate shift: the distribution of each layer’s inputs changes across training iterations as preceding layer weights update. This makes optimization harder because every layer must continually adapt to a moving input distribution. blog.paperspace
Batch Normalization mitigates this by standardizing layer inputs across the current mini-batch.
Batch Normalization
For a mini-batch $B$ of size $m$, Batch Normalization computes:
\[\mu_B = \frac{1}{m} \sum_{i=1}^{m} x_i\] \[\sigma_B^2 = \frac{1}{m} \sum_{i=1}^{m} (x_i - \mu_B)^2\] \[\hat{x}_i = \frac{x_i - \mu_B} {\sqrt{\sigma_B^2 + \epsilon}}\]where:
- $x_i$ is an activation value.
- $\mu_B$ is the batch mean.
- $\sigma_B^2$ is the batch variance.
- $\epsilon$ is a small constant for numerical stability.
To preserve representational capacity, Batch Normalization introduces learnable scale and shift parameters:
\[y_i = \gamma \hat{x}_i + \beta\]where:
- $\gamma$ is a learnable scale parameter.
- $\beta$ is a learnable shift parameter.
During inference, Batch Normalization replaces mini-batch statistics with running exponential moving averages collected during training. blog.paperspace
import torch.nn as nn
batch_norm = nn.BatchNorm2d(num_features=64)
Alternative normalization strategies
| Method | Normalizes over | Batch-size independent? | Common use |
|---|---|---|---|
| Batch Normalization | Batch and spatial dimensions | No | CNNs |
| Layer Normalization | Features within each sample | Yes | Transformers, RNNs |
| Instance Normalization | Spatial dimensions per channel | Yes | Style transfer |
| Group Normalization | Channel groups and spatial dimensions | Yes | Small-batch CNNs |
Layer Normalization
Layer Normalization normalizes activations across features for each individual sample, independently of batch size. This makes it suitable for recurrent neural networks and transformers. blog.paperspace
Instance Normalization
Instance Normalization normalizes across spatial dimensions for each channel independently, effectively treating each sample as a batch of size one. It is widely used in style transfer. blog.paperspace
Group Normalization
Group Normalization divides channels into groups and normalizes features within each group. It bridges Layer Normalization and Instance Normalization while remaining independent of batch size. blog.paperspace
Module 3: Efficient Deep Learning Architectures
Convolutional building blocks for edge devices
Deploying vision models to resource-constrained edge hardware requires minimizing parameters, memory footprint, and Memory Access Cost, or MAC. blog.paperspace
Depthwise separable convolution
Depthwise separable convolution factorizes a standard convolution into two operations:
- Depthwise convolution: applies one spatial filter per input channel.
- Pointwise convolution: applies a $1 \times 1$ convolution to mix channels across depth.
Standard convolution:
Input channels -> spatial filtering + channel mixing in one step
Depthwise separable convolution:
Input channels -> depthwise spatial filtering
-> pointwise 1 x 1 channel mixing
This factorization substantially reduces parameters and computation, especially for mobile and embedded vision models.
Inverted residual block
Inverted residual blocks, also called MBConv blocks, are used in MobileNetV2 and EfficientNet. They:
- Expand channel dimensions using a $1 \times 1$ convolution.
- Apply depthwise spatial filtering.
- Project back to a narrow representation using a linear bottleneck. blog.paperspace
Narrow input
|
v
1 x 1 expansion convolution
|
v
Depthwise convolution
|
v
Linear bottleneck projection
|
v
Narrow output
The inverted residual design preserves information in a compact bottleneck while allowing a high-dimensional intermediate space for nonlinear transformation.
Squeeze-and-Excitation block
Squeeze-and-Excitation, or SE, blocks explicitly model channel interdependencies. They apply Global Average Pooling followed by two fully connected gating layers to dynamically re-weight channel feature maps. blog.paperspace
Feature map
|
v
Global Average Pooling
|
v
Fully connected layer
|
v
ReLU
|
v
Fully connected layer
|
v
Sigmoid channel weights
|
v
Channel-wise feature rescaling
SE blocks answer the question: “Which feature channels are most important for this input?”
Architectural evolution
| Architecture | Key innovation | Primary advantage |
|---|---|---|
| AlexNet | Deep stacked convolutions, ReLU, dropout | Established feasibility of deep CNNs |
| VGG | Uniform stack of small $3 \times 3$ convolutions | Simple, deep, transferable architecture |
| GoogLeNet / Inception v1 | Multi-scale parallel filters and $1 \times 1$ reductions | Compute-efficient width scaling |
| ResNet | Identity shortcut skip connections | Mitigated vanishing gradients in very deep networks |
| MobileNetV1 / V2 | Depthwise separable convolutions and inverted residual bottlenecks | Low latency on mobile hardware |
| EfficientNet | Compound scaling of depth, width, and resolution | Strong accuracy-to-FLOPs trade-off |
AlexNet
AlexNet was proposed for the ImageNet Large Scale Visual Recognition Challenge and helped establish deep convolutional networks as the dominant approach for image classification. It achieved a top-5 error rate of 15.3% on ILSVRC-2010, compared with 26.2% for the next-best result. blog.paperspace
The architecture has eight learned layers: five convolutional layers and three fully connected layers. It uses ReLU activations, overlapping max pooling, dropout, data augmentation, and softmax classification over 1,000 ImageNet classes. blog.paperspace
Reported training details include: blog.paperspace
| Setting | Value |
|---|---|
| Optimizer | SGD |
| Batch size | 128 |
| Momentum | 0.9 |
| Weight decay | 0.0005 |
| Learning rate | 0.001 |
| Training duration | About six days |
| Hardware | Two GTX 580 3GB GPUs |
| Epochs | 90 |
VGG16
VGG16 demonstrated the value of architectural simplicity and depth by using stacks of small $3 \times 3$ convolutions. It achieved 92.7% top-5 test accuracy on ImageNet. blog.paperspace
VGG16 uses:
- $3 \times 3$ convolution filters.
- $1 \times 1$ convolutions in some configurations.
- Five max-pooling layers.
- Two fully connected layers with 4,096 channels.
- A final 1,000-way classification layer.
- Dropout with ratio 0.5 in the first two fully connected layers. blog.paperspace
Its main drawback is model size: the trained VGG16 model is reported to exceed 500 MB, making it less attractive for mobile or edge deployment. blog.paperspace
GoogLeNet
GoogLeNet, also known as Inception v1, introduced the Inception module. Instead of choosing one filter size, it processes the input through parallel $1 \times 1$, $3 \times 3$, and $5 \times 5$ convolutions plus pooling, then concatenates the outputs. blog.paperspace
Input feature map
|
+--> 1 x 1 convolution
|
+--> 1 x 1 -> 3 x 3 convolution
|
+--> 1 x 1 -> 5 x 5 convolution
|
+--> Pooling -> 1 x 1 convolution
|
v
Concatenate outputs
The $1 \times 1$ convolutions reduce channel dimensionality before expensive $3 \times 3$ and $5 \times 5$ convolutions, improving computational efficiency. blog.paperspace
GoogLeNet is 22 layers deep, contains 27 pooling layers, and stacks nine Inception modules. It achieved a 6.67% error rate in ILSVRC 2014. blog.paperspace
Module 4: Training and Inference Optimization
Mixed-precision training
Training models in standard FP32 precision consumes substantial memory and bandwidth. Automatic Mixed Precision, or AMP, executes selected operations using half-precision FP16 or BF16 formats while retaining FP32 master weights for gradient updates. blog.paperspace
Forward pass:
Some operations in FP16 or BF16
Some operations in FP32
Backward pass:
Gradients computed with mixed precision
Optimizer step:
FP32 master weights updated
Loss scaling
FP16 has a narrow dynamic range. Small gradients can underflow to zero. Loss scaling multiplies the loss by a large scaling factor before backpropagation, scaling gradients up safely before dividing them back out at the optimizer step. blog.paperspace
scaler = torch.cuda.amp.GradScaler()
for data, label in data_loader:
optimizer.zero_grad()
with torch.amp.autocast(
device_type="cuda",
dtype=torch.float16,
):
loss = model(data)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
| Precision | Typical use | Benefit | Risk |
|---|---|---|---|
| FP32 | Reference precision | Maximum stability | High memory and bandwidth |
| FP16 | Mixed-precision training | Faster compute, lower memory | Gradient underflow |
| BF16 | Modern accelerator training | Wider dynamic range than FP16 | Hardware-dependent |
| INT8 | Inference quantization | Large memory and speed gain | Accuracy degradation if poorly calibrated |
Distributed Data Parallel
Distributed Data Parallel, or DDP, replicates the full model across multiple worker processes to overcome single-GPU memory and throughput limits. blog.paperspace
Rather than routing updates through a central parameter server, DDP synchronizes gradients locally across workers using an efficient all-reduce communication algorithm. This avoids a central network bottleneck. blog.paperspace
Worker 1: model replica + data shard 1
Worker 2: model replica + data shard 2
Worker 3: model replica + data shard 3
Worker 4: model replica + data shard 4
|
+--> Compute local gradients
|
+--> All-reduce gradient synchronization
|
+--> Identical optimizer update on every worker
Model compression
Quantization
Quantization maps high-precision FP32 parameters and activations to lower-bit formats such as INT8. blog.paperspace
| Method | Description | When to use |
|---|---|---|
| Post-Training Quantization | Calibrates scaling factors on a small dataset after training | Fast deployment with limited retraining |
| Quantization-Aware Training | Injects fake quantization nodes during training | Higher accuracy under aggressive quantization |
Quantization reduces memory footprint, improves cache efficiency, and can enable faster inference on supported hardware.
Knowledge distillation
Knowledge distillation transfers representation capacity from a large teacher model to a compact student model. It minimizes the Kullback-Leibler divergence between softened output distributions using a temperature scaling factor $T > 1$. blog.paperspace
Teacher logits / T
|
v
Soft teacher probabilities
Student logits / T
|
v
Soft student probabilities
Loss:
KL divergence between soft distributions
+ optional supervised cross-entropy loss
A simplified distillation loss is:
\[\mathcal{L}_{distill} = T^2 \cdot D_{KL} \left( \text{softmax}\left(\frac{z_T}{T}\right) \parallel \text{softmax}\left(\frac{z_S}{T}\right) \right)\]where:
- $z_T$ are teacher logits.
- $z_S$ are student logits.
- $T$ is the distillation temperature.
- $T^2$ preserves gradient magnitude as temperature changes.
Module 5: Learning Paradigms
Supervised learning
Supervised learning trains a model on input-label pairs:
\[\mathcal{D} = \{(x_i, y_i)\}_{i=1}^{N}\]where:
- $x_i$ is an input.
- $y_i$ is a label.
- $N$ is the dataset size.
It is the most direct paradigm but requires labeled data, which can be expensive or unavailable at scale.
Semi-supervised learning
Semi-supervised learning leverages a small labeled set alongside abundant unlabeled data using consistency regularization. blog.paperspace
Small labeled dataset
|
+--> Supervised loss
Large unlabeled dataset
|
+--> Pseudo-labels
|
+--> Consistency loss
FixMatch
FixMatch evaluates an unlabeled image under weak augmentation to generate a high-confidence pseudo-label. It then enforces consistency by penalizing cross-entropy loss against a strongly augmented version of the same image. blog.paperspace
Unlabeled image
|
+--> Weak augmentation --> model --> confident pseudo-label
|
+--> Strong augmentation --> model --> prediction
|
v
Cross-entropy between prediction and pseudo-label
The model learns only from unlabeled samples whose weakly augmented prediction exceeds a confidence threshold.
Mean Teacher
Mean Teacher maintains a student network alongside a teacher network whose weights are updated as an Exponential Moving Average, or EMA, of the student parameters: blog.paperspace
\[\theta'_t = \alpha \theta'_{t-1} + (1 - \alpha)\theta_t\]where:
- $\theta_t$ are student weights.
- $\theta’_t$ are teacher weights.
- $\alpha$ is the EMA decay coefficient.
The teacher provides smoother targets than the rapidly changing student, reducing prediction noise.
Domain adaptation
When the test distribution shifts from the training distribution, domain adaptation aligns feature spaces across source and target domains. blog.paperspace
Source domain
|
+--> Source features --> Task classifier
Target domain
|
+--> Target features --> Domain classifier
|
+--> Gradient reversal layer
Domain-Adversarial Neural Networks, or DANN, append a domain classifier connected to a shared feature extractor through a Gradient Reversal Layer, or GRL. During backpropagation, the GRL multiplies gradients by $-1$, forcing the feature extractor to learn domain-invariant representations that confuse the domain classifier. blog.paperspace
The objective combines:
\[\mathcal{L} = \mathcal{L}_{task} - \lambda \mathcal{L}_{domain}\]where:
- $\mathcal{L}_{task}$ is the source-domain task loss.
- $\mathcal{L}_{domain}$ is the domain-classification loss.
- $\lambda$ controls the strength of adversarial adaptation.
Self-supervised learning
Self-supervised learning, or SSL, creates supervisory signals from the data itself. It enables representation learning without manual labels.
Unlabeled data
|
v
Create augmented views or pretext tasks
|
v
Learn invariant or predictive representations
|
v
Transfer to downstream tasks
Contrastive SSL
Contrastive methods such as SimCLR and MoCo learn by pulling augmented views of the same image together and pushing different images apart. They require negative pairs. blog.paperspace
SimCLR / MoCo
|
v
Contrastive learning
|
v
Requires negative samples
Non-contrastive SSL
Non-contrastive methods such as BYOL and SimSiam avoid negative samples. They prevent collapse through architectural asymmetry, predictors, and stop-gradient operations. blog.paperspace
BYOL / SimSiam
|
v
Non-contrastive learning
|
v
Asymmetry / predictor + stop-gradient
SimSiam uses a twin Siamese network structure but prevents collapse by applying a stop-gradient operation on one branch and processing the other through a prediction MLP head. blog.paperspace
Self-distillation SSL
DINO employs Vision Transformer backbones within a student-teacher self-distillation framework. It uses centering and sharpening on output distributions to prevent collapse without negative samples or momentum queues. blog.paperspace
DINO
|
v
Student-teacher self-distillation
|
v
Momentum teacher
|
v
Centering and sharpening
|
v
No negative samples required
Module 6: Compilers and Hardware Optimization
Why compilers matter
A trained model is not automatically fast on every device. Different hardware backends have different memory layouts, cache hierarchies, and compute primitives. CPUs, GPUs, TPUs, mobile accelerators, FPGAs, and ASICs may require different execution strategies. huyenchip
Machine learning compilers bridge the gap between framework-level models and hardware-native execution.
Framework model
|
v
High-level intermediate representation
|
v
Optimization passes
|
v
Low-level intermediate representation
|
v
Hardware-native code
Lowering and optimization
Chip Huyen describes ML compilation as two related activities: huyenchip
- Lowering: generating hardware-native code so a model can run on a target device.
- Optimizing: improving how that model runs on that device.
Optimization can occur at every stage, from high-level computation graphs to low-level hardware instructions. huyenchip
Local optimization techniques
| Technique | Purpose |
|---|---|
| Vectorization | Use hardware primitives to process multiple contiguous elements at once |
| Parallelization | Divide work into independent chunks across cores or threads |
| Loop tiling | Reorder memory access to improve cache locality |
| Operator fusion | Combine operators to avoid redundant memory access |
These standard local optimizations can provide an estimated speedup of around 3 times, though the actual gain is highly context-dependent. huyenchip
Global graph optimization
Higher-level optimization exploits the structure of the full computation graph. For example, a CNN graph can be fused vertically or horizontally to reduce memory access and improve speed. huyenchip
Before fusion:
Convolution -> Bias -> Activation -> Pooling
Each stage reads and writes intermediate tensors.
After fusion:
Fused kernel computes multiple stages together.
Fewer intermediate memory accesses.
Hand-designed versus ML-based compilers
| Approach | Strength | Limitation |
|---|---|---|
| Hand-designed rules | Highly tuned for known models and hardware | Non-optimal and non-adaptive |
| ML-based compilers | Search and adapt across operators and hardware | Tuning can be slow |
Hand-designed optimization depends on expert heuristics and may not generalize to new model architectures or hardware. ML-based compilers narrow the search space, predict execution time, and learn from measured runtime behavior. huyenchip
For example, cuDNN autotuning searches over predefined convolution configurations and caches the fastest result. AutoTVM works at the subgraph level, allocates search time across subgraphs, and trains a cost model from measured execution times. huyenchip
Compiler choices
| Compiler | Scope | Notes |
|---|---|---|
| NVCC | NVIDIA CUDA | Closed-source NVIDIA compiler |
| XLA | TensorFlow and JAX | Accelerated Linear Algebra compiler |
| PyTorch Glow | PyTorch hardware backends | Open-source compiler project |
| Apache TVM | Broad framework and hardware support | Supports autotuning and multiple hardware targets |
| MLIR | Compiler infrastructure | Meta-compiler for building compiler stacks |
Chip Huyen notes that TVM supports a wide range of frameworks and hardware backends, including CPUs, server GPUs, ARM devices, mobile GPUs, and FPGA accelerators. huyenchip
Module 7: Practical Training Checklist
- Use mini-batch SGD or an adaptive optimizer appropriate to the task.
- Add momentum when gradients oscillate or convergence is slow.
- Use weight decay, dropout, and data augmentation to control overfitting.
- Use Batch Normalization for CNNs; use Layer Normalization for transformers.
- Use mixed precision when hardware supports it.
- Use loss scaling with FP16 training.
- Use DDP for multi-GPU data-parallel training.
- Quantize or distill models before edge deployment.
- Validate quantized and distilled models on task-specific metrics.
- Profile memory access, kernel execution, and data movement before optimizing blindly.
- Evaluate robustness under domain shift, not only in-distribution accuracy.
Resources
- Momentum in Neural Networks — background on optimization smoothing and momentum convergence.
- Popular Deep Learning Architectures — reference on AlexNet, VGG16, and GoogLeNet.
- Implementing Dropout in PyTorch — practical dropout implementation guidance.
- Introduction to Batch Normalization — normalization mechanics and training stability.
- Machine Learning Compilers and Optimizers — detailed overview of graph compilation, lowering, optimization, and hardware acceleration.
- Mixed Precision Training — NVIDIA guidance for FP16 and BF16 training pipelines.
Limitations and Open Questions
Optimization limitations
- Momentum can overshoot minima if the learning rate is too high.
- Batch Normalization can perform poorly with very small batches.
- Dropout can slow convergence and is less useful in some transformer architectures.
- Weight decay interacts with optimizer choice and learning-rate schedules.
Architecture limitations
- VGG-style architectures are parameter-heavy and inefficient for edge deployment.
- Depthwise separable convolutions reduce compute but may reduce representational capacity.
- Efficient architectures require careful tuning of width, depth, resolution, and activation design.
- Accuracy-to-latency trade-offs are hardware-specific.
Learning-paradigm limitations
- Semi-supervised methods can amplify incorrect pseudo-labels.
- Domain adaptation may discard useful source-domain information.
- Self-supervised models can learn spurious invariances.
- Contrastive methods require large batch sizes or memory banks.
- Non-contrastive methods can collapse without careful architectural safeguards.
Compiler limitations
- Compilation is hardware- and workload-specific.
- Autotuning can take hours or days for complex models.
- Optimizations that help one architecture may hurt another.
- Model performance on a benchmark does not guarantee similar performance for an arbitrary model on the same hardware. huyenchip
Final Technical Takeaways
- Central mechanism: Deep learning performance depends on the interaction between optimization dynamics, normalization, architecture, data paradigm, and hardware execution.
- Main optimization insight: Momentum smooths noisy gradients and accelerates convergence along consistent directions, while regularization and dropout control overfitting.
- Main stability insight: Batch Normalization stabilizes CNN training; Layer Normalization is generally preferred for transformers because it does not depend on batch statistics.
- Main efficiency insight: Depthwise separable convolutions, inverted residuals, SE blocks, quantization, distillation, and mixed precision reduce the cost of deploying accurate models.
- Important learning insight: Semi-supervised, domain-adaptive, and self-supervised methods extend learning beyond fully labeled stationary datasets.
- Main limitation: No single architecture or training method is universally best; the right choice depends on data, task, latency target, memory budget, and deployment hardware.
- Broader engineering implication: Treat model training and deployment as one system. Optimization, architecture, compression, compilation, and evaluation must be designed together. blog.paperspace