Optimization Fundamentals, Multivariable Calculus for Neural Networks, and PyTorch Implementation

Generative Processes, Inductive Bias, and Machine Learning Fundamentals

  • Generative Processes in Machine Learning:

    • Machine learning operates under the core assumption that observed data is produced by an underlying generative process.
    • A generative process can be framed as a mathematical mapping or equation that generates input-output pairs (x,y)(x, y).
    • Concrete Example: Consider a baseline generative equation given by:         y=2x+1y = 2x + 1
    • Evaluating this generative process at specific input points yields dataset pairs:
      • For x=1x = 1: y=2(1)+1=3→(1,3)y = 2(1) + 1 = 3 \rightarrow (1, 3)
      • For x=−1x = -1: y=2(−1)+1=−1→(−1,−1)y = 2(-1) + 1 = -1 \rightarrow (-1, -1)
    • The primary objective of machine learning is to uncover, learn, or approximate this generative process strictly from observed data pairs (x,y)(x, y).
  • Inductive Bias and Model Families:

    • Inductive Bias: The set of assumptions a learning algorithm uses to predict outputs for unseen inputs. In model selection, this manifests as choosing a specific hypothesis space or family of models.
    • Model Family Definition: Rather than searching through all possible mathematical functions, an inductive bias assumes the generative process belongs to a specific parametric family, such as linear models:         y=ax+by = ax + b
    • Parameters: The variables aa (slope/weight) and bb (intercept/bias) define the parameters of the model family. Every unique parameter configuration (a,b)(a, b) yields a distinct model within the family.
  • Exact Optimization via Algebraic Systems:

    • When data is perfectly noiseless and generated by a simple model family, parameters can be derived analytically by setting up a system of equations.
    • Plugging the training pairs (1,3)(1, 3) and (−1,−1)(-1, -1) into the parameterized equation y=ax+by = ax + b yields:         3=a(1)+b→a+b=33 = a(1) + b \rightarrow a + b = 3−1=a(−1)+b→−a+b=−1-1 = a(-1) + b \rightarrow -a + b = -1
    • Solving this linear system yields exact optimal parameter values: a=2a = 2 and b=1b = 1.
    • Finding model parameters in this exact algebraic fashion is referred to interchangeably as direct solving or exact optimization.
  • Real-World Failures of Exact Algebraic Solving:

    • Observation Noise: Real-world data rarely originates from pure mathematical formulas without corruption. Data points naturally contain random noise, measurement errors, or faulty sensor readings.
    • Model Invalidation / Mismatch: The assumed inductive bias rarely captures the true underlying phenomenon perfectly. For complex domains (e.g., audio, raw video, high-resolution imagery), an exact, simple generative process does not exist or cannot be expressed via elementary mathematical families.
    • Need for Iterative Learning: Because exact systems of equations become inconsistent or unsolvable under noise and structural model mismatch, machine learning replaces direct equation solving with an iterative learning process.
  • The Machine Learning Iterative Process:

    1. Model Initialization: Establish an arbitrary starting parameter set. For instance, initialize parameters to a=1a = 1 and b=1b = 1, yielding current model:         y=x+1y = x + 1
    2. Inference/Prediction: Compute predicted labels yˉ\frac{}{}\bar{y} (or yhat\frac{}{}\frac{}{\text{y}}\text{hat} / y\frac{}{}\frac{}{\text{y}} denoted as predictions\frac{}{}\text{predictions}) for target input points xx using current parameter settings.
    3. Error Evaluation: Quantify discrepancies between predicted values predictions\frac{}{}\text{predictions} and ground truth target values yy.
    4. Parameter Updates: Adjust parameters aa and bb iteratively to decrease prediction error.
  • Mathematical Error Formulation:

    • Prediction error for a single data point is frequently quantified using the Squared Error:         Errori=(Predictioni−yi)2\text{Error}_i = (\text{Prediction}_i - y_i)^2
    • Evaluating current model y=x+1y = x + 1 (a=1,b=1a = 1, b = 1) on training data:
      • For (x1,y1)=(1,3)(x_1, y_1) = (1, 3): Prediction yˉ1=1(1)+1=2\frac{}{}\bar{y}_1 = 1(1) + 1 = 2. Squared error term: (2−3)2=1(2 - 3)^2 = 1
      • For (x2,y2)=(−1,−1)(x_2, y_2) = (-1, -1): Prediction yˉ2=1(−1)+1=0\frac{}{}\bar{y}_2 = 1(-1) + 1 = 0. Squared error term: (0−(−1))2=1(0 - (-1))^2 = 1
    • Error as a Function of Parameters: Because data points (x,y)(x, y) are fixed observations, the total error function depends exclusively on parameters aa and bb:         E(a,b)=(a(1)+b−3)2+(a(−1)+b−(−1))2E(a, b) = (a(1) + b - 3)^2 + (a(-1) + b - (-1))^2E(a,b)=(a+b−3)2+(−a+b+1)2E(a, b) = (a + b - 3)^2 + (-a + b + 1)^2

