You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: keep jac_gauss score gradients finite at repeated eigenvalues of Lam - #2210
ensure_lam_positive_definite previously called torch.linalg.eigh on every dense Lam and reconstructed the correction via the eigenvectors. Because eigenvector backprop divides by eigenvalue gaps, the gradient of the jac_gauss score produced NaNs whenever Lam had repeated eigenvalues, even when Lam was already positive definite and required no correction.
The forward values and nugget remain unchanged. Changes:
The sign checks and nugget calculation now use torch.linalg.eigvalsh, whose backward does not divide by eigenvalue gaps.
A positive-definite Lam bypasses spectral correction, and a negative-semidefinite Lam directly takes -Lam / (N - 1), avoiding eigenvector computation entirely in both cases.
Matrices with mixed-sign eigenvalues use a dedicated torch.autograd.Function (_NegativePart) implemented in sbi.utils.vector_field_utils. Its backward applies Daleckii-Krein divided differences of max(-λ, 0), maintaining finite gradients across repeated eigenvalues while matching standard gradients for distinct eigenvalues.
test_ensure_lam_positive_definite_gradient validates gradients against central finite differences across mixed-sign, negative-semidefinite, and positive-definite matrices with repeated eigenvalues.
test_ensure_lam_positive_definite_gradient_per_batch_element tests mixed cases across a batch.
Ran all 13 lam test cases: 13 passed in 4.73s.
ruff check and ruff format --check passed cleanly on all touched files.
No actionable comments were generated in the recent review.
Walkthrough
The dense precision correction now selects a correction based on the signs of the matrix eigenvalues. A custom autograd function handles mixed-sign matrices. New tests check corrections and gradients for repeated eigenvalues, batched inputs, and Jacobian-corrected scores.
Changes: Dense precision correction
Layer / File(s)
Summary
Negative spectral part sbi/utils/vector_field_utils.py
Adds a custom autograd function that computes the negative spectral part of a symmetric matrix and defines its backward using divided differences.
Uses sign-based cases for dense matrices and applies the custom function for mixed signs. The docstring describes the correction and finite gradients for repeated eigenvalues.
Gradient validation tests/score_samplers_test.py
Adds checks for corrections and gradients with repeated eigenvalues, batched matrices, finite differences, and Jacobian-corrected scores.
This change prevents NaN gradients when the precision correction is differentiated with repeated eigenvalues, and it keeps the forward values and nugget unchanged. No concrete merge-blocking defect was found. The only open question is whether external code applies torch.func transforms around this correction, and nothing in the repository indicates that it does.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: it keeps jac_gauss score gradients finite at repeated eigenvalues of Lam. The changeset adds eigvalsh-based sign checks, a positive-definite bypass, a negative-semidef…
Description check
The description follows the repository template. It covers what the PR does, links the issue (Fixes #2197), lists extra details such as new tests and lint results, and includes the checklist. Several …
Linked Issues check
Issue #2197 requirements, checked against the whole-PR diff from merge base 617fb70 to head acfd5f8:
1. Forward result and nugget: ensure_lam_positive_definite still computes the nugget from eigenv…
Out of Scope Changes check
The PR changes three files: sbi/inference/potentials/vector_field_adaptor.py (the ensure_lam_positive_definite correction path and its docstring), sbi/utils/vector_field_utils.py (new private `_…
Full details: Title check
Explanation
The title names the main change: it keeps jac_gauss score gradients finite at repeated eigenvalues of Lam. The changeset adds eigvalsh-based sign checks, a positive-definite bypass, a negative-semidefinite shortcut, and a custom _NegativePart autograd function for mixed-sign matrices, all aimed at that fix. The title follows the conventional prefix style and stays within a reasonable length.
Full details: Description check
Explanation
The description follows the repository template. It covers what the PR does, links the issue (Fixes #2197), lists extra details such as new tests and lint results, and includes the checklist. Several checklist items are checked, and the optional AI-assistance note is not filled in. The description does not mention the sbi-wide pytest and pyright commands from the checklist, and it omits whether slow tests were marked. These gaps are minor.
Full details: Linked Issues check
Explanation
Issue #2197 requirements, checked against the whole-PR diff from merge base 617fb70 to head acfd5f8:
Forward result and nugget: ensure_lam_positive_definite still computes the nugget from eigenvalues. The diff uses torch.linalg.eigvalsh for the sign checks and the nugget path is unchanged. The correction is divided by N - 1 as before.
Positive-definite Lam: the correction is zero by torch.where, with no eigenvector computation. Met.
Negative-definite (negative-semidefinite) Lam: the correction is -Lam / (N - 1). This matches the forward branch eigenvalues <= 0 -> -eigenvalues, so the result is the same. Met.
Mixed signs: _NegativePart in sbi/utils/vector_field_utils.py uses Daleckii-Krein divided differences of max(-λ, 0). Same-sign pairs use slopes -1 (nonpositive) or 0 (positive). Opposite-sign pairs use the chord, and the denominator is guarded by torch.where(same_sign, 1.0, gaps). Repeated eigenvalues share a sign, so the chord branch never divides by a zero gap. A convention at zero is stated (slope -1 for λ ≤ 0). Met.
Tests: the PR adds test_jac_gauss_score_has_finite_gradients_with_lam_correction for the #2197 reproduction, finite-difference gradient tests for mixed, negative-semidefinite, and positive-definite repeated-eigenvalue cases, and a batched per-element test. These cover the acceptance criteria. I did not read the test bodies, so I did not confirm that the finite-difference perturbation couples negative and positive eigenspaces. The test summary states rotated mixed-sign matrices are used.
The PD and NSD branches are finite in the backward even when _NegativePart.apply runs on the full batch, because torch.where zeroes the upstream gradient for unselected elements and the divided differences stay finite for same-sign pairs.
Full details: Out of Scope Changes check
Explanation
The PR changes three files: sbi/inference/potentials/vector_field_adaptor.py (the ensure_lam_positive_definite correction path and its docstring), sbi/utils/vector_field_utils.py (new private _NegativePart autograd function), and tests/score_samplers_test.py (new gradient tests). Each change connects directly to issue #2197: the function is the one the issue names, _NegativePart implements the mixed-sign backward the issue requests, and the tests implement the acceptance criteria. No unrelated refactoring, public API change, or unrelated behavior change appears in the diff. The _NegativePart import is a required dependency of the change.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 8d96af5a-f4ac-42bf-abbd-f68b67d5031f
Commits
Reviewing files that changed from the base of the PR and between 617fb70 and acfd5f8.
Files selected for processing: 3
sbi/inference/potentials/vector_field_adaptor.py
sbi/utils/vector_field_utils.py
tests/score_samplers_test.py
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
I independently reviewed the implementation and its gradient behavior. The _NegativePart approach looks sound for the repeated-eigenvalue cases, and the finite-difference checks are encouraging.
Currently, torch.linalg.eigvalsh(Lam) is applied to the complete batch. If even one particle produces a non-finite score Jacobian, the eigendecomposition can raise a LinAlgError, causing the entire batch to fail rather than preserving the finite results for the other particles.
I reproduced this with a batch containing otherwise valid positive-definite, negative-semidefinite and mixed-sign matrices alongside a NaN-containing matrix.
Would it make sense to isolate non-finite matrices before the eigendecomposition, perform the correction only on finite entries, and preserve NaN behavior for the invalid particles?
A regression test covering a mixed batch with one invalid particle would help ensure that the behavior matches Jan's expectation and the semantics of PR #2111.
The rest of the repeated-eigenvalue gradient handling looks promising. Thanks for working on this!
@Abhinav3499 thanks for picking this up, and for the clear write-up of the divided-difference backward. The fix looks good, and the backward is the right idea. PR #2111 reworks the same correction: it leaves positive definite directions unchanged and adds the nugget only where it corrects. Once that PR is merged, I will add a few commits on top of yours, as review capacity is limited at the moment:
✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.40%. Comparing base (617fb70) to head (acfd5f8). ⚠️ Report is 31 commits behind head on main.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
ensure_lam_positive_definitepreviously calledtorch.linalg.eighon every denseLamand reconstructed the correction via the eigenvectors. Because eigenvector backprop divides by eigenvalue gaps, the gradient of thejac_gaussscore produced NaNs wheneverLamhad repeated eigenvalues, even whenLamwas already positive definite and required no correction.The forward values and nugget remain unchanged. Changes:
torch.linalg.eigvalsh, whose backward does not divide by eigenvalue gaps.Lambypasses spectral correction, and a negative-semidefiniteLamdirectly takes-Lam / (N - 1), avoiding eigenvector computation entirely in both cases.torch.autograd.Function(_NegativePart) implemented insbi.utils.vector_field_utils. Its backward applies Daleckii-Krein divided differences ofmax(-λ, 0), maintaining finite gradients across repeated eigenvalues while matching standard gradients for distinct eigenvalues.Does this close any issues?
Fixes #2197
Anything else we should know?
_NegativePartis defined insbi/utils/vector_field_utils.pynext to related matrix utilities.tests/score_samplers_test.py:test_jac_gauss_score_has_finite_gradients_with_lam_correctionverifies the reproduction case from NaN gradients of the jac_gauss score in the positive-definite correction #2197 withensure_lam_psd=True.test_ensure_lam_positive_definite_gradientvalidates gradients against central finite differences across mixed-sign, negative-semidefinite, and positive-definite matrices with repeated eigenvalues.test_ensure_lam_positive_definite_gradient_per_batch_elementtests mixed cases across a batch.ruff checkandruff format --checkpassed cleanly on all touched files.Checklist
pytest tests/score_samplers_test.py -k "lam"passes.rufflint and format check pass.