Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions functional_algorithms/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,24 @@ def wrapper(ctx, *args, **kwargs):
return wrapper


@definition("conj", domain="complex")
def complex_conj(ctx, z: complex):
"""Conjugate of complex inputs."""
return ctx.complex(z.real, -z.imag)


@definition("conj", domain="real")
def real_conj(ctx, z: float):
"""Conjugate of real inputs."""
return NotImplemented


@definition("conj")
def conj(ctx, z: float | complex):
"""Conjugate of real and complex inputs."""
assert 0 # unreachable


@definition("square", domain="real")
def real_square(ctx, x: float):
"""Square on real input: x * x"""
Expand Down Expand Up @@ -1306,3 +1324,127 @@ def tanh(ctx, z: complex | float):
See complex_atan for more information.
"""
assert 0 # unreachable


@definition("sqrt", domain="real")
def real_sqrt(ctx, z: float):
"""Square root on real inputs"""
return NotImplemented


@definition("sqrt", domain="complex")
def complex_sqrt(ctx, z: complex):
"""Square root on complex inputs:

sqrt(z) = sqrt((hypot(x, y) + x)/2) + I * sgn(y) * sqrt((hypot(x, y) - x) / 2)

where sgn(y) = 1 if y >= 0, and sgn(y) = -1 otherwise.


Algorithm
---------

In the above formula, catastrophic cancellation errors occur in
the imaginary part when x is positive, and in the real part when x
is negative. To avoid these, let us define

u = sqrt((hypot(x, y) + abs(x))/2)
v = sgn(y) * sqrt((hypot(x, y) - abs(x))/2)

and find

u * v = sgn(y) * sqrt(hypot(x, y) ** 2 - x ** 2) / 2 = y / 2

That is, if x > 0, then we have

sqrt(z) = u + I * y / u / 2

and if x < 0,

sqrt(z) = abs(y) / u / 2 + I * sgn(y) * u

If abs(x) and abs(y) are smaller that smallest normal, then as a
result of underflow, u will be zero and v will be undefined. On
the other hand, if abs(x) and abs(y) are close to largest floating
point number, then `hypot(x, y) + abs(x)` will overflow, and u
will be `inf`. To address the issues from underflow and overflow,
we'll use the following formula:

1. abs(x) == abs(y), or abs(x) == inf and abs(y) == inf, then

u_eq = sqrt(abs(x)) * sqrt((1 + sqrt(2))/2)
abs(y) / u = sqrt(abs(x)) / sqrt((1 + sqrt(2))/2)

2. If abs(x) > abs(y) and u == 0 (the underflow case) or u == inf
(the overflow case), denote r = abs(y) / abs(x), then

u_gt = sqrt(abs(x)) * sqrt((1 + hypot(1, r)) / 2)
abs(y) / u = sqrt(abs(y)) * sqrt(r) / sqrt((1 + hypot(1, r)) / 2)

3. If abs(x) < abs(y) and u == 0 (the underflow case) or u == inf
(the overflow case), denote r = abs(x) / abs(y), then

u_lt = sqrt(abs(y)) * sqrt((r + sqrt(1, r)) / 2)
abs(y) / u = sqrt(abs(y)) / sqrt((r + sqrt(1, r)) / 2)
"""
x = z.real
y = z.imag
ax = abs(x)
ay = abs(y)
sq_ax = ctx.sqrt(ax)
sq_ay = ctx.sqrt(ay)

one = ctx.constant(1, x)
two = ctx.constant(2, x)

if ctx.alt is None:
sq_2 = ctx.sqrt(two)
sq_12 = ctx.sqrt(one + sq_2)
else:
sq_2_ = ctx.alt.sqrt(2)
sq_12_ = ctx.alt.sqrt(1 + sq_2_)
sq_2 = ctx.constant(sq_2_, x)
sq_12 = ctx.constant(sq_12_, x)

u_general = ctx.sqrt((ctx.hypot(ax, ay) / two + ax / two))
ay_div_u_general = ay / (u_general * two)

r = ctx.select(ax == ay, one, ctx.select(ax < ay, ax / ay, ay / ax))
sq_r = ctx.select(ax == ay, one, ctx.select(ax < ay, sq_ax / sq_ay, sq_ay / sq_ax))

h = ctx.hypot(one, r)

u_eq = sq_ax * sq_12 / sq_2
ay_div_eq = sq_ay / (sq_12 * sq_2)

sq_1h = ctx.sqrt(one + h)
u_gt = sq_ax * (sq_1h / sq_2)
ay_div_u_gt = sq_ay * sq_r / (sq_1h * sq_2)

sq_rh = ctx.sqrt(r + h)
u_lt = sq_ay * (sq_rh / sq_2)
ay_div_u_lt = sq_ay / (sq_rh * sq_2)

u = ctx.select(
ax == ay, u_eq, ctx.select(ctx.Or(u_general == 0, u_general.is_posinf), ctx.select(ax > ay, u_gt, u_lt), u_general)
)
ay_div_u = ctx.select(
ax == ay,
ay_div_eq,
ctx.select(
ctx.Or(u_general == 0, u_general.is_posinf), ctx.select(ax > ay, ay_div_u_gt, ay_div_u_lt), ay_div_u_general
),
)

re = ctx.select(x >= 0, u, ay_div_u)
im = ctx.select(x < 0, ctx.select(y < 0, -u, u), ctx.select(y < 0, -ay_div_u, ay_div_u))
return ctx(ctx.complex(re, im))


@definition("sqrt")
def sqrt(ctx, z: complex | float):
"""Square root on complex and real inputs.

See complex_sqrt for more information.
"""
assert 0 # unreachable
1 change: 1 addition & 0 deletions functional_algorithms/targets/cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
# real_asin=[(":float", ":float")],
# square=[(":float", ":float"), (":complex", ":complex")],
# asin=[(":float", ":float"), (":complex", ":complex")],
complex_sqrt=[(":complex", ":complex")],
)

source_file_extension = ".cpp"
Expand Down
4 changes: 4 additions & 0 deletions functional_algorithms/targets/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ def downcast_func(target, expr):
log1p=[(":complex128",), (":complex64",), (":float64",), (":float32",)],
hypot=[(":float32", ":float32"), (":float64", ":float64")],
square=[(":complex128",), (":complex64",), (":float64",), (":float32",)],
sqrt=[
(":complex128",),
(":complex64",),
],
)


Expand Down
1 change: 1 addition & 0 deletions functional_algorithms/targets/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def __rewrite_modifier__(expr):
hypot=[(":float", ":float")],
square=[(":float",), (":complex",)],
log1p=[(":float",), (":complex",)],
sqrt=[(":float",), (":complex",)][1:],
)


Expand Down
1 change: 1 addition & 0 deletions functional_algorithms/targets/stablehlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
log1p=[(":float",), (":complex",)],
hypot=[(":float", ":float")],
square=[(":float",), (":complex",)],
sqrt=[(":complex",)],
)


Expand Down
1 change: 1 addition & 0 deletions functional_algorithms/targets/xla_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
atan=[(":float", ":float"), (":complex", ":complex")],
atanh=[(":float", ":float"), (":complex", ":complex")],
complex_log1p=[(":complex", ":complex")],
complex_sqrt=[(":complex", ":complex")],
)

source_file_extension = ".cc"
Expand Down
30 changes: 19 additions & 11 deletions functional_algorithms/tests/test_accuracy.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import numpy
import functional_algorithms as fa
import os
import pytest
import warnings


@pytest.fixture(scope="function", params=["jax"])
@pytest.fixture(scope="function", params=["jax", "functional_algorithms"])
def backend(request):
return request.param

Expand All @@ -25,9 +26,17 @@ def dtype(request):


def test_unary(unary_func_name, backend, device, dtype):
pytest.importorskip(backend)
if backend == "functional_algorithms":
backend = "algorithms"
else:
pytest.importorskip(backend)

func = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device), unary_func_name)
try:
func = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device, dtype=dtype), unary_func_name)
except NotImplementedError as msg:
pytest.skip(f"{unary_func_name}: {msg}")
except AttributeError as msg:
pytest.skip(f"{unary_func_name}: {msg}")

if not func.backend_is_available(device):
pytest.skip(f"{device} support is unavailable")
Expand All @@ -43,7 +52,7 @@ def test_unary(unary_func_name, backend, device, dtype):
# and smallest normal is defined as 1).
fi = numpy.finfo(dtype)
x = numpy.sqrt(fi.smallest_normal) * dtype(0.5)
v1 = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device), "square")(x)
v1 = getattr(getattr(fa.utils, f"numpy_with_{backend}")(device=device, dtype=dtype), "square")(x)
v2 = numpy.square(x)
d = fa.utils.diff_ulp(v1, v2)
if d > 1000:
Expand All @@ -56,11 +65,10 @@ def test_unary(unary_func_name, backend, device, dtype):
reference = getattr(mpmath, unary_func_name)
npy_reference = getattr(fa.utils.numpy_with_numpy(), unary_func_name)

re_blocks, im_blocks = 101, 52
re_blocksize, im_blocksize = 20, 20

if 0:
# used for testing
if int(os.environ.get("FA_HIGH_RESOLUTION", "0")):
re_blocks, im_blocks = 101, 52
re_blocksize, im_blocksize = 20, 20
else:
re_blocks, im_blocks = 51, 26
re_blocksize, im_blocksize = 5, 5

Expand Down Expand Up @@ -156,7 +164,7 @@ def test_unary(unary_func_name, backend, device, dtype):
print(timage)
print()

if fa_reference is not None:
if fa_reference is not None and backend != "algorithms":
rows = [
(
"ULP-difference",
Expand Down Expand Up @@ -188,7 +196,7 @@ def test_unary(unary_func_name, backend, device, dtype):
clusters = fa.utils.Clusters()
for re, im in zip(*numpy.where(ulp == value)):
clusters.add((re, im))
for cluster in clusters:
for cluster in clusters.clusters + clusters.split().clusters:
re, im = cluster.center_point()
with warnings.catch_warnings(action="ignore"):
np_value = npy_reference(samples[re, im])
Expand Down
45 changes: 39 additions & 6 deletions functional_algorithms/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import itertools
import numpy
import math
Expand Down Expand Up @@ -652,6 +653,26 @@ def context_from_backend(self, sample):
return jax.default_device(jax.devices(self.device)[0])


class vectorize_with_numpy(vectorize_with_backend):

def backend_context(self, context):
return contextlib.nullcontext()

def context_from_backend(self, obj):
return contextlib.nullcontext()

def numpy_to_backend(self, arr):
return arr

def numpy_from_backend(self, obj):
assert isinstance(obj, numpy.ndarray), type(obj)
return obj

@property
def backend_types(self):
return (numpy.ndarray,)


class mpmath_array_api:
"""Array API interface to mpmath functions including workarounds to
mpmath bugs.
Expand Down Expand Up @@ -1103,19 +1124,20 @@ def __getattr__(self, name):
name = dict(arcsinh="asinh", arccos="acos", arcsin="asin", arccosh="acosh", arctan="atan", arctanh="atanh").get(
name, name
)
if name in self._vfunc_cache:
return self._vfunc_cache[name]
dtype = self.params["dtype"]
key = name, dtype.__name__
if key in self._vfunc_cache:
return self._vfunc_cache[key]

import functional_algorithms as fa
import numpy

dtype = self.params["dtype"]
ctx = fa.Context(paths=[fa.algorithms])
graph = ctx.trace(getattr(fa.algorithms, name), dtype)
graph2 = graph.rewrite(fa.targets.numpy, fa.rewrite)
func = fa.targets.numpy.as_function(graph2, debug=0)
vfunc = numpy.vectorize(func)
self._vfunc_cache[name] = vfunc
func = fa.targets.numpy.as_function(graph2, debug=self.params.get("debug", 0))
vfunc = vectorize_with_numpy(func)
self._vfunc_cache[key] = vfunc
return vfunc


Expand Down Expand Up @@ -1947,3 +1969,14 @@ def add(self, point):

def __iter__(self):
return iter(self.clusters)

def split(self):
"""Split clusters by discarding the their center points."""
result = type(self)()
for index, cluster in enumerate(self.clusters):
center = cluster.center_point()
for point in cluster.points:
if point == center:
continue
result.add(point)
return result
2 changes: 2 additions & 0 deletions results/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ Finally,
| square | complex128 | 995705 | 6296 | - | - | - | - |
| sqrt | float32 | 1000001 | - | - | - | - | using native sqrt |
| sqrt | complex64 | 639573 | 362328 | 100 | - | - | using native sqrt |
| sqrt<sub>2</sub> | complex64 | 639573 | 362328 | 100 | - | - | using native sqrt |
| sqrt | complex128 | 637905 | 364008 | 88 | - | - | - |
| angle | complex64 | 940289 | 61332 | 376 | 4 | - | - |
| angle | complex128 | 989787 | 12214 | - | - | - | - |
| log1p | complex64 | 905931 | 94401 | 1661 | 8 | - | - |
Expand Down
Loading