CategoricalMADE.sample() crashes on single-observation multi-dim conditions (MNPE/MNLE + CNNEmbedding), batch norm, and unconditional MADE

Open
#2,237 0 comments 0 reactions 0 assignees View on GitHub

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
Tech stack
python, pytorch

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():

  1. Multi-dimensional conditions with batch_dim=1 (e.g., MNPE with CNNEmbedding sampling for a single observation x_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), while samples has 3D shape (num_samples, 1, num_variables).
    • Inside nflows MADE.forward(), temps += self.context_layer(context) attempts (num_samples, 1, hidden) + (num_samples, hidden), crashing with RuntimeError: output with shape [N, 1, H] doesn't match the broadcast shape [N, N, H].
    • This went undetected in tests/density_estimator_test.py because every 2D-condition test case used batch_dim=10 (never batch_dim=1).
  2. use_batch_norm=True:
    • Passing 3D (num_samples, batch_dim, num_variables) into MADE causes nn.BatchNorm1d(hidden_features) to interpret batch_dim (axis 1) as the channel dimension instead of hidden_features, crashing with RuntimeError: running_mean should contain <batch_dim> elements not <hidden_features>.
  3. Unconditional CategoricalMADE (num_context_features=None, context=None):
    • sample() builds a dummy zero tensor context = torch.zeros(num_samples, 0) (also hardcoded on CPU) and passes it to MADE.forward(), crashing with AttributeError: 'CategoricalMADE' object has no attribute 'context_layer'.
  4. Zero-sized sample_shape (e.g. (0,)): Not guarded before invoking MADE and Categorical.
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

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from sbi-dev/sbi

All issues in sbi-dev/sbi

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.