|
| 1 | +#include <gtest/gtest.h> |
| 2 | +#include <test/cpp/api/support.h> |
| 3 | + |
| 4 | +#include <torch/torch.h> |
| 5 | +#include <torch/csrc/utils/tensor_flatten.h> |
| 6 | +#include <torch/csrc/autograd/variable.h> |
| 7 | + |
| 8 | +using namespace torch::test; |
| 9 | + |
| 10 | +TEST(UnflattenDenseTensorTest, TestEmptyTensor) { |
| 11 | + auto emptyTensor1 = at::tensor(std::vector<int>()); |
| 12 | + auto emptyTensor2 = at::tensor(std::vector<int>()); |
| 13 | + auto tensor1 = at::tensor({1, 2, 3}); |
| 14 | + auto tensor2 = at::tensor({4, 5}); |
| 15 | + auto tensorList = std::vector<at::Tensor>({tensor1, emptyTensor1, emptyTensor2, tensor2}); |
| 16 | + auto flatTensor = at::tensor({1, 2, 3, 4, 5}); |
| 17 | + auto unflatten_results = torch::utils::unflatten_dense_tensors(flatTensor, tensorList); |
| 18 | + ASSERT_EQ(unflatten_results.size(), 4); |
| 19 | + ASSERT_EQ(unflatten_results.at(0).numel(), 3); |
| 20 | + ASSERT_EQ(unflatten_results.at(1).numel(), 0); |
| 21 | + ASSERT_EQ(unflatten_results.at(2).numel(), 0); |
| 22 | + ASSERT_EQ(unflatten_results.at(3).numel(), 2); |
| 23 | + |
| 24 | + // empty tensor address is 0 as memory is not allocated yet |
| 25 | + ASSERT_EQ(unflatten_results.at(1).data_ptr(), nullptr); |
| 26 | + ASSERT_EQ(unflatten_results.at(2).data_ptr(), nullptr); |
| 27 | + // without fix in unflatten_dense_tensors() for empty tensors, |
| 28 | + // unflattend empty tensor unflatten_results.at(1) will share the same storage |
| 29 | + // as other non-empty tenosr like unflatten_results.at(3). |
| 30 | + // after fix, the empty tensor and non-empty tensor do not share the same |
| 31 | + // storage. |
| 32 | + ASSERT_NE(unflatten_results.at(1).data_ptr(), unflatten_results.at(3).data_ptr()); |
| 33 | + unflatten_results.at(1).resize_(1); |
| 34 | + unflatten_results.at(2).resize_(1); |
| 35 | + // after resizing the two empty tensors, the resized tensors do not share |
| 36 | + // the same storage. without fix in unflatten_dense_tensors() for empty tensors, |
| 37 | + // the resized tensors will share the same storage. |
| 38 | + ASSERT_NE(unflatten_results.at(1).data_ptr(), unflatten_results.at(2).data_ptr()); |
| 39 | +} |
0 commit comments