Repository navigation
Numerically stable Sinh, Cosh, Asinh and Acosh - #474
Merged
Merged
Conversation
Contributor
|
Thanks. I noticed it even add a test for the gradient, which is nice it works (it can be tricky with where). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #473, as discussed in gomlx/onnx-gomlx#94: makes the hyperbolic functions numerically stable at the edges.
Sinh: computed on |x| as(t + t/(t+1))/2witht = Expm1(|x|), so there is no cancellation ofe^x - e^-xfor |x| close to 0 (before:Sinh(1e-10) = 0). For |x| > 20 it usesexp(|x| - ln 2), which only overflows wheresinh(x)itself does (before:Sinh(89)was+Infin Float32, althoughsinh(89) ≈ 2.2e38).Cosh: the sameexp(|x| - ln 2)for |x| > 20.Asinh:ln(|x|) + ln 2above 1/sqrt(epsilon) (4096 for Float32, 2^26 for Float64), wherex²loses precision or overflows (before:NaNfor |x| ≳ 1e19 in Float32 / 1e154 in Float64 and for ±Inf).Acosh: the same large-value branch (before:+Inffor x ≳ 1.7e38 in Float32), andLog1p((x-1) + sqrt(x-1)·sqrt(x+1))for more precision close to 1.Expm1: added its gradient (Expm1(x) + 1), whichSinhnow needs.Both branches are always computed with
Where; each one only sees the values it is selected for (the others are clamped to the threshold), so the discarded branch never producesInf/NaN, neither in the forward pass nor in the gradient. TheFloat32promotion for half precision from #473 is unchanged.Tests:
TestHyperbolicTrigNumericalStability(all official backends) covers tiny values, values on both sides of the thresholds, overflow cases, ±Inf and NaN in Float32 and Float64, plus gradients in the large-value branches and ofExpm1. The existingTestHyperbolicTrigand the rest ofcore/graphpass.🤖 Generated with Claude Code