CategoricalMADE.sample() crashes on single-observation multi-dim conditions (MNPE/MNLE + CNNEmbedding), batch norm, and unconditional MADE
Maintainers usually reply within 6 days
@patelshivani2283-lab is already working on this.
Since Nov 26, 2026.
- #2238 by @patelshivani2283-lab — open
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 57/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Active
- Domain
- backend, machine-learning
Research direction
Start with sbi/neural_nets/estimators/categorical_net.py, especially CategoricalMADE.sample() and CategoricalMassEstimator.log_prob, then review tests/density_estimator_test.py. Reproduce the single-observation condition case and the reported batch normalization and unconditional sampling cases. Done means each configuration samples successfully, including a zero-sized sample shape, with regression coverage for the reported failures.
Written by the indexing model from the issue text.
Description
Bug description
CategoricalMADE.sample() (and consequently CategoricalMassEstimator, MNPE, and MNLE) crashes in several standard configurations because it passes 3D (num_samples, batch_dim, num_variables) inputs and inconsistently shaped context tensors directly into MADE.forward():
- Multi-dimensional conditions with
batch_dim=1(e.g.,MNPEwithCNNEmbeddingsampling for a single observationx_o):if context.ndim == 2: context = context.unsqueeze(0)is skipped for 2D/3D conditions like(1, H, W).if batch_dim == 1: context = torchutils.repeat_rows(context, num_samples)turns(1, H, W)into(num_samples, H, W).embedding_net(context)then outputs 2D(num_samples, emb_dim), whilesampleshas 3D shape(num_samples, 1, num_variables).- Inside
nflowsMADE.forward(),temps += self.context_layer(context)attempts(num_samples, 1, hidden) + (num_samples, hidden), crashing withRuntimeError: output with shape [N, 1, H] doesn't match the broadcast shape [N, N, H]. - This went undetected in
tests/density_estimator_test.pybecause every 2D-condition test case usedbatch_dim=10(neverbatch_dim=1).
use_batch_norm=True:- Passing 3D
(num_samples, batch_dim, num_variables)intoMADEcausesnn.BatchNorm1d(hidden_features)to interpretbatch_dim(axis 1) as the channel dimension instead ofhidden_features, crashing withRuntimeError: running_mean should contain <batch_dim> elements not <hidden_features>.
- Passing 3D
- Unconditional
CategoricalMADE(num_context_features=None,context=None):sample()builds a dummy zero tensorcontext = torch.zeros(num_samples, 0)(also hardcoded on CPU) and passes it toMADE.forward(), crashing withAttributeError: 'CategoricalMADE' object has no attribute 'context_layer'.
- Zero-sized
sample_shape(e.g.(0,)): Not guarded before invokingMADEandCategorical.
Minimal code example
import torch
from sbi.neural_nets.embedding_nets import CNNEmbedding
from sbi.neural_nets.net_builders import build_mnpe
batch_theta = torch.cat(
[torch.randn(20, 1), torch.randint(0, 3, (20, 1)).float()], dim=-1
)
batch_x = torch.randn(20, 16, 16)
emb = CNNEmbedding(input_shape=(16, 16), output_dim=8)
estimator = build_mnpe(
batch_x=batch_theta,
batch_y=batch_x,
embedding_net=emb,
z_score_y="structured",
)
# Sampling for a single observation (as posterior.sample((5,), x=x_o) does):
x_o = torch.randn(1, 16, 16)
estimator.sample((5,), condition=x_o)
Error message or traceback
Traceback (most recent call last):
...
File "sbi/neural_nets/estimators/mixed_density_estimator.py", line 95, in sample
discrete_samples = self.discrete_net.sample(
File "sbi/neural_nets/estimators/categorical_net.py", line 315, in sample
return self.net.sample(sample_shape, condition, **kwargs)
File "sbi/neural_nets/estimators/categorical_net.py", line 241, in sample
outputs = self.forward(samples, context)
File "sbi/neural_nets/estimators/categorical_net.py", line 174, in forward
out = super().forward(input, context=embedded_condition)
File "sbi/utils/nn_utils.py", line 126, in forward
outputs = super().forward(concat_input, context)
File "nflows/nn/nde/made.py", line 277, in forward
temps += self.context_layer(context)
RuntimeError: output with shape [5, 1, 50] doesn't match the broadcast shape [5, 5, 50]
sbi version
0.27.0 (main @ 797a5ab3)
Python version
Python 3.12.13
Device
CPU
Inference method
MNLE / MNPE
Single-round or multi-round
Not applicable
Additional context
Embedding context once at its native (batch_dim, *condition_shape) shape before the autoregressive loop and flattening (num_samples, batch_dim) into a single batch dimension (num_samples * batch_dim, ...) — matching what CategoricalMassEstimator.log_prob already does — fixes all of these cases cleanly and avoids re-running embedding_net on every autoregressive step.
- Dominant language
- Python
- Stars
- 894
- Forks
- 306
- Avg merge
- 5d 21h
- Merged PRs (30d)
- 61
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from sbi-dev/sbi
-
simulate_for_sbi(num_simulations=0) returns 1D empty theta/x tensors and breaks append_simulationsOpenbug
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
sbi-dev/sbi#2310 · 3 comments ·
Maintainers usually reply within 6 days
-
bug: RestrictionEstimator.train(subsample_invalid_sims="auto") raises TypeErrorPossibly taken @Nitesh780 claimed this 2 days ago. Openbug
Difficulty 1/5 1-3 hours Newbie friendliness 85/100
sbi-dev/sbi#2309 · 1 comment ·
Maintainers usually reply within 6 days
-
TARP reference sampling fails when a parameter coordinate is fixedPossibly taken @Jayant-kernel claimed this 4 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
sbi-dev/sbi#2264 · 2 comments ·
Maintainers usually reply within 6 days
-
fix: broadcast UniformNormalConvolution batch shapePossibly taken @studentarijitpaul claimed this 32 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
sbi-dev/sbi#2151 · 2 comments ·
Maintainers usually reply within 6 days
-
bug
sbi-dev/sbi#2321 · 1 comment ·
Maintainers usually reply within 6 days
Similar issues
-
Test: to_hijri() accepts datetime.datetime and uses only the date partPossibly taken A pull request linked to this issue is open or already merged. Opengood first issue
Difficulty 1/5 Under an hour Newbie friendliness 95/100
omarelshamy25x/shamy-hijri#63 · 3 comments ·
Maintainers usually reply within 1 day