Optimization Landscapes and Loss Minimization

  • The Loss Landscape Surface:

    • The loss landscape represents the total loss or error as a continuous surface over parameter space.
    • For a two-parameter model, the parameter space is defined by axes aa and bb, with the vertical axis representing total error/loss E(a,b)E(a, b).
    • Every parameter configuration (a,b)(a, b) maps to a single point on this 3D landscape.
    • Goal of Optimization: Navigate from an arbitrary initial point on the surface to the lowest vertical point (minimum loss).
  • The Foggy Landscape Metaphor and Local Information:

    • Optimization algorithms do not possess a global top-down map of the loss surface. An optimization algorithm behaves like an agent standing on a landscape shrouded in dense fog.
    • The agent cannot see where the global minimum lies; it can only measure the local slope (gradient) of the ground immediately beneath its feet.
    • To decrease elevation (loss) as rapidly as possible, the agent must step in the direction of steepest local descent.
  • Gradient Computation and Parameter Updates:

    • The gradient vector ∇E(a,b)\nabla E(a, b) contains partial derivatives of the error function with respect to each model parameter:         \nabla E(a, b) = \begin{pmatrix} \frac{\theta E}{\theta a} \\ \frac{\theta E}{\theta b} \theta \text{end}{pmatrix}
    • Analytical derivatives for the simple linear model error function:         θEθa=2(a+b−3)(1)+2(−a+b+1)(−1)\frac{\theta E}{\theta a} = 2(a + b - 3)(1) + 2(-a + b + 1)(-1)θEθb=2(a+b−3)(1)+2(−a+b+1)(1)\frac{\theta E}{\theta b} = 2(a + b - 3)(1) + 2(-a + b + 1)(1)
    • Substituting current parameter values (a=1,b=1a = 1, b = 1) yields concrete scalar numerical values for gradients.
    • Gradient Descent Update Equations:         anew=aold−ρθEθaa_{\text{new}} = a_{\text{old}} - \rho \frac{\theta E}{\theta a}bnew=bold−ρθEθbb_{\text{new}} = b_{\text{old}} - \rho \frac{\theta E}{\theta b}         where ρ\rho represents the learning rate (or step size).
  • Key Operational Properties of Optimization:

    • Bypassing Symbolic Computation: Optimization solvers do not require symbolic algebraic expressions for gradients. Algorithms only require numerical evaluations of derivatives at current parameter points. Auto-differentiation via backpropagation executes this directly.
    • Mini-Batching: Large datasets cannot fit into single gradient calculations. Datasets are partitioned into subsets called batches.
      • An update step performed on a single batch is a single gradient descent iteration.
      • An Epoch represents one complete pass over all mini-batches in the full dataset.
    • Stochastic Gradient Descent (SGD) and Shuffling: In SGD, mini-batches must be randomly shuffled prior to each epoch to break data ordering biases and improve optimization dynamics.
    • Adaptive Learning Rates: Step size ρ\rho does not need to remain static. Schedules can decrease ρ\rho as parameter updates approach minima, or modern adaptive optimizers can automatically adjust learning rates per parameter.
  • Convex vs. Non-Convex Landscapes & The Mystery of Generalization:

    • Small/Linear Models: Feature a convex loss surface shaped like a bowl. Convex landscapes possess a single global minimum, guaranteeing convergence.
    • High-Dimensional/Deep Models: Millions or billions of parameters form non-visualizable, highly non-convex loss surfaces populated by complex geometries, saddle points, and numerous local minima.
    • The Trap of Local Minima: Standard gradient descent algorithms can become trapped in local minima, failing to reach the absolute global minimum.
    • Mystery of Generalization: Despite getting trapped in local minima on complex non-convex training surfaces, deep learning models consistently demonstrate strong generalization performance on novel, unseen data points. Understanding why overparameterized networks generalize well despite local optimization traps remains an active area of theoretical machine learning research.

