// TODO: write actual tests #include #include #include #include #include #include using tulip::dynamic_extent; // Whatever TEST(Tensor, View) { tulip::tensor tensor; auto view = tensor.view()[1][1]; } TEST(Tensor, Ops) { constexpr float lhsArray[2 * 3] = { 1, 2, 3, 4, 5, 6 }; tulip::tensor lhs; lhs.set_dimensions(2, 3); lhs.view().fill(lhsArray); constexpr float rhsArray[2 * 3] = { 6, 5, 4, 3, 2, 1 }; tulip::tensor, 2, 3> rhs; rhs.view().fill(rhsArray); constexpr float resultArray[2 * 3] = { 6 * 1, 6 * 2, 6 * 3, 6 * 4, 6 * 5, 6 * 6 }; tulip::tensor, 2, 3> result = lhs + rhs - 1; result *= lhs; for (std::size_t i = 0; i < result.size(); ++i) { EXPECT_EQ(result.coeff(i), resultArray[i]); } } TEST(Tensor, MatMul) { constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 }; constexpr float rhsArray[2 * 2] = { 5, 6, 7, 8 }; tulip::tensor, 2, 2> lhs; tulip::tensor, 2, 2> rhs; lhs.view().fill(lhsArray); rhs.view().fill(rhsArray); constexpr float expArray[2 * 2] = { (1 * 5) + (2 * 7), (1 * 6) + (2 * 8), (3 * 5) + (4 * 7), (3 * 6) + (4 * 8) }; tulip::tensor, 2, 2> result = lhs.matmul(rhs); for (std::size_t i = 0; i < result.size(); ++i) { EXPECT_EQ(result.coeff(i), expArray[i]); } } // MatMul was so good they made a sequel TEST(Tensor, MatMul2) { constexpr float lhsArray[3 * 2] = { 1, 2, 5, 6, 7, 8 }; constexpr float rhsArray[2 * 1] = { 3, 4 }; tulip::tensor, 3, 2> lhs; tulip::tensor, 2, 1> rhs; lhs.view().fill(lhsArray); rhs.view().fill(rhsArray); constexpr float expArray[3 * 1] = { 11, 39, 53 }; tulip::tensor, 3, 1> result = lhs.matmul(rhs); for (std::size_t i = 0; i < result.size(); ++i) { EXPECT_EQ(result.coeff(i), expArray[i]); } } TEST(Tensor, Apply) { constexpr float values[2 * 2] = { 1, 2, 3, 4 }; tulip::tensor, 2, 2> tensor; tensor.view().fill(values); constexpr float expected[2 * 2] = { 1, 4, 9, 16 }; tensor = tensor.apply([](auto val) { return val * val; }); for (std::size_t i = 0; i < tensor.size(); ++i) { EXPECT_EQ(tensor.coeff(i), expected[i]); } } TEST(Tensor, Apply2) { constexpr float lhsArray[2 * 2] = { 1, 2, 3, 4 }; constexpr float rhsArray[2 * 2] = { 4, 3, 2, 1 }; tulip::tensor, 2, 2> lhs; tulip::tensor, 2, 2> rhs; lhs.view().fill(lhsArray); rhs.view().fill(rhsArray); constexpr float expArray[2 * 2] = { 4, 3, 3, 4 }; tulip::tensor, 2, 2> result = lhs.apply(rhs, [](auto x1, auto x2) { return std::max(x1, x2); }); for (std::size_t i = 0; i < result.size(); ++i) { EXPECT_EQ(result.coeff(i), expArray[i]); } } TEST(Tensor, Offsets) { tulip::tensor tensor; for (std::size_t i = 0; i < tensor.size(); ++i) tensor.coeff(i) = static_cast(i); EXPECT_EQ(tensor[1][0][0], 12); EXPECT_EQ(tensor[1][2][0], 20); EXPECT_EQ(tensor[1][2][3], 23); } TEST(Tensor, Offsets2) { using shape_type = tulip::static_shape<2, 3, 4>; shape_type shape; EXPECT_EQ(shape.calculate_offset(std::make_tuple(1)), 12); EXPECT_EQ(shape.calculate_offset(std::make_tuple(1, 2)), 20); EXPECT_EQ(shape.calculate_offset(std::make_tuple(1, 2, 3)), 23); }