Skip to content

🐛 fix(incomplete_beta): continued fraction for large b and large a - #65

Open
nstarman wants to merge 31 commits into
JAXtronomy:mainfrom
nstarman:fix-incomplete-beta-large-b
Open

nstarman wants to merge 31 commits into
JAXtronomy:mainfrom
nstarman:fix-incomplete-beta-large-b

Conversation

@nstarman

@nstarman nstarman commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #64. Fixes #66. Fixes #67. Fixes #68. Fixes #73.

incomplete_beta's two series both expand (1-t)^(b-1) binomially. The coefficients (1-b)_k / k! alternate in sign and grow like b^k / k!, so at z = 1/2 the sum cancels catastrophically: at a = 2 it has lost several digits by b = 30, is wrong by orders of magnitude at b = 100, and returns -1.1e44 (answer 1.1e-5) at b = 300.

Fix

Above b = 10, use the DLMF 8.17.22 continued fraction (modified Lentz, 64 fixed double steps):

  • directly below x₀ = (a+1)/(a+b+2);
  • above it, through the reflection B(a,b,z) = B(a,b) − B(b,a,1−z).

The complete B(a,b) is the sum of both fractions at x₀. Both terms are positive, so nothing cancels. It is deliberately not exp(jax.scipy.special.betaln), which is only good to 3e-7 at (a, b) = (8, 10).

Accuracy (against mpmath)

range tested rtol test
a ∈ [0.25, 50], b ∈ (10, 100] 1e-12 test_large_b_matches_mpmath
a ∈ [0.25, 50], b to 1e4 1e-11 test_large_b_matches_mpmath
a = 0.1, b from 1e3 to 1e5 1e-12 test_large_b_small_a
a and b both large, (6, 12) to (30, 70) 1e-13 test_large_a_and_large_b_matches_mpmath

At large b the error is rounding, not truncation, and grows like b·ε. Past b ≈ 1/ε the switch point rounds to zero, and the result is deliberately nan rather than a confident wrong answer. SciPy isn't used as the reference, because beta * betainc is itself only good to about 1e-11 at b = 1e4.

Cost against main

  • Values with b ≤ 10 cost about what they did on main.
  • Values with b > 10 now run the continued fraction and cost several times main's, which was wrong above b ≈ 50. The test_incomplete_beta_large_b benchmarks on CodSpeed track this.
  • The parameter-gradient benchmark is faster than on main (CodSpeed).

Concrete a and b pick their branch in the public wrapper, before jax.custom_jvp traces them, so even under jit only that branch is compiled. A traced a or b goes through the switch, so it compiles every branch and takes longer to compile.

A traced a or b goes through a four-way lax.switch (series, continued fraction, large a, negative b), which runs one branch. Under vmap it becomes a select that runs all four, so each branch is handed parameters it is safe for, and gradients stay finite (tested). The scan counter is an integer arange, so float32 input stays float32.

Tests and docs

  • Large-b accuracy against mpmath, continuity across b = 10, a/b derivatives in both modes (against mp.diff, to rtol 1e-12), and finite gradients under vmap across the switch.
  • A new test_incomplete_beta_large_b benchmark.
  • accuracy-and-domains.md, why-not-upstream.md, the registry notes and the regenerated coverage table are updated. Accuracy figures in the docs and docstrings are stated as the tolerance a named test asserts, or qualitatively where no test covers them.

Also: #68 (mixed partial at small z)

With b traced, the z-rule's factor (1-z)^(b-1) is now exp((b-1)·log(1-z)), with log(1-z) taken from z itself (log1p(-z) up to z = 0.3, a corrected log(1 - z) above). Before, its b-derivative went through log of a rounded 1 - z, which kept only about 1e-16/z relative precision: 5e-9 at z = 1e-8 and 2e-5 at 1e-12. A concrete b keeps pow, which XLA simplifies for constant exponents. The regression test covers both the series and the continued-fraction regimes, and b = 1 at z = 1 still gives exactly 1.

Also: large a

_large_z expands (1-u)^(a-1), so it has the same cancellation in a. Over b ∈ [-5, 10] its worst error sits just above the z = 1/2 seam: below 1e-11 at a = 8, about 1e-8 at 16, about 1e-4 at 24, and wrong by about 50.

Above a = 8 with b ≥ 0.1, the continued fraction now takes over, tested to rtol 1e-12 up to a = 50 (test_large_a_matches_mpmath).

Large a with b < 0.1, including every b ≤ 0: the reflection doesn't apply here, because B(a,b) diverges. A third method, _large_a, handles it:

  • below s = a/(a+2), the continued fraction directly (below its switch point for b ≤ 1 + 2/a);
  • above s, the binomial expansion the series already uses, but over u ∈ [1−z, 2/(a+2)] instead of [1−z, 1/2], so its terms fall like 2^m/m! instead of growing like (a/2)^m/m!.