Differential Calculus for Scalar and Vector Functions

  • Scalar Input to Scalar Output Function:

    • Let f:R→Rf: \text{R} \rightarrow \text{R} take scalar input w ∈ Rw \text{ ∈ } \text{R} and yield scalar output y ∈ Ry \text{ ∈ } \text{R}.
    • The derivative dfdw\frac{df}{dw} represents the instantaneous rate of change (speed) of ff at point ww
    • First-order linear approximation for a small perturbation Δw\text{Δ} w:         ynew≈f(w)+Δw×dfdwy_{\text{new}} \text{≈} f(w) + \text{Δ} w \times \frac{df}{dw}
  • Multi-Scalar Input to Scalar Output Function:

    • Let function f(w1,w2)f(w_1, w_2) take two distinct scalar inputs w1,w2 ∈ Rw_1, w_2 \text{ ∈ } \text{R} and return a scalar output y ∈ Ry \text{ ∈ } \text{R}.
    • Partial derivative θfθw1\frac{\theta f}{\theta w_1} measures output change along the w1w_1 direction while holding w2w_2 fixed as a constant.
    • Partial derivative θfθw2\frac{\theta f}{\theta w_2} measures output change along the w2w_2 direction while holding w1w_1 fixed as a constant.
    • First-order linear approximation for small simultaneous updates Δw1\text{Δ} w_1 and Δw2\text{Δ} w_2:         ynew≈f(w1,w2)+Δw1θfθw1+Δw2θfθw2y_{\text{new}} \text{≈} f(w_1, w_2) + \text{Δ} w_1 \frac{\theta f}{\theta w_1} + \text{Δ} w_2 \frac{\theta f}{\theta w_2}
  • Vector Input to Scalar Output Function:

    • Let function f(w)f(\text{w}) accept a single vector variable w ∈ RK×1\text{w} \text{ ∈ } \text{R}^{K \times 1} formatted as a column vector:         \text{w} = \begin{pmatrix} w_1 \\ w_2 \\ \text{∦} \\ w_K \text{end}{pmatrix}
    • The derivative of scalar-valued function ff with respect to column vector w\text{w} is defined as a row vector of partial derivatives:         \frac{\theta f}{\theta \text{w}} = \begin{pmatrix} \frac{\theta f}{\theta w_1} & \frac{\theta f}{\theta w_2} & \text{⋯} & \frac{\theta f}{\theta w_K} \text{end}{pmatrix}
    • Linear output approximation under vector perturbation Δw\text{Δ} \text{w} (where Δw\text{Δ} \text{w} is a K×1K \times 1 column vector):         ynew≈f(w)+θfθwΔwy_{\text{new}} \text{≈} f(\text{w}) + \frac{\theta f}{\theta \text{w}} \text{Δ} \text{w}
    • Dimensional Consistency Check: The term θfθwΔw\frac{\theta f}{\theta \text{w}} \text{Δ} \text{w} represents an inner product between a 1×K1 \times K row vector and a K×1K \times 1 column vector, yielding a scalar output shift.
  • Vector Input to Vector Output Function (The Jacobian Matrix):

    • Let function f:RK→RJ\text{f}: \text{R}^K \rightarrow \text{R}^J accept input vector w ∈ RK×1\text{w} \text{ ∈ } \text{R}^{K \times 1} and return output vector y ∈ RJ×1\text{y} \text{ ∈ } \text{R}^{J \times 1}.
    • Real-World Example: Common in artificial neural network layers, such as applying an element-wise activation function (e.g., Sigmoid) across a feature vector.
    • Dimensions KK (input length) and JJ (output length) do not need to be equal.
    • The derivative of a vector-to-vector function is a matrix called the Jacobian Matrix (J ∈ RJ×K\text{J} \text{ ∈ } \text{R}^{J \times K}):         \text{J} = \frac{\theta \text{f}}{\theta \text{w}} = \begin{pmatrix} \frac{\theta f_1}{\theta w_1} & \frac{\theta f_1}{\theta w_2} & \text{⋯} & \frac{\theta f_1}{\theta w_K} \\ \frac{\theta f_2}{\theta w_1} & \frac{\theta f_2}{\theta w_2} & \text{⋯} & \frac{\theta f_2}{\theta w_K} \\ \text{∦} & \text{∦} & \text{⋱} & \text{∦} \\ \frac{\theta f_J}{\theta w_1} & \frac{\theta f_J}{\theta w_2} & \text{⋯} & \frac{\theta f_J}{\theta w_K} \text{end}{pmatrix}
    • Row jj of the Jacobian matrix corresponds to the row-vector derivative of output scalar component fjf_j with respect to full input vector w\text{w}.
    • Linear output vector approximation under perturbation vector Δw\text{Δ} \text{w}:         ynew≈f(w)+JΔw\text{y}_{\text{new}} \text{≈} \text{f}(\text{w}) + \text{J} \text{Δ} \text{w}
    • Dimensional Consistency Check: Matrix-vector multiplication of Jacobian J ∈ RJ×K\text{J} \text{ ∈ } \text{R}^{J \times K} and column vector Δw ∈ RK×1\text{Δ} \text{w} \text{ ∈ } \text{R}^{K \times 1} yields updated vector shift of dimension J×1J \times 1.

