Skip to content

✨ feat(sech): add sech with a finite, accurate gradient - #86

Open
nstarman wants to merge 15 commits into
JAXtronomy:mainfrom
nstarman:feat/sech
Open

nstarman wants to merge 15 commits into
JAXtronomy:mainfrom
nstarman:feat/sech

Conversation

@nstarman

@nstarman nstarman commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #85.

What this adds

spexial.sech(x), the hyperbolic secant for real input, with a value and a gradient that stay accurate and finite over the whole range.

1 / cosh(x) is only good to about 5e-14 in value (float64; 1.5e-6 in float32), and its gradient is wrong long before it is nan: from |x| ≈ 355 (float64) and 44 (float32) cosh⁻² drops below the smallest normal number and is flushed, so the gradient is 0 where the true value is non-zero, and from |x| ≈ 710 and 89 it is nan.

  • Value: 2 / (e + 1/e) with e = exp(|x|). When e overflows the result is the correct limit 0, and nothing is flushed while the true value is still a normal number (a form built on exp(-|x|) returns 0 over a band of width ln 2 just below that point).
  • Gradient: a hand-written jax.custom_jvp, -sech(x) tanh(x). Differentiating the value form directly loses the gradient's relative accuracy near zero, where its derivative contains e - 1/e: by up to about ε/|x|, which is 2e-4 at |x| = 1e-12 in float64 and makes the float32 gradient exactly 0 below about 1.5e-8 under jit. The rule is written in terms of sech, so higher derivatives are right as well.
  • Real input only. A complex argument, including one with zero imaginary part, raises ValueError eagerly and under jit; without the guard it would return the secant of the modulus.
  • Integer and bool input give a strong float of the default width; float16, bfloat16, float32 and float64 keep their dtype.

Accuracy

Against mpmath.sech at 50 digits, value and gradient, both signs, eager and jit:

dtype value gradient
float64 below 5e-16 below 1.5e-15
float32 (also with x64 off) below 3e-7 below 7e-7
float16 / bfloat16 about 1e-3 / 1e-2 about 1.4e-3 / 1e-2

The result is in [0, 1]. It is a normal number up to |x| ≈ 709 (float64), 88 (float32 and bfloat16) and 10.4 (float16), and 0 beyond about 709, 88 and 11.1 (float16 computes in its own width, so exp(|x|) overflows first). The one documented ceiling: the gradient at a subnormal x is flushed to zero, an absolute error below tiny. Odd derivatives vanish at zero, so the third and fifth carry an absolute error of one or two ε and up to about 25 ε there.

Cost

Registry row Status.UNIQUE, custom_jvp=True. Over 10,000 points the rule keeps 3.1× less residual memory than differentiating the value form (80,000 against 250,016 bytes). Its gradient takes about 0.7× the time of 1/cosh's, and about 1.6× that of differentiating the value form directly; at the 1,000 points the benchmarks use the timings are within noise. The row is there for correctness, not speed.

Scope

sech is elementary, not special, and there was no elementary function in the registry before it. The case for it is the one the registry already makes for other rows: a JAX-specific numerical gap (accurate, finite gradients) that jax.numpy does not close. Accepted in #85. AGENTS.md now says what belongs in spexial: an elementary function only where the obvious jax.numpy form gives a wrong value or gradient and jax.numpy has no equivalent, so sech does not open the door to csch, logcosh and the like without the same kind of reproduction.

Files

  • src/spexial/_src/sech.py, exported from spexial, with DLMF §4.28 and §4.34 as the references.
  • Registry row, regenerated docs/reference/coverage.md, accuracy-page and errors-page entries, README, skill, how-to and explanation pages. Sentences that said every function is a series, or needs double precision, now name sech as the exception. The function count on the how-to page was already out of date and now reads "Seventeen of the twenty-two".
  • Tests: tests/unit/test_sech.py (known values and special arguments in all four dtypes; value and gradient on a dense grid in every dtype, eager and jit; the underflow edge; forward against reverse mode over each dtype's range; derivatives to fifth order including past the overflow; integer, bool and complex input including under tracing and with x64 off; and the nan in 1 / cosh's gradient that this exists to avoid), a mpmath parity test, and three benchmarks against differentiating the value form directly and against 1 / cosh.

🤖 Generated with Claude Code

Add `sech(x)`, the hyperbolic secant for real input. `1 / cosh(x)` has the
right value everywhere but a gradient that is `inf / inf = nan` from |x| = 710
in float64 (90 in float32), and already 0 from 355. `sech` evaluates
`2e / (1 + e^2)` with `e = exp(-|x|)`, which cannot overflow, and supplies the
derivative `-sech(x) tanh(x)` by hand. Differentiating the value form directly
loses the gradient's relative accuracy near zero, where `1 - e^2` cancels
(1e-4 at |x| = 1e-12 in float64); the hand-written rule has no cancellation and
every higher derivative is right too.

Against 40-digit mpmath the value and gradient are within 9e-16 in float64 and
2.6e-7 in float32. In a band of width ln 2 just above where `exp(-|x|)` goes
subnormal the result is flushed to 0; that ceiling is documented and tested.
A complex argument raises ValueError.