It is tested against mpmath to rtol 5e-13 over a ∈ [12, 100], b ∈ [−50, 0.1) and z up to 1 − 1e−12 (test_large_a_small_b). Dispatch is a four-way lax.switch, still static for concrete parameters.

That expansion is factored out of _large_z, which also fixes two bugs it had on main:

  • Near-pole truncation. The near-pole expansion had 4 terms: 1.2e-12 off at b = −1e−4, z = 1 − 1e−15, and worse for larger |log(1−z)|. That step is now evaluated once after the scan as w^s·Δ·expm1(sΔ)/(sΔ) (see the second audit below), so the series is no slower.
  • nan at z = 1 for 0 < b < 1e−3. B(2, 1e−4, 1) was nan; it's now 9999.0001.

Also: two JVP fixes

  • Parameter-gradient benchmark (the CodSpeed benchmark more than doubled). The JVP rule evaluated the primal on its own and again inside the a/b jvp. With straight-line code XLA merges the two copies; with one lax.switch per copy it can't, so everything ran twice. The primal now comes from the same jvp, and the benchmark is back below main.
  • nan derivatives at z = 1. With b traced, the incomplete_beta: d/db d/dz loses ~1e-16/z relative precision as z -> 0 #68 form exp((b-1)·log(1-z)) is -inf inside at z = 1, and clamping it differentiated as 0 · -inf, so the second and third z-derivatives were nan. A double where now hands z = 1 to pow, which matches the concrete-b path at every order (tested under jit).

Also: #66 and #67

Audit fixes

An independent audit of this PR found the following, all fixed with tests:

  • Integer z with b > 10 returned 0. A dtype cast truncated x₀ to zero.
  • Precision loss in the reflected term. It took log of a rounded 1 − z, scaled by b. The front factor z^a (1−z)^b is the same under the swap, so it's now computed once from z.
  • Premature underflow. The front factor flushed to zero before the fraction multiplied it back: B(301, 1000, 1) returned 0 instead of 3.9e-307. Terms are now combined in log space.
  • Too few steps. 32 steps were short just above x₀ at small a; it's now 64.
  • vmap over scalar z was more than ten times slower than main. It computed the complete beta for every point; that's now done once per call.
  • "A concrete b compiles one branch" was only true eagerly. The branch is now chosen before the custom_jvp, and passed to the core as a static argument.
  • Reverse-mode overhead through the switch. Checkpointing the a/b jvp in the rule fixed it.
  • bfloat16 was 6% off. Half precision is now evaluated in float32.
  • Weak tests. Each guard and fix is now caught by some test when reverted (mutation-checked).

Second audit