Multivariable Chain Rule and Vector Backpropagation

  • Scalar Chain Rule:

    • For composite scalar mapping x→f(x)→z=g(f(x))x \rightarrow f(x) \rightarrow z = g(f(x)) where x,f,z ∈ Rx, f, z \text{ ∈ } \text{R}:         dzdx=dzdf×dfdx\frac{dz}{dx} = \frac{dz}{df} \times \frac{df}{dx}
    • Conceptually, total speed is the product of intermediate speeds.
  • Vectorized Chain Rule for Neural Networks:

    • Consider a neural network graph: input parameter vector w ∈ RK×1\text{w} \text{ ∈ } \text{R}^{K \times 1}, layer mapping vector f(w) ∈ RJ×1\text{f}(\text{w}) \text{ ∈ } \text{R}^{J \times 1}, and final scalar loss output z ∈ R1×1z \text{ ∈ } \text{R}^{1 \times 1}.
    • Goal: Calculate derivative of scalar loss zz with respect to initial parameter vector w\text{w}. Because zz is scalar and w\text{w} is vector, derivative θzθw\frac{\theta z}{\theta \text{w}} must be a 1×K1 \times K row vector.
    • Applying scalar chain rule ordering directly breaks linear algebra matrix product rules (matrix×row vector\text{matrix} \times \text{row vector} is undefined).
    • Correct Vectorized Chain Rule Formulation:         θzθw=θzθf×θfθw\frac{\theta z}{\theta \text{w}} = \frac{\theta z}{\theta \text{f}} \times \frac{\theta \text{f}}{\theta \text{w}}
    • Dimensional Verification:
      • θzθf\frac{\theta z}{\theta \text{f}} is a 1×J1 \times J row vector (derivative of scalar loss with respect to vector layer output).
      • θfθw\frac{\theta \text{f}}{\theta \text{w}} is the J×KJ \times K Jacobian matrix.
      • Product: (1×J)×(J×K)→1×K(1 \times J) \times (J \times K) \rightarrow 1 \times K row vector.
  • Backpropagation as Chain Rule Execution:

    • Backpropagation evaluates gradients by starting at the scalar output loss zz, computing its gradient with respect to the final layer f\text{f}, and multiplying backward by intermediate Jacobian matrices to reach input parameters w\text{w}.
    • This sequence extends directly to arbitrarily deep tensor-to-tensor operations in deep networks.
  • Computational Efficiency of Vector-Jacobian Products (VJP):

    • Suppose a neural network layer maps input vector of dimension 1,000,0001,000,000 to output vector of dimension 1,000,0001,000,000
    • The explicit Jacobian matrix θfθw\frac{\theta \text{f}}{\theta \text{w}} contains 1,000,000×1,000,000=10121,000,000 \times 1,000,000 = 10^{12} (1 trillion) entries, creating prohibitive memory footprint and compute bounds.
    • Key Insight: Backpropagation never explicitly constructs or stores full Jacobian matrices.
    • Instead, autograd frameworks evaluate the Vector-Jacobian Product (VJP) directly: multiplying incoming row vector θzθf\frac{\theta z}{\theta \text{f}} directly through layer mathematical operations, returning target gradient row vector θzθw\frac{\theta z}{\theta \text{w}} efficiently.

