Graduate Deep Learning¶

Spring 2025¶

Instructor and Copyright: Bruno Ribeiro¶


Feedforward Networks (Multilayer Perceptron) & Backpropagation¶

Course Overview¶

This lecture covers the fundamentals of feedforward neural networks, also known as multilayer perceptrons (MLPs), and the backpropagation algorithm. We'll explore both theoretical foundations and practical implementations.

Historical Context¶

  • 1943: McCulloch & Pitts propose the first mathematical model of a neuron
  • 1957: Rosenblatt introduces the perceptron
  • 1969: Minsky & Papert publish "Perceptrons", highlighting limitations
  • 1986: Rumelhart, Hinton & Williams popularize backpropagation
  • Present: MLPs serve as foundation for modern deep learning

Readings¶

For This Lecture:¶

  1. Deep Learning Book Chapters:
    • Linear Algebra (Chapter 2.1-2.2)
    • Probability and Information Theory (Chapter 3.12-3.13)
    • Numerical Computation (Chapter 4.1-4.3)
    • Deep Feedforward Networks (Chapter 6.1-6.5)

For Next Lecture:¶

  1. Linear Algebra (All sections Chapter 2)
  2. Group Theory Fundamentals (Course in Theory of Groups)
    • Binary Operations, Semigroups, and Groups
    • Examples of Groups
    • Subgroups and Cosets

1. The Artificial Neuron: Biological Inspiration and Mathematical Model¶

1.1 From Biological to Artificial Neurons¶

Biological neurons have several key components:

  • Dendrites: Receive input signals
  • Cell body (soma): Processes signals
  • Axon: Transmits output signal
  • Synapses: Connection points between neurons

The artificial neuron abstracts these components into:

  • Input connections: Analogous to dendrites
  • Weighted sum: Analogous to soma processing
  • Activation function: Analogous to firing threshold
  • Output: Analogous to axon signal

1.2 Mathematical Formulation¶

An artificial neuron is characterized by:

  1. Activation function $\sigma : \mathbb{R} \to \mathbb{R}$
    • Activation function must be a non-polynomial function (e.g., $\sigma(x) = x^2$ is not a good activation function)
  2. Weight vector ${\bf w} = (w_1, \ldots, w_n) \in \mathbb{R}^n$
  3. Bias term $b \in \mathbb{R}$

For input ${\bf x} = (x_1, \ldots, x_n)$, output is: $$h({\bf x}) = \sigma({\bf w}^T {\bf x} + b)$$

In [1]:
import numpy as np
import matplotlib.pyplot as plt

# Common activation functions and their derivatives
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x):
    s = sigmoid(x)
    return s * (1 - s)

def relu(x):
    return np.maximum(0, x)

def relu_derivative(x):
    return np.where(x > 0, 1, 0)

def tanh(x):
    return np.tanh(x)

def tanh_derivative(x):
    return 1 - np.tanh(x)**2

# Visualization
x = np.linspace(-5, 5, 100)
functions = {
    'Sigmoid': (sigmoid, sigmoid_derivative),
    'ReLU': (relu, relu_derivative),
    'Tanh': (tanh, tanh_derivative)
}

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))

for name, (f, f_derivative) in functions.items():
    ax1.plot(x, f(x), label=name)
    ax2.plot(x, f_derivative(x), label=f'{name} derivative')

ax1.grid(True)
ax1.legend()
ax1.set_title('Activation Functions')
ax1.set_xlabel('x')
ax1.set_ylabel('f(x)')

ax2.grid(True)
ax2.legend()
ax2.set_title('Derivatives')
ax2.set_xlabel('x')
ax2.set_ylabel('f\'(x)')

plt.tight_layout()
plt.show()
No description has been provided for this image

1.3 Properties of Activation Functions¶

Key characteristics to consider:

  1. Non-linearity:

    • Must be non-polynomial (as proven in Leshno et al. 1993)
    • Enables learning of complex patterns
  2. Differentiability:

    • Required for gradient-based optimization
    • ReLU is non-differentiable at 0 but still works well
  3. Range:

    • Sigmoid: (0,1)
    • Tanh: (-1,1)
    • ReLU: [0,∞)
  4. Gradient Properties:

    • Sigmoid/Tanh: Vanishing gradient for large inputs
    • ReLU: No vanishing gradient for positive inputs

Modern Variations:

  • Leaky ReLU: $f(x) = \max(\alpha x, x)$ where $\alpha < 1$ is tipically small.
  • ELU: $f(x) = \begin{cases} x & \text{if } x ≥ 0 \\ \alpha(e^x - 1) & \text{if } x < 0 \end{cases}$
  • GELU: $x\Phi(x)$ where $\Phi$ is the CDF of the Gaussian distribution
In [2]:
# Demonstration of vanishing gradients
def compare_gradients():
    x = np.linspace(-10, 10, 1000)
    
    plt.figure(figsize=(12, 6))
    plt.plot(x, sigmoid_derivative(x), label='Sigmoid gradient')
    plt.plot(x, relu_derivative(x), label='ReLU gradient')
    plt.plot(x, tanh_derivative(x), label='Tanh gradient')
    
    plt.title('Gradient Magnitudes')
    plt.xlabel('Input')
    plt.ylabel('Gradient')
    plt.legend()
    plt.grid(True)
    plt.show()

compare_gradients()
No description has been provided for this image

2. Multilayer Perceptron Architecture¶

(Single Layer Perceptron for Classification) Logistic Regression¶

Consider the following task. We want to decide the probability that someone is rich. The input data is $\{(h_{i,1},h_{i,2}),y_i\}_i$ where input $h_{\cdot,1} \in {0,1}$ indicates yatch ownership, $h_{\cdot,2} \in {0,1}$ indicates mansion ownership, and $y_{\cdot} \in \{0,1\}$ indicates whether the person is rich. A logistic regression model can be represented as:

No description has been provided for this image

The s-shappped symbol after $\sum$ represents the sigmoid function.

Functional description:¶

$$p(y_i = 1| {\bf x}_i; {\bf w}^{(3)} ) = \sigma(({\bf w}^{(3)})^T {\bf x}_i),$$ $$y_i \sim \text{Bernoulli}(p(y_i = 1| {\bf x}_i; {\bf w}^{(3)} )),$$

where $\sigma$ is the sigmoid function.

Logistic Regressions (LRs) as Input Data¶

Consider the following task:

We have training data to learn if someone owns and yatch $\{{\bf x}_i,h_{i,1}\}_{i=1}^{n_1}$: $$ {\bf w}^{(1,1)\star} = \arg\!\min_{{\bf w}^{(1,1)}} - \sum_{i=1}^{n_1} \sum_{c=0}^1 {\bf 1}\{h_{i,1} = c\} \log p(h_{i,1} = c | {\bf x}_i; {\bf w}^{(1,1)}). $$ We also have training data $\{{\bf x}_j,h_{j,2}\}_{j=1}^{n_2}$ to learn if someone owns a mansion: $$ {\bf w}^{(1,2)\star} = \arg\!\min_{{\bf w}^{(1,2)}} - \sum_{j=1}^{n_2} \sum_{c=0}^1 {\bf 1}\{h_{i,2} = c\} \log p(h_{j,2} = c | {\bf x}_j; {\bf w}^{(1,2)}). $$ This scenario is represented as:

No description has been provided for this image

Using Existing Models as Input to the "Is Rich" Logistic Regression¶

  • Suppose we don't have $h_1$ and $h_2$ but we can use the pre-trained models above ${\bf w}^{(1)\star}$ and ${\bf w}^{(2)\star}$ to predict $h_1$ and $h_2$ for person $i$ from their observed data $x_i = (x_{i,1},x_{i,2},x_{i,3},x_{i,4})$.
  • The predictions $\hat{h}_1$ and $\hat{h}_2$ feed into a logistic regression classifier Layering the previously learned logistic regression models for yatch and mansion as inputs to the logistic regression (${\bf w}^{(3)}$) that learns if a person is rich:
No description has been provided for this image

End-to-end Learning¶

  • A model is learned end-to-end when all its parameters are updated in the optimization

Now consider the setting that we do not see if someone owns a yatch or a mansion and we have no training data for it. That is, the only training data is $\{({\bf x}_k,y_k)\}_{k=1}^n$, where ${\bf x}_k$ is as before and $y_{k} \in \{0,1\}$ indicates whether user $k$ is rich. We can still learn the following classifier by optimizing $$ {\bf w}^{(1,1)\star},{\bf w}^{(1,2)\star},{\bf w}^{(2)\star} = \arg\!\min_{{\bf w}^{(1,1)},{\bf w}^{(1,2)},{\bf w}^{(2)}} - \sum_{k=1}^{n} \sum_{c = 0}^1 {\bf 1}\{y_{k} = c\} \log p(y_{k} = c | {\bf x}_k;{\bf w}^{(1,1)},{\bf w}^{(1,2)},{\bf w}^{(2)}), $$| represented in the neural network architecture:

No description has been provided for this image

Multilayer Perceptron (MLP)¶

A clearly more powerful model (because it also encompases the above model) is:

No description has been provided for this image
  • The above model is a multilayer perceptron with one hidden layer ($\hat{h}_1$ and $\hat{h}_2$).
  • The activation function $\sigma$ (the s-shapped activation) can be any non-polynomial function (more details later)

The MLP encompases the above model because we are setting some of the weights to be zero:

No description has been provided for this image

Inductive Biases¶

Thus, the fully connected model (a.k.a. fully connected neural network or multilayer perceptron) is more powerful than a model with constrained connections (as the model could learn that the extra weights are zero).

  • We say a neural network model has an inductive bias if the model connections are constrained to a subset of all possible connections in any given layer.

Examples of Inductive Biases in Modern Deep Learning¶

Architecture Inductive Bias Assumption
Convolutional Neural Networks (CNNs) Local connectivity, weight sharing, translation equivariance Spatial features are local and translation-invariant
Recurrent Neural Networks (RNNs) Sequential processing, shared weights across time Data has temporal dependencies
Transformers (Self-Attention) Permutation equivariance (without positional encoding), global interactions Relevant information can come from any position; all positions are equally important
Graph Neural Networks (GNNs) Message passing on graph structure, permutation invariance Entities have relational structure
Residual Connections (ResNets) Identity shortcuts Deeper layers should refine rather than completely override shallow features

2.1 Network Topology¶

An MLP consists of:

  1. Input layer: Raw features
  2. Hidden layers: Learned representations
  3. Output layer: Final predictions

Each layer $l$ performs: $$\mathbf{h}^{(l)} = \sigma(\mathbf{W}^{(l)}\mathbf{h}^{(l-1)} + \mathbf{b}^{(l)})$$

where:

  • $\mathbf{h}^{(l)}$ is the output of layer $l$
  • $\mathbf{W}^{(l)}$ is the weight matrix
  • $\mathbf{b}^{(l)}$ is the bias vector
  • $\sigma$ is the activation function

2.2 Geometric Interpretation¶

Each layer performs:

  1. Affine transformation (linear mapping + translation)
  2. Non-linear (non-polynomial) warping through activation function

This creates increasingly complex decision boundaries.

Multilayer Perceptron (MLP, or feedforward network) Architecture¶

The general architecture of a multilayer perceptron is:

  • an input layer with $n$ input-units
  • an output layer with $m$ outputs
  • and one or more hidden layers consisting of intermediate neuron outputs.
    • the superscript $(k)$ in the parameters (weights) ${\bf W}^{(k)}$ will indicate they belong to layer $k$
    • if layer $k$ has $d_\text{in}$ inputs and $d_\text{out}$ outputs, then the neuron weights ${\bf W}^{(k)}\in \mathbb{R}^{n_\text{in} \times n_\text{out}}$ are a $n_\text{in} \times n_\text{out}$ matrix
No description has been provided for this image
In [3]:
import torch
import torch.nn as nn
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)


class MLPWithIntermediates(nn.Module):
    def __init__(self, input_dim, hidden_dims, output_dim):
        super().__init__()
        self.layers = nn.ModuleList()
        
        # Input layer
        self.layers.append(nn.Linear(input_dim, hidden_dims[0]))
        
        # Hidden layers
        for i in range(len(hidden_dims)-1):
            self.layers.append(nn.Linear(hidden_dims[i], hidden_dims[i+1]))
            
        # Output layer
        self.layers.append(nn.Linear(hidden_dims[-1], output_dim))
        
        self.activation = nn.ReLU()
        
    def forward(self, x):
        intermediates = [x]
        
        for layer in self.layers[:-1]:
            x = self.activation(layer(x))
            
        x = self.layers[-1](x)
        
        return x

# Example usage:
model = MLPWithIntermediates(input_dim=2, hidden_dims=[64, 32], output_dim=1)
print(model)
MLPWithIntermediates(
  (layers): ModuleList(
    (0): Linear(in_features=2, out_features=64, bias=True)
    (1): Linear(in_features=64, out_features=32, bias=True)
    (2): Linear(in_features=32, out_features=1, bias=True)
  )
  (activation): ReLU()
)

Can MLPs approximate any function? (Are they universal approximators?)¶

Before we proceed with our study of neural networks, this is a fundamental question we must address:

Q: Assuming we are free to choose any $\sigma$, ${\bf W}$, and $b$, which functions $f : \mathbb{R}^n \to \mathbb{R}^m $ can a multilayer feedforward networks arbitrarily approximate?

A: Neural networks can emulate any continuous function as long as the activation functions $\sigma$ are not algebraic polynomials almost everywhere.

B: Neural networks cannot approximate non-polynomial functions (e.g., sine, cosine).

Since a mapping $f : \mathbb{R}^n \to \mathbb{R}^m$ can be computed by $m$ mappings $f_j : \mathbb{R}^n \to \mathbb{R}$, without loss of generality, we will consider $f : \mathbb{R}^n \to \mathbb{R}$.

An single hidden layer MLP can be described as: $$\begin{equation}f_j({\bf x}) = \sum_{j=1}^k w^{(2)}_j \sigma\left(({\bf w}_{j}^{(1)})^T {\bf x} + w^{(1)}_0 \right)\tag{1}\end{equation}$$

or, if the image of $f$ is constrained to some subset of $\mathbb{R}$:

$$ f_j({\bf x}) = \sigma_\text{out}\left(\sum_{j=1}^k w^{(2)}_j \sigma\left(({\bf w}_{j}^{(1)})^T {\bf x} + w^{(1)}_0 \right)\right) $$

Universal Approximation Properties of Neural Networks¶

1. Introduction and Historical Context¶

The Universal Approximation Theorem (UAT) is one of the most fundamental theoretical results in deep learning. It explains why neural networks can theoretically solve any continuous function approximation problem.

Key Developments:

  • 1989: Cybenko proves UAT for sigmoid activation functions
  • 1991: Hornik extends to bounded, continuous activation functions
  • 1993: Leshno et al. characterize necessary and sufficient conditions

2. Mathematical Formulation¶

2.1 Single Hidden Layer Network¶

Consider a neural network with:

  • Input dimension: $n$
  • Single hidden layer with $k$ neurons
  • Output dimension: 1

The network computes: $$f(\mathbf{x}) = \sum_{j=1}^k w^{(2)}_j \sigma(\mathbf{w}_j^{(1)T} \mathbf{x} + b_j)\tag{1}\label{eq:f}$$

where:

  • $\sigma$ is the activation function
  • $\mathbf{w}_j^{(1)}$ are the first layer weights
  • $w^{(2)}_j$ are the output layer weights
  • $b_j$ are the biases

2.2 The Universal Approximation Theorem¶

Theorem (Leshno et al. 1993) [informal]:

Let $\sigma: \mathbb{R} \to \mathbb{R}$ be an activation function. Neural networks with activation $\sigma$ can approximate any continuous function on compact subsets of $\mathbb{R}^n$ arbitrarily well if and only if $\sigma$ is not a polynomial almost everywhere.

Key Implications:

  1. A single hidden layer is theoretically sufficient
  2. The activation function must be non-polynomial
  3. The size of the hidden layer may need to be very large
  4. The theorem is existential (doesn't tell us how to find the weights)

2.3 Why Non-polynomial?¶

Consider a counterexample with polynomial activation:

  • If $\sigma(x) = x^2$, then any composition of layers would still be polynomial
  • Cannot approximate non-polynomial functions like $\sin(x)$

Formalization¶

Theorem 1. (Leshno et al. 1993): Let $f$ be as in $(1)$. Let $\sigma \in M$, where $M$ is a set of functions where for any $\sigma' \in M$, interval $[a, b]$, and $\delta > 0$, there exists a finite number of open intervals, the union of which we denote by $U$, such that $\sigma'$ is uniformly continuous on $[a, b]\backslash U$. Then the set of outputs $\sigma\left(({\bf w}_j^{(1)})^T {\bf x} + w^{(1)}_0 \right)$, $j=1,2,\ldots$, is dense in the class of all functions that are continuous in the domain, if and only if $\sigma$ is not an algebraic polynomial almost everywhere.

  • Theorem 1 implies that by choosing ${\bf w}_j^{(1)}$, $j=1,2,\ldots$ we can create an infinite set of basis functions for $f({\bf x})$.
    • This set forms a basis for the set of all continuous functions
  • Important: The activation $\sigma$ is not simply non-linear as we often find in tutorials. It is non-polynomial.
    • E.g.: The activation $\sigma(x) = x^2$ will result in an MLP that can only approximate polynomials of order up to two

PS: ReLU activations are polynomials but not almost everywhere due to their discontinuity.

  • (Lu et al., 2017) shows that any Lebesgue-integrable function f from $\mathbb{R}^n$ to $\mathbb{R}$ can be approximated by a fully-connected width-(n + 4) ReLU network to arbitrary accuracy with respect to L 1 distance. In addition, except for a negligible set, all functions f from $\mathbb{R}^n$ to $\mathbb{R}$ cannot be approximated by any ReLU network whose width is no more than n.
  • Q2: Is the threshold (bias) ${\bf b}^{(1)}_j$ necessary for universal approximation?

  • A: No

  • B: Yes

  • B: Yes. Consider the example in (Leshno et al. 1993), with activation function (without a threshold) $\sigma(x) = \sin(x)$. This function is not a polynomial; In addition, it is continuous, bounded, and non-constant. Now, the set of function $\{\sin(w \cdot x) | w \in \mathbb{R}\}$ consists of only odd functions $(\sigma(x) = -\sigma(-x))$. Thus, an even function like $cos(x)$ cannot be approximated using this family in $[-1, 1]$, implying that $\{sin(w \cdot x) | w \in \mathbb{R}\}$ is not dense in the set of continuous functions that output values in the interval $[-1,1]$. This could be corrected by adding to the family $\sin(\cdot)$ functions with a threshold (bias or offset) variable (e.g. $\sin(x + \pi/2) = \cos(x)$).
In [4]:
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)


def plot_activation_approximation(activation, target_fn, x_range=(-5, 5), num_neurons=50):
    """Demonstrate how increasing neurons improves function approximation."""
    x = np.linspace(x_range[0], x_range[1], 1000)
    y_true = target_fn(x)
    
    class SimpleNetwork(nn.Module):
        def __init__(self, num_neurons, activation):
            super().__init__()
            self.layer1 = nn.Linear(1, num_neurons)
            self.layer2 = nn.Linear(num_neurons, 1)
            self.activation = activation
            
        def forward(self, x):
            x = self.activation(self.layer1(x))
            return self.layer2(x)
    
    # Create networks with different numbers of neurons
    neurons_list = [5, 10, num_neurons]
    plt.figure(figsize=(12, 6))
    plt.plot(x, y_true, 'k-', label='Target function', linewidth=2)
    
    for neurons in neurons_list:
        model = SimpleNetwork(neurons, activation)
        
        # Train the network
        optimizer = torch.optim.Adam(model.parameters())
        x_tensor = torch.FloatTensor(x.reshape(-1, 1))
        y_tensor = torch.FloatTensor(y_true.reshape(-1, 1))
        
        for _ in range(1000):
            optimizer.zero_grad()
            y_pred = model(x_tensor)
            loss = nn.MSELoss()(y_pred, y_tensor)
            loss.backward()
            optimizer.step()
        
        # Plot results
        with torch.no_grad():
            y_approx = model(x_tensor).numpy()
        plt.plot(x, y_approx, '--', label=f'{neurons} hidden neurons')
    
    plt.title('Neural Network Function Approximation')
    plt.legend()
    plt.grid(True)
    plt.show()

# Example usage
target_function = lambda x: np.sin(x) * np.exp(-0.1 * np.abs(x))
plot_activation_approximation(nn.ReLU(), target_function)
No description has been provided for this image

3. Beyond the Basic Theorem¶

3.1 Width vs Depth Trade-offs¶

While one hidden layer is sufficient in theory, deeper networks often have advantages:

  1. Expressivity: Deep networks can represent some functions more efficiently

    • Example: Parity function requires exponential width in shallow networks
    • But can be computed efficiently with logarithmic depth
  2. Optimization: Deeper networks may be easier to train

    • Hierarchical representation learning
    • Better gradient flow in some architectures

3.2 Modern Extensions¶

Recent theoretical work has shown:

  1. ReLU networks require width ≥ (n+4) for universal approximation (Lu et al. 2017)
  2. Depth can exponentially reduce width requirements
  3. Specific bounds on approximation rates exist
In [5]:
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)


