Repository navigation
fix(contrib.hsgp): accept NumPy scalars for ell and m - #2447
leninworld wants to merge 2 commits into
Conversation
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
Benchmark reportthis PR run time: unchanged across 32 benchmarks
compile time: unchanged across 32 benchmarksNo significant changesEvery 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
|
| 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
left a comment
There was a problem hiding this comment.
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.ArrayLikealready includesint,floatandnp.number, so the new_convert_ellannotation and docstring changes can be reverted.- Only
eigenindicesgetsnp.integerin its annotation;sqrt_eigenvalues,eigenfunctionsandhsgp_*still sayint. Please widen all of them (as #2425 did forseed) or none.
Tests
The 7 new cases and 2 test-body edits can be one test:
ell-np-float64passes on unpatched master, sincenp.float64is a subclass offloat.ell-unsupported-failuses a string and only checks which exception is raised. With thendimcheck there's no fall-through path left to guard.- The two
np.int64rows intest_eigenindiceshit the same branch. They also need the test-body edits;isinstance(m, list) and ...is only there becausenp.int64(5) == [2, 2, 3]returns a bool array. Dropping the rows lets the body go back to how it was. ell-np-int64andell-np-float32overlap 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.
|
Thanks @juanitorduz, that's a much better shape. Pushed in f14f865:
Locally:
The rest of |
This PR fixes issue #2446.
NumPy scalar
ellvalues could silently leave an empty buffer in place, while NumPy integermvalues raisedTypeError. This is the same NumPy-scalar type-check gap addressed for handler seeds in #2425.Changes:
mvalues like Python integers.ellscalars across dimensions.ValueErrorfor unsupportedellinputs and add regression coverage, including a publicsqrt_eigenvaluescheck.The annotations of the public
hsgp_*,sqrt_eigenvaluesandeigenfunctionsfunctions 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 unpatchednumpyro/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 localenvironment because the installed TensorFlow Probability is incompatible with JAX 0.12.1, and the failure set is
identical before and after this change.
make lintsteps — ruff 0.17.6checkandformat --check,scripts/update_headers.py --check, and ty 0.0.75check: all pass.Closes #2446