PyTorch Automatic Differentiation (Autograd) Architecture

  • Basic Autograd Workflow on Scalars:

    • Tensors initialized with requires_grad=True register operations into PyTorch computational graphs for automatic gradient tracking.
    • Code Example: python import torch x = torch.tensor(2.0, requires_grad=True) y = torch.tensor(3.0, requires_grad=True) f = 3 * x**3 - y**2         
    • Executing f.backward() triggers reverse-mode autograd.
    • Gradient values are accumulated directly into .grad properties:
      • x.grad evaluates analytical derivative θfθx=9x2\frac{\theta f}{\theta x} = 9x^2. At x=2.0x=2.0: 9(2.0)2=36.09(2.0)^2 = 36.0.
      • y.grad evaluates analytical derivative θfθy=−2y\frac{\theta f}{\theta y} = -2y. At y=3.0y=3.0: −2(3.0)=−6.0-2(3.0) = -6.0.
  • Vector Derivatives & Explicit Vector-Jacobian Evaluation:

    • When output tensor f is non-scalar (e.g., a vector), calling f.backward() directly raises a RuntimeError because PyTorch autograd requires a scalar start point to initialize backward seed gradients.
    • To evaluate gradients of a vector-to-vector function, a gradient matching tensor t must be provided as an argument to backward: f.backward(gradient=t).
    • This computes vector-Jacobian product tTJt^T \text{J}, yielding parameter gradients along direction vector t.
  • Leaf Tensors vs. Non-Leaf Tensors:

    • Leaf Tensors: User-created tensors or model parameters directly declared at graph boundary (e.g., inputs x,yx, y). requires_grad attributes are preserved, and .grad attributes are populated upon calling .backward().
    • Non-Leaf Tensors: Intermediate calculated tensors (e.g., f). PyTorch frees intermediate non-leaf node gradients automatically after .backward() to optimize memory usage. Attempting to inspect f.grad returns None unless f.retain_grad() is explicitly registered.
  • Graph Operators and Custom Mathematical Expressions:

    • Autograd can differentiate complex compositions of non-linear trigonometric operations:         f(x, y) = 3 \text{ ∏} \text{cos}(x) - \text{sin}^2(y)
    • Rule of Operator Consistency: Operations must use PyTorch native library calls (e.g., torch.cos(), torch.sin()) to remain traceable in autograd computation graphs. Using NumPy math functions breaks computational graphs.
    • Standard algebraic operators (+, -, *, /, **) operate seamlessly across PyTorch objects.
    • Setting requires_grad=False on specific input parameters freezes parameter updates, disabling gradient allocation during training passes.

