Skip to content

Skip the zero-width pad in soft_vmap - #2318

Merged
juanitorduz merged 2 commits into
pyro-ppl:masterfrom
kyo219:soft-vmap-skip-zero-pad
Oct 4, 2026
Merged

juanitorduz merged 2 commits into
pyro-ppl:masterfrom
kyo219:soft-vmap-skip-zero-pad

Conversation

@kyo219

@kyo219 kyo219 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Changes made

  • numpyro/util.py: soft_vmap padded its inputs with jnp.pad(x, ((0, pad),) + ((0, 0),) * ...) unconditionally. When run eagerly, jnp.pad allocates a new buffer and copies the input even when every pad width is zero (XLA drops the op under jit), so whenever the batch size is a multiple of the chunk size, soft_vmap duplicated all of its input leaves, and the copies stayed alive for the duration of the mapped call. pad == 0 is always the case for the default chunk_size=None (one chunk covering the whole batch), i.e. for every Predictive(..., parallel=True) and log_likelihood(..., parallel=True) call, where the inputs are the entire posterior. The pad is now applied only when pad > 0.
  • The jnp.pad call was also what turned NumPy inputs into jax arrays. Without it, a leaf that fn passes through unchanged (e.g. a deterministic site that returns a latent as is) came back as the caller's own NumPy array, sharing memory with it. soft_vmap now converts its inputs with jnp.asarray at the top of the function (a no-op for jax arrays, so no extra copy), so every path returns jax arrays. This also covers the chunk_size <= 1 path, where on master a batch of size 1 with NumPy inputs already had the same pass-through.

Results are unchanged: with pad == 0 the padded array was equal to the input, and the pad > 0 path is untouched. The memory saving applies to the batch_ndims == 1 layout (the flat posterior); with batch_ndims == 2 the leading reshape that merges the batch axes still copies eagerly, so there the PR only removes one of two copies.

Benchmarks

Apple M2 (24 GB), CPU, jax 0.10.2, Python 3.11. Fresh process per run.

Predictive(model, posterior_samples, parallel=True) for a D-dimensional linear model, posterior w of shape (S, D) in float32, best of 3 calls after a warmup call:

posterior master this PR
S=1000, D=25000 (100 MB) 13.0 ms 8.4 ms
S=4000, D=25000 (400 MB) 49.2 ms 28.6 ms

Live device memory while the mapped function runs (jax.live_arrays() inside fn, soft_vmap(fn, {"w": (4000, 25000) float32}, 1, None)):

master this PR
before the call 400 MB 400 MB
inside fn 800 MB 400 MB

On CPU the saving is one full pass over the posterior per call; on accelerators the transient duplicate of the whole posterior is what matters (OOM headroom for large posteriors). The jnp.asarray conversion does not change these numbers (400 MB inside fn, 6.5 ms for the soft_vmap call alone).

The CI benchmark rows do not exercise this path: predictive_forward_sampling uses the default parallel=False, i.e. chunk_size=1.

Links to related issues/PRs

None.

Tests

  • test_soft_vmap in test/test_util.py is now parametrized over NumPy and jax inputs and has a pass-through leaf; it asserts that every output is a jax.Array. The NumPy cases fail on master for batch_shape=()/(1,) and on the first version of this PR for every pad == 0 case. (3, 4) with chunk_size=5 is the only case that takes the pad > 0 path (chunk_size=16 is clipped to the batch size 12, so pad == 0).
  • pytest test/test_util.py test/infer/test_infer_util.py (Predictive / log_likelihood, parallel and sequential) — 102 passed.
  • ruff check / ruff format --check clean.

Dependencies

None.

jnp.pad allocates and copies its input even when every pad width is
zero, so soft_vmap duplicated all of its inputs (e.g. the whole
posterior for Predictive(parallel=True)) whenever the batch size was a
multiple of the chunk size, which is always the case for the default
chunk_size=None. Only pad when there is something to pad.
@github-actions github-actions Bot added the awaiting review Awaiting review from maintainers label Oct 3, 2026
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Benchmark report

this PR soft-vmap-skip-zero-pad at 5af5ce8b vs baseline master at 5a3e636c

