File: tensor_flatten.cpp

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (43 lines) | stat: -rw-r--r-- 1,871 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <gtest/gtest.h>
#include <test/cpp/api/support.h>

#include <torch/csrc/autograd/variable.h>
#include <torch/csrc/utils/tensor_flatten.h>
#include <torch/torch.h>

using namespace torch::test;

TEST(UnflattenDenseTensorTest, TestEmptyTensor) {
  auto emptyTensor1 = at::tensor(std::vector<int>());
  auto emptyTensor2 = at::tensor(std::vector<int>());
  auto tensor1 = at::tensor({1, 2, 3});
  auto tensor2 = at::tensor({4, 5});
  auto tensorList =
      std::vector<at::Tensor>({tensor1, emptyTensor1, emptyTensor2, tensor2});
  auto flatTensor = at::tensor({1, 2, 3, 4, 5});
  auto unflatten_results =
      torch::utils::unflatten_dense_tensors(flatTensor, tensorList);
  ASSERT_EQ(unflatten_results.size(), 4);
  ASSERT_EQ(unflatten_results.at(0).numel(), 3);
  ASSERT_EQ(unflatten_results.at(1).numel(), 0);
  ASSERT_EQ(unflatten_results.at(2).numel(), 0);
  ASSERT_EQ(unflatten_results.at(3).numel(), 2);

  // empty tensor address is 0 as memory is not allocated yet
  ASSERT_EQ(unflatten_results.at(1).data_ptr(), nullptr);
  ASSERT_EQ(unflatten_results.at(2).data_ptr(), nullptr);
  // without fix in unflatten_dense_tensors() for empty tensors,
  // unflattend empty tensor unflatten_results.at(1) will share the same storage
  // as other non-empty tenosr like unflatten_results.at(3).
  // after fix, the empty tensor and non-empty tensor do not share the same
  // storage.
  ASSERT_NE(
      unflatten_results.at(1).data_ptr(), unflatten_results.at(3).data_ptr());
  unflatten_results.at(1).resize_(1);
  unflatten_results.at(2).resize_(1);
  // after resizing the two empty tensors, the resized tensors do not share
  // the same storage. without fix in unflatten_dense_tensors() for empty
  // tensors, the resized tensors will share the same storage.
  ASSERT_NE(
      unflatten_results.at(1).data_ptr(), unflatten_results.at(2).data_ptr());
}