Adds the registry row (UNIQUE, with measured memory and speed against
differentiating the value form), the accuracy-page entry, unit and mpmath parity
tests, and the README and skill rows. Corrects the function count on the
how-to page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
src/spexial/__init__.py 100.00% <100.00%> (ø)
src/spexial/_src/registry.py 100.00% <ø> (ø)
src/spexial/_src/sech.py 100.00% <100.00%> (ø)
src/spexial/registry.py 100.00% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@codspeed

codspeed Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will improve performance by 33.31%

2 warnings, 1 note

⚠️ 68 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

⚠️ 2 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

ℹ️ 83 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

⚡ 2 improved benchmarks
✅ 78 untouched benchmarks
🆕 3 new benchmarks
⏩ 16 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_reduce_over_terms[4] 645.7 µs 416.2 µs +55.14%
⚡ test_polylog_scalar[intermediate-z1] 1.2 ms 1 ms +14.55%
🆕 test_grad_sech_autodiff N/A 407 µs N/A
🆕 test_grad_sech_custom_jvp N/A 424.2 µs N/A
🆕 test_grad_sech_one_over_cosh N/A 441.9 µs N/A

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing nstarman:feat/sech (a6dcace) with main (925e8c7)

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. ↩

An independent audit re-measured every number in the sech docs and found the
float32 error figures, the gradient speed ratio and the worst-case value error
wrong. Corrected, with the speed now recorded by a benchmark triple.

- Integer and bool input now give a strongly typed float, not a weak one.
- Tests: higher derivatives at x = 0, float16 and bfloat16 value and gradient,
  integer and bool input, negative float32 argument, the subnormal-gradient
  ceiling; mpmath precision no longer set globally.
- Docs: errors-page rows, the odd-derivative and subnormal ceilings, typing
  guard entry, and the parity docstrings.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@nstarman nstarman added this to the v0.3.0 milestone Nov 24, 2026
@nstarman
nstarman requested a review from cgiovanetti November 24, 2026 19:52
nstarman and others added 12 commits November 24, 2026 15:14
Second audit round: error figures are now bounds that hold under dense and
exhaustive measurement, the 1/cosh failure mechanism is stated correctly, and
the tests now cover the top of each dtype's range, negative arguments, -0.0,
float32 higher derivatives and wider float16/bfloat16 arguments.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Third audit round: error bounds are stated with real headroom over dense and
exhaustive measurement, the result is documented as `[0, 1]` up to rounding,
and the tests now include a dense grid for every dtype, forward mode, complex
dtypes, x64-off input, integer and bool kinds, shapes, and the gradient in the
flush band. Tolerances are tighter. The speed ratio is recorded as 1.6x.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The value 2 / (e + 1/e) with e = exp(|x|) is as accurate as 2e / (1 + e^2)
with e = exp(-|x|) (worst 2.8e-16 against 2.9e-16 in float64, 1.4e-7 in
float32) and has no subnormal intermediate, so the band just above where
exp(-|x|) goes subnormal, in which the old form returned 0 for a true value
between tiny and 2 tiny, is gone. Overflow of e gives the correct limit 0.
That removes a documented ceiling, a test, and the (2h)h comparison.

Also tightens the float64 and float32 tolerances to a few times the measured
worst case, adds the fifth derivative and x = 1e-12, and re-measures the
memory ratio (3.1x) and the figures that depended on the value form.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Fifth audit round: higher derivatives are now tested beyond where exp(|x|)
overflows, the value is tested within 1% of the smallest normal number in all
four dtypes, the figures for differentiating the value form directly are
corrected, and stale comments about the integer conversion are replaced.
Adds the DLMF reference, and states the speed figures with the configuration
they were measured in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ct figures

Sixth audit round: forward mode, the moderate float64 range and float16 and
bfloat16 beyond underflow are now tested; the accuracy page states the tested
tolerance, the float16 ceiling, the sawtooth error of differentiating the value
form directly, and the fifth derivative's error near zero.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…6 edge

Seventh audit round: forward mode is tested against reverse mode over the whole
range of every dtype and beyond overflow in the half dtypes, the float16
overflow edge is pinned, the integer-input subprocess test escalates warnings
after the imports, and the figures for differentiating the value form directly
no longer compare eager and jit. A test the grid already covers is removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…n the subnormal band

Eighth audit round: jvp is checked at the special arguments, the float16 and
bfloat16 gradients are evaluated where the result is subnormal, and the
forward-versus-reverse tolerance is tightened to four epsilon.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Ninth audit round: the float16 edge docstring gives the right figure, the
forward-mode test also checks the primal output of the rule against the value,
and the module docstring states what is wrong with 1 / cosh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ch contradicts

Tenth audit round: the skill's accuracy table gets a sech row, and the two
sentences saying that every function is a series or recurrence now say most,
since sech is a closed form that meets its figures in float32.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Eleventh audit round: the four places that say accuracy figures assume double
precision now name sech as the exception, since it is a closed form with
nothing to accumulate.

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

Twelfth and thirteenth audit rounds: the special arguments are tested in all
four dtypes in value, reverse and forward mode, the half dtypes' second
derivative is tested beyond the overflow, the integer conversion and the
complex guard are tested under jit and vmap, and a complex input with a zero
imaginary part is rejected too. The two index lines that call double precision
mandatory now name sech as the exception.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…tolerances

Fourteenth audit round: the dense grid and the underflow-edge tests run both
eagerly and under jax.jit, so a regression that exists only while tracing is
caught. The four plumbing tests use the float64 bound of 4e-15, and the sech
docstring states that it has no scipy.special counterpart.

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

Copy link
Copy Markdown
Collaborator Author

Hi @cgiovanetti, while you're looking at #65, would you mind also reviewing this too? WDYT about including functions like sech ?

@nstarman nstarman modified the milestones: v0.3.0, v0.4.0 Nov 29, 2026
…lementary function

Accepting sech sets a precedent, so AGENTS.md now says an elementary function
belongs only where the obvious form in jax.numpy gives a wrong value or gradient
and jax.numpy has no equivalent, and that a further request needs a reproduction.

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

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.

🟢 Approval recommended

The change is supported by a numerically stable real-only sech implementation with an explicit custom-JVP and broad verification/maintenance updates (unit/parity/typing/smoke tests plus registry, API export, docs, and benchmarks), leaving no active review concerns.

No open issues 🎉

What changed in this PR

Adds spexial.sech(x) (hyperbolic secant) for real inputs with a numerically stable value formula and an analytic custom JVP so gradients remain finite and accurate across the representable range where 1 / cosh(x) can underflow or produce nan.

Changes:

  • Implement sech with stable evaluation and a jax.custom_jvp rule -sech(x) * tanh(x) plus strict real-only validation.
  • Register sech in the coverage/registry system and export it via the public API.
  • Add extensive unit/parity/typing/smoke tests, benchmarks, and documentation updates (accuracy/domains, errors, conventions, scope guidance).
File Description
tests/​unit/​test_sech.py Adds a comprehensive unit test suite for sech covering dtypes, edge cases, jit/AD behavior, and higher derivatives.
tests/​unit/​test_registry.py Updates registry-related tests to include sech and validate its custom-JVP/registry metadata expectations.
tests/​typing/​test_signatures.py Adds typing/signature checks ensuring sech is exposed with the expected call signature.
tests/​smoke/​test_public_api.py Extends public API smoke tests to verify sech is exported and discoverable as intended.
tests/​parity/​test_mpmath_parity.py Adds parity tests comparing sech values against mpmath over a broad real domain.
tests/​parity/​__init__.py Updates parity test module exports/documentation to include the new sech parity coverage.
src/​spexial/​registry.py Adjusts the public registry-facing module (including examples/doctests) to reflect the addition of sech.
src/​spexial/​_src/​sech.py Introduces the core sech implementation with stable value computation, dtype handling, real-only checks, and a custom JVP.
src/​spexial/​_src/​registry.py Registers sech in the internal coverage/registry table with its status and differentiation/cost metadata.
src/​spexial/​__init__.py Exports sech from the top-level package API so users can call spexial.sech directly.
skills/​spexial/​SKILL.md Documents sech usage and constraints in the spexial skill/guidance materials.
README.md Updates the project README to mention sech and its motivation around numerical/gradient correctness.
docs/​reference/​errors.md Documents sech error behavior (e.g., complex input) and relevant numerical ceilings/edge cases.
docs/​reference/​coverage.md Regenerates/updates the coverage reference to include sech and its registry entry details.
docs/​reference/​conventions.md Updates conventions documentation to reflect sech-related precision/domain conventions or exceptions.
docs/​reference/​accuracy-and-domains.md Adds sech to the accuracy/domains reference with documented behavior across dtypes and ranges.
docs/​index.md Updates documentation landing/index content to include the new function and related positioning notes.
docs/​how-to/​port-from-scipy.md Updates porting guidance to note sech as a provided function (including its SciPy-equivalence context).
docs/​how-to/​enable-double-precision.md Adjusts double-precision guidance to account for sech’s documented accuracy behavior across precisions.
docs/​how-to/​choose-between-spexial-and-jax.md Updates guidance on choosing spexial vs JAX implementations to include sech and related rationale/counts.
docs/​explanation/​why-not-upstream.md Updates the explanation of upstreaming decisions to include sech as an example in scope/rationale.
docs/​explanation/​precision.md Refines precision-related explanation pages to incorporate sech as a documented exception/case study.
docs/​explanation/​index.md Updates the explanation section index to reference the new/updated precision and scope content around sech.
benchmarks/​test_derivatives.py Adds benchmarks comparing sech’s custom-JVP derivatives to alternatives (e.g., differentiating the value form or 1/cosh).
AGENTS.md Updates contributor/scope guidance to clarify when elementary functions like sech belong in spexial.

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

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

Development

Successfully merging this pull request may close these issues.

Proposal: a sech with finite gradients at large |x|

2 participants