Skip to content

fix: simulating no longer turns on deterministic cuDNN - #2177

Open
BHARATH0153 wants to merge 1 commit into
sbi-dev:mainfrom
BHARATH0153:fix-simulation-cudnn-flags
Open

BHARATH0153 wants to merge 1 commit into
sbi-dev:mainfrom
BHARATH0153:fix-simulation-cudnn-flags

Conversation

@BHARATH0153

@BHARATH0153 BHARATH0153 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

simulate_for_sbi and simulate_in_batches seeded through seed_all_backends, which also sets torch.backends.cudnn.deterministic = True and torch.backends.cudnn.benchmark = False. Those flags are global to the process, so one call to a simulation helper switched the rest of the session to deterministic cuDNN algorithms and could slow down later training of convolutional embedding nets.

This separates the two concerns. seed_random_states draws the seed and seeds random, numpy, torch and torch.cuda. seed_all_backends is now that call plus the two cuDNN lines, so its behavior is unchanged for the autouse fixture in tests/conftest.py and for the existing test call sites. The simulation paths use seed_random_states: simulate_for_sbi before it samples the parameters, simulate_in_batches before it splits them, and its simulator_seeded closure per batch.

Seeding itself does not change: with seed=None the seed is still drawn from PyTorch's random state, so an upstream torch.manual_seed keeps reproducing a simulate_for_sbi(seed=None) call, and the per-batch seeds used when num_workers > 1 are drawn from the same state as before.

Does this close any issues?

Fixes #2159

Anything else we should know?

  • The issue suggests an option of seed_all_backends. I used a second function instead: a call like seed_all_backends(seed, deterministic_cudnn=False) reads as a contradiction, and this way seed_all_backends keeps exactly its current meaning for the people who do want bit-reproducible convolutions. Say the word if you would rather have the flag.
  • Rebased onto current main (95a4f5e5). Two changes landed since the first version of this PR. PR #1738 rewrote the simulator call path, and simulate_from_theta now seeds each call through the CPU-only _seed_cpu_random_states, which already leaves cuDNN alone. This PR changes the remaining call sites: the single seed of simulate_for_sbi before it samples, and both in ABC's simulate_in_batches. After it, seed_all_backends is the only place in the package that sets the cuDNN flags.
  • I did not export seed_random_states in sbi/utils/__init__.py, matching seed_all_backends, which the tests that use it import from sbi.utils.sbiutils. No public API is added or changed.
  • The two cuDNN lines in seed_all_backends are the only place the package touched cuDNN, and no page in docs/ mentions it. The parallel-simulations how-to says simulate_for_sbi seeds PyTorch's GPU generators once before it samples, which is still true.
  • User visible part: anybody who was relying on a simulate_for_sbi or simulate_in_batches call to quietly make convolutional training deterministic now gets the torch default, and has to call seed_all_backends(seed) or set the flags themselves. That is the point of the issue.

How I checked it:

  • The repro from the issue (simulate_for_sbi(lambda t: t, BoxUniform(...), 5) then printing torch.backends.cudnn.deterministic) prints True on main and False here. simulate_in_batches leaves the flags alone too.
  • test_simulating_leaves_cudnn_flags fails on main for both seed=None and seed=42 and passes with the change. The fixture sets deterministic=False, benchmark=True before the call on purpose: at the all-False default a test cannot tell "left alone" from "set to False", so it would pass without the fix. With num_workers > 1 the seeded simulator runs in a worker process, whose flags the parent cannot see, so the helper is also asserted directly.
  • Reproducibility unchanged: simulate_for_sbi and simulate_in_batches return identical x for seed=42 across two calls, and seed=None is still reproduced by an upstream torch.manual_seed(0).
  • The new tests take about 0.04 s each, except the num_workers=2 case, which takes about 1.3 s for the joblib workers; none is marked slow. Focused suites (simulator_utils_test.py, simulation_utils_test.py, sbiutils_test.py, multiprocessing_test.py) pass with only expected XFAILs, and ruff check, ruff format --check, pyright sbi and git diff --check pass.

