Skip to content

NaN gradients of the jac_gauss score in the positive-definite correction #2197

Open

Description

@janfb

With the default ensure_lam_psd=True, the jac_gauss iid method calls ensure_lam_positive_definite in sbi/inference/potentials/vector_field_adaptor.py. That function forms the combined precision Lam from the prior and per-trial precisions. For a dense Lam in more than one dimension, that function always calls torch.linalg.eigh, also when Lam is already positive definite. When Lam depends on the parameters and has repeated eigenvalues, the backward pass through the eigenvectors of eigh divides by a zero eigenvalue gap. The score itself stays finite, but its derivative with respect to the parameters is NaN. This is in main.

Only callers that differentiate the score are affected, for example through VectorFieldBasedPotential.gradient(..., track_gradients=True). The built-in samplers use the score values only.

Reproduction (both cases print True [nan, nan, nan]; the eigenvalues of Lam are [2, 2, 2] and [-0.25, -0.25, 2]):

import torch
from torch.distributions import MultivariateNormal

from sbi.inference.potentials.vector_field_adaptor import JacCorrectedScoreFn


class ToyEstimator(torch.nn.Module):
    SCORE_DEFINED = MARGINALS_DEFINED = True
    mean_t_fn = staticmethod(lambda t: 1 - t)
    std_fn = staticmethod(lambda t: t)

    def __init__(self, variance):
        super().__init__()
        self.variance = variance

    def score(self, theta, x, t):
        var_t = (1 - t) ** 2 * self.variance + t**2
        return -theta / var_t - (theta - 1) ** 2 + torch.zeros_like(x)


prior = MultivariateNormal(torch.zeros(3), torch.eye(3))
x, t = torch.zeros(3, 1), torch.tensor([0.5])
for variance in (torch.ones(3), torch.tensor([4.0, 4.0, 1.0])):
    theta = torch.ones(1, 1, 3, requires_grad=True)
    score = JacCorrectedScoreFn(ToyEstimator(variance), prior)(theta, x, t)
    (grad,) = torch.autograd.grad(score.sum(), theta)
    print(torch.isfinite(score).all().item(), grad.flatten().tolist())

The fix belongs in ensure_lam_positive_definite. It should keep the forward result, including the nugget. A positive definite Lam needs no spectral correction, and a negative definite one gets -Lam / (N - 1), so sign-definite matrices need no eigenvectors. The nugget still needs the eigenvalues. For mixed signs, a backward with divided differences of max(-λ, 0) handles repeated eigenvalues; it needs a convention at λ = 0. A test should check that both cases above give finite gradients with ensure_lam_psd=True. Finite is not enough: a backward that detaches the eigenvectors is finite but wrong. So the test should also compare the backward of a mixed-sign correction with a finite difference, along a symmetric perturbation that couples a negative and a positive eigenspace.

Activity

  1. janfb commented on Nov 23, 2026

    @janfb
    ContributorAuthor

    One more case for the same rewrite, relevant for PR #2210: a particle with a NaN score Jacobian makes torch.linalg.eigh in ensure_lam_positive_definite raise, and that fails the whole batch. With ensure_lam_psd=False, PR #2111 keeps the other particles finite and gives only that particle a NaN score. The rewritten correction should do the same, for example by running the eigendecomposition only on finite matrices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions