Skip to content

fix: potentials follow the caller's grad mode by default - #2127

Draft
janfb wants to merge 3 commits into
mainfrom
fix/importance-weights-no-grad
Draft

janfb wants to merge 3 commits into
mainfrom
fix/importance-weights-no-grad

Conversation

@janfb

@janfb janfb commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Many samplers only need potential values, so they evaluate the potential inside torch.no_grad(). sbi potentials ignored this. Their track_gradients argument defaulted to True, and each potential set that grad mode itself. So the MCMC init, importance sampling, rejection sampling, the VI quality check and the MAP search all built an autograd graph that they never used.

track_gradients now defaults to None: the potential keeps the grad mode of its caller. An explicit True or False applies to the whole potential, also inside torch.no_grad().

 class BasePotential:
-    def __call__(self, theta, track_gradients: bool = True)
+    def __call__(self, theta, track_gradients: Optional[bool] = None)

 with torch.no_grad():
-    potential(theta)  # builds a graph
+    potential(theta)  # builds none

Three callers change with it. importance_sample runs without gradients. Rejection sampling no longer forces gradients on its potential. gradient_ascent turns gradients on for its optimization step, so map() now also works inside torch.no_grad(); on main it raises there.

This also fixes map() of FMPE and NPSE posteriors built with sample_with="mcmc", "importance" or "rejection". Their potential turned gradients off by default, so the MAP search raised "element 0 of tensors does not require grad" on main.

This helps everyone who samples with MCMC, rejection or importance sampling, most on a GPU.

Evidence

Extra peak GPU memory on mini-sbibm slcp, NLE with the default NSF:

Call Before After
MCMC init resample or sir 199 MB 26 MB
Rejection sampling, 1,000 draws 199 MB 26 MB
VI quality check prop, 10,000 samples 199 MB 26 MB
Importance sampling sir, 100 draws 61 MB 8 MB
MAP, 10 iterations 19 MB 2 MB

The samples, initial parameters and MAP are identical before and after.

New tests check the grad mode for every potential type, with and without track_gradients. Other tests check the samplers above and map() inside torch.no_grad(). 18 of the 20 cases fail on main and pass on this branch.

Merge Danger

Door: two-way

Blast Radius: small

A potential called inside torch.no_grad() without track_gradients now returns no gradients. sbi itself does not rely on this. User code that does must pass track_gradients=True. Subclasses of BasePotential that set their own default keep their behaviour.

janfb added 3 commits October 30, 2026 13:50
sbi potentials defaulted to `track_gradients=True` and switched gradients back on inside `torch.no_grad()`. Every sampler that only needs potential values therefore built an autograd graph it never used: the MCMC init strategies, importance sampling (SIR, the importance posterior and its normalization), the accept/reject loop of rejection sampling, the VI proportionality check and the evaluation steps of the MAP search.

`track_gradients` now defaults to `None`, which keeps the caller's grad mode. An explicit `True` or `False` now applies to the whole potential: the likelihood, ratio and ensemble potentials added the prior or the ensemble weights outside their grad block, so inside `torch.no_grad()` they returned no gradients even with `True`.

`importance_sample` runs without gradients, so a learnable proposal builds no graph either. Rejection sampling no longer forces gradients; `gradient_ascent` turns them on for its optimization step, so `map()` now also works inside `torch.no_grad()`.

On slcp with NLE's default NSF on a V100, the extra peak GPU memory drops from 199 MB to 26 MB for the MCMC init, for 1,000 rejection draws and for the VI check with 10,000 samples, from 61 MB to 8 MB for 100 SIR draws, and from 19 MB to 2 MB for 10 MAP iterations. The results are identical.

The tests check the grad mode inside each potential type with and without `track_gradients`, in the importance and rejection samplers and in the MCMC init, and that `map()` works inside `torch.no_grad()`. 14 of their 16 cases fail on main.
…e too

The vector-field potential still defaulted to `track_gradients=False`. The conditioned potential forwarded the new `None` default into it, which `torch.set_grad_enabled` rejects, so conditional sampling of vector-field posteriors raised a TypeError; a rejection posterior built on a vector-field potential lost the gradients for its max search. It now defaults to `None` like the other potentials.

The conditioned, likelihood-conditioned and ensemble potentials did part of their work before entering the grad block, so an explicit `True` inside `torch.no_grad()` lost the gradient with respect to theta. They now run the whole call in the block. The tutorial potential and the test potentials follow the same pattern.

The grad-mode tests now cover the vector-field and conditioned potentials and use a Gaussian prior, and the override test compares gradients instead of checking `requires_grad`.
@coderabbitai

coderabbitai Bot commented Oct 30, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

This branch has not been deployed

No deployments
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.

1 participant