- run time:     1 slower, 0 faster
  compile time: unchanged across 32 benchmarks

Significant changes (1)

                       ─────── run time ───────     ───── compile time ─────
  benchmark            baseline  this PR      Δ     baseline  this PR      Δ
────────────────────────────────────────────────────────────────────────────
- nuts_eight_schools     1.14 s   1.22 s  +7.2%       2.61 s   2.77 s  +6.3%

Red is slower, green is faster; a row is coloured by the worse of its two columns. A delta in parentheses cleared the threshold on a measurement below the resolution floor, so it is shown without being called a change. † marks a benchmark that could not be compared — see below.

Full results

distributions

                                 ───────── run time ────────     ────── compile time ──────
  benchmark                      baseline  this PR         Δ     baseline   this PR       Δ
───────────────────────────────────────────────────────────────────────────────────────────
  biject_to_constraints            3.8 ms   3.8 ms     -0.1%     372.2 ms  358.9 ms   -3.6%
  categorical_log_prob             2.3 ms   2.1 ms     -4.8%      75.7 ms   67.8 ms  -10.4%
  dirichlet_log_prob               623 µs   621 µs     -0.4%     512.5 ms  477.3 ms   -6.9%
  dirichlet_sample                45.7 ms  44.5 ms     -2.6%     828.2 ms  850.0 ms   +2.6%
  gamma_log_prob                   2.1 ms   2.2 ms     +4.6%       3.21 s    2.62 s  -18.2%
  gamma_sample                    19.8 ms  19.1 ms     -3.5%     848.0 ms  811.0 ms   -4.4%
  lkj_cholesky_sample              5.4 ms   5.4 ms     +0.8%       1.22 s    1.17 s   -4.5%
  mixture_same_family_log_prob     961 µs   967 µs     +0.7%      84.3 ms   83.5 ms   -0.9%
  multivariate_normal_log_prob     319 µs   283 µs  (-11.3%)     618.8 ms  578.7 ms   -6.5%
  normal_log_prob                  735 µs   682 µs   (-7.1%)      69.1 ms   58.3 ms  -15.7%
  normal_sample                   24.0 ms  23.2 ms     -3.2%     212.2 ms  212.4 ms   +0.1%
  stick_breaking_transform         6.2 ms   6.0 ms     -3.3%     232.8 ms  220.1 ms   -5.5%
  student_t_log_prob               3.1 ms   3.1 ms     -0.6%      79.3 ms   80.5 ms   +1.4%
  truncated_normal_log_prob        800 µs   881 µs  (+10.1%)      57.0 ms   53.3 ms   -6.5%

handlers

                                  ───────── run time ────────     ────── compile time ──────
  benchmark                       baseline   this PR        Δ     baseline   this PR       Δ
────────────────────────────────────────────────────────────────────────────────────────────
  initialize_model_hierarchical    46.4 ms   45.7 ms    -1.5%       3.81 s    3.69 s   -3.2%
  log_density_hierarchical          4.2 ms    4.0 ms    -4.0%       1.35 s    1.30 s   -3.4%
  nested_handler_stack              1.5 ms    1.5 ms    -2.6%       570 µs    534 µs   -6.3%
  potential_energy_and_grad          22 µs     21 µs  (-5.9%)     104.9 ms  104.1 ms   -0.8%
  predictive_forward_sampling     685.5 ms  674.8 ms    -1.6%     197.8 ms  184.3 ms   -6.8%
  trace_seeded_model                900 µs    913 µs    +1.4%     607.6 ms  527.0 ms  -13.3%

mcmc

                             ──────── run time ───────     ────── compile time ─────
  benchmark                  baseline   this PR      Δ     baseline  this PR       Δ
────────────────────────────────────────────────────────────────────────────────────
  hmc_logistic_regression    701.8 ms  721.1 ms  +2.7%       3.16 s   3.29 s   +4.1%
  nuts_dense_mass_funnel       1.15 s    1.13 s  -2.0%       2.59 s   2.62 s   +1.1%
