
Source: AIML.com Research
Analogy: If you are trying to find the bottom of a dark valley (minimum loss), AutoGrad is like feeling the slope of the ground under your feet at every step. It doesn’t tell you where the bottom is, but it tells you which way is “down,” allowing you to eventually reach your destination by consistently stepping in that direction.
Training a deep neural network is fundamentally an optimization problem: the model must adjust millions of parameters so that its predictions minimize a loss function. In our analogy, this is the traveler trying to descend the valley. To move intelligently, the traveler needs to feel the slope under their feet: which means to compute gradients, which quantify how much each weight influences the final error.
During the forward pass, input data flows through the network to produce an output and a corresponding loss. This is equivalent to taking a single step forward and checking your current height in the valley. During the backward pass, backpropagation applies the chain rule of calculus to propagate that error backward through every operation, producing partial derivatives for each parameter. This is the exact moment when the traveler feels the ground and senses which direction slopes downward. These gradients are what allow learning to occur; without them, the model is wandering blindly, unable to tell whether a step improves or worsens its position.
Autograd
AutoGrad (automatic differentiation) is the engine that makes this entire journey practical at scale. Rather than requiring developers to manually derive and implement gradient equations for every operation, AutoGrad dynamically builds a computational graph during the forward pass and automatically computes exact derivatives during the backward pass. In the valley analogy, AutoGrad is the reliable mechanism that always tells you the slope beneath your feet no matter how uneven or complex the terrain becomes.
In contrast to traditional, manual gradient calculation (where even small architectural changes require re-deriving long and error-prone derivative chains), AutoGrad removes human error, supports arbitrarily complex models, and enables rapid experimentation. This automation forms the mathematical core of modern deep learning frameworks such as PyTorch and JAX, ensuring that each step downhill is computed accurately and efficiently.
Key Characteristics and Working of an AutoGrad Engine
The working of an AutoGrad engine can be broken down into the following core components, each corresponding to how the traveler understands and navigates the valley.
1. The Value Object (The Wrapper)
To track gradients, the engine wraps raw numbers in a data structure, called a Value object. This object stores:
- Data: The actual numerical value (your current height at a specific point).
- Grad: The derivative of the final output with respect to this value—how steep the slope is at this point.
- _prev: References to the “previous steps” that led here, forming the path taken.
- _op: The operation that produced this value (the type of step taken).
This structure ensures that every step remembers where it came from and how steep it felt.
2. The Forward Pass
During the forward pass, the engine builds a mathematical expression graph. If you add or multiply two Value objects, the engine creates a new Value that remembers its parents. In the analogy, this is the traveler taking a step and mentally noting how they got there. By the time the loss is computed, the engine has a complete map of the path taken through the valley (even though the traveler still cannot see the full terrain).
3. The Backward Pass (Backpropagation)
Once the final output (typically the loss) is computed, the backward pass begins. This process walks backward through the graph, computing gradients for every node. Conceptually, this is the traveler retracing their steps and asking: “How much did this particular step contribute to my current height?” Each gradient answers exactly that question.
4. The Chain Rule: Knowing the Direction
The chain rule is the engine’s “secret sauce” and the heart of how direction is determined. If a car travels twice as fast as a bicycle, and the bicycle travels four times as fast as a walking person, then the car moves 2×4=8 times as fast as the walker.
In AutoGrad terms, we multiply:
- the local derivative (how steep the ground is under one step), by
- the global derivative (how much the final loss changes overall).
This tells us the true direction to move next. Each gradient update is one careful step downhill.
Local vs. Global Minima: When “Good Enough” Is Enough
Ideally, the traveler reaches the global minimum (the deepest point in the valley). But in real landscapes (and real loss surfaces), there are many local minima: smaller dips that are not the absolute lowest point. Gradient-based methods, guided by AutoGrad, follow the slope they feel locally. Sometimes this leads to the global bottom; sometimes it leads to a local one.
Crucially, in deep learning, a local minimum is often good enough. The goal is not perfect terrain awareness, but consistent downhill progress. AutoGrad ensures that every step is informed, directional, and grounded in the true slope beneath the model’s feet.
Explaining AutoGrad via a Mathematical Example
To understand how AutoGrad works under the hood, let us look at a simple expression graph where:
- Step 1: The Inputs
Let a = 1.5, b = 4.0, c = -5.0, and f = 3.0.
- Step 2: Forward Pass
e = a × b = 6.0
d = e + c = 1.0
L = d × f = 3.0
- Step 3: Initializing Gradients
We start at L. The derivative of L with respect to L is naturally 1.0.
- Step 4: Backward Pass (Manual Calculation)
Through Multiplication (L = d × fL ): The local derivative of a product with respect to one input is simply the other input. Thus, the gradient for f is d (which is 1.0), and the gradient for d is f (which is 3.0).
Through Addition (d = e + c): A plus node acts as a “distributor” of gradients. Since the local derivative of a sum is 1.0, the gradient of ddd (3.0) is multiplied by 1.0 and passed to both e and c.
- Final Result: Through this process, AutoGrad determines exactly how wiggling a or b affects the final value L.

Source: AIML.com Research
Application in Neural Networks: The Neuron
Neural networks are simply large mathematical expressions. A single neuron follows the same AutoGrad principles:
- Inputs (x) are multiplied by Weights (w).
- A Bias (b) is added to the sum.
- The result passes through an Activation Function (like tanh or ReLU) to squash the output.
Formula:
AutoGrad calculates the gradient of the Loss with respect to the Weights (w) and Bias (b). This tells the optimizer whether to increase or decrease a specific weight to make the network more accurate.
Operation Behavior Table

