Sampling any Gaussian from standard noise with a Cholesky factor, why the same map makes samples differentiable, and how to store and evaluate a Gaussian whose parameters an optimizer can change freely.
Suppose an optimizer trains the covariance matrix of a 2-D Gaussian directly. It starts at (10.50.51), and one gradient step moves the off-diagonal entries to 1.2. The new matrix has eigenvalues 2.2 and −0.2: it would give one direction a negative variance, so it is no covariance at all, and the model breaks.
The fitting experiments of the next notes need a Gaussian that survives any gradient step, that we can sample from, and whose samples move smoothly when its parameters move. A triangular square root of the covariance gives the second and third. Storing its diagonal through an exponential gives the first: then every value of the trained numbers is a valid covariance. The density, the ellipses and the affine maps of the Gaussian are in the Probability course’s multivariate Gaussian note; here we use them.
For a random vector X=(X1,X2)⊤ with mean μ=E[X], the covariance matrix is
Σ=E[(X−μ)(X−μ)⊤]=(σ12ρσ1σ2ρσ1σ2σ22),
where ρ is the correlation of X1 and X2. It is symmetric, and positive semidefinite because Var(a⊤X)=a⊤Σa≥0 for every vector a. We write X∼N(μ,Σ), with the covariance, never the standard deviation, as the second argument. The running example has μ=0, unit variances and ρ=0.5.
Two variances alone cannot describe this cloud. Its axis variances are both 1, exactly those of the round N(0,I); only the off-diagonal entry records that the cloud leans along the diagonal x1=x2.
Figure
A diagonal matrix only stretches along the axes; covariance tilts the cloud
Both clouds are drawn from the same 260 standard-normal pairs. Left: Σ = diag(1.5, 0.5), independent coordinates. Right: Σ = [[1, 0.5], [0.5, 1]], the same cloud rotated by 45°: both axis variances are 1, and only the off-diagonal entry records the tilt. Braces span ±1 standard deviation; curves are the 1σ and 2σ ellipses.
In one dimension, X=μ+σZ with Z∼N(0,1) and σ>0 has distribution N(μ,σ2): stretch standard noise by σ, then shift it by μ. The change-of-variables formula with g(z)=μ+σz and g′=σ gives the density φ((x−μ)/σ)/σ, where φ is the standard normal density; this is the N(μ,σ2) density.
Figure
Standardization and its inverse in one dimension
The point z = 1 of the standard normal maps to x = μ + σz = 3.5 for μ = 2, σ = 1.5; dividing (x − μ) by σ maps it back. Both points sit one standard deviation above their own mean.
In d dimensions a matrix plays the role of σ. For any A with AA⊤=Σ and Z∼N(0,I),
X=μ+AZ∼N(μ,Σ)
The mean is μ+AE[Z]=μ by linearity of expectation. The covariance follows from the definition, with X−μ=AZ:
That the result is Gaussian at all is shown in the affine maps section of the Probability course: by the change of variables for an invertible A, and by the characteristic function for any A.
Many matrices satisfy AA⊤=Σ. Two are standard. The symmetric square rootΣ1/2=UΛ1/2U⊤ comes from the eigendecomposition Σ=UΛU⊤, with U orthogonal by the spectral theorem. It exists for every covariance, singular ones included: the eigenvalues of a positive semidefinite matrix are ≥0, so their roots are real, and U⊤U=I gives Σ1/2Σ1/2=UΛU⊤. The Cholesky factorL is the unique lower-triangular matrix with positive diagonal and LL⊤=Σ; it exists when Σ is positive definite (Golub and Van Loan, 2013, §4.2; derived in the Cholesky factorization).
For the running example the eigenvalues are 1.5 and 0.5, with eigenvectors along (1,1) and (1,−1), and the two roots are
Both turn independent noise into the same correlated cloud. Code uses L: a finite algorithm computes it in about d3/3 operations (the Cholesky factorization). An eigendecomposition needs an iterative method, because eigenvalues are roots of a polynomial of degree d, and for d≥5 such roots have no general formula in radicals (the Abel–Ruffini theorem). In PyTorch, MultivariateNormal stores the Cholesky factor of the covariance it receives and samples μ+LZ (PyTorch source).
Figure
Sampling any Gaussian from standard noise
Standard normal pairs Z are multiplied by the Cholesky factor L of Σ = [[1, 0.5], [0.5, 1]] and shifted by μ = (1.5, 1). The amber point z = (2, 1) moves to Lz = (2, 1.87) and then to μ + Lz = (3.5, 2.87). Curves are the 1σ and 2σ contours; all panels share one window.
The map x=μ+Lε does more than sample. It moves all randomness into ε∼N(0,I), which does not depend on the parameters, and leaves a deterministic, differentiable function of μ and L. So the gradient of an expectation under the Gaussian becomes an expectation of a gradient:
The first step uses only that μ+Lε has the distribution N(μ,LL⊤), so both expectations are the same number. The second moves the gradient inside an expectation over a distribution that no longer depends on the parameters. This differentiation under the integral sign holds when f is differentiable and its gradient is bounded by a function integrable against the noise density, as for any f whose gradient grows at most polynomially.
The right side is estimated by averaging over a few draws of ε, and backpropagation handles it like any other layer. A sampler called as a black box would give no gradient at all (Kingma and Welling, 2014; Isachenko, lecture 4).
A one-dimensional check: for x=m+sε and f(x)=x2, the expectation is E[x]2+Var(x)=m2+s2, so its derivative in s is 2s. The pathwise estimate averages f′(x)∂x/∂s, and Eε=0, Eε2=1 give
To let an optimizer change the covariance freely, we train the Cholesky factor through three unconstrained numbers a,b,c:
LΣ=LL⊤=(eab0ec),=(e2abeabeab2+e2c).
The exponential keeps the diagonal positive, so L is invertible and v⊤Σv=∥L⊤v∥2>0 for every v=0. Every gradient step on a,b,c lands on a valid covariance, which repairs the opening example. The running example is a=0, b=0.5, c=ln0.75≈−0.144, and a=b=c=0 gives Σ=I.
The same factor gives the log-density without inverting Σ. Start from the Gaussian density, logp(x)=−21(x−μ)⊤Σ−1(x−μ)−21logdet(2πΣ). Inverting the product LL⊤ gives Σ−1=L−⊤L−1, so the quadratic form is ∥L−1(x−μ)∥2. The determinant of a product is the product of determinants, and that of a triangular matrix is the product of its diagonal, so detΣ=∏iLii2. Together,
logp(x)=−21L−1(x−μ)2−i=1∑dlogLii−2dlog2π.
The vector L−1(x−μ) comes from one triangular solve. This is how MultivariateNormal.log_prob computes it, and passing the factor as scale_tril=L skips the re-factorization that covariance_matrix=L @ L.T would trigger. In PyTorch the raw numbers are tensors created with requires_grad=True; the target distribution is built from fixed tensors.
import numpy as npfrom scipy.linalg import solve_triangularfrom scipy.stats import multivariate_normala, b, c = 0.0, 0.5, np.log(np.sqrt(0.75)) # raw parameters: any real numbersL = np.array([[np.exp(a), 0.0], [b, np.exp(c)]]) # lower triangular, positive diagonalmu, Sigma = np.zeros(2), L @ L.Tprint(L.round(3).ravel(), Sigma.round(3).ravel()) # Sigma = [[1, 0.5], [0.5, 1]]def log_density(x, mu, L): w = solve_triangular(L, (x - mu).T, lower=True) # L^{-1}(x - mu): no inverse of Sigma d = len(mu) return -0.5 * (w**2).sum(0) - np.log(np.diag(L)).sum() - 0.5 * d * np.log(2 * np.pi)x = np.array([[0.0, 0.0], [1.0, 1.0], [1.0, -1.0]]) # the centre, along the tilt, across itprint(log_density(x, mu, L).round(4))print(multivariate_normal(mu, Sigma).logpdf(x).round(4)) # the same numbersrng = np.random.default_rng(0)eps = rng.standard_normal((100_000, 2))samples = mu + eps @ L.T # x = mu + L eps, row by rowprint(np.cov(samples.T).round(2).ravel())# reparameterization: x = m + s * eps, f(x) = x^2, so E f = m^2 + s^2 and dE/ds = 2sm, s = 1.0, 0.5e = rng.standard_normal(100_000)print((2 * (m + s * e) * e).mean().round(3)) # pathwise estimate of 2s = 1
The points (1,1) and (1,−1) are equally far from the centre, yet the one along the tilt has log-density −2.36 and the one across it −3.69. The fitting experiments start from a fixed target P and a trainable model Q built this way:
Figure
Target P and model Q before fitting
400 samples each of the fixed target P = N((−5, −5), I) and of the trainable model Q, initialized at N(0, I), on the plot limits (−10, 10). Each dot is coloured by its own cloud’s density, p(x) for target samples and q(x) for model samples, so stronger colour means higher density.
A full covariance in d dimensions has d(d+1)/2 free numbers. For a VAE with a 128-dimensional latent code that is 8,256 numbers per input, which an encoder would have to predict for every image. VAE encoders therefore output a diagonal covariance: d variances, an L with nothing below the diagonal, and a cloud that can stretch along the axes but never tilt, like the left panel of the first figure.
A singular covariance has no Cholesky factor at all. If one coordinate copies another, Σ=(1111), and np.linalg.cholesky stops with “Matrix is not positive definite”; torch.linalg.cholesky fails the same way. Estimated covariances hit this when features are collinear or when there are fewer samples than dimensions. The usual repair adds a small jitter ϵI. With ϵ=10−6 the factor is (1100.0014): a valid Gaussian, flattened almost onto the diagonal line. Its log-density is 4.72 at the origin, against −1.84 for N(0,I), and −20.28 at (0,0.01), a hundredth off the line.
import numpy as npS = np.array([[1.0, 1.0], [1.0, 1.0]]) # X2 = X1: a singular covariancetry: np.linalg.cholesky(S)except np.linalg.LinAlgError as err: print("LinAlgError:", err)L = np.linalg.cholesky(S + 1e-6 * np.eye(2)) # a small jitter on the diagonalprint(L.round(4).ravel())
LinAlgError: Matrix is not positive definite[1. 0. 1. 0.0014]
The trained parametrization cannot produce a singular matrix, because ea and ec are never zero. It can still drift towards one. Write the second coordinate of x=μ+Lε through the first: ε1=(x1−μ1)e−a, so
x2=μ2+bε1+ecε2=μ2+be−a(x1−μ1)+ecε2.
If the training points lie on a line x2=α+βx1, choose be−a=β and μ2−βμ1=α. Then ε2=0 at every point, the quadratic term of the log-density loses its second component, and the term −logL22=−c grows without limit as c→−∞. Two points in the plane always lie on a line, so with no more points than dimensions maximum likelihood follows the same path: the memorizing fit of the first note, in miniature.
The Distances between distributions notebook of the HSE-LAMBDA Deep Generative Models course sets up the Gaussians used here. Parts are named by the notebook’s own headings (its cells count from 1, markdown included), and quoted numbers come from the run saved with the course.
The helper functions draw a scatter plot on the window (−10,10)2 and implement the parametrization above: get_parameters creates the mean (μ,μ) and raw entries a=c=lnσ, b=0; create_distr assembles L and passes LL⊤ as covariance_matrix, where scale_tril=L would avoid a second factorization.
The toy example with a single Gaussian target creates the fixed target N((−5,−5),I) with 1000 samples and the model initialized at N(0,I), and plots both coloured by their own densities. The fit itself is described in Fitting distributions with KL.
With a target and a trainable model in hand, the remaining question is what “fit” means: we need a number that says how far Q is from P. The first candidate is the KL divergence, built from surprise and entropy in Entropy, cross-entropy and KL divergence.
G. H. Golub, C. F. Van Loan. Matrix Computations, 4th ed. Johns Hopkins University Press, 2013. §4.2: positive definite systems and the Cholesky factorization.
D. P. Kingma, M. Welling. Auto-encoding variational Bayes. ICLR, 2014. The reparameterization of a Gaussian as a differentiable map of noise.
R. Isachenko. Deep Generative Models, MIPT/YSDA, 2025. Lecture 4: the reparameterization trick and the Monte Carlo gradient of the ELBO.