class MLP(nn.Module):
    """A flexible MLP that can be configured as shallow-wide, deep-narrow, or deep-wide."""
    def __init__(self, input_dim=1, output_dim=1, hidden_dims=[100], activation=nn.ReLU()):
        """
        Args:
            input_dim: Input dimension
            output_dim: Output dimension
            hidden_dims: List of hidden layer dimensions
            activation: Activation function
        """
        super().__init__()
        
        # Build network architecture
        dims = [input_dim] + hidden_dims + [output_dim]
        layers = []
        for i in range(len(dims)-1):
            layers.append(nn.Linear(dims[i], dims[i+1]))
            if i < len(dims)-2:  # No activation after last layer
                layers.append(activation)
        
        self.network = nn.Sequential(*layers)
    
    def forward(self, x):
        return self.network(x)

def generate_target_function(x):
    """Generate a complex target function with multiple frequencies."""
    return np.sin(x) + 0.6 * np.sin(10*x) + 0.1 * np.sin(100*x)

def train_and_compare_mlps():
    # Generate data
    x = np.linspace(-5, 5, 1000)
    y = generate_target_function(x)
    
    x_tensor = torch.FloatTensor(x.reshape(-1, 1))
    y_tensor = torch.FloatTensor(y.reshape(-1, 1))
    
    # Create three different MLP architectures
    models = {
        'Shallow-Wide': MLP(hidden_dims=[100]),           # One hidden layer, 100 units
        'Deep-Narrow': MLP(hidden_dims=[5]*5),          # 5 hidden layers, 5 units each
        'Deep-Wide': MLP(hidden_dims=[100]*5)            # 5 hidden layers, 100 units each
    }
    
    # Training settings
    epochs = 1000
    losses = {name: [] for name in models}
    optimizer_dict = {name: torch.optim.Adam(model.parameters(), lr=0.01) 
                     for name, model in models.items()}
    criterion = nn.MSELoss()
    
    # Train all models
    for epoch in range(epochs):
        for name, model in models.items():
            optimizer = optimizer_dict[name]
            optimizer.zero_grad()
            
            y_pred = model(x_tensor)
            loss = criterion(y_pred, y_tensor)
            loss.backward()
            optimizer.step()
            
            losses[name].append(loss.item())
    
    # Plotting
    plt.figure(figsize=(15, 5))
    
    # Plot 1: Training curves
    plt.subplot(1, 2, 1)
    for name, loss_list in losses.items():
        plt.plot(loss_list, label=name)
    plt.yscale('log')
    plt.title('Training Loss')
    plt.xlabel('Epochs')
    plt.ylabel('MSE Loss')
    plt.legend()
    plt.grid(True)
    
    # Plot 2: Function approximation
    plt.subplot(1, 2, 2)
    plt.plot(x, y, 'k-', label='Target', alpha=0.5)
    
    with torch.no_grad():
        for name, model in models.items():
            pred = model(x_tensor).numpy()
            plt.plot(x, pred, '--', label=name)
    
    plt.title('Function Approximation')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.grid(True)
    
    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    train_and_compare_mlps()
No description has been provided for this image

Practical Implications of the Universal Approximation Theorem¶

Overview¶

While the Universal Approximation Theorem (UAT) provides theoretical guarantees, translating these into practical network design involves several key considerations. We will now explore the practical implications through hands-on examples.

Contents¶

  1. Effect of Network Width
  2. Depth vs Width Trade-offs
  3. Choice of Activation Functions
  4. Practical Limitations
In [6]:
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from typing import List, Tuple
from tqdm.notebook import tqdm

# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)

# Enable CUDA if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

1. Effect of Network Width¶

The UAT states that a single hidden layer with sufficient width can approximate any continuous function. Let's examine how width affects approximation capability in practice.

In [7]:
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)

class WidthExperiment(nn.Module):
    def __init__(self, input_dim: int, hidden_width: int):
        super().__init__()
        self.layer1 = nn.Linear(input_dim, hidden_width)
        self.layer2 = nn.Linear(hidden_width, 1)
        self.activation = nn.ReLU()
        
    def forward(self, x):
        x = self.activation(self.layer1(x))
        return self.layer2(x)

def generate_complex_function(x: np.ndarray) -> np.ndarray:
    """Generate a complex function that combines multiple frequencies"""
    return np.sin(x) + 1.5 * np.sin(2*x) + 0.25 * np.sin(4*x)

def train_model(model: nn.Module, x: torch.Tensor, y: torch.Tensor, 
                epochs: int = 2000) -> List[float]:
    """Train model and return loss history"""
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    criterion = nn.MSELoss()
    losses = []
    
    for _ in range(epochs):
        optimizer.zero_grad()
        y_pred = model(x)
        loss = criterion(y_pred, y)
        loss.backward()
        optimizer.step()
        losses.append(loss.item())
        
    return losses

# Generate data
x = np.linspace(-5, 5, 500).reshape(-1, 1)
y = generate_complex_function(x)

# Convert to tensors
x_tensor = torch.FloatTensor(x)
y_tensor = torch.FloatTensor(y.reshape(-1, 1))

# Experiment with different widths
widths = [5, 20, 100]
plt.figure(figsize=(15, 5))

for i, width in enumerate(widths, 1):
    model = WidthExperiment(1, width)
    losses = train_model(model, x_tensor, y_tensor)
    
    with torch.no_grad():
        y_pred = model(x_tensor).numpy()
    
    plt.subplot(1, 3, i)
    plt.plot(x, y, 'b-', label='Target', alpha=0.5)
    plt.plot(x, y_pred, 'r--', label=f'Width={width}')
    plt.title(f'Hidden Width: {width}')
    plt.legend()
    plt.grid(True)

plt.tight_layout()
plt.show()
No description has been provided for this image

2. Depth vs Width Trade-offs¶

While UAT guarantees that a single wide layer is sufficient, deep networks often achieve better results with fewer total parameters. Let's compare different architectures with similar parameter counts.

In the following example, pay attention to:

  • Depth for smoothness: Deeper neural networks tend to be smoother functions. Their optimization is also easier, smoother.
  • Width for approximation power: Wide neural networks have better capacity to approximate complex, sharper functions. Note how a wide shallow network with fewer parameters (301) can approximate sharp changes in the function that a deep but narrow network with more parameters (471) cannot.
In [8]:
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)

class FlexibleMLP(nn.Module):
    def __init__(self, input_dim: int, hidden_dims: List[int]):
        super().__init__()
        layers = []
        prev_dim = input_dim
        output_dim = input_dim
        
        for dim in hidden_dims:
            layers.extend([
                nn.Linear(prev_dim, dim),
                nn.ReLU()
            ])
            prev_dim = dim
            
        layers.append(nn.Linear(prev_dim, output_dim))
        self.network = nn.Sequential(*layers)
        
    def forward(self, x):
        return self.network(x)
    
    def count_parameters(self) -> int:
        return sum(p.numel() for p in self.parameters())

# Define architectures with similar parameter counts
architectures = [
    ([100], "Wide Shallow"),
    ([20, 20, 20], "Medium Deep"),
    ([10, 5, 10, 10, 10], "Narrow Deep")
]

# Train and compare
plt.figure(figsize=(15, 5))

for i, (hidden_dims, name) in enumerate(architectures, 1):
    model = FlexibleMLP(1, hidden_dims)
    n_params = model.count_parameters()
    
    losses = train_model(model, x_tensor, y_tensor)
    
    with torch.no_grad():
        y_pred = model(x_tensor).numpy()
    
    plt.subplot(1, 3, i)
    plt.plot(x, y, 'b-', label='Target', alpha=0.5)
    plt.plot(x, y_pred, 'r--', label=f'{name}\n{n_params} params')
    plt.title(name)
    plt.legend()
    plt.grid(True)

plt.tight_layout()
plt.show()
No description has been provided for this image

3. Choice of Activation Functions¶

The UAT requires non-polynomial activation functions. Let's compare different choices and their practical implications.

In the following example, pay attention to:

  • Gradient properties of activation functions: Looking at the relative scales (note the log scale in the tanh and sigmoid plots), these loss spikes have different magnitudes across activation functions. ReLU shows more controlled spikes, while tanh exhibits larger oscillations, which is consistent with their gradient properties.
  • Optimization landscape transitions: The spikes often precede regions of improved convergence (noticeable drops in loss), suggesting the network is escaping local minima or traversing saddle points.
In [9]:
# Set random seeds for reproducibility
torch.manual_seed(42)
np.random.seed(42)

class ActivationExperiment(nn.Module):
    def __init__(self, input_dim: int, hidden_dim: int, activation: nn.Module):
        super().__init__()
        output_dim = input_dim
        self.layer1 = nn.Linear(input_dim, hidden_dim)
        self.layer2 = nn.Linear(hidden_dim, hidden_dim)
        self.layer3 = nn.Linear(hidden_dim, output_dim)
        self.activation = activation
        
    def forward(self, x):
        x = self.activation(self.layer1(x))
        x = self.activation(self.layer2(x))
        return self.layer3(x)

# Compare different activations
activations = [
    (nn.ReLU(), "ReLU"),
    (nn.Tanh(), "Tanh"),
    (nn.Sigmoid(), "Sigmoid")
]

plt.figure(figsize=(15, 10))
for i, (activation, name) in enumerate(activations, 1):
    model = ActivationExperiment(1, 50, activation)
    losses = train_model(model, x_tensor, y_tensor)
    
    with torch.no_grad():
        y_pred = model(x_tensor).numpy()
    
    # Plot function approximation
    plt.subplot(2, 3, i)
    plt.plot(x, y, 'b-', label='Target', alpha=0.5)
    plt.plot(x, y_pred, 'r--', label=name)
    plt.title(f'{name} Approximation')
    plt.legend()
    plt.grid(True)
    
    # Plot loss curves
    plt.subplot(2, 3, i+3)
    plt.plot(losses)
    plt.title(f'{name} Training Loss')
    plt.yscale('log')
    plt.ylim(10**(-4.5), 10**0)  # Set y-axis limits from 10^0 to 10^-4
    plt.grid(True)

plt.tight_layout()
plt.show()
No description has been provided for this image

4. Practical Limitations¶

Key Takeaways from Experiments¶

  1. Width-Depth Trade-off:

    • Wide networks can approximate complex functions but may be harder to train.
    • Deep networks tend to give smoother functions that often achieve better results with fewer parameters.
    • Consider computational budget when choosing architecture.
  2. Activation Functions:

    • ReLU generally provides fastest convergence.
    • Bounded activations (tanh, sigmoid) can help with stability but can suffer from vanishing and exploding gradients.
    • Gradient properties match the application (we will revisit this when we talk about image generation).
  3. Real-world Constraints:

    • Finite precision arithmetic affects approximations.
    • Optimization challenges increase with network size.

Best Practices¶

  1. Start Simple:

    • Begin with small architectures and scale up as needed.
      • Try to see if your application likes depth or width better (smoothness or fitting power).
    • Monitor training dynamics and validation performance.
  2. Architecture Selection:

    • Use domain knowledge to guide initial design.
    • Consider computational and memory constraints.
    • Balance depth and width based on the task.
  3. Training Strategy:

    • Use appropriate initialization for chosen activation
    • Consider learning rate scheduling (we will cover this later)
    • Monitor gradient norms during training

Common Activation Functions¶

