← Back to Pull requests

fix: handle scalar event_shape () in reshape_to_{batch,sample_batch}_event (#2235) #2236

Open
unknown opened this pull request with 412 lines diff across 5 files
View on GitHub
unknown unknown commented on Nov 25, 2026 17:44 UTC
Author

What does this PR do?

Fixes #2235 — reshape_to_batch_event and reshape_to_sample_batch_event in sbi/neural_nets/estimators/shape_handling.py raise a spurious RuntimeError when event_shape is torch.Size([]) (scalar observations/parameters), breaking callers that handle scalar events (such as MarginalTrainer on 1-D data).

Root cause

Python's negative-index slice edge case:

t = torch.randn(10)
t.shape[-0:]   # == t.shape[0:] == torch.Size([10])  ← full shape, NOT torch.Size([])

When event_shape = torch.Size([]), event_shape_dim = 0, and tensor.shape[-0:] returns the full shape instead of the expected empty slice. The trailing-shape check then always fails.

Downstream impact & Caller Hardening

1. Scalar event handling: Callers such as MarginalTrainer on 1-D data (input_shape == torch.Size([])) crashed during estimation and sampling.
2. Batch dimension validation: In likelihood_based_potential.py and npe_b.py, callers passing theta.shape[1:] to the reshape helpers previously raised by accident when theta was 1-D unbatched. With scalar events now supported, explicit theta.dim() < 2 guards were added to ensure unbatched theta continues to raise an informative ValueError:

   if theta.dim() < 2:
       raise ValueError(
           f"`theta` must have a batch dimension, got shape {tuple(theta.shape)}."
       )
   

Fix

1. Add a one-branch guard for event_shape_dim == 0 in both reshape utilities:

   if event_shape_dim == 0:
       trailing_theta_or_x_shape = torch.Size([])
       leading_theta_or_x_shape = theta_or_x.shape
   else:
       trailing_theta_or_x_shape = theta_or_x.shape[-event_shape_dim:]
       leading_theta_or_x_shape = theta_or_x.shape[:-event_shape_dim]
   

The existing Simformer special-case for event_shape == torch.Size([0]) is left untouched.
2. Add explicit batch dimension validation in _log_likelihoods_over_trials (likelihood_based_potential.py) and _log_prob_proposal_posterior (npe_b.py).

Tests added

  • tests/density_estimator_test.py:

  • - 4 parametrized cases for reshape_to_sample_batch_event with event_shape = () covering scalar, 1-D batch, 1-D sample, and 2-D inputs.
    - Standalone test_reshape_to_batch_event_scalar_event covering a 1-D batch and a 0-D scalar input.
  • tests/marginal_estimator_test.py:

  • - test_marginal_trainer_1d_data: trains MarginalTrainer on 1-D scalar data, verifying scalar input_shape == torch.Size([]), sampling shape (10, 1), and log probability shape (10,).
  • tests/potential_test.py:

  • - test_likelihood_based_potential_raises_on_unbatched_theta: asserts LikelihoodBasedPotential raises ValueError on unbatched theta.
  • tests/linearGaussian_snpe_test.py:

  • - test_npe_b_log_prob_proposal_posterior_raises_on_unbatched_theta: asserts NPE_B proposal-posterior evaluation raises ValueError on unbatched theta.

    Checklist

  • Tests pass locally (pytest tests/density_estimator_test.py tests/marginal_estimator_test.py tests/potential_test.py tests/linearGaussian_snpe_test.py)

  • ruff check and ruff format --check pass with no errors

  • No existing special cases modified (Simformer path intact)

  • Linked to issue #2235
  • Diff: 412 lines (+309 / -103) across 5 files Reviewer: patelshivani2283-lab Review duration: 5012m
    All Vouch review confidence checks passed
    Residual risk 0.24 = Change Risk (0.45) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.45 · 412 lines diff across 5 files
    0.45
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.360
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #2236"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 44.9% (MEDIUM) · Higher = larger blast radius
    44.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 23.9% · Safe to merge
    23.9%
    Repository