Skip to content
Closed
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
1 change: 1 addition & 0 deletions docs/generate_rst.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"dpctl.tensor._copy_utils": "Array Construction",
"dpctl.tensor._dlpack": "Array Construction",
"dpctl.tensor._reshape": "Array Manipulation",
"dpctl.tensor._manipulation_functions": "Array Manipulation",
"dpctl.memory._memory": "Functions",
"dpctl.program._program": "Functions",
"dpctl.utils._compute_follows_data": "Functions",
Expand Down
2 changes: 2 additions & 0 deletions dpctl/tensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from dpctl.tensor._ctors import asarray, empty
from dpctl.tensor._device import Device
from dpctl.tensor._dlpack import from_dlpack
from dpctl.tensor._manipulation_functions import permute_dims
from dpctl.tensor._reshape import reshape
from dpctl.tensor._usmarray import usm_ndarray

Expand All @@ -36,6 +37,7 @@
"copy",
"empty",
"reshape",
"permute_dims",
"from_numpy",
"to_numpy",
"asnumpy",
Expand Down
63 changes: 63 additions & 0 deletions dpctl/tensor/_manipulation_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Data Parallel Control (dpctl)
#
# Copyright 2020-2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import numpy as np

import dpctl.tensor as dpt


def _check_value_of_axes(axes):
check_array = np.zeros(len(axes))
for i in axes:
ii = i.__index__()
if ii < 0 or ii > len(axes) or check_array[ii] != 0:
return False
check_array[ii] = 1
del check_array
return True


def permute_dims(X, axes):
"""
permute_dims(X: usm_ndarray, axes: tuple or list) -> usm_ndarray

Permutes the axes(dimensions) of the given usm_ndarray. Returns a view
containing the axes permutation.
"""
if not isinstance(X, dpt.usm_ndarray):
raise TypeError(f"Expected usm_ndarray type, got {type(X)}.")
if not isinstance(axes, (tuple, list)):
axes = (axes,)
if not X.ndim == len(axes):
raise ValueError(
"The length of the passed axes does not match "
"to the number of usm_ndarray dimensions."
)
if not _check_value_of_axes(axes):
raise ValueError(
"The values of the axes must be in the range "
f"from 0 to {X.ndim} and have no duplicates."
)
newstrides = [X.strides[i] for i in axes]
newshape = [X.shape[i] for i in axes]
return dpt.usm_ndarray(
shape=tuple(newshape),
dtype=X.dtype,
buffer=X,
strides=tuple(newstrides),
offset=X.__sycl_usm_array_interface__.get("offset", 0),
)
92 changes: 92 additions & 0 deletions dpctl/tests/test_usm_ndarray_manipulation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Data Parallel Control (dpctl)
#
# Copyright 2020-2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import numpy as np
import pytest
from numpy.testing import assert_array_equal

import dpctl
import dpctl.tensor as dpt


def test_permute_dims_incorrect_type():
X_list = list([[1, 2, 3], [4, 5, 6]])
X_tuple = tuple(X_list)
Xnp = np.array(X_list)

pytest.raises(TypeError, dpt.permute_dims, X_list, (1, 0))
pytest.raises(TypeError, dpt.permute_dims, X_tuple, (1, 0))
pytest.raises(TypeError, dpt.permute_dims, Xnp, (1, 0))


def test_permute_dims_empty_array():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created")

Xnp = np.empty((10, 0))
X = dpt.asarray(Xnp, sycl_queue=q)
Y = dpt.permute_dims(X, (1, 0))
Ynp = np.transpose(Xnp, (1, 0))
assert_array_equal(Ynp, dpt.asnumpy(Y))


def test_permute_dims_0d_1d():
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created")

Xnp_0d = np.array(1, dtype="int64")
X_0d = dpt.asarray(Xnp_0d, sycl_queue=q)
Y_0d = dpt.permute_dims(X_0d, ())
assert_array_equal(dpt.asnumpy(Y_0d), dpt.asnumpy(X_0d))

Xnp_1d = np.random.randint(0, 2, size=6, dtype="int64")
X_1d = dpt.asarray(Xnp_1d, sycl_queue=q)
Y_1d = dpt.permute_dims(X_1d, (0))
assert_array_equal(dpt.asnumpy(Y_1d), dpt.asnumpy(X_1d))

pytest.raises(ValueError, dpt.permute_dims, X_1d, ())
pytest.raises(IndexError, dpt.permute_dims, X_1d, (1))
pytest.raises(ValueError, dpt.permute_dims, X_1d, (1, 0))
pytest.raises(
ValueError, dpt.permute_dims, dpt.reshape(X_1d, (2, 3)), (1, 1)
)


@pytest.mark.parametrize("shapes", [(2, 2), (1, 4), (3, 3, 3), (4, 1, 3)])
def test_permute_dims_2d_3d(shapes):
try:
q = dpctl.SyclQueue()
except dpctl.SyclQueueCreationError:
pytest.skip("Queue could not be created")

Xnp_size = np.prod(shapes)

Xnp = np.random.randint(0, 2, size=Xnp_size, dtype="int64").reshape(shapes)
X = dpt.asarray(Xnp, sycl_queue=q)
X_ndim = X.ndim
if X_ndim == 2:
Y = dpt.permute_dims(X, (1, 0))
Ynp = np.transpose(Xnp, (1, 0))
elif X_ndim == 3:
X = dpt.asarray(Xnp, sycl_queue=q)
Y = dpt.permute_dims(X, (2, 0, 1))
Ynp = np.transpose(Xnp, (2, 0, 1))
assert_array_equal(Ynp, dpt.asnumpy(Y))