Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 17

Matrix Calculus for VAEs and Normalizing Flows

Recommended resources

Welcome back. In our last session, we took a deep dive into the Jacobian of the softmax function, culminating in a full derivation of the elegant predicted - actual gradient for cross-entropy loss. We established that understanding the calculus behind these operations is key to truly grasping how neural networks learn.

Today, we continue to build out your matrix calculus toolkit, focusing on identities that are indispensable for understanding and implementing modern generative models. We will derive the derivatives for linear maps, quadratic forms, and, most importantly, the log-determinant of a matrix. These are not mere academic exercises; they are the fundamental components required to formulate the training objectives for the Variational Autoencoders (VAEs) and Normalizing Flows (like RealNVP) that you aim to implement.

1. Warm-up: Linear and Quadratic Forms

Before tackling the more complex identities, let's begin with two foundational derivatives that appear frequently in machine learning. The first is the derivative of a linear transformation, and the second is the derivative of a quadratic form. These serve as excellent entry points, as their matrix forms are direct analogues of familiar scalar derivatives.

The video below offers a clear, first-principles derivation for both. The presenter starts by expanding the matrix operations into their scalar components for a 2x2 case, computes the partial derivatives to form the Jacobian, and then reveals the elegant, compact matrix result.

Derivative of a Matrix : Data Science Basics

This video from ritvikmath provides a step-by-step walkthrough of these two fundamental matrix calculus identities.

Please watch the following two segments: First, watch the derivation for a linear map, \frac{d}{d\mathbf{x}}(\mathbf{A}\mathbf{x}), from the beginning. Note the analogy to the scalar case \frac{d}{dx}(kx) = k. Next, watch the derivation for a symmetric quadratic form, \frac{d}{d\mathbf{x}}(\mathbf{x}^T\mathbf{A}\mathbf{x}), from the second part. Again, pay attention to the analogy with \frac{d}{dx}(kx^2) = 2kx.

Let's summarize the key results. Using numerator layout (where the gradient is a column vector), we have:

  • Derivative of a linear transformation: For a constant matrix and a vector , the Jacobian of the function is . The gradient with respect to is written as:

    (Note: The video result is , which is the Jacobian matrix. When we speak of the gradient of a vector-valued function, we often mean the transpose of the Jacobian, which is consistent with the chain rule convention we've been using, . The distinction is subtle but important in formal settings.)

  • Derivative of a quadratic form: For a symmetric matrix , the gradient of the scalar function is:

    This identity is fundamental to the analysis of the multivariate Gaussian distribution and in deriving solutions to linear regression (Normal Equations).


2. The Main Event: Derivative of the Log-Determinant

We now arrive at the core identity for this lesson, one that is central to both Normalizing Flows and VAEs: the derivative of the logarithm of a determinant.

First, why is this important? In many generative models, we need to evaluate the probability of data under a transformation. The change of variables formula for probability densities involves the determinant of the Jacobian of the transformation. Since we typically work with log-probabilities for numerical stability and easier optimization, the term naturally appears in the loss function. To train the model, we must differentiate this term with respect to the model parameters.

This diagram illustrates how a Normalizing Flow transforms a simple base distribution \(p_0(\mathbf{z}_0)\) into a complex target distribution \(p_K(\mathbf{z}_K)\) through a sequence of invertible functions. The change in probability density at each step is governed by the determinant of the transformation's Jacobian.

The following video provides an excellent derivation of the identity , which we can then easily adapt for the log-determinant. The presenter uses two approaches: a direct calculation for the 2x2 case, and a more general, elegant proof using the matrix logarithm. Given your background, you will likely appreciate the second approach.

determinants, derivatives, and traces

This video by Michael Penn establishes the relationship between the determinant, derivative, and trace of a matrix-valued function.

Please watch the video to see the full derivation. The introduction states the main formula. The 2x2 case provides concrete intuition. The general case uses the matrix exponential and logarithm for a more abstract and powerful proof.

The video establishes the formula, known as Jacobi's formula:

From here, deriving the gradient for the log-determinant is a simple application of the chain rule. Let .

Substituting Jacobi's formula for :

From the relationship , we can identify the gradient of with respect to the matrix itself.

The MIT lecture notes below formalize this result.

Matrix Calculus for Machine Learning and Beyond

These notes by Prof. Steven G. Johnson provide a concise derivation and statement of the final gradient identity.

Please navigate to page 48 and read the short section 7.2.2 The Logarithmic Derivative. This section formalizes the result we just discussed.

The key takeaway from the reading is the final identity:

If is symmetric, which is often the case for covariance matrices, this simplifies to . This is a remarkably simple and powerful result.


3. Application to Generative Models

Let's make the connection to the papers you plan to implement explicit.

Normalizing Flows (e.g., RealNVP)

A normalizing flow models a complex data distribution by transforming a simple base distribution (e.g., a standard normal) through an invertible function . The change of variables formula dictates the resulting density:

The objective is to maximize the log-likelihood of the data, . Taking the log of the equation above, we get:

The function is a neural network with parameters . The term is the Jacobian of the network, . To train the model using gradient ascent, we must compute the gradient of the log-likelihood with respect to . This requires us to differentiate , which is a direct application of the identity we just derived.

This diagram explicitly shows the change of variables formula used in Normalizing Flows. The training objective directly involves the log-determinant of the Jacobian of the transformation, which must be differentiated to update model parameters.

Variational Autoencoders (VAEs)

In a VAE, we define a probabilistic encoder and a decoder . The training objective is to maximize the Evidence Lower Bound (ELBO):

Often, the encoder is chosen to be a Gaussian distribution, , where a neural network outputs the mean and covariance . The prior is typically a standard normal .

The KL-divergence term between these two multivariate Gaussians has an analytical form which includes the term . Specifically:

To backpropagate the loss through the network that produces , we need to compute , which is precisely the identity (assuming is symmetric).


Conclusion

In this lesson, we have derived three essential matrix calculus identities and, more importantly, established their direct relevance to the mechanics of advanced generative models.

Key Takeaways:

  • The derivatives of linear and quadratic forms, and , are foundational vector calculus results with direct analogues to scalar calculus.
  • The gradient of the log-determinant of a matrix is elegantly given by .
  • This log-determinant gradient is not just a theoretical result; it is the critical component needed to optimize the log-likelihood objective in Normalizing Flows and to compute the KL-divergence term in the VAE's ELBO loss.

You now possess the specific calculus tools to understand the why behind the loss functions of these models. In our next lesson, we will synthesize what we've learned about Jacobians and gradients to trace a full backpropagation pass through a small multi-layer perceptron by hand, solidifying the mechanics of automatic differentiation.