Skip to content

fix(contrib.hsgp): accept NumPy scalars for ell and m - #2447

Open
leninworld wants to merge 2 commits into
pyro-ppl:masterfrom
leninworld:fix-hsgp-numpy-scalars-issue-2446
Open

leninworld wants to merge 2 commits into
pyro-ppl:masterfrom
leninworld:fix-hsgp-numpy-scalars-issue-2446

Conversation

@leninworld

Copy link
Copy Markdown
Contributor

This PR fixes issue #2446.

NumPy scalar ell values could silently leave an empty buffer in place, while NumPy integer m values raised TypeError. This is the same NumPy-scalar type-check gap addressed for handler seeds in #2425.

Changes:

  • Treat NumPy integer m values like Python integers.
  • Broadcast NumPy integer and floating ell scalars across dimensions.
  • Raise ValueError for unsupported ell inputs and add regression coverage, including a public sqrt_eigenvalues check.

The annotations of the public hsgp_*, sqrt_eigenvalues and eigenfunctions functions are unchanged; NumPy scalars passed through them now reach the helpers correctly.

Tests:

  • pytest test/contrib/hsgp/test_laplacian.py — 38 passed (7 new cases); with the unpatched
    numpyro/contrib/hsgp/laplacian.py, the new cases fail (6 failed, 32 passed).
  • pytest test/contrib/hsgp — 99 passed; 64 rational-quadratic/periodic failures are pre-existing in the local
    environment because the installed TensorFlow Probability is incompatible with JAX 0.12.1, and the failure set is
    identical before and after this change.
  • make lint steps — ruff 0.17.6 check and format --check, scripts/update_headers.py --check, and ty 0.0.75
    check: all pass.

Closes #2446

Treat NumPy integer and floating scalars like Python scalars in the HSGP
Laplacian helpers. A NumPy scalar ell was silently treated as zero and a
NumPy integer m raised TypeError. An unsupported ell now raises ValueError.

Closes pyro-ppl#2446
@github-actions github-actions Bot added the awaiting review Awaiting review from maintainers label Nov 21, 2026
@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Benchmark report

this PR fix-hsgp-numpy-scalars-issue-2446 at f14f865c vs baseline master at fc7691c7

  run time:     unchanged across 32 benchmarks
  compile time: unchanged across 32 benchmarks

No significant changes

Every benchmark stayed within ±5% run time and ±25% compile time.

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            4.1 ms   4.1 ms     +0.0%     325.1 ms  305.1 ms  -6.1%
  categorical_log_prob             2.3 ms   2.3 ms     +0.3%      67.3 ms   63.5 ms  -5.5%
  dirichlet_log_prob               651 µs   648 µs     -0.5%     743.0 ms  754.1 ms  +1.5%
  dirichlet_sample                59.0 ms  58.5 ms     -0.9%       3.02 s    3.11 s  +2.9%
  gamma_log_prob                   2.0 ms   2.0 ms     -1.1%       3.47 s    3.45 s  -0.3%
  gamma_sample                    21.4 ms  21.3 ms     -0.1%       2.86 s    2.89 s  +1.0%
  lkj_cholesky_sample              3.4 ms   3.4 ms     +0.1%       2.83 s    3.01 s  +6.6%
  mixture_same_family_log_prob     1.0 ms   1.0 ms     +1.1%      75.0 ms   72.3 ms  -3.6%
  multivariate_normal_log_prob     425 µs   316 µs  (-25.6%)     417.2 ms  436.0 ms  +4.5%
  normal_log_prob                  727 µs   729 µs     +0.2%      50.7 ms   50.5 ms  -0.3%
  normal_sample                   46.0 ms  45.5 ms     -1.1%     753.2 ms  745.0 ms  -1.1%
  stick_breaking_transform         5.9 ms   5.7 ms     -2.3%     198.3 ms  192.7 ms  -2.8%
  student_t_log_prob               2.4 ms   2.4 ms     +0.6%      81.5 ms   75.0 ms  -7.9%
  truncated_normal_log_prob        842 µs   815 µs     -3.2%      70.2 ms   68.7 ms  -2.2%

handlers

                                  ──────── run time ────────     ────── compile time ─────
  benchmark                       baseline  this PR        Δ     baseline   this PR      Δ
