From d310891eca4d1ae0f343c13000ada7db439d1900 Mon Sep 17 00:00:00 2001 From: He Wei Date: Thu, 6 Aug 2020 20:06:08 +0800 Subject: [PATCH] Fix a bug in Tensor::equals() 1. Check if data_ is null before compare it; 2. Always allocate an array for data_ even if size is zero. --- mindspore/core/ir/tensor.cc | 17 +++++++++-------- tests/ut/cpp/ir/meta_tensor_test.cc | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/mindspore/core/ir/tensor.cc b/mindspore/core/ir/tensor.cc index e09c371f504..b0af4411d68 100644 --- a/mindspore/core/ir/tensor.cc +++ b/mindspore/core/ir/tensor.cc @@ -176,13 +176,8 @@ class TensorDataImpl : public TensorData { ssize_t ndim() const override { return static_cast(ndim_); } void *data() override { - static T empty_data = static_cast(0); - if (data_size_ == 0) { - // Prevent null pointer for empty shape. - return &empty_data; - } - // Lazy allocation. if (data_ == nullptr) { + // Lazy allocation. data_ = std::make_unique(data_size_); } return data_.get(); @@ -193,8 +188,14 @@ class TensorDataImpl : public TensorData { if (ptr == nullptr) { return false; } - return (ptr == this) || ((ndim_ == ptr->ndim_) && (data_size_ == ptr->data_size_) && - (std::equal(data_.get(), data_.get() + data_size_, ptr->data_.get()))); + if (ptr == this) { + return true; + } + if (data_ == nullptr || ptr->data_ == nullptr) { + return false; + } + return (ndim_ == ptr->ndim_) && (data_size_ == ptr->data_size_) && + std::equal(data_.get(), data_.get() + data_size_, ptr->data_.get()); } std::string ToString(const TypeId type, const std::vector &shape) const override { diff --git a/tests/ut/cpp/ir/meta_tensor_test.cc b/tests/ut/cpp/ir/meta_tensor_test.cc index 555a4e96548..928e90a1a1d 100644 --- a/tests/ut/cpp/ir/meta_tensor_test.cc +++ b/tests/ut/cpp/ir/meta_tensor_test.cc @@ -225,6 +225,27 @@ TEST_F(TestTensor, EqualTest) { ASSERT_EQ(TypeId::kNumberTypeFloat64, tensor_float64->data_type_c()); } +TEST_F(TestTensor, ValueEqualTest) { + py::tuple tuple = py::make_tuple(1, 2, 3, 4, 5, 6); + TensorPtr t1 = TensorPy::MakeTensor(py::array(tuple), kInt32); + TensorPtr t2 = TensorPy::MakeTensor(py::array(tuple), kInt32); + ASSERT_TRUE(t1->ValueEqual(*t1)); + ASSERT_TRUE(t1->ValueEqual(*t2)); + + std::vector shape = {6}; + TensorPtr t3 = std::make_shared(kInt32->type_id(), shape); + TensorPtr t4 = std::make_shared(kInt32->type_id(), shape); + ASSERT_TRUE(t3->ValueEqual(*t3)); + ASSERT_FALSE(t3->ValueEqual(*t4)); + ASSERT_FALSE(t3->ValueEqual(*t1)); + ASSERT_FALSE(t1->ValueEqual(*t3)); + + memcpy_s(t3->data_c(), t3->data().nbytes(), t1->data_c(), t1->data().nbytes()); + ASSERT_TRUE(t1->ValueEqual(*t3)); + ASSERT_FALSE(t3->ValueEqual(*t4)); + ASSERT_FALSE(t4->ValueEqual(*t3)); +} + TEST_F(TestTensor, PyArrayTest) { py::array_t input({2, 3}); auto array = input.mutable_unchecked();