Skip to content

Fix: resolve NaN gradients in RQS out-of-bounds inverse pass#240

Merged
danielward27 merged 2 commits into
danielward27:mainfrom
cschoenle:fix/rqs-nan-gradient
Jun 21, 2026
Merged

Fix: resolve NaN gradients in RQS out-of-bounds inverse pass#240
danielward27 merged 2 commits into
danielward27:mainfrom
cschoenle:fix/rqs-nan-gradient

Conversation

@cschoenle

Copy link
Copy Markdown
Contributor

Fix: Resolve NaN gradients for out-of-bounds inputs in RationalQuadraticSpline

Closes #239

Description

This PR resolves a regression introduced in v18.0.0 where evaluating the RationalQuadraticSpline on out-of-bounds inputs caused NaNs in the reverse-mode gradients for the inverse pass, poisoning the gradients for the entire batch.

The Issue:
Although the final output safely defaults to the identity mapping via jnp.where for out-of-bounds inputs, the mathematical operations were still being evaluated on the raw, unclipped variables. In the inverse pass, this caused jnp.sqrt to evaluate a negative discriminant for out-of-bounds data. This resulted in NaN values that propagated through the unselected branches during backpropagation.

The Fix:

  • Inverse Pass (The Bug): Restored numerical safety by applying jnp.clip to y to bound it to self.interval strictly before computing the bin index k and intermediate variables. The original, unclipped y is preserved solely for the final jnp.where fallback.
  • Forward Pass (Safeguard): Proactively applied the exact same clipping logic to x in transform_and_log_det. While the forward pass was not strictly producing NaNs (as the polynomial math happens to avoid undefined domains), applying this ensures architectural consistency and protects against potential overflows.

Testing:

  • Added a new parametrized unit test test_RationalQuadraticSpline_out_of_bounds_grad_nan in test_rational_quadratic_spline.py.
  • The test simulates a noisy initialized state and evaluates both the forward and inverse passes on out-of-bounds inputs (50.0), asserting that no NaNs exist in the resulting gradient leaves. Both passes test cleanly.

@danielward27 danielward27 merged commit 2ec0c05 into danielward27:main Jun 21, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NaN gradients in RationalQuadraticSpline for out-of-bounds inputs

2 participants