Skip to content
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

refactor: move typetracer ufunc handling to backend [1 of 2] #2150

Merged
merged 6 commits into from
Jan 21, 2023
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
34 changes: 33 additions & 1 deletion src/awkward/_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from awkward.typing import Callable, Final, Tuple, TypeAlias, TypeVar, Unpack

np = NumpyMetadata.instance()
numpy = ak._nplikes.Numpy.instance()


T = TypeVar("T", covariant=True)
Expand All @@ -20,7 +21,10 @@


class Backend(Singleton, ABC):
name: str
@property
@abstractmethod
def name(self) -> str:
raise ak._errors.wrap_error(NotImplementedError)
Comment on lines +24 to +27
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Misc cleanup.


@property
@abstractmethod
Expand Down Expand Up @@ -163,6 +167,34 @@ def __init__(self):
def __getitem__(self, index: KernelKeyType) -> TypeTracerKernel:
return TypeTracerKernel(index)

def _coerce_ufunc_argument(self, x):
if isinstance(x, ak._typetracer.TypeTracerArray):
return numpy.empty((0,) + x.shape[1:], dtype=x.dtype)
# Convert scalars to 0-d arrays
elif isinstance(x, ak._typetracer.UnknownScalar):
return numpy.empty((0,), dtype=x.dtype)
elif x is ak._typetracer.UnknownLength:
return numpy.empty((0,), dtype=np.int64)
elif isinstance(x, ak._typetracer.MaybeNone):
return self._coerce_ufunc_argument(x.content)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jpivarski this is one part I'm hesitant on. We're throwing away type information here because this might not fail at runtime, i.e. if the value is not actually none.

Copy link
Collaborator Author

@agoose77 agoose77 Jan 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we do want this, should MaybeNone also support operators (unrelated to this PR, but a more general point), e.g.. MaybeNone(x) + y? I'm inclined to say yes - MaybeNone should be fairly transparent, and serve as the outermost type like Haskell's Maybe.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And, what should we do about OneOf? The proper approach would be to try all branches and re-wrap the result, but if one branch fails, we would need to handle that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our strategy is for typetracers to give code the benefit of the doubt and let it fail at runtime. The typetracer is not a type-check.

So if a typetracer (including MaybeNone or OneOf) represents $x$ or $y$ and $f(x)$ would yield some result but $f(y)$ would raise an error—great! We say that the result is $f(x)$.

If a typetracer represents $x$ or $y$ and both $f(x)$ and $f(y)$ would yield results, and they're different, that's a harder situation to deal with. I hope we don't have to because there might not be a good solution. We're not prepared to propagate non-deterministic type information. (If we had to, maybe we could go with the information-losing process of finding a common superclass of both results, like np.numerical.)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, that sounds like the best path to me, too. Let's go with the safe, minimal approach and see what happens. I haven't implemented OneOf here, but we can do that in another PR, as it's probably better to keep momentum of the changes that are already in the pipeline.

else:
return x

def apply_ufunc(self, ufunc, method, args, kwargs):
shape = None
numpy_args = []

for x in args:
if isinstance(x, ak._typetracer.TypeTracerArray):
x.touch_data()
shape = x.shape

numpy_args.append(self._coerce_ufunc_argument(x))

assert shape is not None
tmp = getattr(ufunc, method)(*numpy_args, **kwargs)
return self._typetracer.empty((shape[0],) + tmp.shape[1:], dtype=tmp.dtype)


def _backend_for_nplike(nplike: ak._nplikes.NumpyLike) -> Backend:
# Currently there exists a one-to-one relationship between the nplike
Expand Down
32 changes: 8 additions & 24 deletions src/awkward/_connect/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,32 +209,16 @@ def action(inputs, **ignore):
inputs
)
(parameters,) = parameters_factory(1)
if nplike.known_data:
args = []
for x in inputs:
if isinstance(x, NumpyArray):
args.append(x._raw(nplike))
else:
args.append(x)

result = backend.apply_ufunc(ufunc, method, args, kwargs)
args = []
for x in inputs:
if isinstance(x, NumpyArray):
args.append(x._raw(nplike))
else:
args.append(x)

result = backend.apply_ufunc(ufunc, method, args, kwargs)

else:
shape = None
args = []
for x in inputs:
if isinstance(x, NumpyArray):
# some ufuncs have multiple array arguments, and they might
# not all be typetracers
if isinstance(x.data, ak._typetracer.TypeTracerArray):
x.data.touch_data()
shape = x.shape
args.append(numpy.empty((0,) + x.shape[1:], dtype=x.dtype))
else:
args.append(x)
assert shape is not None
tmp = getattr(ufunc, method)(*args, **kwargs)
result = nplike.empty((shape[0],) + tmp.shape[1:], dtype=tmp.dtype)
return (NumpyArray(result, backend=backend, parameters=parameters),)

for x in inputs:
Expand Down
53 changes: 53 additions & 0 deletions tests/test_2150_typetracer_high_level_ufunc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE

import numpy as np
import pytest # noqa: F401

import awkward as ak


def test():
array = ak.Array([1, 2, 3, 4])
typetracer_array = ak.Array(array.layout.to_typetracer(forget_length=True))
typetracer_result = np.sqrt(typetracer_array)

assert typetracer_result.type == ak.types.ArrayType(
ak.types.NumpyType("float64"), ak._typetracer.UnknownLength
)


def test_add():
left = ak.Array([1, 2, 3, 4])
right = ak.Array([1, 2, 3, 4.0])
typetracer_left = ak.Array(left.layout.to_typetracer(forget_length=True))
typetracer_right = ak.Array(right.layout.to_typetracer(forget_length=True))
typetracer_result = np.add(typetracer_left, typetracer_right)

assert typetracer_result.type == ak.types.ArrayType(
ak.types.NumpyType("float64"), ak._typetracer.UnknownLength
)


def test_add_scalar():
array = ak.Array([1, 2, 3, 4])
typetracer_array = ak.Array(array.layout.to_typetracer(forget_length=True))
other = ak.min(typetracer_array, mask_identity=False, initial=10)
assert isinstance(other, ak._typetracer.UnknownScalar)

typetracer_result = np.add(typetracer_array, other)
assert typetracer_result.type == ak.types.ArrayType(
ak.types.NumpyType("int64"), ak._typetracer.UnknownLength
)


def test_add_none_scalar():
array = ak.Array([1, 2, 3, 4])
typetracer_array = ak.Array(array.layout.to_typetracer(forget_length=True))
other = ak.min(typetracer_array, mask_identity=True, initial=10)
assert isinstance(other, ak._typetracer.MaybeNone)
assert isinstance(other.content, ak._typetracer.UnknownScalar)

typetracer_result = np.add(typetracer_array, other)
assert typetracer_result.type == ak.types.ArrayType(
ak.types.NumpyType("int64"), ak._typetracer.UnknownLength
)