jax icon indicating copy to clipboard operation
jax copied to clipboard

fix(stats): multinomial.logpmf returns -inf for every row of a batched input

Open Sumu004 opened this issue 5 months ago • 0 comments

What

jax.scipy.stats.multinomial.logpmf (and .pmf) return -inf / 0 for every row of a batched input, even when each row is individually a valid count vector summing to n:

import jax; jax.config.update("jax_enable_x64", True)
import numpy as np
import jax.scipy.stats.multinomial as jmn
import scipy.stats as ss

p = np.array([0.2, 0.3, 0.5])
x = np.array([[2, 3, 5], [1, 4, 5]])  # each row sums to n=10

print(jmn.logpmf(x, 10, p))           # [-inf -inf]            (wrong)
print(ss.multinomial.logpmf(x, 10, p))  # [-2.4645 -2.7522]    (correct)

Root cause

jax/_src/scipy/stats/multinomial.py::logpmf ends with a validity mask:

logprobs = gammaln(n + 1) + jnp.sum(xlogy(x, p) - gammaln(x + 1), axis=-1)
return jnp.where(jnp.equal(jnp.sum(x), n), logprobs, -np.inf)

logprobs is correctly computed per-row (axis=-1), but the mask's jnp.sum(x) reduces over every axis. For a batch of shape (B, K), this compares the grand total of all B*K entries against n instead of each row's own count. Once B > 1 the grand total essentially never equals n, so every row is incorrectly forced to -inf.

This stayed hidden because the existing test suite (testMultinomialLogPmf) only ever exercises single, unbatched examples, where the grand total trivially equals the per-row sum.

Fix

One line: jnp.sum(x) → jnp.sum(x, axis=-1), matching the shape logprobs already broadcasts against.

Cross-checks

scipy.stats.multinomial.logpmf and torch.distributions.Multinomial(10, probs=p).log_prob(x) both return [-2.4645, -2.7522] for the example above — JAX was the lone outlier, and only for batched inputs.

Fixes #38605

Checklist

  • [x] New testMultinomialLogPmfBatched regression test: checks a batched valid input against scipy, and confirms a row that does not sum to n is still correctly rejected with -inf
  • [x] Existing testMultinomialLogPmf (unbatched) still passes — the fix is a strict generalization
  • [x] One-line diff

Sumu004 avatar Jun 25 '26 01:06 Sumu004