KroneckerNormal's gradient is nan for a factor with a repeated eigenvalue #8622

Hello all,

For Kronecker Normal Distribution gradient becomes NaN because KroneckerNormal.logp evaluates the density through EighGrad implementation. GPT gave me a solution to differentiate the multivariate Gaussian log density directly instead of differentiating the eigenvectors. This way we can bypass \[ \frac{1}{\lambda_i-\lambda_j} \] which becomes the core problem for identical eigenvalues.

Log probability:

where r = x-mu. Differentiating log probability directly works for simple covariance matrices.

image

where

imageThis works for arbitrary covariance matrices.

Problem: The Default Autodiff Path (Node-by-Node Chain Rule)

By default, reverse-mode automatic differentiation (pt.grad) evaluates derivatives by stepping backward node-by-node through the execution graph:

image

To compute the final gradient , PyTensor uses the Chain Rule through every intermediate node:

image

Because it passes explicitly through delta(Q) / delta (theta), PyTensor calls EighGrad (Method 1), which attempts to calculate how individual eigenvectors shift—forcing division by eigenvalue gaps (lambda(i) - lambda(j)) and producing NaNs when eigenvalues repeat.

Solution: The Analytical Shortcut (Graph Rewrite)

When we derive the full gradient of the Gaussian log likelihood analytically on paper, the terms involving the eigenvector derivatives delta(Q) / delta(theta) sum to zero and cancel out completely due to orthogonal rotation invariance2