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

Fix from_numpy in stride #7042

Merged
merged 2 commits into from
Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 13 additions & 2 deletions oneflow/api/python/functional/tensor_api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,19 @@ class LocalTensorSharedNumpyDataFunctor {
DataType data_type = JUST(numpy::GetOFDataTypeFromNpArray(array));
Symbol<Device> device = JUST(Device::New("cpu"));
const npy_intp* stride_ptr = PyArray_STRIDES(array);
const auto stride = std::make_shared<Stride>(DimVector(stride_ptr, stride_ptr + dim));
auto tensor_meta = std::make_shared<MirroredTensorMeta>(shape, data_type, device, stride, 0);
// stride
auto strides_vec = DimVector(stride_ptr, stride_ptr + dim);
auto element_size_in_bytes = PyArray_ITEMSIZE(array);
// NumPy strides use bytes. OneFlow strides use element counts.
for (auto& stride : strides_vec) {
if (stride % element_size_in_bytes != 0) {
return Error::RuntimeError() << "given numpy array strides not a multiple of the element "
"byte size. Copy the numpy array to reallocate the memory.";
}
stride /= element_size_in_bytes;
}
const auto strides = std::make_shared<Stride>(strides_vec);
auto tensor_meta = std::make_shared<MirroredTensorMeta>(shape, data_type, device, strides, 0);

// Build TensorBuffer
const auto& Free = [obj](char* dptr) {
Expand Down
3 changes: 3 additions & 0 deletions python/oneflow/test/modules/test_from_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ def test_same_data(test_case):
np_arr = np.random.randn(3, 4, 5)
tensor = flow.from_numpy(np_arr)
test_case.assertTrue(np.array_equal(np_arr, tensor.numpy()))
test_case.assertEqual(tensor.size(), (3, 4, 5))
test_case.assertEqual(tensor.stride(), (20, 5, 1))
Copy link
Contributor

Choose a reason for hiding this comment

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

这个assert在下面tensor ** 2的那个test case也加一下吧

Copy link
Contributor Author

Choose a reason for hiding this comment

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

应该不需要吧,因为 shape 的推导逻辑是 Op 的事,只要 Tensor 创建没问题了,后面TensorMeta 的检察应该在 Op 的测试中覆盖了,就和这个单测没关系了

test_case.assertEqual(tensor.storage_offset(), 0)

np_arr[1:2, 2:3, 3:4] = random.random()
test_case.assertTrue(np.array_equal(np_arr, tensor.numpy()))
Expand Down