Skip to content

ENH: Improve performance of np.isclose in the common case - #33599

Open
eendebakpt wants to merge 1 commit into
numpy:mainfrom
eendebakpt:isclose-tolerance-fastpath
Open

eendebakpt wants to merge 1 commit into
numpy:mainfrom
eendebakpt:isclose-tolerance-fastpath

Conversation

@eendebakpt

Copy link
Copy Markdown
Contributor

isclose validates that atol and rtol are finite with np.all(np.isfinite(...)). Both are plain Python floats by default, and
for small inputs that check takes roughly half of the total call time. In the PR we add a fast path for float input of atol/rtol.

Benchmark main PR Change
isclose(1.0, 1.0) 10.2 us 5.27 us 1.94x faster
isclose(np.float64, np.float64) 12.1 us 7.31 us 1.66x faster
isclose(arr[10], arr[10]) 13.4 us 8.74 us 1.53x faster
isclose(arr[1000], arr[1000]) 16.1 us 11.5 us 1.40x faster
isclose(arr[100k], arr[100k]) 673 us 690 us not significant
Geometric mean (ref) 1.46x faster

allclose benefits equally, since it calls isclose.

Note: some open PRs improve performance of np.all and np.isfinite. With those the gain would be smaller, but still relevant.

Benchmark script (pyperf)
import ast
import math

import numpy as np
import pyperf
from numpy._core import numeric


def load_isclose(path):
    """Compile `isclose` (including its decorators) from a numeric.py file.

    This runs both variants on the same installed NumPy build, so only the
    Python source of `isclose` differs.
    """
    src = open(path).read()
    for node in ast.parse(src).body:
        if isinstance(node, ast.FunctionDef) and node.name == "isclose":
            decos = "".join(
                "@" + ast.get_source_segment(src, d) + "\n"
                for d in node.decorator_list
            )
            ns = dict(vars(numeric))
            ns["math"] = math
            exec(decos + ast.get_source_segment(src, node), ns)
            return ns["isclose"]


def add_cmdline_args(cmd, args):
    cmd.extend(["--numeric", args.numeric])


runner = pyperf.Runner(add_cmdline_args=add_cmdline_args)
runner.argparser.add_argument("--numeric", required=True,
                              help="numeric.py to take isclose from")
args = runner.parse_args()
isclose = load_isclose(args.numeric)

rng = np.random.default_rng(0)
a10 = rng.random(10)
a1k = rng.random(1000)
a100k = rng.random(100_000)

runner.bench_func("isclose(1.0, 1.0)", isclose, 1.0, 1.0)
runner.bench_func("isclose(np.float64, np.float64)", isclose,
                  np.float64(1.0), np.float64(1.0))
runner.bench_func("isclose(arr[10], arr[10])", isclose, a10, a10 + 1e-9)
runner.bench_func("isclose(arr[1000], arr[1000])", isclose, a1k, a1k + 1e-9)
runner.bench_func("isclose(arr[100k], arr[100k])", isclose,
                  a100k, a100k + 1e-9)

AI Disclosure

Claude was used for running the benchmarks.

Validating the default float `rtol` and `atol` with
`np.all(np.isfinite(...))` takes about half the runtime of a small
`isclose` call. Use `math.isfinite` when both are plain floats and keep
the generic check otherwise.

`isclose` on scalars and small arrays is 1.5-1.9x faster. See numpygh-23483.

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.

1 participant