PyTorch Model Building and Training Paradigms

  • Data Prep, Devices, and Bit-Precision Defaults:

    • Device assignment: Select CUDA GPU execution when available, falling back to CPU execution (device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')).
    • Precision Contrast: Standard CPU arrays (NumPy) default to 64-bit double precision (float64). PyTorch GPU tensor operations default to 32-bit single precision (torch.float32 / Float.Tensor) to leverage tensor core compute efficiency.
  • Dynamic Computation Graphs (DAGs):

    • PyTorch constructs Dynamic Directed Acyclic Graphs (DAGs) on-the-fly during execution.
    • Node representation: Leaf variables map to inputs/weights; intermediate nodes represent mathematical operations (Addition, Multiplication, Powers).
    • Graph visualization tools (e.g., torchviz.make_dot) inspect compiled autograd execution traces dynamically.
  • Progression of Optimization Implementations in PyTorch:

    • Level 1: Manual NumPy Implementation:         Explicit loop calculating manual predictions, explicit scalar loss, explicit analytical gradient formulas, and manual scalar updates.

    • Level 2: Manual Autograd with torch.no_grad(): python loss = loss_fn(y_hat, y) loss.backward() with torch.no_grad(): a -= learning_rate * a.grad b -= learning_rate * b.grad a.grad.zero_() b.grad.zero_()         

      • with torch.no_grad(): ensures parameter update math is omitted from autograd tracking graph.
      • grad.zero_() is mandatory; without it, PyTorch accumulates gradients on subsequent backward passes.
    • Level 3: PyTorch Optimizers & Built-in Losses: ```python optimizer = torch.optim.SGD([a, b], lr=learning_rate) loss_fn = torch.nn.MSELoss()

      Training step:

      loss = loss_fn(y_hat, y) loss.backward() optimizer.step() optimizer.zero_grad()         ```

      • optimizer.step() automates parameter update mechanics across assigned parameters.
      • optimizer.zero_grad() flushes accumulated gradients clean across all optimizer parameters concurrently.
    • Level 4: Object-Oriented Subclassing via nn.Module: ```python class ManualLinearRegression(torch.nn.Module): def init(self): super().init() self.linear = torch.nn.Linear(in_features=1, out_features=1)

      def forward(self, x):
          return self.linear(x)
      

              ```

      • Custom architectures subclass torch.nn.Module.
      • Layer weights are instantiated inside __init__() (e.g., nn.Linear(1, 1) containing weights aa and bias bb).
      • Forward inference path is implemented inside forward(self, x).
  • Encapsulated Functional train_step Abstraction: python def make_train_step(model, loss_fn, optimizer): def perform_train_step(x, y): model.train() y_hat = model(x) loss = loss_fn(y_hat, y) loss.backward() optimizer.step() optimizer.zero_grad() return loss.item() return perform_train_step     

PyTorch Data Management: Datasets, DataLoaders, and Validation Protocols

  • PyTorch Dataset Abstraction:

    • Dataset objects centralize data storage, indexing, and transformations.
    • TensorDataset: Simple wrapper binding features and labels directly: python train_data = torch.utils.data.TensorDataset(x_tensor, y_tensor)         
    • Custom Dataset Class: Built by subclassing torch.utils.data.Dataset and implementing three required methods:
      1. __init__(self, ...): Initialize data sources.
      2. __len__(self): Return total dataset length.
      3. __getitem__(self, index): Fetch specific sample pair at integer index.
  • PyTorch DataLoader Iterator:

    • DataLoader wraps a Dataset object to automate mini-batching, memory streaming, and shuffling: python train_loader = torch.utils.data.DataLoader( dataset=train_data, batch_size=16, shuffle=True )         
    • Memory Streaming: Loads mini-batches from system storage to RAM sequentially, preventing out-of-memory crashes caused by loading full datasets to GPU memory.
    • Batch Loop Iteration Structure: python for epoch in range(num_epochs): for x_batch, y_batch in train_loader: x_batch = x_batch.to(device) y_batch = y_batch.to(device) # Run train step on batch...         
  • Data Splitting and Validation Protocols:

    • Data Partitioning: Splitting dataset into training and validation sets using random_split: python train_dataset, val_dataset = torch.utils.data.random_split(dataset, [80, 20]) train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=16, shuffle=False)         
    • Strict Evaluation Protocol Requirements:
      1. Switch model context: model.eval(). Disables training layers like Dropout or Batch Normalization.
      2. Disable autograd graph construction: with torch.no_grad():. Suppresses gradient tracking overhead, freeing GPU VRAM.
      3. Execute validation forward pass over val_loader mini-batches without invoking .backward() or optimizer.step().
      4. Reset model context: Switch back to model.train() before initiating subsequent training epochs.