fix(thermo): stable kappa_dot/dkd_dloga gradient via n_H_0 rescaling - #20
Open
MinhMPA wants to merge 1 commit into
Open
fix(thermo): stable kappa_dot/dkd_dloga gradient via n_H_0 rescaling#20MinhMPA wants to merge 1 commit into
MinhMPA wants to merge 1 commit into
Conversation
…ling The Friedmann-scan accumulates a spurious d(a_grid[i])/d(omega_b) eigenvalue product (~10^14 at loga=-8). The spline derivative's 1/h factor amplifies this by ~1200x, causing AD to return ~10^17 instead of the physical ~-335. Fix: stop all accumulated gradient in kappa_dot_grid, then restore only the n_H_0 ∝ omega_b path (exact, since kappa_dot ∝ n_H_0 linearly): _kappa_dot_for_deriv = sg(kappa_dot_grid) * n_H_0 / sg(n_H_0) Also adds dkappa_dot_dloga_of_loga to ThermoResult and the regression test test_opacity_logderivative_gradient_matches_fd_for_omega_b (<1% vs FD). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This was referenced May 12, 2026
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Fixes an exploding-gradient bug in the `kappa_dot` spline path. During reverse-mode AD, the Friedmann-scan eigenvalue blows up ~10¹² × for typical `omega_b` perturbations.
Root cause: `kappa_dot ∝ n_H_0 ∝ omega_b / m_H`. The recombination solver builds a spline over a frozen tau grid. During `jax.grad`, JAX differentiates through both the spline evaluation and the frozen-grid construction simultaneously, producing an ill-conditioned Jacobian.
Fix: Rescale at the evaluation site so that traced `n_H_0` enters only as a ratio:
```python
_kd_safe = stop_gradient(kappa_dot) * (n_H_0 / stop_gradient(n_H_0))
```
Value is unchanged (ratio = 1 at evaluation point); gradient routes through the analytic rescaling factor, not the spline Jacobian.
Changes
Merge order (4-PR AD-correctness series)
Test plan