distrax icon indicating copy to clipboard operation
distrax copied to clipboard

fix(distrax): Tanh NaN clip + MultivariateNormal vmap batch_shape fix

Open Sumu004 opened this issue 5 months ago • 1 comments

What does this PR do?

Two related numerical-correctness fixes in distrax:


Fix 1: Tanh bijector — clip inverse to prevent NaN in log_prob (Fixes #216)

In float32, sampling from a Tanh-transformed distribution (SAC, PPO with squashed Gaussian) can produce values equal to ±1 due to limited precision. arctanh(±1) = ±∞, propagating to NaN in log_prob.

Fix: clip y to (-1+ε, 1-ε) where ε = jnp.finfo(y.dtype).eps before calling arctanh. Dtype-aware (float64 uses 2.2e-16, float32 uses 1.2e-7).


Fix 2: MultivariateNormalFromBijector — batch_shape stale after vmap (Fixes #276)

When distributions are constructed inside jax.vmap, the vmapped execution prepends a batch dimension to _loc at run time. The _batch_shape tuple captured at trace time doesn't include this extra dimension, causing dist.loc to raise:

ValueError: Cannot broadcast to shape with fewer dimensions: arr_shape=(B, D) shape=(D,)

Fix: override batch_shape as a computed property. Detect extra leading dimensions in _loc beyond what _batch_shape + _event_shape predict, and prepend them. Preserves scale-broadcasting semantics for the non-vmap case.


Tests

Fix 1: test_stability updated; test_inverse_clips_boundary_values_to_prevent_nan + test_log_prob_finite_at_float32_boundary_samples added.

Fix 2: VmapBatchShapeTest with 4 cases: vmap batch_shape, vmap loc accessible, non-vmapped unchanged, scale-broadcasting unchanged.

All 69 Tanh tests and 359 MVN tests pass.

Sumu004 avatar Jun 04 '26 16:06 Sumu004

Friendly bump, this fix (Tanh NaN clip + MultivariateNormal vmap batch_shape) has been open about a month with no review yet. Happy to address any feedback. Thanks!

Sumu004 avatar Jul 10 '26 10:07 Sumu004