We add non-polynomial activation functions after the inner product layers. Here are some of the popular choices for non-polynomial activation:

  • Sigmoid: $\sigma(z) = \frac{1}{(1+e^{-z})}$
  • tanh: $\text{tanh}(z) = \frac{(e^{2z} - 1)}{(e^{2z} + 1)}$
  • ReLU: $\text{relu}(z) = \max(0, z)$
  • ELU: $\text{elu}(z) = \begin{cases} z & \text{if }z \geq 0,\\ \alpha (\exp(z) - 1) &\text{if } z < 0, \end{cases}$ where $\alpha$ is a small constant.
  • LeakyReLU: $\text{LeakyRelu}(z) = \begin{cases} z & \text{if }z \geq 0,\\ \alpha z &\text{if } z < 0, \end{cases}$ where $\alpha$ is a small constant.

If the input is a vector ${\bf z}$, then each function is applied to each element of the vector. Rectified Linear Units (ReLU) and Exponential Linear Units (ELUs) have been found to work well in vision-related problems.

5. Equivariance in Neural Network Weight Spaces¶

5.1 Introduction to Equivariance¶

Definition (Group Action): Let $G$ be a group and $X$ be a set. A left group action of $G$ on $X$ is a function $\phi: G \times X \to X$, written as $\phi(g,x) = g \circ x$, satisfying:

  1. $e \circ x = x$ for all $x \in X$ (identity)
  2. $g_1 \circ (g_2 \circ x) = (g_1 g_2) \circ x$ for all $g_1, g_2 \in G, x \in X$ (compatibility)

Definition (Equivariance): Let $G$ be a group with actions on sets $X$ and $Y$. A function $f: X \to Y$ is $G$-equivariant if: $$f(g \circ x) = g \circ f(x) \quad \forall g \in G, x \in X$$

Definition (Invariance): A function $f: X \to Y$ is $G$-invariant if: $$f(g \circ x) = f(x) \quad \forall g \in G, x \in X$$

5.2 Symmetries in Neural Network Weight Spaces¶

Neural networks exhibit several important symmetries in their weight spaces. Understanding these symmetries is important for:

  1. Model merging and averaging
  2. Neural network theory

5.2.1 Permutation Symmetry¶

Consider an MLP with one hidden layer: $$f({\bf x}; W^{(1)}, W^{(2)}) = W^{(2)} \sigma(W^{(1)} {\bf x})$$

where $W^{(1)} \in \mathbb{R}^{h \times d}$ and $W^{(2)} \in \mathbb{R}^{o \times h}$.

Theorem (Neuron Permutation Invariance): The function computed by the network is invariant to permutations of hidden neurons. Specifically, for any permutation $\pi \in S_h$ (the symmetric group on $h$ elements):

$$f({\bf x}; W^{(1)}, W^{(2)}) = f({\bf x}; P_\pi W^{(1)}, W^{(2)} P_\pi^T)$$

where $P_\pi$ is the permutation matrix corresponding to $\pi$.

Proof sketch: $$W^{(2)} \sigma(W^{(1)} {\bf x}) = W^{(2)} P_\pi^T P_\pi \sigma(W^{(1)} {\bf x}) = W^{(2)} P_\pi^T \sigma(P_\pi W^{(1)} {\bf x})$$

The last equality holds because $P_\pi$ commutes with element-wise operations.

Implication: For an MLP with $h$ hidden units per layer and $L$ hidden layers, there are at least $h!^L$ functionally equivalent parameter configurations.

5.2.2 Scaling Symmetry (for ReLU networks)¶

For ReLU networks, there exists a scaling symmetry:

Theorem (ReLU Scaling Symmetry): For any positive scalar $\alpha > 0$: $$W^{(2)} \text{ReLU}(W^{(1)} {\bf x}) = (W^{(2)} \alpha) \text{ReLU}((W^{(1)} / \alpha) {\bf x})$$

This creates a continuous symmetry in the loss landscape for certain network architectures.

5.2.3 Sign-Flip Symmetry (for certain activations)¶

For activation functions satisfying $\sigma(-x) = -\sigma(x)$ (like tanh, ReLU): $$W^{(2)} \sigma(W^{(1)} {\bf x}) = (-W^{(2)}) \sigma((-W^{(1)}) {\bf x})$$

This creates $2^h$ additional symmetries per hidden layer.

5.3 Weight Space Geometry and Loss Landscape¶

The symmetries described above have profound implications:

  1. Non-unique minima: The loss function $\mathcal{L}(W)$ has multiple global minima that are related by symmetry transformations

  2. Mode connectivity: Many empirically observed properties of neural network loss landscapes can be understood through these symmetries

  3. Model averaging challenges: Naively averaging weights from different training runs may perform poorly due to permutation misalignment

Weight Matching Problem¶

Given two networks with weights $W_A$ and $W_B$ that implement similar functions, find the permutation alignment:

$$\pi^* = \arg\min_{\pi \in S_h} \|W_A - P_\pi W_B P_\pi^T\|_F$$

This is computationally hard (NP-hard in general), but approximate solutions enable:

  • Git Re-Basin (matching network checkpoints)
  • Model merging and averaging
  • Understanding loss barrier reduction

5.4 Equivariant Functions on Weight Spaces¶

Definition: A function $\Phi: \mathcal{W} \to \mathcal{W}$ on the weight space is permutation-equivariant if:

$$\Phi(P_\pi W P_\pi^T) = P_\pi \Phi(W) P_\pi^T$$

for all permutations $\pi$.

5.5 Example of invariance¶

In [10]:
import torch
import torch.nn as nn
import numpy as np
import math


class MLPWithSymmetry(nn.Module):
    """MLP demonstrating weight space symmetries"""
    def __init__(self, input_dim, hidden_dim, output_dim):
        super().__init__()
        self.w1 = nn.Linear(input_dim, hidden_dim, bias=False)
        self.w2 = nn.Linear(hidden_dim, output_dim, bias=False)
        
    def forward(self, x):
        return self.w2(torch.relu(self.w1(x)))
    
    def get_weights(self):
        return self.w1.weight.data.clone(), self.w2.weight.data.clone()
    
    def set_weights(self, w1, w2):
        self.w1.weight.data = w1
        self.w2.weight.data = w2

def create_permutation_matrix(perm, device='cpu'):
    """Create permutation matrix from permutation list"""
    n = len(perm)
    P = torch.zeros(n, n, device=device)
    for i, j in enumerate(perm):
        P[i, j] = 1.0
    return P

# Demonstration of permutation symmetry
torch.manual_seed(42)
input_dim, hidden_dim, output_dim = 5, 10, 3

# Create model
model = MLPWithSymmetry(input_dim, hidden_dim, output_dim)
w1, w2 = model.get_weights()

# Create random permutation
perm = torch.randperm(hidden_dim)
P = create_permutation_matrix(perm)

# Apply permutation to weights
w1_perm = P @ w1  # Permute rows of W1 (output dimension)
w2_perm = w2 @ P.T  # Permute columns of W2 (input dimension)

# Test on random input
x_test = torch.randn(100, input_dim)

# Original output
with torch.no_grad():
    output_original = model(x_test)

# Permuted weights output
model.set_weights(w1_perm, w2_perm)
with torch.no_grad():
    output_permuted = model(x_test)

# Check equivalence
difference = torch.abs(output_original - output_permuted).max().item()
print(f"Maximum output difference after permutation: {difference:.10f}")
print(f"Outputs are equivalent: {difference < 1e-6}")

# Demonstrate that there are h! equivalent parameterizations
print(f"\nFor {hidden_dim} hidden units, there are {math.factorial(hidden_dim):,} "
      f"equivalent permutations")

# Counting all symmetries
num_layers = 2
hidden_per_layer = hidden_dim
total_permutations = math.factorial(hidden_per_layer) ** (num_layers - 1)
sign_flips = 2 ** hidden_per_layer
print(f"\nTotal symmetries (permutations × sign flips) ≥ "
      f"{total_permutations * sign_flips:.2e}")
Maximum output difference after permutation: 0.0000000596
Outputs are equivalent: True

For 10 hidden units, there are 3,628,800 equivalent permutations

Total symmetries (permutations × sign flips) ≥ 3.72e+09

5.6 Connection to Modern LLM Practices¶

These symmetries have important implications for LLM development:

  1. Model Merging: MLP merging must account for permutation symmetries

  2. Continued Pre-training: When continuing to train from a checkpoint, the optimization trajectory explores the symmetry orbit

  3. Ensemble Methods: Naive averaging of LLM weights requires careful alignment

  4. Lottery Ticket Hypothesis: The existence of multiple equivalent weight configurations supports findings about subnetworks]

References

  • Ainsworth et al. "Git Re-Basin: Merging Models modulo Permutation Symmetries" (ICLR 2023)
  • Navon et al. "Equivariant architectures for learning in deep weight spaces" (ICML 2023)
  • Entezari et al. "The Role of Permutation Invariance in Linear Mode Connectivity" (ICLR 2022)
  • Brea et al. "Weight-space symmetry in deep networks gives rise to permutation saddles" (NeurIPS 2019)

6. MLPs in Transformer Architectures¶

6.1 The Role of MLPs in Modern LLMs¶

In transformer-based language models, the feedforward network (FFN) - essentially an MLP - plays a crucial role alongside the attention mechanism. The standard transformer block alternates between:

  1. Multi-head self-attention (MHSA): Processes relationships between tokens
  2. Feedforward network (FFN/MLP): Applies position-wise transformations

The MLP component typically accounts for ~67% of total parameters in standard transformer architectures, making it the dominant contributor to model capacity.

6.2 Architecture of Transformer FFN Blocks¶

The canonical transformer FFN is a two-layer MLP with expansion:

$$\text{FFN}({\bf x}) = \sigma({\bf x} W_1 + {\bf b}_1) W_2 + {\bf b}_2$$

where:

  • Input dimension: $d_{\text{model}}$ (e.g., 768, 4096, 8192)
  • Hidden dimension: $d_{\text{ff}} = 4 \times d_{\text{model}}$ (expansion factor of 4 is standard)
  • $W_1 \in \mathbb{R}^{d_{\text{model}} \times d_{\text{ff}}}$: Up-projection
  • $W_2 \in \mathbb{R}^{d_{\text{ff}} \times d_{\text{model}}}$: Down-projection
  • $\sigma$: Non-linear activation function

Key insight: This creates a bottleneck architecture: $$d_{\text{model}} \xrightarrow{\text{expand}} 4 \cdot d_{\text{model}} \xrightarrow{\text{compress}} d_{\text{model}}$$

The expansion allows the network to learn richer intermediate representations.

6.3 Modern Activation Functions in LLMs¶

Recent LLMs have moved beyond traditional activations:

GELU (Gaussian Error Linear Unit)¶

Used in BERT, GPT-2, GPT-3: $$\text{GELU}(x) = x \cdot \Phi(x) = x \cdot \frac{1}{2}\left[1 + \text{erf}\left(\frac{x}{\sqrt{2}}\right)\right]$$

Approximation used in practice: $$\text{GELU}(x) \approx 0.5 x \left(1 + \tanh\left[\sqrt{2/\pi}(x + 0.044715x^3)\right]\right)$$

SwiGLU (Swish-Gated Linear Unit)¶

Used in PaLM, LLaMA, Mistral: $$\text{SwiGLU}({\bf x}, W, V, b, c) = \text{Swish}({\bf x}W + b) \odot ({\bf x}V + c)$$

where $\text{Swish}(x) = x \cdot \sigma(\beta x)$ (typically $\beta=1$), and $\odot$ is element-wise multiplication.

Modern FFN with SwiGLU: $$\text{FFN}_{\text{SwiGLU}}({\bf x}) = (\text{Swish}({\bf x}W_1) \odot {\bf x}W_3) W_2$$

This requires three weight matrices instead of two, trading parameters for better performance.

GeGLU (GELU-Gated Linear Unit)¶

Used in some recent models: $$\text{GeGLU}({\bf x}, W, V) = \text{GELU}({\bf x}W) \odot ({\bf x}V)$$

In [11]:
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt

class SwiGLU(nn.Module):
    """SwiGLU activation as used in LLaMA and PaLM"""
    def __init__(self, dim, hidden_dim, bias=False):
        super().__init__()
        self.w1 = nn.Linear(dim, hidden_dim, bias=bias)  # Gate projection
        self.w2 = nn.Linear(hidden_dim, dim, bias=bias)  # Down projection
        self.w3 = nn.Linear(dim, hidden_dim, bias=bias)  # Up projection
    
    def forward(self, x):
        # SwiGLU: (Swish(xW1) ⊙ xW3)W2
        return self.w2(F.silu(self.w1(x)) * self.w3(x))  # silu = swish

class GeGLU(nn.Module):
    """GeGLU activation"""
    def __init__(self, dim, hidden_dim, bias=False):
        super().__init__()
        self.w1 = nn.Linear(dim, hidden_dim, bias=bias)
        self.w2 = nn.Linear(hidden_dim, dim, bias=bias)
        self.w3 = nn.Linear(dim, hidden_dim, bias=bias)
    
    def forward(self, x):
        return self.w2(F.gelu(self.w1(x)) * self.w3(x))

class StandardFFN(nn.Module):
    """Standard transformer FFN with GELU"""
    def __init__(self, dim, hidden_dim, bias=False):
        super().__init__()
        self.w1 = nn.Linear(dim, hidden_dim, bias=bias)
        self.w2 = nn.Linear(hidden_dim, dim, bias=bias)
    
    def forward(self, x):
        return self.w2(F.gelu(self.w1(x)))

# Visualization of activation functions
x = np.linspace(-5, 5, 1000)
x_torch = torch.tensor(x, dtype=torch.float32)

def swish(x, beta=1):
    return x * torch.sigmoid(beta * x)

plt.figure(figsize=(14, 5))

# Plot activation functions
plt.subplot(1, 2, 1)
plt.plot(x, F.gelu(x_torch).numpy(), label='GELU', linewidth=2)
plt.plot(x, F.silu(x_torch).numpy(), label='SiLU/Swish', linewidth=2)
plt.plot(x, F.relu(x_torch).numpy(), label='ReLU', linewidth=2, alpha=0.7)
plt.grid(True, alpha=0.3)
plt.legend(fontsize=11)
plt.title('Modern LLM Activation Functions', fontsize=12)
plt.xlabel('x', fontsize=11)
plt.ylabel('f(x)', fontsize=11)

# Plot derivatives
plt.subplot(1, 2, 2)
x_grad = torch.tensor(x, dtype=torch.float32, requires_grad=True)

for name, func in [('GELU', F.gelu), ('SiLU/Swish', F.silu), ('ReLU', F.relu)]:
    y = func(x_grad)
    y.sum().backward(retain_graph=True)
    plt.plot(x, x_grad.grad.numpy(), label=f'{name} derivative', linewidth=2)
    x_grad.grad.zero_()

plt.grid(True, alpha=0.3)
plt.legend(fontsize=11)
plt.title('Activation Derivatives', fontsize=12)
plt.xlabel('x', fontsize=11)
plt.ylabel("f'(x)", fontsize=11)

plt.tight_layout()
plt.savefig('modern_activations.png', dpi=150, bbox_inches='tight')
plt.show()
No description has been provided for this image

6.4 Importance of MLPs: Parameter Distribution in LLMs¶

Let's analyze the parameter distribution in modern LLM architectures.

Example: GPT-3 style architecture

  • Token dimension: $d_{\text{model}} = 12288$
  • Number of layers: $L = 96$
  • Number of attention heads: $h = 96$
  • FFN hidden dimension: $d_{\text{ff}} = 4 \times 12288 = 49152$

Parameter count per layer:

  1. Multi-head attention:

    • Query, Key, Value projections: $3 \times d_{\text{model}}^2 = 3 \times 12288^2$
    • Output projection: $d_{\text{model}}^2 = 12288^2$
    • Total attention: $4 \times d_{\text{model}}^2$
  2. FFN (standard, 2-layer):

    • Up-projection: $d_{\text{model}} \times d_{\text{ff}} = 12288 \times 49152$
    • Down-projection: $d_{\text{ff}} \times d_{\text{model}} = 49152 \times 12288$
    • Total FFN: $2 \times d_{\text{model}} \times d_{\text{ff}} = 2 \times d_{\text{model}} \times 4d_{\text{model}} = 8 \times d_{\text{model}}^2$

Ratio of FFN to attention parameters: $$\frac{\text{FFN params}}{\text{Attention params}} = \frac{8 \times d_{\text{model}}^2}{4 \times d_{\text{model}}^2} = 2$$

For a full model:

  • Attention parameters per layer: $4d_{\text{model}}^2$
  • FFN parameters per layer: $8d_{\text{model}}^2$
  • GPt-3: FFN represents 67% of layer parameters

7. End-to-end Optimization: Backpropagation for gradient computation¶

In a large MLP, we need an efficient way to compute the gradients. For this, we will use the chain rule.

Consider again the task of determining if someone is rich (note that the bias is denoted $w^{(k)}_1$): No description has been provided for this image

The model can be described as a MLP, where the loss function (objective) is the log-likelihood over the training data:

  • Training data: $\{({\bf x}(1),y(1)),\ldots,({\bf x}(n),y(n))\}$
  • ${\bf x} = (1,x_{11},x_{12},x_{21},x_{22})$
  • ${\bf w}^{(1,k)} = (w^{(1,k)}_1, w^{(1,k)}_2,w^{(1,k)}_3,w^{(1,k)}_4,w^{(1,k)}_5)$, $k=1,2$
  • ${\bf w}^{(2)} = (w^{(2)}_1,w^{(2)}_2,w^{(2)}_3)$

Optimize using maximum likelihood estimation $$\begin{align*} {\bf w}^{(1,1)\star},{\bf w}^{(1,2)\star},{\bf w}^{(2)\star} &={\arg\!\max}_{{\bf w}^{(1,1)},{\bf w}^{(1,2)},{\bf w}^{(2)}} \frac{1}{n} \sum_{i=1}^n \log p(y = y(i) | {\bf x}(i); {\bf w}^{(1,1)}, {\bf w}^{(1,2)}, {\bf w}^{(2)} ) \\ &= {\arg\!\max}_{{\bf w}^{(1,1)},{\bf w}^{(1,2)},{\bf w}^{(2)}}\frac{1}{n} \sum_{i=1}^n y_i \log \sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i)) + b^{(2)}) + (1 - y(i)) \log (1-\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}_i) ))  , \end{align*}$$ where $\sigma(x) = \frac{\exp(x)}{1 + \exp(x)}$, and ${\bf h}({\bf x}) = (1,\hat{h}^{(1)}_{1}({\bf x}),\hat{h}^{(1)}_{2}({\bf x}))$,  $$ \hat{h}^{(1)}_{1}({\bf x}) = p(h^{(1)}_{1} = 1 | {\bf x}) = \sigma(({\bf w}^{(1,1)})^T {\bf x})   $$ and $$ \hat{h}^{(1)}_{2}({\bf x}) = p(h^{(1)}_{2} = 1 | {\bf x}) = \sigma(({\bf w}^{(1,2)})^T {\bf x})   $$

How can we compute these gradients? Here, we will resort to the chain rule of Calculus.

In a deep neural network each layer is a composition of previous layers, in our previous example the composition looks like: No description has been provided for this image

General problem: Consider a neural network with $K > 1$ layers. The influence of a lower layer parameter in the final error can be recovered by the chain rule, which generally states:

$$ \frac{\partial f^K(f^{K-1}(\cdots f^2(f^1(x;{\bf w}))\cdots))}{\partial w_m} = \frac{\partial f^K(f^{K-1})}{\partial f^{K-1}} \cdot \frac{\partial f^{K-1}(f^{K-2})}{\partial f^{K-2}} \cdots \frac{\partial f^2(f^1)}{\partial f^1} \cdot \frac{\partial f^1({\bf x};{\bf w})}{\partial w_m}, \quad m \in \{1,\ldots\} $$

7.1 Vanishing and Exploding gradients¶

Note that the series

$$ \frac{\partial f^K(f^{K-1}(\cdots f^2(f^1({\bf x};{\bf w}))\cdots))}{\partial w_m} = \frac{\partial f^K(f^{K-1})}{\partial f^{K-1}} \cdot \frac{\partial f^{K-1}(f^{K-2})}{\partial f^{K-2}} \cdots \frac{\partial f^2(f^1)}{\partial f^1} \cdot \frac{\partial f^1({\bf x};{\bf w})}{\partial w_m}, \quad m \in \{1,\ldots\} $$

can be lower bounded by $$ \left\vert \frac{\partial f^K(f^{K-1})}{\partial f^{K-1}} \cdot \frac{\partial f^{K-1}(f^{K-2})}{\partial f^{K-2}} \cdots \frac{\partial f^2(f^1)}{\partial f^1} \cdot \frac{\partial f^1({\bf x};{\bf w})}{\partial w_m} \right\vert < a_\text{lo}^K, $$ for $a_\text{lo} > \vert \frac{\partial f^m}{\partial f^{m-1}} \vert$ for all $1 < m \leq K$ and upper bounded by the geometric series $$ a_\text{hi}^K < \left| \frac{\partial f^K(f^{K-1})}{\partial f^{K-1}} \cdot \frac{\partial f^{K-1}(f^{K-2})}{\partial f^{K-2}} \cdots \frac{\partial f^2(f^1)}{\partial f^1} \cdot \frac{\partial f^1({\bf x};{\bf w})}{\partial w_m} \right| , $$ for $0 \leq a_\text{hi} < |\frac{\partial f^m}{\partial f^{m-1}}|$ for all $1 < m \leq K$.

  • If $a_\text{lo}$ is small, the gradient will get closer and closer to zero as the number of layers $K$ grows, giving vanishing gradients.
  • If $a_\text{hi}$ is large, the gradient will get larger and larger as the number of layers $K$ grows, giving exploding gradients.

7.1.1 Vanishing and Exploding Gradients: A Simple Guide¶

This notebook demonstrates gradient problems in deep networks and their solutions using simple examples.

In [12]:
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(42)
Out[12]:
<torch._C.Generator at 0x10d9dee10>

1. Demonstrating the Problem¶

Let's create a simple deep network and observe how gradients change across layers:

In [13]:
class SimpleDeepNet(nn.Module):
    def __init__(self, depth, activation=nn.Tanh()):
        super().__init__()
        self.layers = nn.ModuleList([
            # Just a single hidden neuron per layer
            nn.Linear(1, 1) for _ in range(depth)
        ])
        self.activation = activation
    
    def forward(self, x):
        for layer in self.layers:
            x = self.activation(layer(x))
        return x
    
def check_gradients(model, x, target):
    """Forward and backward pass, return gradient norms"""
    output = model(x)
    loss = (output - target).pow(2).mean()
    loss.backward()
    
    return [layer.weight.grad.norm().item() for layer in model.layers]

# Create models of different depths
depths = [5, 10, 20]
x = torch.ones(1, 1)
target = torch.zeros(1, 1)

plt.figure(figsize=(10, 4))
for depth in depths:
    model = SimpleDeepNet(depth)
    grads = check_gradients(model, x, target)
    plt.plot(grads, label=f'Depth={depth}')

plt.title('Gradient Norms Across Layers')
plt.xlabel('Layer (from input)')
plt.ylabel('Gradient Norm')
plt.yscale('log')
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

2. Solutions¶

2.1 Better Initialization¶

  • We will cover neural network initializations when we see optimizations.
In [14]:
def compare_initializations(depth=20):
    def init_model(init_type):
        model = SimpleDeepNet(depth)
        for layer in model.layers:
            if init_type == 'xavier':
                nn.init.xavier_normal_(layer.weight)
            elif init_type == 'standard normal':
                nn.init.normal_(layer.weight, std=0.01)
            layer.bias.data.fill_(0)
        return model
    
    inits = ['standard normal', 'xavier']
    plt.figure(figsize=(10, 4))
    
    for init in inits:
        model = init_model(init)
        grad_norm = check_gradients(model, x, target)
        plt.plot(grad_norm, label=init)
    
    plt.title('Effect of Weight Initialization')
    plt.xlabel('Layer')
    plt.ylabel('Gradient Norm')
    plt.legend()
    plt.grid(True)
    plt.show()

compare_initializations()
No description has been provided for this image

2.2 Skip Connections¶

  • Skip connections provide lower layers more direct access to the loss gradients
In [15]:
class ResNet(nn.Module): # Residual neural networks
    def __init__(self, depth):
        super().__init__()
        self.layers = nn.ModuleList([
            # Just a single hidden neuron per layer
            nn.Linear(1, 1) for _ in range(depth)
        ])
        
    def forward(self, x):
        for layer in self.layers:
            # Simple residual connection
            x = x + sigma(layer(x))
        return x

# Compare regular network vs ResNet
depth = 20
models = {
    'Plain': SimpleDeepNet(depth),
    'ResNet': ResNet(depth)
}

plt.figure(figsize=(10, 4))
for name, model in models.items():
    grads = check_gradients(model, x, target)
    plt.plot(grads, label=name)

plt.title('Plain Network vs ResNet Gradients')
plt.xlabel('Layer')
plt.ylabel('Gradient Norm')
plt.yscale('log')
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

Key Takeaways¶

  1. The Problem:

    • Gradients tend to vanish or explode in deep networks
    • Deeper networks suffer more from these issues (we will see next that this is due to backpropagation effects).
  2. Solutions:

    • Proper initialization (e.g., Xavier) helps maintain gradient magnitudes
    • Skip connections (Residual Networks) provide direct gradient paths
    • Other solutions include batch normalization and careful activation choice
      • We will cover batch normalization later in the course
  3. Best Practices:

    • Monitor gradient norms during training
    • Use modern architectures with skip connections for very deep networks
    • Consider gradient clipping if exploding gradients occur
      • Scales down gradient magnitudes when they exceed a threshold
      • Preserves the direction of the gradients while controlling their magnitude
      • Formula: if $\|g\|_2 > c$, then $g \leftarrow (c/\|g\|_2)g$, where:
        • $g$ is the gradient vector
        • $c$ is the clipping threshold
        • $\|g\|_2$ is the L2 norm of the gradient

7.2. MLE backpropagation example¶

The maximum log-likelihood optimization will use gradient ascent:
Let ${\bf W} = ({\bf w}^{(1,1)},{\bf w}^{(1,2)},{\bf w}^{(2)})$. Obtaining ${\bf W}$ via maximum likelihood estimation $$\begin{align*} &\frac{\partial}{\partial {\bf W}}\frac{1}{n} \sum_{i=1}^n \log p(y = y(i) | {\bf x}(i); {\bf w}^{(1,1)}, {\bf w}^{(1,2)}, {\bf w}^{(2)} ) \\ &= \frac{1}{n} \sum_{i=1}^n y(i) \frac{\partial}{\partial {\bf W}} \log \sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i))) + (1 - y(i)) \frac{\partial}{\partial {\bf W}} \log (1-\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i))))  \\ &= \frac{1}{n} \sum_{i=1}^n y(i) \frac{\frac{\partial}{\partial {\bf W}}\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i)))}{\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i)))} - (1 - y(i)) \frac{\frac{ \partial}{\partial {\bf W}} \sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i))))}{ (1-\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i))))} \\ &= \frac{1}{n} \sum_{i=1}^n \frac{\partial}{\partial {\bf W}}\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i))) \left( \frac{y(i)}{\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i)))} - \frac{1 - y(i)}{ (1-\sigma(({\bf w}^{(2)})^T {\bf h}({\bf x}(i))))} \right)  \end{align*} $$ where $\sigma(x) = \frac{\exp(x)}{1 + \exp(x)}$, and ${\bf h}({\bf x}) = (1,\hat{h}_{1,1}({\bf x}),\hat{h}_{1,2}({\bf x}))$,  $$ \hat{h}_{1,1}({\bf x}) = p(h_{1,1} = 1 | {\bf x}) = \sigma(({\bf w}^{(1,1)})^T {\bf x})   $$ and $$ \hat{h}_{1,2}({\bf x}) = p(h_{1,2} = 1 | {\bf x}) = \sigma(({\bf w}^{(1,2)})^T {\bf x})   $$

General Recursive Gradient Computation (Backpropagation)¶

Recap: MLP¶

The general architecture of a multilayer perceptron is:

  • an input layer with $n$ input-units
  • an output layer with $m$ outputs
  • and one or more hidden layers consisting of intermediate neuron outputs.
    • the superscript $(k)$ in the parameters (weights) ${\bf W}^{(k)}$ will indicate they belong to layer $k$
    • if layer $k$ has $d_\text{in}$ inputs and $d_\text{out}$ outputs, then the neuron weights ${\bf W}^{(k)}\in \mathbb{R}^{n_\text{in} \times n_\text{out}}$ are a $n_\text{in} \times n_\text{out}$ matrix
No description has been provided for this image

Forward-backward gradient computation procedure¶

More generally, for deep neural networks we have no hope of writing down gradient formula for all parameters. We need a recursive method.

  • backpropagation = recursive application of the chain rule along a computational graph to compute the gradients of all inputs/parameters/intermediates

    • Widely used implementations maintain a graph structure, where the nodes implement the forward() / backward() functions.
    • forward pass: compute result of an operation and save any intermediates needed for gradient computation in memory
    • backward pass: apply the chain rule to compute the gradient of the loss function with respect to the inputs.

    The recursion can be explained with a single image. Consider the following general algorithm to recursively compute the gradient:

  • Training data: $\{({\bf x}(1),y(1)),\ldots,({\bf x}(N),y(N))\}$

  • The activations of the hidden neurons are given by $\hat{\bf h}^{(k)} = (1,\sigma((\hat{\bf h}^{(k-1)})^T {\bf W}^{(k)}))$, $k=1,\ldots,K$, where

    • The input is $\hat{{\bf h}}^{(0)} = ({\bf x},1)$, where ${\bf x}$ is a single training example.
  • $L({\bf h}^{(K)}(i))$ is the loss of a single training example.

No description has been provided for this image

Backpropagation: Practical Challenges with Deep Models¶

Quiz 1: As we make a model deeper ($K \gg 1$), which gradient computation issues could we face?

Example: MultiLayer Perceptron (MLP) Classifier¶

Part of the code of this notebook uses the incomplete example here (the original code does not contain the bias)

First, let's create a simple dataset and split into training and testing.

In [16]:
%matplotlib inline
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
import pylab
import numpy as np

X, y = make_moons(n_samples=5000, random_state=42, noise=0.1)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42,test_size=0.3)

pylab.scatter(X[:,0], X[:,1], c=y)
pylab.show()
No description has been provided for this image

Create the Neural Network Weights and Initialize Them¶

We first define:

  • the input layer (two coordinates)
  • number of hidden layers (we will use one)
  • the number of output neurons (number of classes, two in our case)

These are all defined by defining the hidden layer matrices¶

Q1:We have only one hidden layer, how many matrices do we have?

(a) Two (b) Three (c) Four (d) One

A1: Two matrices, $W^{(1)}$ and $W^{(2)}$.

Q2: How do we initialize these matrices? What would happen if we were to initialized both $W^{(1)}$ and $W^{(2)}$ with zeros?

(a) Zeros (b) Uniform (c) Standard Normal

  • A2.1: Initialize randomly. We can use a Standard Normal distribution, for instance.
  • A2.2: Initializing with zeros would make the neurons associated with $w^{(1,1)}$ and $w^{(1,2)}$ always output the same values.
In [17]:
# There are only two features in the data X[:,0] and X[:,1]
n_feature = 2
# There are only two classes: 0 (purple) and 1 (yellow)
n_class = 2

def init_weights(n_hidden=100):
    # Initialize weights with Standard Normal random variables
    model = dict(
        W1=np.random.randn(n_feature + 1, n_hidden),
        W2=np.random.randn(n_hidden + 1, n_class)
    )

    return model

Define the nonlinear activation function (will be used in the last layer)¶

We will use the softmax function.

$$ \text{softmax}(x_i) = \frac{\exp(x_i)}{\sum_j \exp(x_j)} $$

If there are only two classes, the softmax is equivalent to the logistic function (do the math to convince yourself).

Python + Numpy tricks¶

Numpy is very handy. If we give a vector ${\bf z}$, np.exp(${\bf z}$) returns a vector with all elements of $z$ exponentiated.

If ${\bf z}$ is a vector, ${\bf z}$.sum() returns the sum of the elements in ${\bf z}$.

In [18]:
# Defines the softmax function. For two classes, this is equivalent to the logistic regression
def softmax(x):
    return np.exp(x + 1e-2) / np.exp(x + 1e-2).sum()

Define the forward pass¶

Here, we define how the neural network get an input $x$ and use the model paramters (weights) ${\bf W}^{(1)}$ and ${\bf W}^{(2)}$ and biases ${\bf b}^{(1)}$ and ${\bf b}^{(2)}$ to predict the class labels of the input

Hidden layer activation¶

From the input vector $x$ to the hidden layer neurons $h$, we need to get the intermediate value $$ {\bf z}^{(1)} = {\bf x}^T {\bf W}^{(1)} + {\bf b}^{(1)} $$ and pass it through an activation function.

Our activation function is the ReLU: $$ \text{ReLU}(z) = \begin{cases} z & ,\text{if }z > 0 \\ 0 & ,\text{if }z \leq 0 \end{cases} $$ Thus, $${\bf h} = \text{ReLU}({\bf z}^{(1)}).$$

Once we get the hidden layer values ${\bf h}$, we do $$ {\bf z}^{(2)} = {\bf h}^T {\bf W}^{(2)} + {\bf b}^{(2)} $$ and pass it through the activation of the last layer $$ \hat{\bf y} = \text{softmax}({\bf z}^{(2)}). $$

In [19]:
# For a single example $x$
def forward(x, model):
    x = np.append(x, 1)
    
    # Input times first layer matrix 
    z_1 = x @ model['W1']

    # ReLU activation goes to hidden layer
    h = z_1
    h[z_1 < 0] = 0

    # Hidden layer values to output
    h = np.append(h, 1)
    hat_y = softmax(h @ model['W2'])

    # return hidden values (for ReLUs we should really return the 
     #   pre-activation values but that makes the code more complex) and final model output
    return h, hat_y

Define backpropagation¶

Now, we need to backpropagate the derivatives of each example

The backpropagation function gets:

  • all input data $\{{\bf x}(i)\}_i$
  • corresponding hidden values of all training examples: $\{{\bf h}(i)\}_i$
  • errors of each output neuron for all training examples: $\{\hat{\bf y}(i) - {\bf y}(i)\}_i$ (this is a subtraction of two vectors)

Negative Log-likelihood of our model: Our loss function for training example $i$ is the log-likelihood of a one-hot enconding vector of the classes, $$ L(i) = - \sum_j y_j(i) \log \hat{y}_j(i) , $$ where $y_i(j)$ is the element $j$ of the vector representing the one-hot enconding of the class of training example $i$ and $\hat{y}_j(i)$ is the output of the $j$-th output neuron for training example $i$, $$ \hat{y}_j(i) = \frac{\exp(z^{(2)}_j)}{\sum_m \exp(z^{(2)}_m)}. $$

The derivative of the loss with respect to $\textbf{z}^{(2)}$ will be a vector (that we will represent using the variables without the index $j$) $$\frac{\partial L(i)}{\partial \mathbf{z}^{(2)}} = -(\hat{y}1(i) - y_1(i),\ldots,\hat{y}_{\text{n\_class}}(i) - y_{\text{n\_class}}(i)) = -(\hat{\mathbf{y}}(i) - \mathbf{y}(i))$$ Note that we can get this derivative directly from the relative error errs.

Other derivatives¶

It will compute the following derivatives for each training example:

  • The derivative of the last layer parameters are $$ \frac{\partial L(i)}{\partial {\bf W}^{(2)}} = \frac{\partial {\bf z}^{(2)}(i)}{\partial {\bf W}^{(2)}} \frac{\partial L(i)}{\partial {\bf z}^{(2)}} = {\bf h}(i)^T ({\bf y}(i) - \hat{\bf y}(i)) $$ and $$ \frac{\partial L(i)}{\partial {\bf b}^{(2)}} = \frac{\partial {\bf z}^{(2)}(i)}{\partial {\bf b}^{(2)}} \frac{\partial L(i)}{\partial {\bf z}^{(2)}} = ({\bf y}(i) - \hat{\bf y}(i)), $$ as $$ \frac{\partial {\bf z}^{(2)}(i)}{\partial {\bf b}^{(2)}} = 1. $$

  • The derivatives with respect to the hidden values of the previous layer are $$ \frac{\partial L(i)}{\partial {\bf h}} = \frac{\partial {\bf z}^{(2)}(i)}{\partial {\bf h}} \frac{\partial L(i)}{\partial {\bf z}^{(2)}} = {\bf W}^{(2)} ({\bf y}(i) - \hat{\bf y}(i)) $$

We then backpropagate $\partial L(i)/\partial {\bf h} $ to the previous layer. This will be needed in the final derivative the final derivatives are $$ \frac{\partial L(i)}{\partial {\bf W}^{(1)}} = \frac{\partial {\bf z}^{(1)}(i)}{\partial {\bf W}^{(1)}} \frac{\partial {\bf h}(i)}{\partial {\bf z}^{(1)}} \frac{\partial L(i)}{\partial {\bf h}}, $$ and $$ \frac{\partial L(i)}{\partial {\bf b}^{(1)}} = \frac{\partial {\bf z}^{(1)}(i)}{\partial {\bf b}^{(1)}} \frac{\partial {\bf h}(i)}{\partial {\bf z}^{(1)}} \frac{\partial L(i)}{\partial {\bf h}}, $$ where $$ \frac{\partial {\bf z}^{(1)}(i)}{\partial {\bf W}^{(1)}} = {\bf x}(i)^T, $$ and $$ \frac{\partial {\bf z}^{(1)}(i)}{\partial {\bf b}^{(1)}} = 1, $$ and the derivative of the ReLU $$ \frac{\partial {\bf h}(i)}{\partial {\bf z}^{(1)}} = \begin{cases} 1 &, \text{if }{\bf z}^{(1)}(i) \geq 0\\ 0 & \text{otherwise}. \end{cases}. $$

The final output are the derivatives of the parameters.

  • In the above, we have described the backpropagation algorithm per training example.
  • The following python code will, as described earlier, give all examples as inputs.
  • Thus, the input is a matrix whose rows are the vectors of each training example.

This function outputs $$ {\bf \text{d}W}^{(1)} = \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf W}^{(1)}}, $$ $$ {\bf \text{d}b}^{(1)} = \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf b}^{(1)}}, $$ $$ {\bf \text{d}W}^{(2)} = \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf W}^{(2)}}, $$ and $$ {\bf \text{d}b}^{(2)} = \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf b}^{(2)}}. $$

In [20]:
def backward(model, xs, hs, errs):
    """xs, hs, errs contain all information (input, hidden state, error) of all data in the minibatch"""
    # errs is the gradients of output layer for the minibatch
    dW2 = (hs.T @ errs)

    # Get gradient of hidden layer
    dh = errs @ model['W2'].T
    # This is not quite correct since we should consider the pre-activation value
    dh[hs <= 0] = 0
    
    # The bias "neuron" is the constant 1, we don't need to backpropagate its gradient
    # since it has no inputs, so we just remove its column from the gradient
    dh = dh[:, :-1]

    # Add the 1 to the data, to compute the gradient of W1
    xs = np.hstack([xs, np.ones((xs.shape[0], 1))])

    dW1 = (xs.T @ dh)

    return dict(W1=dW1, W2=dW2)

Perform the forward and backward procedures to get gradients¶

For each input example $i$ in the training data, perform a forward pass and:

  • store all the hidden units of all the hidden layers associated with example $i$ (we only have to store one vector of hidden values)
  • store the gradient of the error of example $i$ with respect to the prediction

Once we have store all hidden layer values and all the derivatives of all examples, we will do the backard pass and return the derivatives of the error with respect to the paramters ${\bf W}^{(1)}$, ${\bf b}^{(1)}$, ${\bf W}^{(2)}$, and ${\bf b}^{(2)}$.

In [21]:
def get_gradient(model, X_train, y_train):
    xs, hs, errs = [], [], []

    for x, cls_idx in zip(X_train, y_train):
        h, y_pred = forward(x, model)

        # Create one-hot coding of true label
        y_true = np.zeros(n_class)
        y_true[int(cls_idx)] = 1.

        # Compute the gradient of output layer
        err = y_pred - y_true

        # Accumulate the informations of the examples
        # x: input
        # h: hidden state
        # err: gradient of output layer
        xs.append(x)
        hs.append(h)
        errs.append(err)

    # Backprop using the informations we get from the current minibatch
    return backward(model, np.array(xs), np.array(hs), np.array(errs))

Define one gradient descent step¶

We now perform a single gradient descent step.

Get the gradients and perform the following updates for $N$ training examples: $$ {\bf W}^{(1)} ={\bf W}^{(1)} - \epsilon \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf W}^{(1)}}, $$ $$ {\bf b}^{(1)} ={\bf b}^{(1)} - \epsilon \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf b}^{(1)}}, $$ $$ {\bf W}^{(2)} ={\bf W}^{(2)} - \epsilon \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf W}^{(2)}}, $$ and $$ {\bf b}^{(2)} ={\bf b}^{(2)} - \epsilon \sum_{i=1}^N \frac{\partial L(i)}{\partial {\bf b}^{(2)}}, $$ where $\epsilon = 10^{-1}$ in our example.

In [22]:
def gradient_step(model, X_train, y_train, learning_rate=1e-3):
    grad = get_gradient(model, X_train, y_train)

    # Update every parameters in our networks (W1 and W2) using their gradients
    for layer in grad:
        # Learning rate: 1e-1
        model[layer] -= learning_rate * grad[layer]

    return model

Repeat gradient descent a few more times...¶

In [23]:
def gradient_descent(model, X_train, y_train, no_iter=10):
    for epoch in range(no_iter):
        
        if epoch % 10 == 0:
            print(f'Epoch {epoch}')

        model = gradient_step(model, X_train, y_train)

    print(f'Epoch {epoch}')
    return model

Optimize the model¶

We now optimize the model via gradient descent

In [24]:
no_iter = 100

# Reset model
model = init_weights()

# Train the model
model = gradient_descent(model, X_train, y_train, no_iter=no_iter)
Epoch 0
Epoch 10
Epoch 20
Epoch 30
Epoch 40
Epoch 50
Epoch 60
Epoch 70
Epoch 80
Epoch 90
Epoch 99

Let's evaluate the model on test data¶

Note that the output has two neurons for the two classes. Our prediction will chose the class corresponding to the largest output neuron value.

In [25]:
y_pred = np.zeros_like(y_test)

accuracy = 0

for i, x in enumerate(X_test):
    # Predict the distribution of label
    _, prob = forward(x, model)
    # Get label by picking the most probable one
    y = np.argmax(prob)
    y_pred[i] = y

# Accuracy of predictions with the true labels and take the percentage
# Because our dataset is balanced, measuring just the accuracy is OK
accuracy = (y_pred == y_test).sum() / y_test.size
print('Test accuracy after {} gradient steps: {}'.format(no_iter,accuracy))
Test accuracy after 100 gradient steps: 0.996

