Skip to content

Commit 7d16e87

Browse files
vishwakftwfacebook-github-bot
authored andcommitted
Fix byte ordering issue in from_numpy (#9508)
Summary: Fixes #3671 . Pull Request resolved: #9508 Differential Revision: D9307186 Pulled By: soumith fbshipit-source-id: 39dcaa6fd2d330d7085802acd6f63c19270164fa
1 parent facb293 commit 7d16e87

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

test/test_torch.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7925,7 +7925,7 @@ def test_from_numpy(self):
79257925

79267926
@unittest.skipIf(not TEST_NUMPY, "Numpy not found")
79277927
def test_ctor_with_numpy_array(self):
7928-
dtypes = [
7928+
correct_dtypes = [
79297929
np.double,
79307930
np.float,
79317931
np.float16,
@@ -7934,7 +7934,11 @@ def test_ctor_with_numpy_array(self):
79347934
np.int16,
79357935
np.uint8
79367936
]
7937-
for dtype in dtypes:
7937+
7938+
incorrect_byteorder = '>' if sys.byteorder == 'little' else '<'
7939+
incorrect_dtypes = map(lambda t: incorrect_byteorder + t, ['d', 'f'])
7940+
7941+
for dtype in correct_dtypes:
79387942
array = np.array([1, 2, 3, 4], dtype=dtype)
79397943

79407944
# Upcast

torch/csrc/utils/tensor_numpy.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,11 @@ at::Tensor tensor_from_numpy(PyObject* obj) {
117117

118118
void* data_ptr = PyArray_DATA(array);
119119
auto& type = CPU(numpy_dtype_to_aten(PyArray_TYPE(array)));
120+
if (!PyArray_EquivByteorders(PyArray_DESCR(array)->byteorder, NPY_NATIVE)) {
121+
throw ValueError(
122+
"given numpy array has byte order different from the native byte order. "
123+
"Conversion between byte orders is currently not supported.");
124+
}
120125
Py_INCREF(obj);
121126
return type.tensorFromBlob(data_ptr, sizes, strides, [obj](void* data) {
122127
AutoGIL gil;

0 commit comments

Comments
 (0)