A second independent audit found the following, now fixed with tests:

  • Dtypes (incomplete_beta: TypeError for float32 z with a float64 b (scan carry dtype) #66, completed). a, b and z are promoted together. That fixes a crash new in this PR (float64 a with float32 b), integer a with float32 z, float32 a with float64 b, and gradients when the other parameter is an integer.
  • Near-pole cancellation. The one step with |b+m| < 1/2 is now evaluated as w^s·Δ·expm1(sΔ)/(sΔ). Values are tested to rtol 5e-14 and the first three b-derivatives to 1e-13 (test_just_outside_the_old_pole_band, test_b_derivatives_just_outside_the_old_pole_band), and float32 to 1e-5 (test_near_pole_float32). Before, the error was up to 5.8e-12 in value, 1.5e-3 in the third derivative, and 3.5e-4 in float32.
  • Overflow. No intermediate overflows while the result is representable, a true overflow returns +inf (never nan), and a concrete b = −1100 no longer raises OverflowError.
  • Mixed derivative at z = 1/2. ∂z∂b was halved there; it's now symmetric.
  • Half precision. a and b are also computed in float32 now; bfloat16 was 6.5% off.
  • Dead code. The large-a | pole guard is removed.

One more gap, which the audit didn't report but which surfaced while testing: on main, the series is wrong for very negative b: around 1e-11 at b = −10, wrong by percents at −50, garbage by −200. For a ≤ 8 and b < −5, the continued fraction now takes over (128 steps; no reflection needed), up to z = 1/2 and above it with the binomial tail added, as in _large_a. It is tested to rtol 2e-12 over a ∈ [0.01, 8], b ∈ [−1100, −5.5] (test_very_negative_b).

CI. The Python 3.11 job has been killed for running out of memory on every commit since the large-a work. JAX keeps every compiled program for the session, and one test process peaked at 5.9 GB on a 16 GB runner shared by four workers. tests/unit/conftest.py now clears JAX's caches after a test once that worker passes 2 GB. That keeps the peak under 3 GB, at some extra runtime. The full suite passed locally on 3.11 with coverage and four workers.

Known cost, documented rather than fixed: vmap over a or b runs every branch on every lane. For 64 parameter pairs that is more than ten times main's time, and a Python loop of static calls is faster. Fixing this properly needs a custom batching rule, which is left as a follow-up.

Later fixes

  • incomplete_beta: second z-derivative is nan at z = 1 for b = 1 (and at z = 0 for a = 1) #73, nan higher z-derivatives at an integer-exponent endpoint. JAX differentiates a float x ** y as y·x^(y-1), which is 0·∞ at x = 0 once y reaches 0 (by design, jax.grad computes incorrect derivative for polynomials jax-ml/jax#14397). With a − 1 or b − 1 an integer n ≥ 0, every z-derivative from order n + 2 was nan at that endpoint. Both z-rules, the general one and the a == 1 closed form's, now use a power whose x-derivative of x^0 is exactly 0 at x = 0, and only there.
  • Reverse mode through vmap over a or b. With the switch inside the custom JVP, grad(sum(vmap(f))) raised (a stop_gradient JAX cannot transpose). The switch is now outside, each branch its own static core.
  • jax 0.12. The rule computed its primal with the raw implementation, so higher derivatives differentiated the series itself, including z**a at z = 0 (0·∞ by the fifth); jax 0.12 no longer pruned that inside the switch, and the fifth z-derivative at (2, 3, 0) with traced b was nan. The primal now goes through the custom JVP, which also makes traced-b second derivatives about 10x cheaper in compiled flops.
  • Further audits found and fixed, with tests: gradients past the float range (now 0, as at the pole); mixed ∂z∂a, ∂z∂b exactly at the large-a and negative-b split points (were 0); a subnormal subtrahend in the large-b reflection, flushed to 0 by XLA (2.4% off at (301, 1000, 0.255); the difference is now taken in logarithms); _large_a rounding its split and the start of its expansion separately (3.7e-13 just above the split at (100, -164.29); the start is now exactly 1 - split); the z-derivative where its two factors under- and overflow apart (nan at (1100, −1100, 1/2), where it is 4.0; now formed as one exponential when one factor could leave the float range while the product does not, or a parameter is traced, keeping the plain product, which XLA simplifies, otherwise; and in float32 for half precision); mixed ∂z∂a, ∂z∂b in the first ulps above the large-a split (were 0); a float32 b past 1/ε returning a wrong number where nan is documented (the guard was judged in float64); and several measured figures in the docs, including that a traced a = 1 keeps its accuracy at any b and loses only the closed form's speed.

Rebased onto main after #63 (closed form for a == 1) and #84 (jax 0.12) merged.

🤖 Generated with Claude Code

@nstarman
nstarman requested review from ColmTalbot, adrn and cgiovanetti and a balanced review from Copilot October 9, 2026 00:01
@codecov

codecov Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.87640% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/spexial/_src/beta.py 98.87% 1 Missing and 2 partials ⚠️
Files with missing lines Coverage Δ
src/spexial/_src/registry.py 100.00% <ø> (ø)
src/spexial/_src/beta.py 98.29% <98.87%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

It adds substantial new numerical code (continued fraction, reflection, and NaN-safe cond/vmap dispatch with autodiff implications) whose correctness warrants final human verification.

2 open findings
What changed in this PR

This PR fixes catastrophic cancellation in incomplete_beta for large positive b (GH-64). The two existing Taylor series both expand (1-t)^{b-1} binomially, whose coefficients alternate and grow like b^k/k!, so above b ≈ 50 the sum loses all accuracy (e.g. -1.1e44 for 1.1e-5 at b=300). Above b = 10 the implementation now switches to the DLMF 8.17.22 continued fraction (modified Lentz, 32 fixed double steps), evaluated directly below x₀ = (a+1)/(a+b+2) and via the reflection B(a,b,z) = B(a,b) − B(b,a,1−z) above it, with the complete B(a,b) formed as the sum of two positive continued-fraction terms (no cancellation). The implementation verified cleanly against Numerical Recipes' betacf and against mpmath.

Changes:

  • New continued-fraction path (_continued_fraction, _cf_direct, _large_b) used for b > 10; the two series are refactored into _series, and _incomplete_beta_impl dispatches concrete-vs-traced b (concrete picks one branch; traced uses lax.cond with a jnp.where clamp so vmap's select keeps both branches finite for autodiff).
  • Tests: large-b accuracy vs mpmath, continuity across the b = 10 switch, a/b derivatives in both AD modes, finite vmap gradients across the switch, plus a new benchmark.
  • Docs/registry notes, accuracy-and-domains, coverage table, and why-not-upstream updated to record the continued fraction.
File Description
src/​spexial/​_src/​beta.py Adds the continued-fraction path, reflection, and concrete/traced branch dispatch; refactors the two series into _series.
tests/​unit/​test_beta.py Adds large-b accuracy, continuity, parameter-derivative, and vmap finite-gradient tests.
benchmarks/​test_beta.py Adds a test_incomplete_beta_large_b benchmark.
src/​spexial/​_src/​registry.py Updates the incomplete_beta coverage note to mention the continued fraction.
docs/​reference/​accuracy-and-domains.md Documents the large-b continued fraction, domain, and tolerances.
docs/​reference/​coverage.md Regenerated note mirroring the registry change.
docs/​explanation/​why-not-upstream.md Mentions the b > 10 continued fraction alongside the series.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread tests/unit/test_beta.py Resolved
Comment thread src/spexial/_src/beta.py Resolved
@codspeed

codspeed Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will regress 1 benchmark

2 warnings, 1 note

⚠️ 67 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 11 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

ℹ️ 82 benchmarks have no flamegraph

The flamegraph wasn't generated: this Python version can't be profiled. Use CPython 3.12 or later on Linux x86-64 or ARM64 with glibc, e.g., from actions/setup-python or uv.

See affected benchmarks

⚡ 7 improved benchmarks
❌ 4 (👁 3) regressed benchmarks
✅ 69 untouched benchmarks
🆕 2 new benchmarks
⏩ 16 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_zeta_vector[negative-n1] 629.4 µs 944.7 µs -33.37%
⚡ test_polylog_scalar[intermediate-z1] 4.8 ms 1.1 ms ×4.5
⚡ test_grad_incomplete_beta_a_eq_1_b[series] 25.6 ms 16 ms +60.44%
⚡ test_grad_incomplete_beta_parameters 30.7 ms 20.8 ms +47.63%
⚡ test_sph_harm_y_vector[16] 993 µs 679.5 µs +46.14%
⚡ test_reduce_over_terms[12] 744.6 µs 651.6 µs +14.28%
⚡ test_kn_scalar[large-z1-k2] 480.4 µs 424.9 µs +13.08%
🆕 test_incomplete_beta_large_b[1000.0] N/A 4.3 ms N/A
🆕 test_incomplete_beta_large_b[50.0] N/A 4.3 ms N/A
👁 test_polylog_scalar[large-z2] 790.8 µs 644.3 µs +22.74%
👁 test_kn_scalar[small-z0-k2] 427.8 µs 3,146.9 µs -86.41%
👁 test_eval_gegenbauers_vector_via_vmap 1.1 ms 1.6 ms -30.2%
👁 test_grad_incomplete_beta_custom_jvp 375 µs 522.7 µs -28.26%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing nstarman:fix-incomplete-beta-large-b (baccc92) with main (59afea4)

Open in CodSpeed

Footnotes

  1. 16 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@nstarman nstarman changed the title 🐛 fix(incomplete_beta): continued fraction for b > 10 🐛 fix(incomplete_beta): continued fraction for large b and large a Oct 9, 2026
@nstarman nstarman added this to the v0.3.0 milestone Oct 9, 2026
@nstarman
nstarman requested a balanced review from Copilot October 9, 2026 01:57

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

It changes numerical correctness of a core special function across wide domains with subtle continued-fraction, reflection, and vmap-gradient-safety logic that warrants human numerical verification.

0 open findings

2 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Low severity Test name claims regularized form but uses unregularized mpmath

tests/​unit/​test_beta.py:242

This test's name says "matches_the_regularized_form", but it does not use the regularized form as its reference — it compares against mp.betainc(a, b, 0, zi), which is mpmath's unregularized incomplete beta (the docstring even stresses "The reference is mpmath, not beta * betainc"). In this same file, test_matches_the_regularized_form (line 52) genuinely uses scipy_beta(a, b) * scipy_betainc(a, b, z), so "the regularized form" already has a specific, different meaning here. The parallel large-a test added in this PR is named test_large_a_matches_mpmath (line 340). Consider renaming this one to match that convention so the name reflects the actual reference.

🧠 Review effort: Balanced

nstarman added a commit to nstarman/spexial that referenced this pull request Oct 16, 2026
…ional-only

Every private function in beta.py, and the nested `scan` steps, now ends
its parameters with `/`, matching JAXtronomy#65.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nstarman

Copy link
Copy Markdown
Collaborator Author

Ping @cgiovanetti :)

@cgiovanetti

Copy link
Copy Markdown
Collaborator

Sorry @nstarman ! I'm super swamped right now and won't have the bandwidth for this for another couple of weeks. I've set a reminder for myself for the week of November 2nd to take a look if you don't mind the wait

@nstarman

nstarman commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up: custom batching rule for vmap over a/b

I looked into implementing the custom batching rule mentioned above ("left as a follow-up") and want to record why it's a bigger lift than it looks, rather than just leaving it unimplemented silently.

The setup. _dispatch's traced-a/b path picks its branch at runtime via lax.switch, with the branch functions (_incomplete_beta_core) each carrying their own custom_jvp. _dispatch itself has no custom differentiation rule — it relies entirely on cond_p's native jvp/transpose. That's deliberate: putting a custom JVP around the switch is exactly what, in an earlier revision, left an untransposable stop_gradient in the linearized program once batched, breaking grad(vmap(...)).

Why custom_vmap can't just be bolted on. jax.custom_batching.custom_vmap requires pairing with custom_jvp or custom_vjp — unpaired, it breaks any reverse-mode AD through the function, vmap or not (confirmed empirically). I tried both pairings against the real code, testing every combination (grad(vmap), vmap(grad), direct jax.jacfwd, jax.jacfwd(jax.jacrev(...)) for Hessians, plain grad, jit(grad)):

  • custom_vjp pairing breaks jax.jacfwd(sp.incomplete_beta, ...) outright (TypeError: can't apply forward-mode autodiff (jvp) to a custom_vjp function) — and that's a currently-passing test (test_large_b_parameter_derivatives calls jacfwd directly).
  • custom_jvp pairing, with the new JVP rule computed via jax.jvp(_dispatch, ...) (reusing the existing switch), reproduces the exact historical stop_gradient/transpose bug under grad(vmap(...)) — batching a "linearize-a-switch" computation is exactly the pattern the original fix avoided.
  • Swapping the JVP rule to a switch-free, jnp.where-based reconstruction fixes correctness everywhere — but then every traced-but-non-batched a/b gradient (the common, already-benchmarked case — test_grad_incomplete_beta_parameters) runs all 4 branches instead of 1, a real regression to a documented optimization ("a traced a or b goes through lax.switch, which compiles all four and runs one").
  • The only way to get both (fast switch when not batched, safe select when batched) is to detect "am I under vmap right now" from inside the JVP rule. An ndim/shape check doesn't work — vmap hides the batch axis from code running inside the vmapped function. The only signal that works is jax.extend.core.unsafe_am_i_under_a_vmap_DO_NOT_USE(), which is explicitly named and documented as unstable/discouraged by JAX itself. Its failure mode if it ever changes is silently wrong gradients, not an error — a bad trade for a library this focused on numerical correctness.

Conclusion: a correctness-preserving custom batching rule, using only stable public JAX API, isn't achievable here without either regressing an existing optimized/benchmarked path or depending on something JAX's own maintainers flag as unsafe. Leaving this documented as a known cost (as the PR already does) rather than attempting it seems like the right call unless someone finds a cleaner primitive-level approach.

@nstarman
nstarman force-pushed the fix-incomplete-beta-large-b branch from 4001ce1 to be0a47c Compare November 3, 2026 09:06
Copilot AI balanced review requested due to automatic review settings November 3, 2026 09:06

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Note

Copilot was unable to complete this review at the selected tier due to model policy or plan restrictions.

🟡 Changes recommended

A critical active finding remains in src/spexial/_src/beta.py where _branch uses Python if on ScalarLike values that can be 0-d jax.Array, causing invalid array-boolean conditionals and likely runtime errors for common concrete JAX inputs.

1 open issue

Review effort: Balanced

Comment thread src/spexial/_src/beta.py Resolved
Copilot AI balanced review requested due to automatic review settings November 3, 2026 10:25

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Note

Copilot was unable to complete this review at the selected tier due to model policy or plan restrictions.

🔵 Needs a closer look

The change is a large, numerically sensitive refactor of incomplete_beta (new multi-regime branching, continued-fraction implementation, and custom JVP/fixture updates) whose stability and edge-case accuracy need domain-expert sanity checks beyond the tested grids.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@nstarman

nstarman commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Ping @cgiovanetti when you get a chance. I think we can release the next version after this PR.

@nstarman

Copy link
Copy Markdown
Collaborator Author

Hi @cgiovanetti :)

nstarman and others added 2 commits November 23, 2026 13:21
… with a strong a

- The rule that scales the term's tangents formed them in float32 against
  a float64 primal when a float32 parameter met a Python float under x64,
  and jax.jvp raised TypeError. Every regime was hit, since a traced
  parameter traces all branches. Lanes and tangents now take the primal's
  own dtype.
- At a == 1 the output dtype left out a strong a: result_type(a, b, z) now,
  as on every other path, so it does not depend on whether a is 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… no cross-lane nan

- The binomial tail in _large_a and _negative_b was carried divided by
  w0^b: for very negative b, (w / w0)^b overflowed inside the sum, and
  reverse mode multiplied the sum's intermediates by w0^b before anything
  brought them back down. Gradients were nan from values of ~1e297 in
  _large_a and ~4e306 in _negative_b. The sum is now scaled per point by
  the larger of w0^b and w^b, so every term is at most 1, and the scale
  is applied through _exp_of_log_term, as the fraction's term already
  was. The log-space rescale and the overflow guard it needed are gone:
  a result past the range is exp of a log past it, inf.
- _exp_of_log_term now gives a value past the float range a zero
  tangent, as at the pole, so that lane's 0 * inf no longer turns other
  lanes' reverse-mode gradients nan through the shared a and b.
- Against mpmath, values and a/b gradients are 8.3e-14 or better up to
  1.78e308; a derivative past the range is -inf, as it should be. Hessians
  2.7e-14. The strict xfail for the old band is now a passing test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nstarman
nstarman force-pushed the fix-incomplete-beta-large-b branch from 2ce620c to aafdbcb Compare November 23, 2026 19:32
nstarman and others added 19 commits November 23, 2026 15:55
…e float range

Above the split in `_large_a` and `_negative_b` the value is B(a, b, s)
plus the tail. Only the tail's tangent was zeroed past the float range,
so where the sum is `inf` the a- and b-gradients were those of the finite
B(a, b, s): -2.4e87 at (2, -300, 0.999), the gradients at z = 1/2. They
are now 0 there, as at the pole and as the docs say, in forward and
reverse mode and through `_dispatch`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With only z differentiated, the rule computed its primal with the raw
implementation, so differentiating again went through the series' own
autodiff rather than this rule. That cost 10x the flops of a traced-b
second z-derivative (8.7M -> 0.88M at 1e4 points; d/db d/dz 3.8M ->
0.29M), and its z**a at z = 0, a = 2 is `0 * inf` by the fifth
derivative. jax 0.11 pruned that unused path; jax 0.12 does not inside
`_dispatch`'s `switch`, so the fifth z-derivative at (2, 3, 0) with b
traced was `nan`. Value, z-gradient and b-gradient compile to the same
cost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At z equal to the split -- 1/2 in `_negative_b`, a/(a+2) in `_large_a`
-- the tail has zero (or one ulp of negative) length, so its value and
tangent are 0, while the fraction was held at the split. Both d/dz d/da
and d/dz d/db came out 0: at (2, -20, 1/2) they are -7.3e5. Such points
now go to the fraction, at z itself, as `_series` does at 1/2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… subnormal

`_large_b` reflected as B(a, b) - B(b, a, 1-z). With B(a, b) near the
bottom of the float range the subtrahend is subnormal, which XLA flushes
to 0, so a normal result came back as B(a, b): 2.4% high at (301, 1000,
0.255). The difference is now B(a, b) * -expm1(log term - log B(a, b)),
which never forms the subnormal. Worst over the reflected region against
mpmath (a <= 50, b <= 1e5): 2.5e-12 in value, 2.2e-12 in d/da.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h comment

- `_CF_FROM` and the accuracy page quoted the series' error at z = 1/2
  for a ~ 1-2 as the worst case. Over a <= 8 it is 4e-15 at b = 10,
  1e-7 at 30 and 4e15 at 100, all at a = 8.
- `_CF_A_FROM`'s figures hold over b in [-5, 10], the series' range, not
  [-50, 10]. At a = 8 the series is 1e-11 off at b = -10 and 8% at -50.
- `_NEG_B_STEPS` now names the z its figures hold at: 2.4e-5 at 64 steps
  and 1.5e-13 at 128 at z = 0.45.
- The accuracy page said a traced b uses log1p(-z). It uses log(1-z) taken
  from z: log1p up to 0.3, a corrected log above.
- `_dispatch`'s comment credited the where-masks with keeping nan out of
  the vmapped gradients. Removing them changes no value or gradient in any
  probe or test, so they are described as a guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JAXtronomyGH-73 was fixed in the general z-rule, but the closed form at a == 1 has
its own rule, which still wrote (1-z)^(b-1) with `**`: with b - 1 an
integer n >= 0, every z-derivative from order n + 2 was `nan` at z = 1
((1, 1, 1): the second; (1, 2, 1): the third). It now uses `_pow`, and
takes its primal through the custom JVP, as `_incomplete_beta_jvp` does,
so that higher orders never differentiate the closed form's (1-z)^b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The docstring's worst point is now 1e-13 at (12, -50, 1 - 1e-6); the old
(100, -50, 100/102) measures 1.3e-14 since the split-point fix. The
accuracy page's rounding at a = 1e5 is 1.2e-11, not 9e-12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fraction stops

`_large_a` relies on B(z) = B(s) + int_{1-z}^{w0} with w0 = 1 - s. It
rounded s = a/(a+2) and w0 = 2/(a+2) separately, which miss by an ulp,
and |b| (a+2)/2 amplified that: 3.7e-13 just above the split at
(100, -164.29), past the documented 2e-13, and 5.9e-11 at a = 1e5. w0 is
now 1 - s. Worst at large a is back to the a*eps rounding: 1.6e-13 at
a = 1e3, 6e-13 at 1e4, 1.2e-11 at 1e5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…igures

- A traced `a = 1` no longer loses accuracy outside |b| <= 10: the
  dispatch routes very negative and large b to the continued fractions
  as for any a. Measured against the closed form: 5e-14 at b = -1000,
  3e-14 at -50, 8e-16 at 100 and 1.5e-13 at 1e4. What it loses is the
  closed form's speed.
- `_large_a`'s rounding with w0 = 1 - s: 1.6e-13 at a = 1e3, 6e-13 at 1e4.
- why-not-upstream: the continued fractions also cover large a and b < -5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…float range

The z-rule multiplied z^(a-1) and (1-z)^(b-1) after forming each one, and
at large a with very negative b one underflowed while the other
overflowed: dB/dz was 0 * inf = nan at (1100, -1100, 1/2), where it is
4.0, and the nan reached jacfwd's a/b entries too. In float16 (1-z)^-4 at
z = 0.95 overflowed while the derivative, 61569, does not.

Where an exponent is large enough for that (past log(max)/log 2), or a or
b is traced, the integrand is now one exponential, with `_log1m` keeping
JAXtronomyGH-68's b-derivative precision and `_pow` still at z = 0 and 1 (JAXtronomyGH-73).
Concrete a and b below that keep the plain product, whose constant
exponents XLA simplifies: the exponential cost 13x the flops of the
(2, 1.5) z-gradient. A traced b's z-gradient goes from 18k to 27k flops at
1000 points. Half precision is evaluated in float32 and rounded once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… their worst

The worst case of the series near its limits sits just above the z = 1/2
seam, which the earlier measurements missed:
- `_CF_A_FROM`: 2e-12 at a = 8, 1e-8 at 16, 4e-7 at 24 (was 2.5e-14,
  7e-11, 2e-8); the accuracy page likewise at a = 16.
- `_NEG_B_FROM`: 2e-14 at b = -5 and 1e-11 at -10 (was 2e-15, 6e-12).
- `_CF_A_B_MIN`: `_large_b` at b = 1e-8 is 5e-8 to 2e-7 for a in [8.5, 50].
- The accuracy page's traced a = 1 figures: about 1e-13 at b = -1000 and
  2e-15 at 100.
The switch points still sit where the series is within its tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s safe

The previous commit kept the product of powers for concrete a and b with
exponents below log(max)/log 2, on the claim that one factor could not
leave the float range while the other does not bring it back. It can:
(1-z)^-1023 overflows at z = 0.502 while z^1023 is only 2^-1023-ish, so
the z-gradient at (1024, -1022, 0.502) was inf where it is 3583; in
float32 0.502^127 flushed to 0 and (128, -126, 0.502) gave 0, not 2.76.

The product is now kept for exponents of one sign (both factors <= 1 or
both >= 1, so a factor leaves the range only where the product does), or
both of magnitude <= maxexp/(nmant+1) -- 19 in float64, 5 in float32 --
for which (1-z)^q stays in range at every representable z and z^p leaves
it only where 1 - z is exactly 1. The (2, 1.5) z-gradient still compiles
to 2000 flops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d at their worst

- `_CF_A_FROM` and a test docstring: the series just above z = 1/2 is
  1e-4 off at a = 24 (was 4e-7) and 3e-12 at a = 8.
- `_large_a` and a test docstring: the series is 8% off at (24, -50, 1/2)
  (was "1e-9 at a = 24", true only on a coarse z grid with b >= -2.5).
- `_NEG_B_FROM`: 3e-13 at b = -5, just above z = 1/2 (was 2e-14).
- `_CF_FROM`: 7e-14 at b = 10 just below the seam; a test docstring's
  b = -10 figure is 1e-11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Measured worst-case figures kept turning out optimistic: the true worst
point sat where an earlier sweep had not looked (just above the z = 1/2
seam, say), and each correction was a new docs change. Accuracy of the
current code is now stated as the tolerance a named test asserts for that
regime (e.g. rtol 1e-12 in `test_large_b_matches_mpmath`), or qualitatively
where no test covers it ("loses about half its digits by b = 30"), and no
bound is below a worst case an audit measured. Illustrations of main's
behaviour and exact facts (thresholds, step counts) stay as they were.
Prose only: no code or test assertion changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h dtypes

Mixed-sign exponents just inside and just past maxexp/(nmant+1), in
float64 and float32, at z down to one ulp from 1 and from 0: the
z-derivative matches the integrand wherever that is in range, and is inf
or 0 only where it is not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…it_at's split

The fix at the split itself left the next ulps: there the tail's
alternating sum rounds to 0 or below, its value and tangent are 0, and the
fraction is held at the split, so d/dz d/da and d/dz d/db were 0 an ulp
above 12/14 at (12, -0.5) and two above 9/11 at (9, -1). Such points now
take the fraction at z itself, decided from the tail already computed for
the sum; the fraction converges there, below its own switch point. The pole
keeps its own handling. The `1 - z >= w0` clause is gone: with w0 = 1 - s
exactly it was the same test as z <= s. Costs 6-30% on the large-a and
negative-b value paths (measured under load).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Past b ~ 1/eps `_large_b` returns `nan` rather than a confident wrong
number. The guard read `1 - x0 == 1` with x0 from Python-float a and b,
so in float64, and float32 past 1/eps32 went through: -1.5e-16 at
(2, 1e8, 3.3e-8), where it is 8.4e-17; a strong float32 b gave 40% error.
It is now `x0 < eps` in z's dtype.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ion b at a == 1

Concrete jax-array `a` and `b` closed over inside `jax.jit` raised
`TracerBoolConversionError`: the static branch choice compared them with `>`,
which the enclosing trace stages. They are now compared as Python floats.

At `a == 1` a strong lower-precision `b` was never cast to the output dtype,
so the closed form ran in `b`'s precision (1e-5 off for a float16 `b` with a
float64 `z`). That path now promotes through `_promote`, like the others, and
its weak type matches theirs.