The Training Loop: Putting AutoGrad to Work
In a production environment, AutoGrad is used within a Training Loop consisting of several stages:
- Forward Pass: Feed data into the model to get a prediction.
- Loss Calculation: Compare the prediction to the ground truth (e.g., using Mean Squared Error) to get a single “loss” number.
- Zero Grad: This is a crucial step. Gradients must be reset to zero before the backward pass, or they will accumulate (add up) from previous iterations, causing incorrect updates. ( In most deep learning frameworks (e.g., PyTorch), gradients are accumulated by default rather than overwritten. This design enables advanced techniques such as gradient accumulation across multiple mini-batches to simulate larger batch sizes. However, during standard training, gradients must be explicitly cleared (e.g., optimizer.zero_grad()) before each backward pass to ensure that parameter updates reflect only the current batch.)
- Backward Pass: Call .backward() on the loss to calculate all gradients via AutoGrad.
- Update (Gradient Descent): Nudge the weights in the opposite direction of the gradient (because we want to decrease loss) by a small step size or learning rate.
Computational Graphs
AutoGrad becomes truly special once you understand how it turns an entire neural network into a simple computation graph. At its core, every model (no matter the complexity) can be decomposed into a sequence of very basic operations: additions, multiplications, matrix multiplies, and nonlinear activations. AutoGrad doesn’t care whether those operations represent a tiny linear regression model or a trillion-parameter LLM. It represents them all the same way: as a directed acyclic graph (DAG) where nodes are values and edges are operations. This abstraction is powerful because it reduces “learning” to navigating a graph rather than solving a massive symbolic math problem.
What Sets it Apart
What makes AutoGrad different from a traditional gradient calculator is not that it knows calculus better but it’s that it remembers how the computation happened. During the forward pass, AutoGrad dynamically builds this graph as the program runs. Each node stores not only a value, but also how it was computed and which nodes contributed to it. A traditional gradient calculator might tell you how to differentiate a fixed equation, but AutoGrad can differentiate any computation you actually executed, even if the structure of that computation depends on data, conditionals, loops, or runtime decisions. This ability to differentiate programs, not just equations, is what sets AutoGrad apart.
Importantly, AutoGrad does not “infer” the loss function in a semantic sense. It doesn’t know what your loss means. Instead, it treats the loss as just another node at the end of the graph. As long as the loss is constructed from differentiable operations, AutoGrad can compute gradients for it automatically. This means you never need to manually derive gradients for new loss functions. Want to invent a custom loss tomorrow? As long as it’s differentiable, AutoGrad will handle it without any additional math from you. If an operation is non-differentiable (or only piecewise differentiable), AutoGrad can only propagate gradients where derivatives exist. This is why most learning relies on differentiable approximations.
Implications
This graph-based approach is the real breakthrough. Before AutoGrad, changing a model architecture or loss function often meant re-deriving gradient equations by hand (a slow, error-prone process that severely limited experimentation). AutoGrad removes this bottleneck entirely. You write the forward computation once, and the backward computation emerges automatically from the graph. That’s why the same mechanism works for a 41-parameter toy model and a massive language model: the scale changes, but the graph logic does not.
In the valley analogy, AutoGrad isn’t just feeling the slope but it is also remembering exactly how you got to your current position, so it can tell you how each individual step contributed to where you are now. That memory, encoded in the computation graph, is what allows learning to scale from simple equations to modern deep learning systems.
Scalar vs. Tensor Engines
While pedagogical tools like micrograd operate on individual scalars (single numbers), production libraries like PyTorch use Tensors. Tensors are n-dimensional arrays of scalars.
The math behind AutoGrad remains identical whether using scalars or tensors. The shift to tensors is purely for efficiency. By packaging scalars into large arrays, computers can use parallelism (running many operations at once) to speed up training by orders of magnitude. This hardware acceleration, primarily through GPUs, is what allows for the training of massive models like GPT, which contain billions or even trillions of parameters.
Conclusion
AutoGrad is the invisible machinery that allows machines to learn. By representing complex neural architectures as simple graphs of additions, multiplications, and activations, AutoGrad provides a systematic way to calculate the sensitivity of the final output to every single parameter in the system. Whether it is a tiny model with 41 parameters or a massive LLM, the principle is the same: use the chain rule to flow gradients backward, and use those gradients to step toward a more accurate mode. Backpropagation tells you how to walk downhill, but AutoGrad builds the map of the terrain while you walk, so the descent can happen automatically.
Video Explanations
- This is the most step-by-step spelled-out explanation of backpropagation and training of neural networks by Andrej Karpathy in Neural Networks – Zero to Hero series. It only assumes basic knowledge of Python and a vague recollection of calculus from high school (Runtime: ~2hrs, 25 mins)
- This Backpropagation video by 3Blue1Brown explains how gradients flow through layered computations and why backpropagation is mathematically sound (Runtime: ~50 mins)
- In this video, Elliot Waite explains how the PyTorch autograd system works by going through some examples and visualizing the graphs with diagrams (Runtime: ~14 mins)
- This playlist and especially this video by Patrick Loeber is fantastic and goes through all pytorch concepts and a wonderful explanation of autograd and its respective code.
(Runtime: ~18 mins)
References
- Baydin et al. (2018)
Automatic Differentiation in Machine Learning: A Survey
Journal of Machine Learning Research
https://jmlr.org/papers/v18/17-468.html - Griewank & Walther (2008)
Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation
SIAM
https://epubs.siam.org/doi/book/10.1137/1.9780898717761 - Paszke et al. (2017)
Automatic Differentiation in PyTorch
https://openreview.net/pdf?id=BJJsrmfCZ