Let's visually evaluate the model on the test data¶

In [26]:
pylab.scatter(X_test[:,0], X_test[:,1], c=y_pred)
pylab.show()
No description has been provided for this image

MLP code using Pytorch¶

  • Understanding Pytorch tensors: tutorial

Step 1: Understanding Pytorch's Automatic Differentiation¶

First, we will create a variable $x \in \mathbb{R}$ and assign it value $x = 3$.

This is the wrong way to do it:

In [27]:
### The following code is intuitive but ***wrong***

import torch

x = torch.zeros(1, requires_grad=True) # Assigns a constant zero to unidimensional variable x 
                                       # requires_grad=True tells pytorch we will compute gradients for this variable

x = 3. ## Here we assign float(3.) to "x" ... which is no longer a differentiable torch tensor

print(f'Value of x = {x.data}') # Will return 1 as a tersor variable
print(f'Gradient of x = {x.grad}') # Will return None because it we need to invoke .backward() first
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[27], line 10
      6                                        # requires_grad=True tells pytorch we will compute gradients for this variable
      8 x = 3. ## Here we assign float(3.) to "x" ... which is no longer a differentiable torch tensor
---> 10 print(f'Value of x = {x.data}') # Will return 1 as a tersor variable
     11 print(f'Gradient of x = {x.grad}') # Will return None because it we need to invoke .backward() first

AttributeError: 'float' object has no attribute 'data'

This is the correct way to do it:

In [28]:
import torch

x = torch.zeros(1, requires_grad=True) # Assigns a constant zero to unidimensional variable x 
                                       # requires_grad=True tells pytorch we will compute gradients for this variable
x.data.fill_(3.)  

print(f'Value of x = {x.data}') # Will return 1 as a tersor variable
print(f'Gradient of x = {x.grad}') # Will return None because it we need to invoke .backward() first
Value of x = tensor([3.])
Gradient of x = None

Consider the following function: $$ z(x) = 10 y(x)^2, $$ where $$ y(x) = 2 x + 1. $$

Now, let's compute $$\left. \frac{\partial z}{\partial x} \right|_{x = 3}.$$

In [29]:
x = torch.zeros(1, requires_grad=True) # Assigns a constant zero to unidimensional variable x 
                                       # requires_grad=True tells pytorch we will compute gradients for this variable

x.data.fill_(3.) # Constant MUST be floating point (if the tensor is an Integer, it won't work)

y = 2 * x + 1
z = 10 * y * y
z.backward()     # automatically computes the gradient ∂z/∂x evaluated at x = 1 using backpropagation
print(x.grad)    # ∂z/∂x = 280
tensor([280.])

Step 2: MLP with Pytorch Libraries¶

We now create a 2-hidden layer Feed Forward neural network using Pytorch's libraries

class FeedForward(nn.Module):
    def __init__(self, input_size, hidden_size, output_size): ## This will also take care of initilizing the weights
        super(FeedForward, self).__init__() 
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.layer3 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        x = F.relu(self.layer1(x)) # ReLu activations in the first layer
        x = F.relu(self.layer2(x)) # ReLu activations in the second layer
        return torch.sigmoid(self.layer3(x)) # Sigmoid output
In [30]:
import torch.nn as nn
import torch.nn.functional as F

class FeedForward(nn.Module):
    def __init__(self, input_size, hidden_size, output_size): ## This will also take care of initilizing the weights
        super(FeedForward, self).__init__() 
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.layer3 = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        x = F.relu(self.layer1(x)) # ReLu activations in the first layer
        x = F.relu(self.layer2(x)) # ReLu activations in the second layer
        return torch.sigmoid(self.layer3(x)) # Sigmoid output
    

Can we use a GPU?¶

In [31]:
use_cuda = torch.cuda.is_available()  # Our flag to check if Nvidia GPU is available

device = torch.device("cuda" if use_cuda else "cpu") # Decide device between CUDA (GPU) and CPU compute

print(f'Is CUDA available? {use_cuda}')
Is CUDA available? False

Move training data into Torch tensors¶

  • Training data becomes a tensor
    • One of the tensor dimensions is the number of training examples
  • The data moves to the GPU if device = torch.device("cuda")
In [32]:
# Transform original data into pytorch tensors and send to device (send data to GPU if available)
torch_X_train = torch.FloatTensor(X_train).to(device)
torch_X_test = torch.FloatTensor(X_test).to(device)
torch_y_train = torch.FloatTensor(y_train).to(device)
torch_y_test = torch.FloatTensor(y_test).to(device)

print(f'Now data is in Pytorch tensor form: {torch_y_train}')
Now data is in Pytorch tensor form: tensor([1., 0., 0.,  ..., 1., 0., 1.])

Instantiate neural network¶

Creates a Feed Forward network with

  • 2-dimensional input
  • Two hidden layers
  • Hidden layers have no_hidden_neurons hidden neurons
  • 1-dimensional sigmoid output
  • Default weight initialization
    • Linear layer weight and bias values are initialized by sampling $\text{Uniform}(-\sqrt{k}, \sqrt{k})$, where $k = \frac{1}{\text{in\_dimension}}$
In [33]:
no_hidden_neurons = 10

## Create FeedForward network (MLP) instance from our FeedForward class
##    Send model parameters to "device" (GPU if the device is on the GPU)
MLP = FeedForward(input_size = 2, hidden_size = no_hidden_neurons, output_size = 1).to(device)

print(f'MLP neural network created: {MLP}')
MLP neural network created: FeedForward(
  (layer1): Linear(in_features=2, out_features=10, bias=True)
  (layer2): Linear(in_features=10, out_features=10, bias=True)
  (layer3): Linear(in_features=10, out_features=1, bias=True)
)

MLP prediction¶

Get current predicted training label probabilities from the MLP

In [34]:
y_pred = MLP(torch_X_train) ### Get output of FeedForward network over the training data

print(f'Predicted values of X: {y_pred}')
Predicted values of X: tensor([[0.5149],
        [0.5039],
        [0.5021],
        ...,
        [0.5183],
        [0.5019],
        [0.5155]], grad_fn=<SigmoidBackward0>)

Compute the Negative log-likelihood loss¶

  • Define the loss function (negative log-likelihood loss for unidimensional sigmoid outputs)
  • Compute the loss
In [35]:
# Define the loss function
# Negative log-likelihood loss (aka, cross-entropy loss) for binary classes
loss = nn.BCELoss() 

## Compute the loss of the predicted values
error = loss(y_pred, torch_y_train.view(-1,1)) ## .view(-1,1) avoids a warning about the tensor dimension

Use the loss to compute gradients¶

  • Computes gradients from the loss via backpropagation
    • Never forget to zero the gradient vectors first (Pytorch accumulate gradients by default)
In [36]:
# Compute the gradients of the linear layers of MLP with respect to the error
##  Gradient computation performed via backpropagation

MLP.zero_grad() ## Zero current gradients (Pytorch accumulate gradients by default)

error.backward() ## Compute gradients via backpropagation

Define the learning rate¶

  • We will revisit the effect of learning rates later
    • Very small learning rates can result in poor generalization error
    • Commonly a number between 1 and 1e-05
In [37]:
## Define learning rate
learning_rate = 1e-1

Perform one gradient step¶

  • Will subtract the (gradient * learning_rate) from all parameters
In [38]:
print(f"Before gradient step: Layer 1 bias {MLP.layer1.bias}")

## Go over all parameters and subtract their gradient
##   Subtract (not sum) the gradient since we want to minimize the loss
for f in MLP.parameters():
    f.data.sub_(f.grad.data * learning_rate)

print(f"After gradient step: Layer 1 bias {MLP.layer1.bias}")
Before gradient step: Layer 1 bias Parameter containing:
tensor([ 0.4772,  0.1184, -0.5378, -0.5673,  0.3518, -0.5260, -0.0871,  0.3392,
        -0.3273, -0.0771], requires_grad=True)
After gradient step: Layer 1 bias Parameter containing:
tensor([ 0.4772,  0.1197, -0.5378, -0.5673,  0.3516, -0.5260, -0.0876,  0.3393,
        -0.3273, -0.0755], requires_grad=True)

Optimize the model¶

  • We will now perform 1000 optimization steps using the entire dataset
    • Epoch: Each time the entire dataset is used in the optimization
  • It is useful to plot the training accuracy
In [39]:
## Loop through multiple gradient steps

for epoch in range(1000):
    ## Predict values using updated model
    y_pred = MLP(torch_X_train)
    
    ## Find predicted class (as a number {1,0})
    pred = y_pred.gt(0.5) + 0.0
    
    # Compute accuracy
    if epoch % 100 == 9:
        correct = pred.eq(torch_y_train.view_as(pred)).sum().item()
        print(f'Epoch {epoch} training accuracy: {int(correct/torch_y_train.shape[0] * 100)}%')

    ## Compute the new error
    error = loss(y_pred, torch_y_train.view(-1,1)) ## .view(-1,1) avoids a warning about the tensor dimension
    
    MLP.zero_grad() ## Zero current gradients (Pytorch accumulate gradients by default)

    error.backward() ## Compute gradients via backpropagation
    
    ## Go over all parameters and subtract their gradient
    for f in MLP.parameters():
        f.data.sub_(f.grad.data * learning_rate)

## Final train accuracy
if epoch % 100 == 9:
    correct = pred.eq(torch_y_train.view_as(pred)).sum().item()
    print(f'Correct {int(correct/torch_y_train.shape[0] * 100)}%')
Epoch 9 training accuracy: 63%
Epoch 109 training accuracy: 83%
Epoch 209 training accuracy: 90%
Epoch 309 training accuracy: 93%
Epoch 409 training accuracy: 95%
Epoch 509 training accuracy: 98%
Epoch 609 training accuracy: 99%
Epoch 709 training accuracy: 99%
Epoch 809 training accuracy: 99%
Epoch 909 training accuracy: 99%

Extra: Weight initialization (we will revisit this when we talk about the optimization)¶

In [40]:
## Try different weight initializations of the linear layers
## Not needed, but you can apply a different initialization of the weights before optimizing

def init_weights(layer):
    if type(layer) == nn.Linear:
        torch.nn.init.normal_(layer.weight)
        layer.bias.data.fill_(0.01)

MLP.apply(init_weights) ## Function apply will go over all layers
Out[40]:
FeedForward(
  (layer1): Linear(in_features=2, out_features=10, bias=True)
  (layer2): Linear(in_features=10, out_features=10, bias=True)
  (layer3): Linear(in_features=10, out_features=1, bias=True)
)

References¶

  • D. Rumelhart, G. Hinton, and R. Williams. Learning internal representations by error propagation. Parallel Distributed Processing. Vol 1: Foundations. MIT Press, Cambridge, MA, 1986.
  • P. Vincent, H. Larochelle, Y. Bengio, and P. Manzagol. Extracting and composing robust features with denoising autoencoders. International Conference on Machine Learning, 2008.