Also simplify: the half-precision upcast lives once in
`_incomplete_beta_impl` instead of in each of the four methods; the
already-done promotion there is dropped; `_dispatch` no longer masks the
unselected branches' parameters (no probe or test needs it); the continued
fraction's step count defaults to `_CF_STEPS` directly. The accuracy ranges
in the docs now match what the cited tests sample.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d guards

At `a == 1` the closed form dropped the promoted `a`, so a strong `a` with
weak `b` and `z` gave a weak result where the branch dispatch returns a
strong one. A strong `a` now makes the result strong there too.

Also:
- `_series` no longer substitutes z at the pole: `_large_z` is finite there
  since `_expand_parts` handles w = 0, and the pole is still returned as inf.
- `_expand_parts` no longer zeroes w == w0: both callers mask those lanes.
- The accuracy ranges for large a with b >= 0.1 and for very negative b now
  match what the tests sample, and a test docstring no longer describes the
  removed `_dispatch` masks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
nstarman and others added 3 commits November 30, 2026 17:53
…without x64

The w = 0 term's quotient in `_expand_parts` was formed on every lane. For
0 < |b| < 1.5e-154 its derivative in `s` overflowed, and the `where` that
discarded it turned its zero cotangent into `0 * inf = nan` in the reverse
b-gradient. It is now divided only where it is used.