Checklist

  • I have read the contributing guide.
  • uv run pytest -n auto -m "not slow and not gpu" passes.
  • uv run pre-commit run --all-files passes (ruff and formatting).
  • uv run pyright sbi passes.
  • I added or updated tests for the changed behavior.
  • I used Google-style docstrings for new or changed public functions.
  • (If applicable) I reported how long new tests run and marked slow ones with pytest.mark.slow.

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Random-state seeding is separated from cuDNN configuration. Simulation functions now seed random states without changing cuDNN flags. Tests cover both seeding helpers and simulation behavior.

Changes: Seeding and simulation behavior

Layer / File(s) Summary
Seeding helper behavior
sbi/utils/sbiutils.py, tests/simulator_utils_test.py
seed_random_states seeds random states without changing cuDNN flags. seed_all_backends calls it and sets deterministic cuDNN flags. Tests verify both behaviors.
Simulation seeding call sites
sbi/simulators/simutils.py, sbi/utils/simulation_utils.py, tests/simulator_utils_test.py, CHANGELOG.md
Simulation functions use seed_random_states before sampling or simulator calls. Tests check that simulation leaves cuDNN flags unchanged for omitted and supplied seeds. The changelog describes this behavior and the option to set cuDNN flags directly.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • sbi-dev/sbi#1738: Adds simulation paths whose seeding behavior overlaps with the paths changed here.

Suggested reviewers: janfb, manuelgloeckler, dgedon

Merge Risk: Minimal · up to 73f4b

