Repository navigation
Conversation
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 Report✅ All modified and coverable lines are covered by tests.
🚀 New features to boost your workflow:
|
Merging this PR will improve performance by 33.31%2 warnings, 1 note
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
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>
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>
|
Hi @cgiovanetti, while you're looking at #65, would you mind also reviewing this too? WDYT about including functions like |
…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>
There was a problem hiding this comment.
🟢 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
sechwith stable evaluation and ajax.custom_jvprule-sech(x) * tanh(x)plus strict real-only validation. - Register
sechin 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.
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 isnan: from |x| ≈ 355 (float64) and 44 (float32)cosh⁻²drops below the smallest normal number and is flushed, so the gradient is0where the true value is non-zero, and from |x| ≈ 710 and 89 it isnan.2 / (e + 1/e)withe = exp(|x|). Wheneoverflows the result is the correct limit0, and nothing is flushed while the true value is still a normal number (a form built onexp(-|x|)returns 0 over a band of width ln 2 just below that point).jax.custom_jvp,-sech(x) tanh(x). Differentiating the value form directly loses the gradient's relative accuracy near zero, where its derivative containse - 1/e: by up to about ε/|x|, which is 2e-4 at |x| = 1e-12 in float64 and makes the float32 gradient exactly0below about 1.5e-8 underjit. The rule is written in terms ofsech, so higher derivatives are right as well.ValueErroreagerly and underjit; without the guard it would return the secant of the modulus.Accuracy
Against
mpmath.sechat 50 digits, value and gradient, both signs, eager andjit:The result is in
[0, 1]. It is a normal number up to |x| ≈ 709 (float64), 88 (float32 and bfloat16) and 10.4 (float16), and0beyond about 709, 88 and 11.1 (float16 computes in its own width, soexp(|x|)overflows first). The one documented ceiling: the gradient at a subnormalxis flushed to zero, an absolute error belowtiny. 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 of1/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
sechis 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) thatjax.numpydoes not close. Accepted in #85.AGENTS.mdnow says what belongs in spexial: an elementary function only where the obviousjax.numpyform gives a wrong value or gradient andjax.numpyhas no equivalent, sosechdoes not open the door tocsch,logcoshand the like without the same kind of reproduction.Files
src/spexial/_src/sech.py, exported fromspexial, with DLMF §4.28 and §4.34 as the references.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 namesechas the exception. The function count on the how-to page was already out of date and now reads "Seventeen of the twenty-two".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 andjit; 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 thenanin1 / cosh's gradient that this exists to avoid), ampmathparity test, and three benchmarks against differentiating the value form directly and against1 / cosh.🤖 Generated with Claude Code