未验证 提交 bdb80550 编写于 作者: W wangchaochaohu 提交者: GitHub

【API2.0】add numel API for paddle test=develop (#26311)

上级 623e14fb
...@@ -54,5 +54,6 @@ REGISTER_OPERATOR( ...@@ -54,5 +54,6 @@ REGISTER_OPERATOR(
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>, paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>); paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(size, ops::SizeKernel<int>, ops::SizeKernel<int32_t>, REGISTER_OP_CPU_KERNEL(size, ops::SizeKernel<int>, ops::SizeKernel<int32_t>,
ops::SizeKernel<paddle::platform::float16>,
ops::SizeKernel<float>, ops::SizeKernel<double>, ops::SizeKernel<float>, ops::SizeKernel<double>,
ops::SizeKernel<bool>); ops::SizeKernel<bool>);
...@@ -14,8 +14,9 @@ limitations under the License. */ ...@@ -14,8 +14,9 @@ limitations under the License. */
#include "paddle/fluid/operators/size_op.h" #include "paddle/fluid/operators/size_op.h"
REGISTER_OP_CUDA_KERNEL(size, paddle::operators::SizeKernel<int>, REGISTER_OP_CUDA_KERNEL(
paddle::operators::SizeKernel<int32_t>, size, paddle::operators::SizeKernel<int>,
paddle::operators::SizeKernel<float>, paddle::operators::SizeKernel<int32_t>,
paddle::operators::SizeKernel<bool>, paddle::operators::SizeKernel<paddle::platform::float16>,
paddle::operators::SizeKernel<double>); paddle::operators::SizeKernel<float>, paddle::operators::SizeKernel<bool>,
paddle::operators::SizeKernel<double>);
...@@ -237,6 +237,7 @@ from .tensor.stat import reduce_mean #DEFINE_ALIAS ...@@ -237,6 +237,7 @@ from .tensor.stat import reduce_mean #DEFINE_ALIAS
from .tensor.stat import std #DEFINE_ALIAS from .tensor.stat import std #DEFINE_ALIAS
from .tensor.stat import var #DEFINE_ALIAS from .tensor.stat import var #DEFINE_ALIAS
from .fluid.data import data from .fluid.data import data
from .tensor.stat import numel #DEFINE_ALIAS
from .device import get_cudnn_version from .device import get_cudnn_version
from .device import set_device from .device import set_device
from .device import get_device from .device import get_device
......
...@@ -11182,6 +11182,7 @@ def rank(input): ...@@ -11182,6 +11182,7 @@ def rank(input):
return out return out
@deprecated(since="2.0.0", update_to="paddle.numel")
def size(input): def size(input):
""" """
**Size Layer** **Size Layer**
...@@ -11189,11 +11190,14 @@ def size(input): ...@@ -11189,11 +11190,14 @@ def size(input):
Returns the number of elements for a tensor, which is a int64 Tensor with shape [1]. Returns the number of elements for a tensor, which is a int64 Tensor with shape [1].
Args: Args:
input (Variable): The input variable. input (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, int32, int64.
Returns: Returns:
Variable: The number of elements for the input variable. Tensor: The number of elements for the input Tensor.
Raises:
TypeError: ``input`` must be a Tensor and the data type of ``input`` must be one of bool, float16, float32, float64, int32, int64.
Examples: Examples:
.. code-block:: python .. code-block:: python
...@@ -11204,6 +11208,11 @@ def size(input): ...@@ -11204,6 +11208,11 @@ def size(input):
rank = layers.size(input) # 300 rank = layers.size(input) # 300
""" """
if in_dygraph_mode():
return core.ops.size(x)
check_variable_and_dtype(
x, 'x', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],
"size")
helper = LayerHelper('size', **locals()) helper = LayerHelper('size', **locals())
out = helper.create_variable_for_type_inference(dtype='int64') out = helper.create_variable_for_type_inference(dtype='int64')
helper.append_op(type='size', inputs={'Input': input}, outputs={'Out': out}) helper.append_op(type='size', inputs={'Input': input}, outputs={'Out': out})
......
# Copyright (c) 2020 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.
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest
import paddle.fluid.core as core
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
import functools
import paddle
class TestNumelOp(OpTest):
def setUp(self):
self.op_type = "size"
self.init()
x = np.random.random((self.shape)).astype("float64")
self.inputs = {'Input': x, }
self.outputs = {'Out': np.array([np.size(x)])}
def test_check_output(self):
self.check_output()
def init(self):
self.shape = (6, 56, 8, 55)
class TestNumelOp1(TestNumelOp):
def init(self):
self.shape = (11, 66)
class TestNumelOp2(TestNumelOp):
def init(self):
self.shape = (0, )
class TestNumelOoAPI(unittest.TestCase):
def test_numel_static(self):
main_program = fluid.Program()
startup_program = fluid.Program()
with fluid.program_guard(main_program, startup_program):
shape1 = [2, 1, 4, 5]
shape2 = [1, 4, 5]
x_1 = paddle.data(shape=shape1, dtype='int32', name='x_1')
x_2 = paddle.data(shape=shape2, dtype='int32', name='x_2')
input_1 = np.random.random(shape1).astype("int32")
input_2 = np.random.random(shape2).astype("int32")
out_1 = paddle.numel(x_1)
out_2 = paddle.numel(x_2)
exe = paddle.static.Executor(place=paddle.CPUPlace())
res_1, res_2 = exe.run(feed={
"x_1": input_1,
"x_2": input_2,
},
fetch_list=[out_1, out_2])
assert (np.array_equal(
res_1, np.array([np.size(input_1)]).astype("int64")))
assert (np.array_equal(
res_2, np.array([np.size(input_2)]).astype("int64")))
def test_numel_imperative(self):
paddle.disable_static(paddle.CPUPlace())
input_1 = np.random.random([2, 1, 4, 5]).astype("int32")
input_2 = np.random.random([1, 4, 5]).astype("int32")
x_1 = paddle.to_variable(input_1)
x_2 = paddle.to_variable(input_2)
out_1 = paddle.numel(x_1)
out_2 = paddle.numel(x_2)
assert (np.array_equal(out_1.numpy().item(0), np.size(input_1)))
assert (np.array_equal(out_2.numpy().item(0), np.size(input_2)))
paddle.enable_static()
def test_error(self):
main_program = fluid.Program()
startup_program = fluid.Program()
with fluid.program_guard(main_program, startup_program):
def test_x_type():
shape = [1, 4, 5]
input_1 = np.random.random(shape).astype("int32")
out_1 = paddle.numel(input_1)
self.assertRaises(TypeError, test_x_type)
if __name__ == '__main__':
unittest.main()
...@@ -181,5 +181,7 @@ from .stat import mean #DEFINE_ALIAS ...@@ -181,5 +181,7 @@ from .stat import mean #DEFINE_ALIAS
from .stat import reduce_mean #DEFINE_ALIAS from .stat import reduce_mean #DEFINE_ALIAS
from .stat import std #DEFINE_ALIAS from .stat import std #DEFINE_ALIAS
from .stat import var #DEFINE_ALIAS from .stat import var #DEFINE_ALIAS
from .stat import numel #DEFINE_ALIAS
# from .tensor import Tensor #DEFINE_ALIAS
# from .tensor import LoDTensor #DEFINE_ALIAS # from .tensor import LoDTensor #DEFINE_ALIAS
# from .tensor import LoDTensorArray #DEFINE_ALIAS # from .tensor import LoDTensorArray #DEFINE_ALIAS
...@@ -15,9 +15,10 @@ ...@@ -15,9 +15,10 @@
# TODO: define statistical functions of a tensor # TODO: define statistical functions of a tensor
from ..fluid.layers import reduce_mean #DEFINE_ALIAS from ..fluid.layers import reduce_mean #DEFINE_ALIAS
__all__ = ['mean', 'reduce_mean', 'std', 'var'] __all__ = ['mean', 'reduce_mean', 'std', 'var', 'numel']
import numpy as np import numpy as np
from ..fluid.framework import Variable
from ..fluid.layer_helper import LayerHelper from ..fluid.layer_helper import LayerHelper
from ..fluid.framework import core, in_dygraph_mode from ..fluid.framework import core, in_dygraph_mode
from ..fluid import layers from ..fluid import layers
...@@ -244,3 +245,41 @@ def std(input, axis=None, keepdim=False, unbiased=True, out=None, name=None): ...@@ -244,3 +245,41 @@ def std(input, axis=None, keepdim=False, unbiased=True, out=None, name=None):
return out return out
else: else:
return tmp return tmp
def numel(x, name=None):
"""
Returns the number of elements for a tensor, which is a int64 Tensor with shape [1] in static mode
or a scalar value in imperative mode
Args:
x (Tensor): The input Tensor, it's data type can be bool, float16, float32, float64, int32, int64.
Returns:
Tensor: The number of elements for the input Tensor.
Raises:
TypeError: ``x`` must be a Tensor and the data type of ``x`` must be one of bool, float16, float32, float64, int32, int64.
Examples:
.. code-block:: python
import paddle
paddle.disable_static()
x = paddle.full(shape=[4, 5, 7], fill_value=0, dtype='int32')
numel = paddle.numel(x) # 140
"""
if in_dygraph_mode():
return core.ops.size(x)
if not isinstance(x, Variable):
raise TypeError("x must be a Tensor in numel")
helper = LayerHelper('numel', **locals())
out = helper.create_variable_for_type_inference(
dtype=core.VarDesc.VarType.INT64)
helper.append_op(type='size', inputs={'Input': x}, outputs={'Out': out})
return out
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册