-
Notifications
You must be signed in to change notification settings - Fork 132
Fix numerical stability of TorchLib erfcx #3038
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Yusef Syed (YusefSyed)
wants to merge
1
commit into
microsoft:main
Choose a base branch
from
YusefSyed:codex/stable-erfcx
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # Third-party notices | ||
|
|
||
| ## SciPy XSF Cephes `ndtr.h` coefficients | ||
|
|
||
| `onnxscript/function_libs/torch_lib/ops/special.py` adapts the `ndtr_P`, | ||
| `ndtr_Q`, `ndtr_R`, `ndtr_S`, `ndtr_T`, and `ndtr_U` coefficient tables from | ||
| [SciPy XSF revision 5dbdff8de0dab99b475076612ea227d3f29d6cf6](https://github.com/scipy/scipy/blob/5dbdff8de0dab99b475076612ea227d3f29d6cf6/subprojects/xsf/include/xsf/cephes/ndtr.h). | ||
|
|
||
| The source file identifies the original Cephes Math Library Release 2.2 as | ||
| copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier. SciPy's 2024 C++ | ||
| translation is distributed under the BSD 3-Clause License: | ||
|
|
||
| ```text | ||
| BSD 3-Clause License | ||
|
|
||
| Copyright (c) 2024, SciPy | ||
|
|
||
| Redistribution and use in source and binary forms, with or without | ||
| modification, are permitted provided that the following conditions are met: | ||
|
|
||
| 1. Redistributions of source code must retain the above copyright notice, this | ||
| list of conditions and the following disclaimer. | ||
|
|
||
| 2. Redistributions in binary form must reproduce the above copyright notice, | ||
| this list of conditions and the following disclaimer in the documentation | ||
| and/or other materials provided with the distribution. | ||
|
|
||
| 3. Neither the name of the copyright holder nor the names of its | ||
| contributors may be used to endorse or promote products derived from | ||
| this software without specific prior written permission. | ||
|
|
||
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
| FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
| OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| ``` |
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| """Focused TorchLib tests for special functions.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import math | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
| import torch | ||
|
|
||
| from onnxscript.function_libs.torch_lib.ops import special | ||
| from tests.function_libs.torch_lib import ops_test_common | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("dtype", "rtol", "atol"), | ||
| ((np.float16, 2e-3, 0), (np.float32, 1.3e-6, 0), (np.float64, 2e-14, 0)), | ||
| ) | ||
| def test_erfcx_ort_matches_torch_at_boundaries_and_special_values(dtype, rtol, atol): | ||
| """Exercises each approximation range and the low-precision working path.""" | ||
|
|
||
| values = np.array( | ||
| [ | ||
| -np.inf, | ||
| -30.0, | ||
| -26.0, | ||
| -12.0, | ||
| -8.001, | ||
| -8.0, | ||
| -7.999, | ||
| -1.001, | ||
| -1.0, | ||
| -0.999, | ||
| -0.0, | ||
| 0.0, | ||
| 0.999, | ||
| 1.0, | ||
| 1.001, | ||
| 7.999, | ||
| 8.0, | ||
| 8.001, | ||
| 12.0, | ||
| 30.0, | ||
| np.inf, | ||
| np.nan, | ||
| ], | ||
| dtype=dtype, | ||
| ) | ||
| with np.errstate(over="ignore"): | ||
| expected = torch.special.erfcx(torch.from_numpy(values).float()).numpy().astype(dtype) | ||
| if dtype is np.float64: | ||
| expected = torch.special.erfcx(torch.from_numpy(values)).numpy() | ||
| actual = ops_test_common.graph_executor("test_erfcx", [torch.from_numpy(expected)])( | ||
| special.aten_special_erfcx, (values,), {} | ||
| )[0] | ||
|
|
||
| np.testing.assert_allclose(actual, expected, rtol=rtol, atol=atol, equal_nan=True) | ||
| assert np.isposinf(actual[0]) | ||
| assert actual[-2] == 0 | ||
| assert np.isnan(actual[-1]) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("dtype", (np.float32, np.float64)) | ||
| def test_erfcx_ort_has_correct_large_positive_asymptote(dtype): | ||
| """Checks the reciprocal tail form that prevents polynomial overflow.""" | ||
|
|
||
| values = np.array([8.0, 12.0, 30.0, np.finfo(dtype).max], dtype=dtype) | ||
| expected = torch.special.erfcx(torch.from_numpy(values)).numpy() | ||
| actual = ops_test_common.graph_executor("test_erfcx_tail", [torch.from_numpy(expected)])( | ||
| special.aten_special_erfcx, (values,), {} | ||
| )[0] | ||
|
|
||
| rtol = 1.3e-6 if dtype is np.float32 else 2e-14 | ||
| np.testing.assert_allclose(actual, expected, rtol=rtol, atol=0) | ||
| np.testing.assert_allclose(values[-1] * actual[-1], 1 / math.sqrt(math.pi), rtol=rtol) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("dtype", (np.float16, np.float32, np.float64)) | ||
| @pytest.mark.parametrize("shape", ((), (0,), (2, 0, 3), (2, 3))) | ||
| def test_erfcx_ort_preserves_shape_and_dtype(dtype, shape): | ||
| values = np.ones(shape, dtype=dtype) | ||
| expected = torch.special.erfcx(torch.from_numpy(values).double()).numpy().astype(dtype) | ||
| actual = ops_test_common.graph_executor("test_erfcx_shape", [torch.from_numpy(expected)])( | ||
| special.aten_special_erfcx, (values,), {} | ||
| )[0] | ||
| assert actual.shape == values.shape | ||
| assert actual.dtype == values.dtype | ||
| np.testing.assert_allclose(actual, expected, rtol=2e-3 if dtype is np.float16 else 1e-6) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("dtype", (np.float32, np.float64)) | ||
| def test_erfcx_ort_across_approximation_intervals(dtype): | ||
| # Include adjacent representable values at each piecewise boundary. | ||
| boundaries = np.array([-8, -1, 0, 1, 8], dtype=dtype) | ||
| values = np.concatenate( | ||
| [ | ||
| np.linspace(-9, 0, 257, dtype=dtype), | ||
| np.linspace(0, 1, 257, dtype=dtype), | ||
| np.linspace(1, 8, 257, dtype=dtype), | ||
| np.geomspace(8, 1e30 if dtype is np.float32 else 1e300, 257).astype(dtype), | ||
| boundaries, | ||
| np.nextafter(boundaries, -np.inf), | ||
| np.nextafter(boundaries, np.inf), | ||
| ] | ||
| ) | ||
| expected = torch.special.erfcx(torch.from_numpy(values)).numpy() | ||
| actual = ops_test_common.graph_executor( | ||
| "test_erfcx_intervals", [torch.from_numpy(expected)] | ||
| )(special.aten_special_erfcx, (values,), {})[0] | ||
| np.testing.assert_allclose( | ||
| actual, expected, rtol=1.3e-6 if dtype is np.float32 else 2e-14, atol=0 | ||
| ) |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks. Is there a version that comes from pytorch?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Codex-assisted response: yes. PyTorch has Steven G. Johnson's
erfcx_y100/calc_erfcximplementation. It uses a 100-region polynomial table for the central positive range and a continued-fraction tail. The CPU kernel calls it; CUDA uses either the corresponding Jiterator implementation or the same helper.Those are different coefficients from the Cephes rational approximation used here. A PyTorch-sourced ONNX translation is feasible using coefficient lookup and Horner evaluation, but it would replace this approximation with the 700-coefficient table and its tail rules. I chose the current 42-coefficient rational form to avoid that lookup table in the export graph. Its SciPy provenance is explicit in the source/notice, and the focused erfcx tests still pass against PyTorch (20 passed, four expected skips). No performance comparison between the two ONNX representations has been established.