diff --git a/mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.cc b/mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.cc new file mode 100644 index 0000000000..74d9c86523 --- /dev/null +++ b/mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.cc @@ -0,0 +1,41 @@ +/** + * Copyright 2020 Huawei Technologies Co., Ltd + * + * 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 + +#include "backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.h" + +namespace mindspore { +namespace kernel { +MS_REG_GPU_KERNEL_ONE(ZerosLike, KernelAttr().AddInputAttr(kNumberTypeBool).AddOutputAttr(kNumberTypeBool), + ZerosLikeGpuKernel, bool) + +MS_REG_GPU_KERNEL_ONE(ZerosLike, KernelAttr().AddInputAttr(kNumberTypeInt8).AddOutputAttr(kNumberTypeInt8), + ZerosLikeGpuKernel, int8_t) + +MS_REG_GPU_KERNEL_ONE(ZerosLike, KernelAttr().AddInputAttr(kNumberTypeUInt8).AddOutputAttr(kNumberTypeUInt8), + ZerosLikeGpuKernel, uint8_t) + +MS_REG_GPU_KERNEL_ONE(ZerosLike, KernelAttr().AddInputAttr(kNumberTypeInt32).AddOutputAttr(kNumberTypeInt32), + ZerosLikeGpuKernel, int32_t) + +MS_REG_GPU_KERNEL_ONE(ZerosLike, KernelAttr().AddInputAttr(kNumberTypeFloat16).AddOutputAttr(kNumberTypeFloat16), + ZerosLikeGpuKernel, half) + +MS_REG_GPU_KERNEL_ONE(ZerosLike, KernelAttr().AddInputAttr(kNumberTypeFloat32).AddOutputAttr(kNumberTypeFloat32), + ZerosLikeGpuKernel, float) + +} // namespace kernel +} // namespace mindspore diff --git a/mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.h b/mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.h new file mode 100644 index 0000000000..b1ba37a841 --- /dev/null +++ b/mindspore/ccsrc/backend/kernel_compiler/gpu/arrays/zeroslike_gpu_kernel.h @@ -0,0 +1,88 @@ +/** + * Copyright 2020 Huawei Technologies Co., Ltd + * + * 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. + */ + +#ifndef MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_ZEROSLIKE_GPU_KERNEL_H +#define MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_ZEROSLIKE_GPU_KERNEL_H + +#include + +#include "backend/kernel_compiler/gpu/gpu_kernel.h" +#include "backend/kernel_compiler/gpu/gpu_kernel_factory.h" + +namespace mindspore { +namespace kernel { +template +class ZerosLikeGpuKernel : public GpuKernel { + public: + ZerosLikeGpuKernel() { ResetResource(); } + ~ZerosLikeGpuKernel() override = default; + const std::vector &GetInputSizeList() const override { return input_size_list_; } + const std::vector &GetOutputSizeList() const override { return output_size_list_; } + const std::vector &GetWorkspaceSizeList() const override { return workspace_size_list_; } + + bool Launch(const std::vector &inputs, const std::vector &workspace, + const std::vector &outputs, void *stream_ptr) override { + T *output_device_address = GetDeviceAddress(outputs, 0); + + CHECK_CUDA_RET_WITH_EXCEPT( + kernel_node_, + // have to use a float literal instead of an int literal beacuse of ambigious half() overload. + cudaMemsetAsync(output_device_address, static_cast(0.0), input_size_ * sizeof(T), + reinterpret_cast(stream_ptr)), + "cudaMemset failed"); + + return true; + } + + bool Init(const CNodePtr &kernel_node) override { + kernel_node_ = kernel_node; + + std::vector input_shape = AnfAlgo::GetInputRealDeviceShapeIfExist(kernel_node, 0); + for (size_t i = 0; i < input_shape.size(); i++) { + input_size_ *= input_shape[i]; + } + + InitSizeLists(); + + return true; + } + + void ResetResource() noexcept override { + kernel_node_ = nullptr; + input_size_ = 1; + input_size_list_.clear(); + output_size_list_.clear(); + workspace_size_list_.clear(); + } + + protected: + void InitSizeLists() override { + // allocate space for input even though we don't need to do anything with the input + input_size_list_.push_back(input_size_ * sizeof(T)); + output_size_list_.push_back(input_size_ * sizeof(T)); + } + + private: + CNodePtr kernel_node_; + size_t input_size_; + std::vector input_size_list_; + std::vector output_size_list_; + std::vector workspace_size_list_; +}; +} // namespace kernel +} // namespace mindspore + +#endif // MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_GPU_ARRAYS_ZEROSLIKE_GPU_KERNEL_H diff --git a/mindspore/ccsrc/frontend/optimizer/irpass/special_op_eliminate.h b/mindspore/ccsrc/frontend/optimizer/irpass/special_op_eliminate.h index 00fcef715b..9354eb3467 100644 --- a/mindspore/ccsrc/frontend/optimizer/irpass/special_op_eliminate.h +++ b/mindspore/ccsrc/frontend/optimizer/irpass/special_op_eliminate.h @@ -195,6 +195,13 @@ class ZeroLikeFillZero : public AnfVisitor { TypePtr tensor_type_ptr = tensor_abstract->element()->BuildType(); std::vector tensor_shape = tensor_abstract->shape()->shape(); + // if shape is unknown, don't optimize this operator away + for (const int64_t &dimension : tensor_shape) { + if (dimension < 0) { + return node; + } + } + tensor::TensorPtr new_tensor_ptr = std::make_shared(tensor_type_ptr->type_id(), tensor_shape); size_t mem_size = GetTypeByte(tensor_type_ptr) * LongToSize(new_tensor_ptr->ElementsNum()); char *data = reinterpret_cast(new_tensor_ptr->data_c()); diff --git a/mindspore/core/abstract/infer_functions.h b/mindspore/core/abstract/infer_functions.h index d656d3369c..e2642da41f 100644 --- a/mindspore/core/abstract/infer_functions.h +++ b/mindspore/core/abstract/infer_functions.h @@ -275,9 +275,9 @@ AbstractBasePtr InferImplSplit(const AnalysisEnginePtr &, const PrimitivePtr &pr const AbstractBasePtrList &args_spec_list); AbstractBasePtr InferImplSequenceMask(const AnalysisEnginePtr &, const PrimitivePtr &primitive, const AbstractBasePtrList &args_spec_list); - AbstractBasePtr InferImplAddN(const AnalysisEnginePtr &, const PrimitivePtr &primitive, const AbstractBasePtrList &args_spec_list); + template AbstractBasePtr InferTupleOrListOrDictLen(const std::string &op_name, const AbstractBasePtrList &args_spec_list) { // Inputs: a tuple or list or dict. diff --git a/mindspore/core/abstract/prim_arrays.cc b/mindspore/core/abstract/prim_arrays.cc index 1ebb9a2dbc..b607e4214c 100644 --- a/mindspore/core/abstract/prim_arrays.cc +++ b/mindspore/core/abstract/prim_arrays.cc @@ -767,9 +767,21 @@ AbstractBasePtr InferImplDynamicShape(const AnalysisEnginePtr &, const Primitive AbstractBasePtr InferImplZerosLike(const AnalysisEnginePtr &, const PrimitivePtr &primitive, const AbstractBasePtrList &args_spec_list) { - // Inputs: a tensor. - CheckArgsSize(primitive->name(), args_spec_list, 1); - return args_spec_list[0]->Broaden(); + const std::string op_name = primitive->name(); + CheckArgsSize(op_name, args_spec_list, 1); + AbstractTensorPtr input_x = CheckArg(op_name, args_spec_list, 0); + ShapeVector x_shape = input_x->shape()->shape(); + ShapeVector x_shape_min = input_x->shape()->min_shape(); + if (x_shape_min.empty()) { + x_shape_min = x_shape; + } + ShapeVector x_shape_max = input_x->shape()->max_shape(); + if (x_shape_max.empty()) { + x_shape_max = x_shape; + } + + ShapePtr output_shape = std::make_shared(x_shape, x_shape_min, x_shape_max); + return std::make_shared(input_x->element(), output_shape); } AbstractBasePtr InferImplTranspose(const AnalysisEnginePtr &, const PrimitivePtr &primitive, diff --git a/tests/st/ops/gpu/test_zeroslike_op.py b/tests/st/ops/gpu/test_zeroslike_op.py index d31197badd..25fec97be9 100644 --- a/tests/st/ops/gpu/test_zeroslike_op.py +++ b/tests/st/ops/gpu/test_zeroslike_op.py @@ -20,6 +20,7 @@ import mindspore.context as context import mindspore.nn as nn from mindspore import Tensor from mindspore.ops import operations as P +from mindspore.ops.operations import _inner_ops as inner context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU") @@ -74,3 +75,96 @@ def test_ZerosLike(): error1 = np.ones(shape=expect1.shape) * 1.0e-5 assert np.all(diff1 < error1) assert output1.shape == expect1.shape + + +class ZerosLikeDynamicNet(nn.Cell): + def __init__(self): + super(ZerosLikeDynamicNet, self).__init__() + self.gpu_convert_to_dynamic_shape = inner.GpuConvertToDynamicShape() + self.zeros_like = P.ZerosLike() + + def construct(self, x): + converted_to_dynamic = self.gpu_convert_to_dynamic_shape(x) + return self.zeros_like(converted_to_dynamic) + + +def zeros_like_dynamic(x): + context.set_context(mode=context.GRAPH_MODE, device_target="GPU") + net = ZerosLikeDynamicNet() + return net(x) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_bool(): + x = Tensor(np.arange(120).reshape(3, 4, 1, 2, 5).astype(np.bool)) + output = zeros_like_dynamic(x) + expected = np.zeros([3, 4, 1, 2, 5]) + np.testing.assert_array_equal(output.asnumpy(), expected) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_int8(): + x = Tensor(np.arange(24).reshape(1, 4, 1, 6).astype(np.int8)) + output = zeros_like_dynamic(x) + expected = np.zeros([1, 4, 1, 6]) + print(output) + np.testing.assert_array_equal(output.asnumpy(), expected) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_uint8(): + x = Tensor(np.arange(30).reshape(3, 2, 5).astype(np.uint8)) + output = zeros_like_dynamic(x) + expected = np.zeros([3, 2, 5]) + np.testing.assert_array_equal(output.asnumpy(), expected) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_int32(): + x = Tensor(np.arange(16).reshape(2, 2, 2, 2).astype(np.int32)) + output = zeros_like_dynamic(x) + expected = np.zeros([2, 2, 2, 2]) + np.testing.assert_array_equal(output.asnumpy(), expected) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_float16(): + x = Tensor(np.arange(120).reshape(3, 4, 1, 2, 5).astype(np.float16)) + output = zeros_like_dynamic(x) + expected = np.zeros([3, 4, 1, 2, 5]) + np.testing.assert_array_almost_equal(output.asnumpy(), expected) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_float32(): + x = Tensor(np.arange(63).reshape(3, 7, 3).astype(np.float32)) + output = zeros_like_dynamic(x) + expected = np.zeros([3, 7, 3]) + np.testing.assert_array_almost_equal(output.asnumpy(), expected) + +@pytest.mark.level0 +@pytest.mark.platform_x86_gpu_training +@pytest.mark.env_onecard +def test_zeros_like_dynamic_multiple_inputs(): + net = ZerosLikeDynamicNet() + + x = Tensor(np.arange(4).reshape(4).astype(np.float32)) + output = net(x) + expected = np.zeros([4]) + np.testing.assert_array_almost_equal(output.asnumpy(), expected) + + x = Tensor(np.arange(8).reshape(2, 1, 2, 2).astype(np.uint8)) + output = net(x) + expected = np.zeros([2, 1, 2, 2]) + np.testing.assert_array_equal(output.asnumpy(), expected) + + x = Tensor(np.arange(1).reshape(1).astype(np.float16)) + output = net(x) + expected = np.zeros([1]) + np.testing.assert_array_almost_equal(output.asnumpy(), expected)