-
Notifications
You must be signed in to change notification settings - Fork 115
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented Sort/Argsort Ops in PyTorch (#897)
- Loading branch information
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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 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,25 @@ | ||
import torch | ||
|
||
from pytensor.link.pytorch.dispatch.basic import pytorch_funcify | ||
from pytensor.tensor.sort import ArgSortOp, SortOp | ||
|
||
|
||
@pytorch_funcify.register(SortOp) | ||
def pytorch_funcify_Sort(op, **kwargs): | ||
stable = op.kind == "stable" | ||
|
||
def sort(arr, axis): | ||
sorted, _ = torch.sort(arr, dim=axis, stable=stable) | ||
return sorted | ||
|
||
return sort | ||
|
||
|
||
@pytorch_funcify.register(ArgSortOp) | ||
def pytorch_funcify_ArgSort(op, **kwargs): | ||
stable = op.kind == "stable" | ||
|
||
def argsort(arr, axis): | ||
return torch.argsort(arr, dim=axis, stable=stable) | ||
|
||
return argsort |
This file contains 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,26 @@ | ||
import numpy as np | ||
import pytest | ||
|
||
from pytensor.graph import FunctionGraph | ||
from pytensor.tensor import matrix | ||
from pytensor.tensor.sort import argsort, sort | ||
from tests.link.pytorch.test_basic import compare_pytorch_and_py | ||
|
||
|
||
@pytest.mark.parametrize("func", (sort, argsort)) | ||
@pytest.mark.parametrize( | ||
"axis", | ||
[ | ||
pytest.param(0), | ||
pytest.param(1), | ||
pytest.param( | ||
None, marks=pytest.mark.xfail(reason="Reshape Op not implemented") | ||
), | ||
], | ||
) | ||
def test_sort(func, axis): | ||
x = matrix("x", shape=(2, 2), dtype="float64") | ||
out = func(x, axis=axis) | ||
fgraph = FunctionGraph([x], [out]) | ||
arr = np.array([[1.0, 4.0], [5.0, 2.0]]) | ||
compare_pytorch_and_py(fgraph, [arr]) |