Simulation helpers will no longer change global cuDNN settings. Users who relied on simulation to enable deterministic convolutions must call seed_all_backends or set the flags themselves, and the changelog says so. No merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: simulation helpers no longer enable deterministic cuDNN. The changeset adds seed_random_states, which seeds random states without touching cuDNN flags, and switches si…
Linked Issues check Passed Issue #2159 requires simulation helpers to seed random states without changing process-wide cuDNN flags, and requires seed=None to stay reproducible through torch.manual_seed. At head 73f4b88, sbi/sim…
Out of Scope Changes check Passed The changes map to #2159. sbi/utils/sbiutils.py splits seeding from cuDNN configuration. sbi/simulators/simutils.py and sbi/utils/simulation_utils.py switch simulation paths to seed_random_states. tes…
Description check Passed The description states the problem (global cuDNN flags switched by simulation helpers), the fix (split seeding into seed_random_states, keep cuDNN setting in seed_all_backends), and the linked issue (…
Full details: Title check

Explanation

The title names the main change: simulation helpers no longer enable deterministic cuDNN. The changeset adds seed_random_states, which seeds random states without touching cuDNN flags, and switches simulate_for_sbi and simulate_in_batches to it. The title is short, specific, and matches the primary behavior change.

Full details: Linked Issues check

Explanation

Issue #2159 requires simulation helpers to seed random states without changing process-wide cuDNN flags, and requires seed=None to stay reproducible through torch.manual_seed. At head 73f4b88, sbi/simulators/simutils.py imports seed_random_states and calls it in simulate_in_batches and in the seeded simulator_seeded closure. It does not call seed_all_backends. The raw summary states that seed_random_states in sbi/utils/sbiutils.py seeds Python, NumPy, PyTorch and CUDA only, that seed=None is drawn from PyTorch's random state, and that seed_all_backends delegates to it and then sets cudnn.deterministic=True and cudnn.benchmark=False. The raw summary also states that sbi/utils/simulation_utils.py simulate_for_sbi now calls seed_random_states. The previous review verified the same behavior on the whole-PR diff at c63e784. The new tests in tests/simulator_utils_test.py cover the cuDNN flag behavior for seed=None and seed=42. Limitation: the incremental diff from c63e784 to 73f4b88 could not be read (diff tool unavailable), so changes between those commits are known only from the summary. The head file read of sbiutils.py was truncated before seed_random_states, so its body was not read directly at head. The test results come from the PR author's report and were not re-run.

Full details: Out of Scope Changes check

Explanation

The changes map to #2159. sbi/utils/sbiutils.py splits seeding from cuDNN configuration. sbi/simulators/simutils.py and sbi/utils/simulation_utils.py switch simulation paths to seed_random_states. tests/simulator_utils_test.py adds tests for the flag behavior. The CHANGELOG.md entry (+4 lines, per the raw summary) documents the behavior change for users, which is documentation that supports this objective. The only new name is seed_random_states, which the PR states is not exported publicly. No unrelated logic change was found in the inspected head content. Limitation: the incremental diff since c63e784 could not be read, so the CHANGELOG and any other later edits are assessed from the summary only.

Full details: Description check

Explanation

The description states the problem (global cuDNN flags switched by simulation helpers), the fix (split seeding into seed_random_states, keep cuDNN setting in seed_all_backends), and the linked issue (Fixes #2159). It covers the template's 'What does this PR do' and 'Does this close any issues' sections well. It also lists testing, reproducibility checks, and a user-visible impact. The checklist is present and checked off. The template's 'Anything else' section is filled in. The AI-assistance disclosure comment from the template is not addressed. This is a minor gap, so the description is mostly complete.

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.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c6eb0ba8-3e1a-4481-8583-b2cb6e62a8f1
Commits

Reviewing files that changed from the base of the PR and between c63e784 and 73f4b88.

Files selected for processing: 2

  • CHANGELOG.md
  • sbi/utils/sbiutils.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.

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 90.99%. Comparing base (95a4f5e) to head (05743dc).
⚠️ Report is 11 commits behind head on main.

Files with missing lines Patch % Lines
sbi/simulators/simutils.py 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2177      +/-   ##
==========================================
+ Coverage   88.52%   90.99%   +2.47%     
==========================================
  Files         149      149              
  Lines       16529    16531       +2     
==========================================
+ Hits        14632    15043     +411     
+ Misses       1897     1488     -409     
Flag Coverage Δ
fast 88.89% <87.50%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
sbi/utils/sbiutils.py 91.54% <100.00%> (+3.81%) ⬆️
sbi/utils/simulation_utils.py 87.33% <100.00%> (+5.33%) ⬆️
sbi/simulators/simutils.py 95.34% <66.66%> (ø)

... and 64 files with indirect coverage changes

@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@janfb once look into this please!

@janfb

janfb commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

@janfb once look into this please!

review will take time given the current number of open PRs.

@BHARATH0153

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@BHARATH0153

Copy link
Copy Markdown
Contributor Author

#2159

@BHARATH0153
BHARATH0153 force-pushed the fix-simulation-cudnn-flags branch 3 times, most recently from c63e784 to 73f4b88 Compare November 26, 2026 16:29
simulate_for_sbi and simulate_in_batches seeded through seed_all_backends, which
also sets torch.backends.cudnn.deterministic and clears benchmark. Both flags are
global to the process, so simulating switched convolutional training running later
in the same session onto deterministic cuDNN algorithms.

The seeding moves to seed_random_states in sbi/utils/sbiutils.py, and
seed_all_backends calls it before setting the two flags, which keeps its behavior
for the autouse fixture in tests/conftest.py and for existing callers. The
simulation paths, including the simulator_seeded closures used with num_workers >
1, call seed_random_states instead.

Seeding itself is unchanged: with seed=None the seed is still drawn from the torch
random state, so an upstream torch.manual_seed keeps reproducing a
simulate_for_sbi(seed=None) call, and the per-batch seeds are drawn from the same
state as before.

Fixes sbi-dev#2159

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.

Simulating turns on deterministic cuDNN for the rest of the session, even without a seed

2 participants