Skip to content

Feature : LC2ST MLP GPU support (closes : #1160) - #1715

Merged
janfb merged 4 commits into
sbi-dev:mainfrom
Dev-Sudarshan:feature/lc2st-mlp-gpu-support
Feb 9, 2026
Merged

janfb merged 4 commits into
sbi-dev:mainfrom
Dev-Sudarshan:feature/lc2st-mlp-gpu-support

Conversation

@Dev-Sudarshan

Copy link
Copy Markdown
Contributor

This PR adds optional GPU support to L-C2ST by introducing a PyTorch-based
MLP classifier implemented via skorch. This addresses issue #1160 .

Changes:

  • Add a PyTorch MLP with skorch to support GPU training
  • Preserve sklearn-like defaults and training dynamics
  • Add device handling (cpu / cuda)
  • Support user overrides via classifier_kwargs while preserving sbi defaults
  • Extend tests to cover:
    • GPU/CPU device placement
    • Default parameter behavior
    • User override merging

@janfb

janfb commented Jan 7, 2026

Copy link
Copy Markdown
Contributor

Hi @Dev-Sudarshan,

Thank you for this contribution adding GPU support to LC2ST! Apologies for the long silence on this PR.

Note: This PR contains some unrelated PyMC version pinning changes. Please remove those by rebasing on main so we can focus on the GPU support implementation.

I've done a review and found the following issues:

Issues Found

  1. Missing dependency: skorch not added to pyproject.toml. please add it as core dependency in alphabetical order pyproject.toml.

  2. Incorrect input_dim for PyTorchMLP: At line 191-195, the module__input_dim is set to thetas.shape[-1], but the classifier receives concatenated [theta, x] data in train_lc2st() (line 769). This causes a dimension mismatch error when training on GPU.

Current:

elif self.clf_class == NeuralNetClassifier:                                                                                                                                           
      ndim = thetas.shape[-1]                                                                                                                                                           
      self.clf_kwargs = {                                                                                                                                                               
          "module": PyTorchMLP,                                                                                                                                                         
          "module__input_dim": ndim,  # Bug: only theta dim

Fix:

elif self.clf_class == NeuralNetClassifier:                                                                                                                                           
      ndim = thetas.shape[-1]                                                                                                                                                           
      input_dim = thetas.shape[-1] + xs.shape[-1]  # theta + x concatenated                                                                                                             
      self.clf_kwargs = {                                                                                                                                                               
          "module": PyTorchMLP,                                                                                                                                                         
          "module__input_dim": input_dim,                                                                                                                                               

(Keep ndim for hidden_layer_sizes calculation as that scaling is intentional.)

  1. PyTorchMLP should live in sbi/utils/metrics.py

The PyTorchMLP class is currently defined in lc2st.py, but we'd like it moved to sbi/utils/metrics.py where the existing C2ST code lives. This will allow reuse when we add GPU support to C2ST as well. We could also rename it to a more generic MLPClassifierModule, matching sklearn's MLPClassifier and skorch's module kwarg.

  1. Add MPS support and use generic GPU detection

The current implementation only checks for CUDA. Please add MPS support (for Apple Silicon) and refactor to use a generic use_gpu pattern:
For example. something like:

  if classifier.lower() == 'mlp':                                                                                                                                                       
      use_gpu = (                                                                                                                                                                       
          (self.device.lower() == 'cuda' and torch.cuda.is_available()) or                                                                                                              
          (self.device.lower() == 'mps' and torch.backends.mps.is_available())                                                                                                          
      ) 
      if use_gpu:                                                                                                                                                                       
          classifier = NeuralNetClassifier                                                                                                                                              
      else:                                                                                                                                                                             
          classifier = MLPClassifier                                                                                                                                                    

Similarly, update the RandomForest warning to check for device.lower() in ('cuda', 'mps').

  1. Warn when requested GPU is unavailable

When a user explicitly requests device="cuda" (or "mps") but that backend isn't available, the code silently falls back to sklearn's MLPClassifier. Please add a warning (similar to the RandomForest case) so users know their GPU request wasn't honored.

  1. Test organization

Instead of running the lc2st device test on both cpu and gpu, restrict it to GPU by adding a marker decorator:

@pytest.mark.gpu
  def test_lc2st_runs_on_requested_device(calibration_data):
      """Test that LC2ST runs on cpu and cuda/mps (if available)."""
      ...

and testing only cuda and mps (if available).

Thanks again for working on this feature – the overall approach using skorch looks good!

Let me know if you have any questions about the feedback above.

@janfb
janfb self-requested a review January 7, 2026 14:04

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See PR comment above.

@Dev-Sudarshan

Copy link
Copy Markdown
Contributor Author

Thank you for the feedback. I will review everything thoroughly and make the required changes.

@Dev-Sudarshan
Dev-Sudarshan force-pushed the feature/lc2st-mlp-gpu-support branch from 505ec2d to a41a52f Compare January 13, 2026 17:37
@codecov

codecov Bot commented Jan 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 58.97436% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.43%. Comparing base (937efc2) to head (5269ac1).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
sbi/utils/metrics.py 33.33% 10 Missing ⚠️
sbi/diagnostics/lc2st.py 75.00% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1715      +/-   ##
==========================================
- Coverage   88.54%   88.43%   -0.11%     
==========================================
  Files         137      137              
  Lines       11515    11547      +32     
==========================================
+ Hits        10196    10212      +16     
- Misses       1319     1335      +16     
Flag Coverage Δ
fast 84.61% <58.97%> (?)

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

Files with missing lines Coverage Δ
sbi/diagnostics/lc2st.py 93.63% <75.00%> (-2.41%) ⬇️
sbi/utils/metrics.py 87.34% <33.33%> (-3.69%) ⬇️

@Dev-Sudarshan

Copy link
Copy Markdown
Contributor Author

I have implemented all the changes as per your suggestions, including refactoring the MLP module to metrics.py, fixing the input_dim, adding MPS support, and cleaning the git history.

While running tests/lc2st_test.py, I encountered the following failure: FAILED tests/lc2st_test.py::test_lc2st_false_positiv_rate[LC2ST_NF] - AssertionError: LC2ST p-values too small, test should be rejected less then 5.00% of the time, but was rejected 24.00% of the time.

I verified that this failure is pre-existing by resetting to a clean upstream/main and confirming the test fails identically there. This PR introduces no regressions to that baseline.

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates @Dev-Sudarshan !

I added a couple of minor comments, otherwise it looks very good!

Regarding the test error: I can confirm that they fail on main, that's fine for now.

Comment thread sbi/utils/metrics.py Resolved
Comment thread sbi/utils/metrics.py Outdated
"""PyTorch implementation of a fully-connected multilayer perceptron (MLP)
with similar training dynamics."""

def __init__(self, input_dim, hidden_layer_sizes, output_dim=2):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add types and docstrings throughout.

Comment thread tests/lc2st_test.py Resolved
Comment thread tests/lc2st_test.py Resolved
Comment thread pyproject.toml Resolved
Comment thread pyproject.toml Resolved
Comment thread pyproject.toml Resolved
Comment thread pyproject.toml Resolved
Comment thread sbi/diagnostics/lc2st.py Resolved
Comment thread sbi/diagnostics/lc2st.py Resolved
@janfb janfb mentioned this pull request Jan 14, 2026
@Dev-Sudarshan

Dev-Sudarshan commented Jan 14, 2026 •

Copy link
Copy Markdown
Contributor Author

I will revert all the notebook related changes .I didn’t add those manually, they must have slipped in during merge/rebase.
I will also update the MLP docstring, add the missing type hints, switch to NeuralNetBinaryClassifier, remove the extra defaults test, and include the note about GPU behavior and passing skorch kwargs.

@Dev-Sudarshan
Dev-Sudarshan requested a review from janfb January 30, 2026 03:53

@janfb janfb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks all good, can be merged. Thanks a lot @Dev-Sudarshan and congrats to your sbi contribution 🎉

@janfb
janfb merged commit cf96ed9 into sbi-dev:main Feb 9, 2026
janfb added a commit that referenced this pull request Feb 9, 2026
Resolved conflicts integrating GPU support (PR #1715) into the
refactored LC2ST code:
- Added device parameter to LC2ST.__init__ with GPU detection
- Integrated NeuralNetBinaryClassifier for GPU-accelerated training
- Added skorch ValidSplit and EarlyStopping configuration
- Fixed target dtype for skorch (float32) vs sklearn (int64)
- Updated tests to use refactored cal_data fixture

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@Dev-Sudarshan
Dev-Sudarshan deleted the feature/lc2st-mlp-gpu-support branch March 27, 2026 12:34
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.

2 participants