test_ddim.cc 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// 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.

#include <sstream>

#include "gtest/gtest.h"
18
#include "paddle/phi/core/ddim.h"
19

20
namespace phi {
21 22
namespace tests {

23 24
TEST(DDim, Equality) {
  // construct a DDim from an initialization list
25
  phi::DDim ddim = phi::make_ddim({9, 1, 5});
26 27 28 29 30 31
  EXPECT_EQ(ddim[0], 9);
  EXPECT_EQ(ddim[1], 1);
  EXPECT_EQ(ddim[2], 5);

  // construct a DDim from a vector
  std::vector<int64_t> vec({9, 1, 5});
32
  phi::DDim vddim = phi::make_ddim(vec);
33 34 35 36 37 38 39 40 41 42 43
  EXPECT_EQ(ddim[0], 9);
  EXPECT_EQ(ddim[1], 1);
  EXPECT_EQ(ddim[2], 5);

  // mutate a DDim
  ddim[1] = 2;
  EXPECT_EQ(ddim[1], 2);
  ddim[0] = 6;
  EXPECT_EQ(ddim[0], 6);

  // vectorize a DDim
44
  std::vector<int64_t> res_vec = phi::vectorize(vddim);
45 46 47
  EXPECT_EQ(res_vec[0], 9);
  EXPECT_EQ(res_vec[1], 1);
  EXPECT_EQ(res_vec[2], 5);
48 49
  phi::Dim<3> d(3, 2, 1);
  res_vec = phi::vectorize(phi::DDim(d));
50 51 52 53 54
  EXPECT_EQ(res_vec[0], 3);
  EXPECT_EQ(res_vec[1], 2);
  EXPECT_EQ(res_vec[2], 1);

  // arity of a DDim
55
  EXPECT_EQ(phi::arity(ddim), 3);
56 57 58
  EXPECT_EQ(ddim.size(), 3);

  // product of a DDim
59 60
  EXPECT_EQ(phi::product(vddim), 45);
  EXPECT_EQ(phi::product(phi::make_ddim({3, 2, 5, 3})), 90);
61 62

  // slice a DDim
63 64
  phi::DDim ddim2 = phi::make_ddim({1, 2, 3, 4, 5, 6});
  phi::DDim ss = phi::slice_ddim(ddim2, 2, 5);
65 66 67 68
  EXPECT_EQ(arity(ss), 3);
  EXPECT_EQ(ss[0], 3);
  EXPECT_EQ(ss[1], 4);
  EXPECT_EQ(ss[2], 5);
69
  phi::DDim ss2 = phi::slice_ddim(ddim2, 0, 6);
70 71 72 73 74 75 76 77 78 79 80 81
  EXPECT_EQ(arity(ss2), 6);
  EXPECT_EQ(ss2[0], 1);
  EXPECT_EQ(ss2[1], 2);
  EXPECT_EQ(ss2[2], 3);
  EXPECT_EQ(ss2[3], 4);
  EXPECT_EQ(ss2[4], 5);
  EXPECT_EQ(ss2[5], 6);
}

TEST(DDim, Print) {
  // print a DDim
  std::stringstream ss;
82
  phi::DDim ddim = phi::make_ddim({2, 3, 4});
83 84 85
  ss << ddim;
  EXPECT_EQ("2, 3, 4", ss.str());
}
86 87

}  // namespace tests
88
}  // namespace phi