- nuts_eight_schools           1.14 s    1.22 s  +7.2%       2.61 s   2.77 s   +6.3%
  nuts_hierarchical_glm        3.21 s    3.26 s  +1.4%       4.69 s   5.21 s  +11.0%
  nuts_logistic_regression     1.08 s    1.07 s  -1.2%       3.18 s   3.13 s   -1.7%
  nuts_vectorized_chains       2.49 s    2.48 s  -0.4%       3.03 s   2.89 s   -4.6%

svi

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
  svi_autodelta_map_logistic                 320.3 ms  310.2 ms  -3.1%       3.12 s   3.06 s  -1.9%
  svi_autodiagonalnormal_hierarchical          1.03 s  996.1 ms  -3.7%       4.96 s   4.93 s  -0.6%
  svi_automultivariatenormal_eight_schools   743.5 ms  737.0 ms  -0.9%       4.36 s   4.38 s  +0.4%
  svi_autonormal_logistic                    723.0 ms  731.4 ms  +1.2%       3.42 s   3.39 s  -0.7%
  svi_multi_particle_elbo                      1.45 s    1.47 s  +1.4%       3.55 s   3.45 s  -2.8%
  svi_trace_mean_field_elbo                    1.27 s    1.26 s  -1.0%       5.30 s   5.27 s  -0.7%
Methodology and environment

Each benchmark is set up untimed, then called once with the JAX caches cleared and several more times warm. Run is the fastest warm call; compile is the first call minus that, i.e. the tracing, lowering and XLA compilation the warm calls did not have to pay for.

Both refs were measured on the same runner over 2 interleaved round(s), taking the best observation per benchmark. A result is called neutral when it moves less than ±5% (run) or ±25% (compile), or when the measurement itself is under 1 ms (run) / 50 ms (compile) — a shared CI runner cannot resolve changes below that. Compile time gets the looser band because it is measured once per round rather than best-of-N, and swings by roughly 20% even between two runs of identical code. A delta shown in parentheses did clear its threshold, but on a measurement below the resolution floor, so it is reported without being called a change.

baseline this PR
ref master soft-vmap-skip-zero-pad
commit 5a3e636c 5af5ce8b
numpyro 0.22.0 0.22.0
jax 0.11.2 0.11.2
backend cpu cpu
python 3.14.8 3.14.8

Runner: Linux-6.17.0-1022-azure-x86_64-with-glibc2.39, 4 CPUs.

Produced by this benchmark run.

@juanitorduz

Copy link
Copy Markdown
Collaborator

Thanks for this! I checked e60904d5 against its base 5a3e636c (jax 0.10.2, CPU). The optimization works, but one side effect needs fixing first: when the posterior holds NumPy arrays, Predictive(parallel=True) now returns some sites as NumPy arrays. A one-line else branch fixes this and keeps the full gain.

What I confirmed

Claim Result
jnp.pad copies even when every pad width is zero (outside jit) Confirmed: the output lands in a new buffer
Same-shape jnp.reshape and the output-side [:batch_size] don't copy Confirmed, so the pad was the only copy on the pad == 0 path
Live memory inside fn for a (4000, 25000) float32 input 800 MB → 400 MB
Predictive(parallel=True) speed, S=4000, D=25000 13.8 ms → 10.3 ms
Under jit No difference; XLA already drops zero-width pads
test_soft_vmap + test/infer/test_infer_util.py, ruff check / ruff format --check 71 passed, clean

Issue: NumPy inputs now pass straight through as NumPy arrays

The old jnp.pad also turned every input into a jax.Array. That conversion is now gone when pad == 0. In jax 0.10.2, a same-shape jnp.reshape hands a NumPy array back unchanged, and so does vmap(identity). So if a site's value just passes through, the user's own NumPy array comes back out.

import numpy as np
import jax, jax.numpy as jnp
import numpyro, numpyro.distributions as dist
from numpyro.infer import Predictive

def model(X):
    w = numpyro.sample("w", dist.Normal(0, 1).expand([3]).to_event(1))
    numpyro.deterministic("w2", w)
    numpyro.sample("y", dist.Normal(X @ w, 1.0))

post = {"w": np.ones((4, 3), dtype=np.float32)}
out = Predictive(model, post, parallel=True, return_sites=["w", "w2", "y"])(
    jax.random.key(0), jnp.ones((5, 3))
)
print({k: type(v).__name__ for k, v in out.items()})
post["w"][0, 0] = 99.0
print(out["w"][0, 0])
base this PR
parallel=True output types w, w2, y are all ArrayImpl w: ndarray, w2: ndarray, y: ArrayImpl
parallel=False output types all ArrayImpl all ArrayImpl
Changing post["w"] in place after the call output unaffected output w changes too (it shares memory with the input)

Three consequences:

  • The output type now depends on parallel= and on whether the input was NumPy or JAX.
  • Predictive output can change silently, because it shares memory with a NumPy array the user can still edit.
  • Default calls are affected too: by default Predictive returns deterministic sites, and one that passes a latent through unchanged now comes back as a NumPy array without any return_sites.

The existing test_soft_vmap only uses jnp.ones inputs, so it can't catch this.

Suggested fix (I checked it locally):

if pad > 0:
    xs = jax.tree.map(
        lambda x: jnp.pad(x, ((0, pad),) + ((0, 0),) * (np.ndim(x) - 1)),
        xs,
    )
else:
    xs = jax.tree.map(jnp.asarray, xs)
  • jnp.asarray(jax_array) returns the same object, so there's still no copy: memory inside fn stayed at 400 MB and timing at 10.5 ms.
  • jnp.asarray(np_array) makes a copy that doesn't share memory with the user's array. With the patch, all outputs above were ArrayImpl again, and the 71 tests still pass.
  • It also works on typed key arrays: jnp.asarray(key_array) is key_array.

It's worth adding a test for this: run test_soft_vmap with both np.ones and jnp.ones inputs and assert every output is a jax.Array.

Minor

  1. The memory saving only applies when batch_ndims == 1. With batch_ndims=2 (posterior grouped by chain), the first jnp.reshape that merges the batch axes already copies outside jit. Memory inside fn stays at 800 MB both before and after this PR; there it only saves time (one fewer copy). Worth narrowing the "every Predictive(..., parallel=True)" wording in the description.
  2. Test coverage note in the description: (3, 4) with chunk_size=16 gives min(12, 16) = 12, so pad == 0. Only (3, 4) with chunk_size=5 runs the pad > 0 path.
  3. The CI benchmark doesn't touch this code. predictive_forward_sampling uses the default parallel=False, so chunk_size=1 and the changed branch never runs. The normal_sample +5.3% is noise unrelated to soft_vmap. The local numbers in the description are the real evidence, and they reproduce.
  4. Context: numpyro's own callers (Predictive, log_likelihood) only use chunk_size of 1 or the full batch, so they never pad. The pad > 0 path only runs when someone calls soft_vmap directly with a custom chunk size.
  5. Nice side effect: typed PRNG key leaves now work when pad == 0. On base, soft_vmap over jax.random.split(jax.random.key(0), 6) failed for every chunk_size > 1 with Cannot convert_element_type from int32 to key<fry>. With this PR, chunk_size=None and 3 work. chunk_size=4 (which pads) still fails; that's an existing issue outside this PR.
  6. Comment wording: the copy only happens outside jit, so something like "jnp.pad copies its input when run eagerly, even for zero widths (XLA drops it under jit)" would be more precise, and it could be shorter than three lines.

@kyo219

kyo219 commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Good catch, thanks. I went with jnp.asarray as suggested but put it at the top of soft_vmap rather than in an else: while extending the test I noticed that batch_shape=(1,) (or any batch of size 1, where chunk_size ends up as 1) has the same pass-through on master, since that path skips the pad entirely. Converting once up front covers both and is still free for jax inputs. Pushed as 5af5ce8.

Your repro now gives ArrayImpl for w/w2/y and editing post["w"] afterwards doesn't touch the output. Memory inside fn stays at 400 MB and the typed-key cases (chunk_size=None/3) still work.

test_soft_vmap is parametrized over np/jnp inputs with a pass-through leaf; the NumPy variants fail on master for the size-1 batches and failed on the first version of this PR for every pad == 0 case. Description updated for the batch_ndims == 1 scope, the chunk_size=16 coverage note and the CI benchmark.

@juanitorduz
juanitorduz merged commit ac3f64f into pyro-ppl:master Oct 4, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review Awaiting review from maintainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants