Repository navigation
Skip the zero-width pad in soft_vmap - #2318
Conversation
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.
Benchmark reportthis PR - run time: 1 slower, 0 faster
compile time: unchanged across 32 benchmarksSignificant 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
|
| 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.
|
Thanks for this! I checked What I confirmed
Issue: NumPy inputs now pass straight through as NumPy arraysThe old 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])
Three consequences:
The existing 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)
It's worth adding a test for this: run Minor
|
|
Good catch, thanks. I went with Your repro now gives
|
Changes made
numpyro/util.py:soft_vmappadded its inputs withjnp.pad(x, ((0, pad),) + ((0, 0),) * ...)unconditionally. When run eagerly,jnp.padallocates a new buffer and copies the input even when every pad width is zero (XLA drops the op underjit), so whenever the batch size is a multiple of the chunk size,soft_vmapduplicated all of its input leaves, and the copies stayed alive for the duration of the mapped call.pad == 0is always the case for the defaultchunk_size=None(one chunk covering the whole batch), i.e. for everyPredictive(..., parallel=True)andlog_likelihood(..., parallel=True)call, where the inputs are the entire posterior. The pad is now applied only whenpad > 0.jnp.padcall was also what turned NumPy inputs into jax arrays. Without it, a leaf thatfnpasses through unchanged (e.g. adeterministicsite that returns a latent as is) came back as the caller's own NumPy array, sharing memory with it.soft_vmapnow converts its inputs withjnp.asarrayat the top of the function (a no-op for jax arrays, so no extra copy), so every path returns jax arrays. This also covers thechunk_size <= 1path, where on master a batch of size 1 with NumPy inputs already had the same pass-through.Results are unchanged: with
pad == 0the padded array was equal to the input, and thepad > 0path is untouched. The memory saving applies to thebatch_ndims == 1layout (the flat posterior); withbatch_ndims == 2the 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, posteriorwof shape(S, D)in float32, best of 3 calls after a warmup call:Live device memory while the mapped function runs (
jax.live_arrays()insidefn,soft_vmap(fn, {"w": (4000, 25000) float32}, 1, None)):fnOn 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.asarrayconversion does not change these numbers (400 MB insidefn, 6.5 ms for thesoft_vmapcall alone).The CI benchmark rows do not exercise this path:
predictive_forward_samplinguses the defaultparallel=False, i.e.chunk_size=1.Links to related issues/PRs
None.
Tests
test_soft_vmapintest/test_util.pyis now parametrized over NumPy and jax inputs and has a pass-through leaf; it asserts that every output is ajax.Array. The NumPy cases fail on master forbatch_shape=()/(1,)and on the first version of this PR for everypad == 0case.(3, 4)withchunk_size=5is the only case that takes thepad > 0path (chunk_size=16is clipped to the batch size 12, sopad == 0).pytest test/test_util.py test/infer/test_infer_util.py(Predictive/log_likelihood, parallel and sequential) — 102 passed.ruff check/ruff format --checkclean.Dependencies
None.