──────────────────────────────────────────────────────────────────────────────────────────
  initialize_model_hierarchical    48.1 ms  50.0 ms    +3.9%       3.25 s    3.34 s  +2.8%
  log_density_hierarchical          4.2 ms   4.2 ms    +1.9%     934.2 ms  971.9 ms  +4.0%
  nested_handler_stack              1.6 ms   1.6 ms    +2.6%       529 µs    507 µs  -4.2%
  potential_energy_and_grad          23 µs    21 µs  (-6.3%)      85.8 ms   83.4 ms  -2.8%
  predictive_forward_sampling       1.00 s   1.01 s    +1.0%     240.8 ms  253.2 ms  +5.1%
  trace_seeded_model                949 µs   929 µs    -2.1%     666.5 ms  662.5 ms  -0.6%

mcmc

                             ─────── run time ───────     ───── compile time ─────
  benchmark                  baseline  this PR      Δ     baseline  this PR      Δ
──────────────────────────────────────────────────────────────────────────────────
  hmc_logistic_regression      1.37 s   1.38 s  +0.8%       2.92 s   2.79 s  -4.4%
  nuts_dense_mass_funnel       1.61 s   1.62 s  +1.0%       2.51 s   2.50 s  -0.5%
  nuts_eight_schools           2.22 s   2.24 s  +0.8%       2.44 s   2.45 s  +0.4%
  nuts_hierarchical_glm        3.31 s   3.29 s  -0.6%       4.06 s   4.02 s  -1.1%
  nuts_logistic_regression     2.10 s   2.10 s  +0.0%       2.77 s   2.81 s  +1.4%
  nuts_vectorized_chains       4.45 s   4.48 s  +0.8%       3.47 s   3.39 s  -2.3%

svi

                                             ──────── run time ───────     ───── compile time ─────
  benchmark                                  baseline   this PR      Δ     baseline  this PR      Δ
───────────────────────────────────────────────────────────────────────────────────────────────────
  svi_autodelta_map_logistic                 432.7 ms  437.0 ms  +1.0%       2.85 s   2.91 s  +1.9%
  svi_autodiagonalnormal_hierarchical          1.01 s  998.0 ms  -1.1%       4.38 s   4.39 s  +0.3%
  svi_automultivariatenormal_eight_schools   815.3 ms  846.5 ms  +3.8%       4.13 s   4.10 s  -0.7%
  svi_autonormal_logistic                      1.38 s    1.38 s  -0.2%       3.10 s   3.14 s  +1.1%
  svi_multi_particle_elbo                      1.77 s    1.75 s  -1.0%       3.29 s   3.24 s  -1.5%
  svi_trace_mean_field_elbo                    1.47 s    1.47 s  +0.4%       5.13 s   5.37 s  +4.8%
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 fix-hsgp-numpy-scalars-issue-2446
commit fc7691c7 f14f865c
numpyro 0.22.0 0.22.0
jax 0.12.1 0.12.1
backend cpu cpu
python 3.14.4 3.14.4

Runner: Linux-7.0.0-1020-azure-x86_64-with-glibc2.43, 4 CPUs.

Produced by this benchmark run.

@juanitorduz juanitorduz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix. It handles the inputs from #2446, but I'd like a smaller version before merging.

Fix

_convert_ell picks a branch by Python type and starts from jnp.empty((dim, 1)), which is all zeros in JAX, so any input that matches no branch falls through with the right shape. This PR adds np.floating/np.integer to the type list and an else: raise. Other scalars are still rejected, with an error that says "ell must be a scalar":

ell (sqrt_eigenvalues, m=3, dim=1) master this PR ndim check below
np.float32, e.g. 1.5 * np.max(np.abs(x_f32)) inf ok ok
np.array(2.0) ValueError ValueError ok
jnp.array(2.0), e.g. 1.5 * jnp.max(jnp.abs(x)) ValueError ValueError ok
traced ell under jit ValueError ValueError ok
tuple (2.0,) inf ValueError ValueError

Branching on ndim handles every scalar case and removes the jnp.empty default, so no input can fall through:

if isinstance(ell, list):
    if len(ell) != dim:
        raise ValueError(
            "The length of ell must be equal to the dimension of the space."
        )
    ell_ = jnp.array(ell)[..., None]  # dim x 1 array
elif jnp.ndim(ell) == 0:  # Python, NumPy or JAX scalar
    ell_ = jnp.full((dim, 1), ell)
else:
    ell_ = jnp.asarray(ell)
if jnp.shape(ell_) != (dim, 1):
    raise ValueError("ell must be a scalar or a list of length `dim`.")
return ell_

For eigenindices, the ms rename, list(m) and the reflowed return aren't needed. This passes ty check:

if isinstance(m, (int, np.integer)):
    m = [int(m)] * dim
elif len(m) != dim:
    raise ValueError("The length of m must be equal to the dimension of the space.")

With both changes, test/contrib/hsgp passes except ell-unsupported-fail, where the string now raises TypeError from jnp.full instead of ValueError.

Smaller points:

  • jax.typing.ArrayLike already includes int, float and np.number, so the new _convert_ell annotation and docstring changes can be reverted.
  • Only eigenindices gets np.integer in its annotation; sqrt_eigenvalues, eigenfunctions and hsgp_* still say int. Please widen all of them (as #2425 did for seed) or none.

Tests

The 7 new cases and 2 test-body edits can be one test:

  • ell-np-float64 passes on unpatched master, since np.float64 is a subclass of float.
  • ell-unsupported-fail uses a string and only checks which exception is raised. With the ndim check there's no fall-through path left to guard.
  • The two np.int64 rows in test_eigenindices hit the same branch. They also need the test-body edits; isinstance(m, list) and ... is only there because np.int64(5) == [2, 2, 3] returns a bool array. Dropping the rows lets the body go back to how it was.
  • ell-np-int64 and ell-np-float32 overlap with the public-API test.

Suggested replacement:

@pytest.mark.parametrize(
    "ell",
    [np.float32(2.0), np.int64(2), np.array(2.0)],
    ids=["np-float32", "np-int64", "0d-array"],
)
def test_sqrt_eigenvalues_scalar_types(ell):
    actual = sqrt_eigenvalues(ell=ell, m=np.int64(3), dim=2)
    expected = sqrt_eigenvalues(ell=2.0, m=3, dim=2)
    assert jnp.array_equal(actual, expected)

All 3 cases fail on master and pass with the changes above. dim=2 checks that both ell and m are repeated per dimension. The 0-d case uses np.array because test/conftest.py asserts no live JAX arrays exist before the first test.

The test-modeling/test-inference failures (test_funsor::test_scan_history, truncated gamma, test_logdiffexp_grads, test_handlers::test_scale) are unrelated to this diff; all test_laplacian.py cases pass in that run.

…view

Handle every scalar ell (Python, NumPy or JAX, including 0-d arrays) with
jnp.ndim and drop the jnp.empty default, keep eigenindices to the minimal
np.integer branch, revert the annotation and docstring changes, and replace
the added test cases with one scalar-types test.
@leninworld

Copy link
Copy Markdown
Contributor Author

Thanks @juanitorduz, that's a much better shape. Pushed in f14f865:

  • _convert_ell: now your ndim version. A 0-d input (Python, NumPy or JAX scalar) goes through jnp.full, and there's no jnp.empty default, so nothing falls through.
  • eigenindices: your version. The ms rename, list(m) and the reflowed return are gone.
  • Annotations and docstrings: reverted to master for both functions. I went with "none" rather than widening every signature.
  • Tests: replaced the 7 cases and the 2 test-body edits with your test_sqrt_eigenvalues_scalar_types. The PR's diff against master is now just the two function bodies plus that test.

Locally:

  • test/contrib/hsgp/test_laplacian.py: 34 passed.
  • The 3 new cases fail with master's laplacian.py.
  • ruff check and ruff format --check (0.17.6), and ty check numpyro/contrib/hsgp/laplacian.py (0.0.75), pass.

The rest of test/contrib/hsgp has 64 failures in test_approximation.py and test_spectral_densities.py in my local env. They're the same 64 with master's laplacian.py, so they're unrelated to this change.

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.

HSGP: a NumPy scalar ell is silently treated as zero, and a NumPy integer m raises TypeError

2 participants