An integer `z` was cast to `promote_types(int, float)`, which is float64
whatever the x64 setting, so with x64 off JAX warned on every call. It now
takes the default float dtype.

The series-band test now checks the first b-derivative too, as the docs say.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… jax

`jax.enable_x64` does not exist in jax 0.7.2, the oldest supported version,
so the integer-z test errored there. It now sets `jax_enable_x64` through
`jax.config` and restores the previous value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lf-precision upcast

At `a == 1` the closed form's far branch for b < 0 overflowed its exponential
on an `inf` lane, and the two infinite paths cancelled to `nan` in the reverse
b-gradient, where every other path gives 0. The exponent is now handed a
harmless 0 where the value overflows, and the value is `inf` there.

The half-precision upcast is written once, in `_half_up`, around the closed
form and the branch dispatch, outside the custom JVPs. It replaces the copies
in `_incomplete_beta_impl` and `_integrand`.

The accuracy claim for very negative b is narrowed to a >= 0.01, where the
tests cover it; below that it falls as a -> 0. Single-run timings, memory
sizes and error figures that no test asserts are now qualitative, and two
stale comments are corrected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 05:02

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The change is a numerics-heavy rewrite of incomplete_beta with new regime-dependent continued-fraction/branching logic and refactored custom-JVP/autodiff behavior, so correctness, stability, and performance hinge on subtle floating-point and JAX-compatibility edge cases that require expert runtime/CI validation beyond static review.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants