Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
44 changes: 44 additions & 0 deletions pytensor/link/numba/dispatch/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from pytensor.tensor.math import Dot
from pytensor.tensor.shape import Reshape, Shape, Shape_i, SpecifyShape
from pytensor.tensor.slinalg import Solve
from pytensor.tensor.sort import ArgSortOp, SortOp
from pytensor.tensor.type import TensorType
from pytensor.tensor.type_other import MakeSlice, NoneConst

Expand Down Expand Up @@ -432,6 +433,49 @@ def shape_i(x):
return shape_i


@numba_funcify.register(SortOp)
def numba_funcify_SortOp(op, node, **kwargs):
@numba_njit
def sort_f(a, axis):
return np.sort(a) # numba supports sort without arguments

if op.kind != "quicksort":
warnings.warn(
(
f'Numba function sort doesn\'t support kind="{op.kind}"'
" switching to `quicksort`."
),
UserWarning,
)

return sort_f


@numba_funcify.register(ArgSortOp)
def numba_funcify_ArgSortOp(op, node, **kwargs):
def argsort_f_kind(kind):
@numba_njit
def argsort_f(a, axis):
return np.argsort(a, kind=kind)

return argsort_f

kind = op.kind

if kind in ["quicksort", "mergesort"]:
return argsort_f_kind(kind)
else:
warnings.warn(
(
f'Numba function argsort doesn\'t support kind="{op.kind}"'
" switching to `quicksort`."
),
UserWarning,
)

return argsort_f_kind("quicksort")


@numba.extending.intrinsic
def direct_cast(typingctx, val, typ):
if isinstance(typ, numba.types.TypeRef):
Expand Down
44 changes: 44 additions & 0 deletions tests/link/numba/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from pytensor.tensor import blas
from pytensor.tensor.elemwise import Elemwise
from pytensor.tensor.shape import Reshape, Shape, Shape_i, SpecifyShape
from pytensor.tensor.sort import ArgSortOp, SortOp


if TYPE_CHECKING:
Expand Down Expand Up @@ -378,6 +379,49 @@ def test_Shape(x, i):
compare_numba_and_py([], [g], [])


@pytest.mark.parametrize(
"kind, exc",
[
["quicksort", None],
["mergesort", UserWarning],
["heapsort", UserWarning],
["stable", UserWarning],
],
)
def test_Sort(kind, exc):
x = [5, 4, 3, 2, 1]

g = SortOp(kind)(pt.as_tensor_variable(x))

if exc:
with pytest.warns(exc):
compare_numba_and_py([], [g], [])
else:
compare_numba_and_py([], [g], [])

compare_numba_and_py([], [g], [])


@pytest.mark.parametrize(
"kind, exc",
[
["quicksort", None],
["mergesort", None],
["heapsort", UserWarning],
["stable", UserWarning],
],
)
def test_ArgSort(kind, exc):
x = [5, 4, 3, 2, 1]
g = ArgSortOp(kind)(pt.as_tensor_variable(x))

if exc:
with pytest.warns(exc):
compare_numba_and_py([], [g], [])
else:
compare_numba_and_py([], [g], [])


@pytest.mark.parametrize(
"v, shape, ndim",
[
Expand Down