math_ops.py 121.7 KB
Newer Older
Z
zhunaipan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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.
# ============================================================================

"""Operators for math."""

G
gong chen 已提交
18
import copy
Z
zhunaipan 已提交
19
import numpy as np
Z
zhaozhenlong 已提交
20
from ... import context
W
Wei Luning 已提交
21
from .. import signature as sig
22
from ..._checkparam import Validator as validator
Z
zhunaipan 已提交
23 24 25
from ..._checkparam import Rel
from ...common import dtype as mstype
from ...common.tensor import Tensor
B
buxue 已提交
26
from .._utils import get_broadcast_shape
F
fary86 已提交
27
from ..primitive import PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op
Z
zhunaipan 已提交
28 29


30
def _infer_shape_reduce(x, axis, keep_dims, prim_name):
Z
zhunaipan 已提交
31 32 33
    """Common infer for reduce operator"""

    def reduce_one_axis(one_axis):
34
        validator.check_int_range('axis', one_axis, -dim, dim, Rel.INC_LEFT, prim_name)
Z
zhunaipan 已提交
35 36 37 38
        if one_axis < 0:
            one_axis += dim
        axis_reduce.add(one_axis)

39
    validator.check_value_type('axis', axis, [int, tuple, list], prim_name)
Z
zhunaipan 已提交
40 41 42 43 44 45 46 47 48 49 50
    dim = len(x)
    axis_reduce = set()

    if isinstance(axis, int):
        reduce_one_axis(axis)
    else:
        if not axis:
            if keep_dims:
                return [1] * dim
            return []
        for index, one_axis in enumerate(axis):
51
            validator.check_value_type('axis[%d]' % index, one_axis, [int], prim_name)
Z
zhunaipan 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
            reduce_one_axis(one_axis)

    out_shape = []
    for i in range(dim):
        if i in axis_reduce:
            if keep_dims:
                out_shape.append(1)
        else:
            out_shape.append(x[i])
    return out_shape


class _BinaryOp(PrimitiveWithInfer):
    """
    Define binary operators.
    """

W
Wei Luning 已提交
69
    __mindspore_signature__ = (sig.sig_dtype.T, sig.sig_dtype.T)
Z
zhunaipan 已提交
70 71 72

    @prim_attr_register
    def __init__(self):
73
        """init _BinaryOp"""
Z
zhunaipan 已提交
74 75 76
        self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])

    def infer_shape(self, x_shape, y_shape):
B
buxue 已提交
77
        return get_broadcast_shape(x_shape, y_shape, self.name)
Z
zhunaipan 已提交
78 79 80 81 82 83 84 85


class _MathBinaryOp(_BinaryOp):
    """
    Define math binary operators.
    """

    @staticmethod
86
    def do_infer_dtype(x_dtype, y_dtype, valid_dtype=mstype.number_type, prim_name=None):
Z
zhunaipan 已提交
87
        args_type = {"x": x_dtype, "y": y_dtype}
88
        validator.check_tensor_type_same(args_type, valid_dtype, prim_name)
Z
zhunaipan 已提交
89 90 91
        return x_dtype

    def infer_dtype(self, x_dtype, y_dtype):
92
        return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type, self.name)
Z
zhunaipan 已提交
93 94


95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
class _BitwiseBinaryOp(_MathBinaryOp):
    """
    Define bitwise binary operators.
    """

    @prim_attr_register
    def __init__(self):
        """init _BitwiseBinaryOp"""
        self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['y'])

    @staticmethod
    def _check_bitwise_op_input_type(x1_type, x2_type, prim):
        args = {'x1': x1_type, 'x2': x2_type}
        valid_types = mstype.int_type + mstype.uint_type
        validator.check_tensor_type_same(args, valid_types, prim)
        return x1_type

    def infer_dtype(self, x1_type, x2_type):
        return _BitwiseBinaryOp._check_bitwise_op_input_type(x1_type, x2_type, self.name)


Z
zhunaipan 已提交
116 117 118 119
class TensorAdd(_MathBinaryOp):
    """
    Adds two input tensors element-wise.

120
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
121
    The inputs must be two tensors or one tensor and one scalar.
122
    When the inputs are two tensors,
123
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
124
    When the inputs are one tensor and one scalar,
S
simson 已提交
125
    the scalar could only be a constant.
Z
zhunaipan 已提交
126 127

    Inputs:
128 129 130 131
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
132 133

    Outputs:
S
simson 已提交
134
        Tensor, the shape is the same as the one after broadcasting,
135
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
136 137 138

    Examples:
        >>> add = P.TensorAdd()
139 140 141
        >>> input_x = Tensor(np.array([1,2,3]).astype(np.float32))
        >>> input_y = Tensor(np.array([4,5,6]).astype(np.float32))
        >>> add(input_x, input_y)
Z
zhunaipan 已提交
142 143 144
        [5,7,9]
    """

G
gong chen 已提交
145 146 147 148 149 150 151 152 153
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = x + y
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
154 155 156 157 158

class AssignAdd(PrimitiveWithInfer):
    """
    Updates a `Parameter` by adding a value to it.

159 160 161 162 163 164 165
    Inputs of `variable` and `value` comply with the implicit type conversion rules to make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    If `value` is a number, the number is automatically converted to Tensor,
    and the data type is consistent with the Tensor data type involved in the operation.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

Z
zhunaipan 已提交
166
    Inputs:
167 168 169
        - **variable** (Parameter) - The `Parameter`.
        - **value** (Union[numbers.Number, Tensor]) - The value to be added to the `variable`.
          It should have the same shape as `variable` if it is a Tensor.
Z
zhunaipan 已提交
170 171 172 173

    Examples:
        >>> class Net(Cell):
        >>>     def __init__(self):
万万没想到 已提交
174
        >>>         super(Net, self).__init__()
Z
zhunaipan 已提交
175
        >>>         self.AssignAdd = P.AssignAdd()
176
        >>>         self.variable = mindspore.Parameter(initializer(1, [1], mindspore.int64), name="global_step")
Z
zhunaipan 已提交
177 178
        >>>
        >>>     def construct(self, x):
179 180
        >>>         self.AssignAdd(self.variable, x)
        >>>         return self.variable
Z
zhunaipan 已提交
181 182
        >>>
        >>> net = Net()
183 184
        >>> value = Tensor(np.ones([1]).astype(np.int64)*100)
        >>> net(value)
Z
zhunaipan 已提交
185 186
    """
    __mindspore_signature__ = (
W
Wei Luning 已提交
187 188
        sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
        sig.make_sig('value', dtype=sig.sig_dtype.T)
Z
zhunaipan 已提交
189 190 191 192 193 194 195 196 197 198 199
    )

    @prim_attr_register
    def __init__(self):
        """init AssignAdd"""
        self.init_prim_io_names(inputs=['ref', 'value'], outputs=['output'])

    def infer_shape(self, variable, value):
        return value

    def infer_dtype(self, variable, value):
W
Wei Luning 已提交
200
        args = {"variable": variable, "value": value}
201
        validator.check_scalar_or_tensor_type_same(args, mstype.number_type, self.name)
Z
zhunaipan 已提交
202 203 204 205 206 207 208
        return value


class AssignSub(PrimitiveWithInfer):
    """
    Updates a `Parameter` by subtracting a value from it.

209 210 211 212 213 214 215
    Inputs of `variable` and `value` comply with the implicit type conversion rules to make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    If `value` is a number, the number is automatically converted to Tensor,
    and the data type is consistent with the Tensor data type involved in the operation.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

Z
zhunaipan 已提交
216
    Inputs:
217 218 219
        - **variable** (Parameter) - The `Parameter`.
        - **value** (Union[numbers.Number, Tensor]) - The value to be subtracted from the `variable`.
          It should have the same shape as `variable` if it is a Tensor.
Z
zhunaipan 已提交
220 221 222 223

    Examples:
        >>> class Net(Cell):
        >>>     def __init__(self):
224
        >>>         super(Net, self).__init__()
Z
zhunaipan 已提交
225
        >>>         self.AssignSub = P.AssignSub()
J
jiangjinsheng 已提交
226
        >>>         self.variable = mindspore.Parameter(initializer(1, [1], mindspore.int32), name="global_step")
Z
zhunaipan 已提交
227 228
        >>>
        >>>     def construct(self, x):
229 230
        >>>         self.AssignSub(self.variable, x)
        >>>         return self.variable
Z
zhunaipan 已提交
231 232
        >>>
        >>> net = Net()
J
jiangjinsheng 已提交
233
        >>> value = Tensor(np.ones([1]).astype(np.int32)*100)
234
        >>> net(value)
Z
zhunaipan 已提交
235 236 237
    """

    __mindspore_signature__ = (
W
Wei Luning 已提交
238 239
        sig.make_sig('variable', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
        sig.make_sig('value', dtype=sig.sig_dtype.T)
Z
zhunaipan 已提交
240 241 242 243 244 245 246 247 248 249
    )

    @prim_attr_register
    def __init__(self):
        """init AssignSub"""

    def infer_shape(self, variable, value):
        return value

    def infer_dtype(self, variable, value):
W
Wei Luning 已提交
250
        args = {"variable": variable, "value": value}
251
        validator.check_scalar_or_tensor_type_same(args, mstype.number_type, self.name)
Z
zhunaipan 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264
        return value


class _Reduce(PrimitiveWithInfer):
    """
    Definition of base class of reduction class operators.

    Args:
         keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                           If False, don't keep these dimensions.
    """

    __mindspore_signature__ = (
W
Wei Luning 已提交
265 266
        sig.make_sig('input_x'),
        sig.make_sig('axis', default=())
Z
zhunaipan 已提交
267 268 269 270 271
    )

    @prim_attr_register
    def __init__(self, keep_dims=False):
        """init Reduce"""
272
        validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
Z
zhunaipan 已提交
273
        self.init_prim_io_names(inputs=['input_x', 'axis'], outputs=['y'])
W
Wei Luning 已提交
274
        self.add_prim_attr("io_format", "ND")
Z
zhunaipan 已提交
275

L
lvliang 已提交
276 277 278 279 280
    def __call__(self, x, axis=()):
        args = [x, axis]
        output = _run_op(self, self.name, args)
        return output

Z
zhunaipan 已提交
281
    def do_infer(self, input_x, axis, valid_dtype=mstype.number_type):
G
gong chen 已提交
282
        """ return meta infos of input parameters """
Z
zhunaipan 已提交
283 284
        axis_v = axis['value']
        input_shp = input_x['shape']
285
        args = {'input_x': input_x['dtype']}
286
        validator.check_tensor_type_same(args, valid_dtype, self.name)
287

288 289
        if axis_v is None:
            raise ValueError(f"For {self.name}, axis must be const.")
290
        input_shp = _infer_shape_reduce(input_shp, axis_v, self.keep_dims, self.name)
G
gong chen 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        value = None
        if input_x['value'] is not None:
            prim_map = {
                'ReduceSum': np.sum,
                'ReduceMax': np.max,
                'ReduceMin': np.min,
            }
            np_reduce_func = prim_map.get(self.name, None)

            if np_reduce_func is not None:
                value = input_x['value'].asnumpy()
                if not axis_v:
                    axis_v = [i for i in range(len(input_x['shape']))]
                    axis_v = tuple(axis_v)
                value = np_reduce_func(value, axis_v, keepdims=self.keep_dims)
                value = np.array(value)
                value = Tensor(value)
Z
zhunaipan 已提交
308 309
        return {'shape': input_shp,
                'dtype': input_x['dtype'],
G
gong chen 已提交
310
                'value': value}
Z
zhunaipan 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

    def __infer__(self, input_x, axis):
        return self.do_infer(input_x, axis)


class ReduceMean(_Reduce):
    """
     Reduce a dimension of a tensor by averaging all elements in the dimension.

     The dtype of the tensor to be reduced is number.

    Args:
        keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                          If False, don't keep these dimensions. Default : False.

    Inputs:
        - **input_x** (Tensor[Number]) - The input tensor.
        - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
          Only constant value is allowed.

    Outputs:
        Tensor, has the same dtype as the 'input_x'.

        - If axis is (), and keep_dims is false,
L
lihongkang 已提交
335
          the output is a 0-D tensor representing the mean of all elements in the input tensor.
Z
zhunaipan 已提交
336 337 338 339 340 341
        - If axis is int, set as 2, and keep_dims is false,
          the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
342
        >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
万万没想到 已提交
343
        >>> op = P.ReduceMean(keep_dims=True)
344
        >>> output = op(input_x, 1)
Z
zhunaipan 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    """


class ReduceSum(_Reduce):
    """
    Reduce a dimension of a tensor by summing all elements in the dimension.

    The dtype of the tensor to be reduced is number.

    Args:
        keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                          If False, don't keep these dimensions. Default : False.

    Inputs:
         - **input_x** (Tensor[Number]) - The input tensor.
         - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
           Only constant value is allowed.

    Outputs:
        Tensor, has the same dtype as the 'input_x'.

        - If axis is (), and keep_dims is false,
          the output is a 0-D tensor representing the sum of all elements in the input tensor.
        - If axis is int, set as 2, and keep_dims is false,
          the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
374
        >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
万万没想到 已提交
375
        >>> op = P.ReduceSum(keep_dims=True)
376
        >>> output = op(input_x, 1)
Z
zhunaipan 已提交
377 378
    """

G
gong chen 已提交
379 380 381 382 383 384
    @prim_attr_register
    def __init__(self, keep_dims=False):
        """init ReduceSum"""
        super(ReduceSum, self).__init__(keep_dims)
        self.__setattr_flag__ = True

Z
zhunaipan 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

class ReduceAll(_Reduce):
    """
    Reduce a dimension of a tensor by the "logical and" of all elements in the dimension.

    The dtype of the tensor to be reduced is bool.

    Args:
       keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                         If False, don't keep these dimensions.
                         Default : False, don't keep these reduced dimensions.

    Inputs:
        - **input_x** (Tensor[bool]) - The input tensor.
        - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
          Only constant value is allowed.

    Outputs:
        Tensor, the dtype is bool.

        - If axis is (), and keep_dims is false,
          the output is a 0-D tensor representing the "logical and" of of all elements in the input tensor.
        - If axis is int, set as 2, and keep_dims is false,
          and keep_dims is false, the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
413
        >>> input_x = Tensor(np.array([[True, False], [True, True]]))
万万没想到 已提交
414
        >>> op = P.ReduceAll(keep_dims=True)
415
        >>> output = op(input_x, 1)
Z
zhunaipan 已提交
416 417 418 419 420 421
    """

    def __infer__(self, input_x, axis):
        return self.do_infer(input_x, axis, (mstype.bool_,))


F
fangzehua 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
class ReduceAny(_Reduce):
    """
    Reduce a dimension of a tensor by the "logical or" of all elements in the dimension.

    The dtype of the tensor to be reduced is bool.

    Args:
       keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                         If False, don't keep these dimensions.
                         Default : False, don't keep these reduced dimensions.

    Inputs:
        - **input_x** (Tensor[bool]) - The input tensor.
        - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
          Only constant value is allowed.

    Outputs:
        Tensor, the dtype is bool.

        - If axis is (), and keep_dims is false,
          the output is a 0-D tensor representing the "logical or" of of all elements in the input tensor.
        - If axis is int, set as 2, and keep_dims is false,
          and keep_dims is false, the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
        >>> input_x = Tensor(np.array([[True, False], [True, True]]))
        >>> op = P.ReduceAny(keep_dims=True)
        >>> output = op(input_x, 1)
    """

    def __infer__(self, input_x, axis):
        return self.do_infer(input_x, axis, (mstype.bool_,))
Z
zhunaipan 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484


class ReduceMax(_Reduce):
    """
    Reduce a dimension of a tensor by the maximum value in this dimension.

    The dtype of the tensor to be reduced is number.

    Args:
        keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                          If False, don't keep these dimensions.
                          Default : False, don't keep these reduced dimensions.

    Inputs:
         - **input_x** (Tensor[Number]) - The input tensor.
         - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
           Only constant value is allowed.

    Outputs:
        Tensor, has the same dtype as the 'input_x'.

        - If axis is (), and keep_dims is false,
          the output is a 0-D tensor representing the maximum of all elements in the input tensor.
        - If axis is int, set as 2, and keep_dims is false,
          the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
485
        >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
万万没想到 已提交
486
        >>> op = P.ReduceMax(keep_dims=True)
487
        >>> output = op(input_x, 1)
Z
zhunaipan 已提交
488 489
    """

G
gong chen 已提交
490 491 492 493 494 495
    @prim_attr_register
    def __init__(self, keep_dims=False):
        """ReduceMax"""
        super(ReduceMax, self).__init__(keep_dims)
        self.__setattr_flag__ = True

Z
zhunaipan 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

class ReduceMin(_Reduce):
    """
    Reduce a dimension of a tensor by the minimum value in the dimension.

    The dtype of the tensor to be reduced is number.

    Args:
        keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                          If False, don't keep these dimensions.
                          Default : False, don't keep these reduced dimensions.

    Inputs:
        - **input_x** (Tensor[Number]) - The input tensor.
        - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
          Only constant value is allowed.

    Outputs:
        Tensor, has the same dtype as the 'input_x'.

        - If axis is (), and keep_dims is false,
          the output is a 0-D tensor representing the minimum of all elements in the input tensor.
        - If axis is int, set as 2, and keep_dims is false,
          the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
524
        >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
万万没想到 已提交
525
        >>> op = P.ReduceMin(keep_dims=True)
526
        >>> output = op(input_x, 1)
Z
zhunaipan 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    """


class ReduceProd(_Reduce):
    """
    Reduce a dimension of a tensor by multiplying all elements in the dimension.

    The dtype of the tensor to be reduced is number.

    Args:
        keep_dims (bool): If True, keep these reduced dimensions and the length is 1.
                          If False, don't keep these dimensions.
                          Default : False, don't keep these reduced dimensions.

    Inputs:
542 543 544
        - **input_x** (Tensor[Number]) - The input tensor.
        - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
          Only constant value is allowed.
Z
zhunaipan 已提交
545 546 547 548 549 550 551 552 553 554 555 556

    Outputs:
        Tensor, has the same dtype as the 'input_x'.

        - If axis is (), and keep_dims is false,
          the output is a 0-D tensor representing the product of all elements in the input tensor.
        - If axis is int, set as 2, and keep_dims is false,
          the shape of output is :math:`(x_1, x_3, ..., x_R)`.
        - If axis is tuple(int), set as (2, 3), and keep_dims is false,
          the shape of output is :math:`(x_1, x_4, ..., x_R)`.

    Examples:
557
        >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
万万没想到 已提交
558
        >>> op = P.ReduceProd(keep_dims=True)
559
        >>> output = op(input_x, 1)
Z
zhunaipan 已提交
560 561 562 563 564 565 566 567 568 569 570 571
    """


class CumProd(PrimitiveWithInfer):
    """
    Compute the cumulative product of the tensor x along axis.

    Args:
        exclusive (bool): If True, perform exclusive cumulative product. Default: False.
        reverse (bool): If True, reverse the result along axis. Default: False

    Inputs:
572 573 574
        - **input_x** (Tensor[Number]) - The input tensor.
        - **axis** (int) - The dimensions to compute the cumulative product.
          Only constant value is allowed.
Z
zhunaipan 已提交
575 576 577 578 579

    Outputs:
        Tensor, has the same shape and dtype as the 'input_x'.

    Examples:
580
        >>> input_x = Tensor(np.array([a, b, c]).astype(np.float32))
万万没想到 已提交
581
        >>> op0 = P.CumProd()
582
        >>> output = op0(input_x, 0) # output=[a, a * b, a * b * c]
万万没想到 已提交
583
        >>> op1 = P.CumProd(exclusive=True)
584
        >>> output = op1(input_x, 0) # output=[1, a, a * b]
万万没想到 已提交
585
        >>> op2 = P.CumProd(reverse=True)
586
        >>> output = op2(input_x, 0) # output=[a * b * c, b * c, c]
万万没想到 已提交
587
        >>> op3 = P.CumProd(exclusive=True, reverse=True)
588
        >>> output = op3(input_x, 0) # output=[b * c, c, 1]
Z
zhunaipan 已提交
589
    """
590

Z
zhunaipan 已提交
591 592
    @prim_attr_register
    def __init__(self, exclusive=False, reverse=False):
593
        cls_name = self.name
594 595
        self.exclusive = validator.check_value_type("exclusive", exclusive, [bool], cls_name)
        self.reverse = validator.check_value_type("reverse", reverse, [bool], cls_name)
Z
zhaojichen 已提交
596
        self.init_prim_io_names(inputs=['x', 'axis'], outputs=['y'])
Z
zhunaipan 已提交
597 598 599 600 601

    def infer_shape(self, x_shape, axis_shape):
        return x_shape

    def infer_dtype(self, x_type, axis_type):
602
        cls_name = self.name
603 604
        validator.check_tensor_type_same({'x': x_type}, mstype.number_type, cls_name)
        validator.check_subclass("axis", axis_type, mstype.int_, cls_name)
Z
zhunaipan 已提交
605 606
        return x_type

607 608 609 610
    def infer_value(self, x, axis):
        if axis is None:
            raise ValueError(f"For {self.name}, axis must be const.")

Z
zhunaipan 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

class MatMul(PrimitiveWithInfer):
    """
    Multiplies matrix `a` by matrix `b`.

    The rank of input tensors must be `2`.

    Args:
        transpose_a (bool): If True, `a` is transposed before multiplication. Default: False.
        transpose_b (bool): If True, `b` is transposed before multiplication. Default: False.

    Inputs:
        - **input_x** (Tensor) - The first tensor to be multiplied. The shape of the tensor is :math:`(N, C)`. If
          `transpose_a` is True, its shape should be :math:`(N, C)` after transposing.
        - **input_y** (Tensor) - The second tensor to be multiplied. The shape of the tensor is :math:`(C, M)`. If
          `transpose_b` is True, its shape should be :math:`(C, M)` after transpose.

    Outputs:
        Tensor, the shape of the output tensor is :math:`(N, M)`.

    Examples:
        >>> input_x = Tensor(np.ones(shape=[1, 3]), mindspore.float32)
        >>> input_y = Tensor(np.ones(shape=[3, 4]), mindspore.float32)
万万没想到 已提交
634
        >>> matmul = P.MatMul()
Z
zhunaipan 已提交
635 636 637 638 639 640
        >>> output = matmul(input_x, input_y)
    """

    @prim_attr_register
    def __init__(self, transpose_a=False, transpose_b=False):
        self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['output'])
641
        cls_name = self.name
642 643
        validator.check_value_type("transpose_a", transpose_a, [bool], cls_name)
        validator.check_value_type("transpose_b", transpose_b, [bool], cls_name)
W
Wei Luning 已提交
644
        self.add_prim_attr("io_format", "ND")
Z
zhunaipan 已提交
645 646 647 648 649 650

    def check_shape_size(self, x, y):
        if len(x) != 2 or len(y) != 2:
            raise ValueError('MatMul input x, y should be the same dimension size and should be '
                             + f'equal to 2, while x size = {len(x)}, y size= {len(y)}')

W
Wei Luning 已提交
651
    def infer_shape(self, x, y, bias=None):
Z
zhunaipan 已提交
652
        self.check_shape_size(x, y)
653
        cls_name = self.name
Z
zhunaipan 已提交
654 655 656
        # expected dimension of x, y, x:[...,a,b] y:[..., c,d], the dim size should be the same except the last two
        for i in range(len(x) - 2):
            if x[i] != y[i]:
657
                raise ValueError(f'For \'{cls_name}\' shape in dim[{i}] not the same, while x is {x[i]}, y is {y[i]}')
Z
zhunaipan 已提交
658 659 660 661 662 663 664 665

        # validate whether last two dims satifing matrix multiply
        x_last = x[-2:]
        y_last = y[-2:]

        x_col = x_last[not self.transpose_a]  # x_col = x_last[1] if (not transpose_a) else x_last[0]
        y_row = y_last[self.transpose_b]  # y_row = y_last[0] if (not transpose_b) else y_last[1]
        if x_col != y_row:
666 667
            raise ValueError(f'For \'{cls_name}\' evaluator shapes of inputs can not do this operator,'
                             + f' got {x_col} and {y_row}, with x shape {x}(transpose_a={self.transpose_a})'
Z
zhunaipan 已提交
668 669 670 671 672 673 674 675
                             + f', y shape {y}(transpose_b={self.transpose_b}).')
        # set attribute
        self.add_prim_attr('transpose_x1', self.transpose_a)
        self.add_prim_attr('transpose_x2', self.transpose_b)

        ret_dims = x[: -2] + [x_last[self.transpose_a], y_last[not self.transpose_b]]
        return ret_dims

W
Wei Luning 已提交
676
    def infer_dtype(self, x, y, bias=None):
677
        args = {"x": x, "y": y}
678
        validator.check_tensor_type_same(args, mstype.float_type + mstype.int_type, self.name)
679 680
        if x.element_type() == mstype.int8:
            return mstype.tensor_type(mstype.int32)
Z
zhunaipan 已提交
681 682 683 684 685 686 687 688 689
        return x


class BatchMatMul(MatMul):
    """
    Computes matrix multiplication between two tensors by batch

    `result[..., :, :] = tensor(a[..., :, :]) * tensor(b[..., :, :])`.

S
simson 已提交
690
    The two input tensors must have the same rank and the rank must be not less than `3`.
Z
zhunaipan 已提交
691 692

    Args:
S
simson 已提交
693
        transpose_a (bool): If True, the last two dimensions of `a` is transposed before multiplication.
Z
zhunaipan 已提交
694
            Default: False.
S
simson 已提交
695
        transpose_b (bool): If True, the last two dimensions of `b` is transposed before multiplication.
Z
zhunaipan 已提交
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
            Default: False.

    Inputs:
        - **input_x** (Tensor) - The first tensor to be multiplied. The shape of the tensor is :math:`(*B, N, C)`,
          where :math:`*B` represents the batch size which can be multidimensional, :math:`N` and :math:`C` are the
          size of the last two dimensions. If `transpose_a` is True, its shape should be :math:`(*B, C, N)`.
        - **input_y** (Tensor) - The second tensor to be multiplied. The shape of the tensor is :math:`(*B, C, M)`. If
          `transpose_b` is True, its shape should be :math:`(*B, M, C)`.

    Outputs:
        Tensor, the shape of the output tensor is :math:`(*B, N, M)`.

    Examples:
        >>> input_x = Tensor(np.ones(shape=[2, 4, 1, 3]), mindspore.float32)
        >>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
万万没想到 已提交
711
        >>> batmatmul = P.BatchMatMul()
Z
zhunaipan 已提交
712 713 714 715
        >>> output = batmatmul(input_x, input_y)
        >>>
        >>> input_x = Tensor(np.ones(shape=[2, 4, 3, 1]), mindspore.float32)
        >>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
万万没想到 已提交
716
        >>> batmatmul = P.BatchMatMul(transpose_a=True)
Z
zhunaipan 已提交
717 718 719 720 721 722
        >>> output = batmatmul(input_x, input_y)
    """

    @prim_attr_register
    def __init__(self, transpose_a=False, transpose_b=False):
        self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['output'])
723
        cls_name = self.name
724 725
        validator.check_value_type("transpose_a", transpose_a, [bool], cls_name)
        validator.check_value_type("transpose_b", transpose_b, [bool], cls_name)
Z
zhunaipan 已提交
726 727 728

    def check_shape_size(self, x, y):
        if len(x) != len(y) or len(x) < 3:
729
            raise ValueError('For \'BatchMatMul\' input x, y should be the same dimension size and should be '
Z
zhunaipan 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742
                             'greater or equal to 3,' + f' while x size = {len(x)}, y size= {len(y)}')


class CumSum(PrimitiveWithInfer):
    """
    Computes the cumulative sum of input tensor along axis.

    Args:
        exclusive (bool): If True, perform exclusive mode. Default: False.
        reverse (bool): If True, perform inverse cumulative sum. Default: False.

    Inputs:
        - **input** (Tensor) - The input tensor to accumulate.
J
jiangjinsheng 已提交
743
        - **axis**  (int) - The axis to accumulate the tensor's value. Only constant value is allowed.
L
lihongkang 已提交
744
          Must be in the range [-rank(input), rank(input)).
Z
zhunaipan 已提交
745 746 747 748 749 750

    Outputs:
        Tensor, the shape of the output tensor is consistent with the input tensor's.

    Examples:
        >>> input = Tensor(np.array([[3, 4, 6, 10],[1, 6, 7, 9],[4, 3, 8, 7],[1, 3, 7, 9]]).astype(np.float32))
万万没想到 已提交
751
        >>> cumsum = P.CumSum()
Z
zhunaipan 已提交
752 753 754 755 756 757 758 759 760 761
        >>> output = cumsum(input, 1)
        [[ 3.  7. 13. 23.]
         [ 1.  7. 14. 23.]
         [ 4.  7. 15. 22.]
         [ 1.  4. 11. 20.]]
    """

    @prim_attr_register
    def __init__(self, exclusive=False, reverse=False):
        """init cumsum"""
762
        cls_name = self.name
763 764
        validator.check_value_type('exclusive', exclusive, [bool], cls_name)
        validator.check_value_type('reverse', reverse, [bool], cls_name)
Z
zhunaipan 已提交
765 766 767
        self.init_prim_io_names(inputs=['x', 'axis'], outputs=['y'])

    def __infer__(self, x, axis):
768
        cls_name = self.name
Z
zhunaipan 已提交
769
        x_shp = x['shape']
J
jiangjinsheng 已提交
770 771
        if axis['value'] is None:
            raise ValueError(f"For {self.name}, axis must be const.")
772 773 774
        validator.check_value_type('axis', axis['value'], [int], cls_name)
        valid_types = [mstype.uint8, mstype.int8, mstype.int32, mstype.float16, mstype.float32]
        validator.check_tensor_type_same({'x': x['dtype']}, valid_types, cls_name)
Z
zhunaipan 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
        return {'shape': x_shp,
                'dtype': x['dtype'],
                'value': None}


class AddN(PrimitiveWithInfer):
    """
    Computes addition of all input tensors element-wise.

    All input tensors should have the same shape.

    Inputs:
        - **input_x** (Union(tuple[Tensor], list[Tensor])) - The input tuple or list
          is made up of multiple tensors whose dtype is number or bool to be added together.

    Outputs:
        Tensor, has the same shape and dtype as each entry of the `input_x`.

    Examples:
        >>> class NetAddN(nn.Cell):
        >>>     def __init__(self):
        >>>         super(NetAddN, self).__init__()
万万没想到 已提交
797
        >>>         self.addN = P.AddN()
Z
zhunaipan 已提交
798 799 800 801 802
        >>>
        >>>     def construct(self, *z):
        >>>         return self.addN(z)
        >>>
        >>> net = NetAddN()
803 804
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
        >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.float32)
Z
zhunaipan 已提交
805
        >>> net(input_x, input_y, input_x, input_y)
806
        [10.0, 14.0, 18.0]
Z
zhunaipan 已提交
807 808 809 810 811 812
    """

    @prim_attr_register
    def __init__(self):
        self.init_prim_io_names(inputs=["inputs"], outputs=["sum"])

813 814 815 816 817 818 819
    def check_elim(self, inputs):
        if len(inputs) != 1:
            return (False, None)
        if isinstance(inputs[0], Tensor):
            return (True, inputs[0])
        raise TypeError("Expecting Tensor, got : {}".format(type(inputs[0])))

Z
zhunaipan 已提交
820
    def infer_shape(self, inputs):
821
        cls_name = self.name
822
        validator.check_integer("inputs", len(inputs), 1, Rel.GE, cls_name)
Z
zhunaipan 已提交
823 824 825
        self.add_prim_attr('n', len(inputs))
        shp0 = inputs[0]
        for i, shp in enumerate(inputs):
826
            validator.check(f"shape of inputs[{i}]", shp, 'shape of inputs[0]', shp0, Rel.EQ, cls_name)
Z
zhunaipan 已提交
827 828 829
        return shp0

    def infer_dtype(self, inputs):
830
        cls_name = self.name
831 832
        validator.check_value_type("inputs", inputs, [tuple, list], cls_name)
        validator.check_integer("inputs", len(inputs), 1, Rel.GE, cls_name)
Z
zhunaipan 已提交
833
        args = {}
P
panyifeng 已提交
834
        contains_undetermined = False
Z
zhunaipan 已提交
835 836
        for i, dtype in enumerate(inputs):
            args[f"inputs[{i}]"] = dtype
P
panyifeng 已提交
837 838 839 840
            if dtype == mstype.undetermined:
                contains_undetermined = True
        if not contains_undetermined:
            validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), cls_name)
Z
zhunaipan 已提交
841 842
        return inputs[0]

G
gong chen 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855 856
    def infer_value(self, inputs):
        if inputs is None:
            return None

        for x in inputs:
            if x is None:
                return None

        added = copy.deepcopy(inputs[0].asnumpy())
        for x in inputs[1:]:
            added += x.asnumpy()
        out = np.array(added, inputs[0].asnumpy().dtype)
        return Tensor(out)

Z
zhunaipan 已提交
857

Z
zhangz0911gm 已提交
858 859 860 861
class AccumulateNV2(PrimitiveWithInfer):
    """
    Computes accumulation of all input tensors element-wise.

S
simson 已提交
862 863 864 865 866
    AccumulateNV2 is similar to AddN, but there is a significant difference
    among them: AccumulateNV2 will not wait for all of its inputs to be ready
    before summing. That is to say, AccumulateNV2 is able to save
    memory when inputs are ready at different time since the minimum temporary
    storage is proportional to the output size rather than the input size.
Z
zhangz0911gm 已提交
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915

    Inputs:
        - **input_x** (Union(tuple[Tensor], list[Tensor])) - The input tuple or list
          is made up of multiple tensors whose dtype is number to be added together.

    Outputs:
        Tensor, has the same shape and dtype as each entry of the `input_x`.

    Examples:
        >>> class NetAccumulateNV2(nn.Cell):
        >>>     def __init__(self):
        >>>         super(NetAccumulateNV2, self).__init__()
        >>>         self.accumulateNV2 = P.AccumulateNV2()
        >>>
        >>>     def construct(self, *z):
        >>>         return self.accumulateNV2(z)
        >>>
        >>> net = NetAccumulateNV2()
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
        >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.float32)
        >>> net(input_x, input_y, input_x, input_y)
        Tensor([10., 14., 18.], shape=(3,), dtype=mindspore.float32)
    """

    @prim_attr_register
    def __init__(self):
        self.__setattr_flag__ = True
        self.init_prim_io_names(inputs=["inputs"], outputs=["sum"])

    def infer_shape(self, inputs):
        cls_name = self.name
        validator.check_integer("inputs", len(inputs), 1, Rel.GE, cls_name)
        self.add_prim_attr('n', len(inputs))
        shp0 = inputs[0]
        for i, shp in enumerate(inputs):
            validator.check(f"shape of inputs[{i}]", shp, 'shape of inputs[0]', shp0, Rel.EQ, cls_name)
        return shp0

    def infer_dtype(self, inputs):
        cls_name = self.name
        validator.check_value_type("inputs", inputs, [tuple, list], cls_name)
        validator.check_integer("inputs", len(inputs), 1, Rel.GE, cls_name)
        args = {}
        for i, dtype in enumerate(inputs):
            args[f"inputs[{i}]"] = dtype
        validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), cls_name)
        return inputs[0]


Z
zhunaipan 已提交
916 917 918 919 920 921 922 923 924
class Neg(PrimitiveWithInfer):
    """
    Returns a tensor with negative values of the input tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor whose dtype is number.

    Outputs:
        Tensor, has the same shape and dtype as input.
925 926 927 928 929 930

    Examples:
        >>> neg = P.Neg()
        >>> input_x = Tensor(np.array([1, 2, -1, 2, 0, -3.5]), mindspore.float32)
        >>> result = neg(input_x)
        [-1.  -2.   1.  -2.   0.   3.5]
Z
zhunaipan 已提交
931 932 933 934 935 936 937 938 939 940 941
    """

    @prim_attr_register
    def __init__(self):
        """init Neg"""
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, input_x):
        return input_x

    def infer_dtype(self, input_x):
942
        validator.check_tensor_type_same({"input_x": input_x}, mstype.number_type, self.name)
Z
zhunaipan 已提交
943 944
        return input_x

G
gong chen 已提交
945 946 947
    def infer_value(self, input_x):
        if input_x is not None:
            input_x = input_x.asnumpy()
G
geekun 已提交
948 949
            out = np.array(-input_x, input_x.dtype)
            return Tensor(out)
G
gong chen 已提交
950 951 952

        return None

Z
zhunaipan 已提交
953

954 955 956 957 958
class InplaceAdd(PrimitiveWithInfer):
    """
    Adds v into specified rows of x. Computes y = x; y[i,] += v.

    Args:
959
        indices (Union[int, tuple]): Indices into the left-most dimension of x, and determines which rows of x
S
simson 已提交
960
            to add with v. It is an integer or a tuple, whose value is in [0, the first dimension size of x).
961 962

    Inputs:
963
        - **input_x** (Tensor) - The first input is a tensor whose data type is float16, float32 or int32.
S
simson 已提交
964
        - **input_v** (Tensor) - The second input is a tensor that has the same dimension sizes as x except
965
          the first dimension, which must be the same as indices's size. It has the same data type with `input_x`.
966 967 968 969 970

    Outputs:
        Tensor, has the same shape and dtype as input.

    Examples:
971
        >>> indices = (0, 1)
972 973 974 975 976 977 978 979 980 981 982 983 984 985
        >>> input_x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
        >>> input_v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
        >>> inplaceAdd = P.InplaceAdd(indices)
        >>> inplaceAdd(input_x, input_v)
        [[1.5 3.]
         [4. 5.5]
         [5. 6.]]
    """

    @prim_attr_register
    def __init__(self, indices):
        """init InplaceAdd"""
        self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
        self.indices = indices
986 987 988 989 990
        validator.check_value_type('indices', indices, [tuple, int], self.name)
        if isinstance(indices, int):
            self.indices = (indices,)
        for item in self.indices:
            validator.check_value_type("item of indices", item, [int], self.name)
991 992 993 994 995 996 997

    def infer_dtype(self, x_dtype, v_dtype):
        args = {'x': x_dtype, 'v': v_dtype}
        valid_type = [mstype.int32, mstype.float16, mstype.float32]
        validator.check_tensor_type_same(args, valid_type, self.name)
        return x_dtype

998 999 1000 1001 1002 1003 1004 1005 1006
    def infer_shape(self, x_shape, v_shape):
        validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
        validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
                        Rel.EQ, self.name)
        for i in self.indices:
            if i < 0 or i >= x_shape[0]:
                raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
        x_rank = len(x_shape)
        for idx in range(x_rank)[1:]:
1007
            validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
1008 1009 1010

        return x_shape

1011 1012 1013 1014 1015 1016

class InplaceSub(PrimitiveWithInfer):
    """
    Subtracts v into specified rows of x. Computes y = x; y[i, :] -= v; return y.

    Args:
1017
        indices (Union[int, tuple]): Indices into the left-most dimension of x, and determines which rows of x
S
simson 已提交
1018
            to subtract with v. It is a int or tuple, whose value is in [0, the first dimension size of x).
1019 1020

    Inputs:
1021
        - **input_x** (Tensor) - The first input is a tensor whose data type is float16, float32 or int32.
1022
        - **input_v** (Tensor) - The second input is a tensor who has the same dimension sizes as x except
1023
          the first dimension, which must be the same as indices's size. It has the same data type with `input_x`.
1024 1025 1026 1027 1028

    Outputs:
        Tensor, has the same shape and dtype as input.

    Examples:
1029
        >>> indices = (0, 1)
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
        >>> input_x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
        >>> input_v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
        >>> inplaceSub = P.InplaceSub(indices)
        >>> inplaceSub(input_x, input_v)
        [[0.5 1.]
         [2. 2.5]
         [5. 6.]]
    """

    @prim_attr_register
    def __init__(self, indices):
        """init InplaceSub"""
        self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
        self.indices = indices
1044 1045 1046 1047 1048
        validator.check_value_type('indices', indices, [tuple, int], self.name)
        if isinstance(indices, int):
            self.indices = (indices,)
        for item in self.indices:
            validator.check_value_type("item of indices", item, [int], self.name)
1049 1050 1051 1052 1053 1054 1055

    def infer_dtype(self, x_dtype, v_dtype):
        args = {'x': x_dtype, 'v': v_dtype}
        valid_type = [mstype.int32, mstype.float16, mstype.float32]
        validator.check_tensor_type_same(args, valid_type, self.name)
        return x_dtype

1056 1057 1058 1059 1060 1061 1062 1063 1064
    def infer_shape(self, x_shape, v_shape):
        validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
        validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
                        Rel.EQ, self.name)
        for i in self.indices:
            if i < 0 or i >= x_shape[0]:
                raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
        x_rank = len(x_shape)
        for idx in range(x_rank)[1:]:
1065
            validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
1066 1067 1068

        return x_shape

1069

Z
zhunaipan 已提交
1070 1071 1072 1073
class Sub(_MathBinaryOp):
    """
    Subtracts the second input tensor from the first input tensor element-wise.

1074
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1075
    The inputs must be two tensors or one tensor and one scalar.
1076
    When the inputs are two tensors,
1077
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1078
    When the inputs are one tensor and one scalar,
S
simson 已提交
1079
    the scalar could only be a constant.
Z
zhunaipan 已提交
1080

B
buxue 已提交
1081
    Inputs:
1082 1083 1084 1085
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1086 1087

    Outputs:
S
simson 已提交
1088
        Tensor, the shape is the same as the one after broadcasting,
1089
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1090 1091 1092 1093

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
万万没想到 已提交
1094
        >>> sub = P.Sub()
Z
zhunaipan 已提交
1095 1096 1097 1098
        >>> sub(input_x, input_y)
        [-3, -3, -3]
    """

G
gong chen 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = x - y
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1108 1109 1110 1111 1112

class Mul(_MathBinaryOp):
    """
    Multiplies two tensors element-wise.

1113
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1114
    The inputs must be two tensors or one tensor and one scalar.
1115
    When the inputs are two tensors,
1116
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1117
    When the inputs are one tensor and one scalar,
S
simson 已提交
1118
    the scalar could only be a constant.
Z
zhunaipan 已提交
1119 1120

    Inputs:
1121 1122 1123 1124
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1125 1126

    Outputs:
S
simson 已提交
1127
        Tensor, the shape is the same as the one after broadcasting,
1128
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1129 1130

    Examples:
Z
zhangz0911gm 已提交
1131 1132
        >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
万万没想到 已提交
1133
        >>> mul = P.Mul()
Z
zhunaipan 已提交
1134 1135 1136
        >>> mul(input_x, input_y)
        [4, 10, 18]
    """
1137

B
biffex 已提交
1138 1139 1140 1141 1142 1143 1144 1145
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = x * y
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None
Z
zhunaipan 已提交
1146 1147


L
liuxiao93 已提交
1148 1149 1150 1151
class SquaredDifference(_MathBinaryOp):
    """
    Subtracts the second input tensor from the first input tensor element-wise and returns square of it.

1152
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
L
liuxiao93 已提交
1153 1154
    The inputs must be two tensors or one tensor and one scalar.
    When the inputs are two tensors,
L
liuxiao93 已提交
1155
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
L
liuxiao93 已提交
1156
    When the inputs are one tensor and one scalar,
S
simson 已提交
1157
    the scalar could only be a constant.
L
liuxiao93 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166

    Inputs:
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is float16, float32, int32 or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is
          float16, float32, int32 or bool.

    Outputs:
S
simson 已提交
1167
        Tensor, the shape is the same as the one after broadcasting,
L
liuxiao93 已提交
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        and the data type is the one with high precision or high digits among the two inputs.

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([2.0, 4.0, 6.0]), mindspore.float32)
        >>> squared_difference = P.SquaredDifference()
        >>> squared_difference(input_x, input_y)
        [1.0, 4.0, 9.0]
    """

    def infer_dtype(self, x_dtype, y_dtype):
        valid_type = [mstype.float16, mstype.float32, mstype.int32]
        return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, valid_type, self.name)


Z
zhunaipan 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
class Square(PrimitiveWithInfer):
    """
    Returns square of a tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor whose dtype is number.

    Outputs:
        Tensor, has the same shape and dtype as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
万万没想到 已提交
1195
        >>> square = P.Square()
Z
zhunaipan 已提交
1196 1197 1198 1199 1200 1201 1202
        >>> square(input_x)
        [1.0, 4.0, 9.0]
    """

    @prim_attr_register
    def __init__(self):
        """init Square"""
G
gong chen 已提交
1203
        self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
Z
zhunaipan 已提交
1204 1205 1206 1207 1208

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
1209
        validator.check_tensor_type_same({"x": x_type}, mstype.number_type, self.name)
Z
zhunaipan 已提交
1210 1211
        return x_type

G
gong chen 已提交
1212 1213 1214 1215 1216 1217 1218 1219
    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
            out = x * x
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232

class Rsqrt(PrimitiveWithInfer):
    """
    Computes reciprocal of square root of input tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input of Rsqrt. Each element should be a non-negative number.

    Outputs:
        Tensor, has the same type and shape as `input_x`.

    Examples:
        >>> input_tensor = Tensor([[4, 4], [9, 9]], mindspore.float32)
万万没想到 已提交
1233
        >>> rsqrt = P.Rsqrt()
Z
zhunaipan 已提交
1234 1235 1236 1237 1238 1239 1240
        >>> rsqrt(input_tensor)
        [[0.5, 0.5], [0.333333, 0.333333]]
    """

    @prim_attr_register
    def __init__(self):
        """init Rsqrt"""
G
gong chen 已提交
1241
        self.init_prim_io_names(inputs=['x'], outputs=['output'])
Z
zhunaipan 已提交
1242 1243 1244 1245 1246

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
1247
        validator.check_tensor_type_same({"x": x_type}, mstype.number_type, self.name)
Z
zhunaipan 已提交
1248 1249
        return x_type

G
gong chen 已提交
1250 1251 1252 1253 1254 1255 1256 1257
    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
            out = 1.0 / np.sqrt(x)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1258

F
fary86 已提交
1259
class Sqrt(PrimitiveWithCheck):
Z
zhunaipan 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    """
    Returns square root of a tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor whose dtype is number.

    Outputs:
        Tensor, has the same shape as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.0, 4.0, 9.0]), mindspore.float32)
万万没想到 已提交
1271
        >>> sqrt = P.Sqrt()
Z
zhunaipan 已提交
1272 1273 1274 1275 1276 1277 1278
        >>> sqrt(input_x)
        [1.0, 2.0, 3.0]
    """

    @prim_attr_register
    def __init__(self):
        """init Sqrt"""
G
gong chen 已提交
1279
        self.init_prim_io_names(inputs=['x'], outputs=['output'])
Z
zhunaipan 已提交
1280

F
fary86 已提交
1281
    def check_dtype(self, x_type):
1282
        validator.check_tensor_type_same({"x": x_type}, mstype.number_type, self.name)
Z
zhunaipan 已提交
1283

G
gong chen 已提交
1284 1285 1286 1287 1288 1289 1290 1291
    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
            out = np.sqrt(x)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304

class Reciprocal(PrimitiveWithInfer):
    """
    Returns reciprocal of a tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
万万没想到 已提交
1305
        >>> reciprocal = P.Reciprocal()
Z
zhunaipan 已提交
1306 1307 1308 1309 1310 1311 1312
        >>> reciprocal(input_x)
        [1.0, 0.5, 0.25]
    """

    @prim_attr_register
    def __init__(self):
        """init Reciprocal"""
1313 1314 1315 1316
        if context.get_context("device_target") == "GPU":
            self.target = "GPU"
        else:
            self.target = "OTHER"
Z
zhunaipan 已提交
1317 1318 1319 1320 1321 1322
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x):
        return x

    def infer_dtype(self, x):
1323
        validator.check_subclass("x", x, mstype.tensor, self.name)
Z
zhunaipan 已提交
1324 1325
        return x

G
gong chen 已提交
1326 1327 1328 1329 1330 1331 1332 1333
    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
            out = 1.0 / x
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1334

1335
class Pow(_MathBinaryOp):
Z
zhunaipan 已提交
1336 1337 1338
    """
    Computes a tensor to the power of the second input.

1339
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
1340 1341
    The inputs must be two tensors or one tensor and one scalar.
    When the inputs are two tensors,
1342
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1343
    When the inputs are one tensor and one scalar,
S
simson 已提交
1344
    the scalar could only be a constant.
1345

Z
zhunaipan 已提交
1346
    Inputs:
1347 1348 1349 1350
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1351 1352

    Outputs:
S
simson 已提交
1353
        Tensor, the shape is the same as the one after broadcasting,
1354
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1355 1356 1357 1358

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
        >>> input_y = 3.0
万万没想到 已提交
1359
        >>> pow = P.Pow()
Z
zhunaipan 已提交
1360 1361 1362 1363 1364
        >>> pow(input_x, input_y)
        [1.0, 8.0, 64.0]
        >>>
        >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
万万没想到 已提交
1365
        >>> pow = P.Pow()
Z
zhunaipan 已提交
1366 1367 1368 1369
        >>> pow(input_x, input_y)
        [1.0, 16.0, 64.0]
    """

G
gong chen 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378
    def infer_value(self, x, power):
        if x is not None and power is not None:
            x = x.asnumpy()
            power = power.asnumpy()
            out = np.power(x, power)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1379 1380 1381 1382 1383 1384

class Exp(PrimitiveWithInfer):
    """
    Returns exponential of a tensor element-wise.

    Inputs:
L
lihongkang 已提交
1385
        - **input_x** (Tensor) - The input tensor. The data type mast be float16 or float32.
Z
zhunaipan 已提交
1386 1387

    Outputs:
L
lihongkang 已提交
1388
        Tensor, has the same shape and dtype as the `input_x`.
Z
zhunaipan 已提交
1389 1390 1391

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
万万没想到 已提交
1392
        >>> exp = P.Exp()
Z
zhunaipan 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
        >>> exp(input_x)
        [ 2.71828183,  7.3890561 , 54.59815003]
    """

    @prim_attr_register
    def __init__(self):
        """init Exp"""
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
1406
        validator.check_subclass("x", x_type, mstype.tensor, self.name)
Z
zhunaipan 已提交
1407 1408
        return x_type

G
gong chen 已提交
1409 1410 1411 1412 1413 1414 1415 1416
    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
            out = np.exp(x)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1417

Z
zhouneng 已提交
1418 1419 1420 1421 1422
class Expm1(PrimitiveWithInfer):
    """
    Returns exponential then minus 1 of a tensor element-wise.

    Inputs:
1423
        - **input_x** (Tensor) - The input tensor. With float16 or float32 data type.
Z
zhouneng 已提交
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444

    Outputs:
        Tensor, has the same shape as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([0.0, 1.0, 2.0, 4.0]), mindspore.float32)
        >>> expm1 = P.Expm1()
        >>> expm1(input_x)
        [ 0.,  1.71828183,  6.3890561 , 53.59815003]
    """

    @prim_attr_register
    def __init__(self):
        """init Exp"""
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
        validator.check_subclass("x", x_type, mstype.tensor, self.name)
1445
        validator.check_tensor_type_same({"x": x_type}, [mstype.float16, mstype.float32], self.name)
Z
zhouneng 已提交
1446 1447 1448
        return x_type


1449 1450 1451 1452 1453 1454
class HistogramFixedWidth(PrimitiveWithInfer):
    """
    Returns a rank 1 histogram counting the number of entries in values that fall into every bin. The bins are equal
    width and determined by the arguments range and nbins.

    Args:
L
lihongkang 已提交
1455
        dtype (str): An optional attribute. Must be one of the following types: "int32", "int64". Default: "int32".
S
simson 已提交
1456
        nbins (int): The number of histogram bins, the type is a positive integer.
1457 1458 1459

    Inputs:
        - **x** (Tensor) - Numeric Tensor. Must be one of the following types: int32, float32, float16.
S
simson 已提交
1460
        - **range** (Tensor) - Must has the same data type as `x`, and the shape is [2].
J
jiangjinsheng 已提交
1461
          x <= range[0] will be mapped to hist[0], x >= range[1] will be mapped to hist[-1].
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476

    Outputs:
        Tensor, the type is int32.

    Examples:
        >>> x = Tensor([-1.0, 0.0, 1.5, 2.0, 5.0, 15], mindspore.float16)
        >>> range = Tensor([0.0, 5.0], mindspore.float16)
        >>> hist = P.HistogramFixedWidth(5)
        >>> hist(x, range)
        [2 1 1 0 2]
    """

    @prim_attr_register
    def __init__(self, nbins, dtype='int32'):
        self.nbins = validator.check_value_type("nbins", nbins, [int], self.name)
J
jiangjinsheng 已提交
1477
        validator.check_integer("nbins", nbins, 1, Rel.GE, self.name)
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
        valid_values = ['int32', 'int64']
        self.dtype = validator.check_string("dtype", dtype, valid_values, self.name)
        self.init_prim_io_names(inputs=['x', 'range'], outputs=['y'])

    def infer_shape(self, x_shape, range_shape):
        return (self.nbins,)

    def infer_dtype(self, x_dtype, range_dtype):
        validator.check_subclass("x", x_dtype, mstype.tensor, self.name)
        valid_types = (mstype.float16, mstype.float32, mstype.int32)
        validator.check_tensor_type_same({"x": x_dtype}, valid_types, self.name)
        validator.check_tensor_type_same({"range": range_dtype}, valid_types, self.name)
        y_dtype = mstype.int32
        return y_dtype


Z
zhunaipan 已提交
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
class Log(PrimitiveWithInfer):
    """
    Returns the natural logarithm of a tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
万万没想到 已提交
1506
        >>> log = P.Log()
Z
zhunaipan 已提交
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
        >>> log(input_x)
        [0.0, 0.69314718, 1.38629436]
    """

    @prim_attr_register
    def __init__(self):
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x):
        return x

    def infer_dtype(self, x):
1519
        validator.check_subclass("x", x, mstype.tensor, self.name)
J
jiangjinsheng 已提交
1520 1521
        return x

G
gong chen 已提交
1522 1523 1524 1525 1526 1527 1528 1529
    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
            out = np.log(x)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

J
jiangjinsheng 已提交
1530 1531 1532 1533 1534 1535

class Log1p(PrimitiveWithInfer):
    """
    Returns the natural logarithm of one plus the input tensor element-wise.

    Inputs:
1536
        - **input_x** (Tensor) - The input tensor. With float16 or float32 data type.
J
jiangjinsheng 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556

    Outputs:
        Tensor, has the same shape as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
        >>> log1p = P.Log1p()
        >>> log1p(input_x)
        [0.6931472, 1.0986123, 1.609438]
    """

    @prim_attr_register
    def __init__(self):
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x):
        return x

    def infer_dtype(self, x):
        validator.check_subclass("x", x, mstype.tensor, self.name)
1557
        validator.check_tensor_type_same({"x": x}, [mstype.float16, mstype.float32], self.name)
Z
zhunaipan 已提交
1558 1559 1560
        return x


L
liuxiao 已提交
1561 1562 1563 1564 1565
class Erf(PrimitiveWithInfer):
    r"""
    Computes the Gauss error function of `input_x` element-wise.

    Inputs:
1566
        - **input_x** (Tensor) - The input tensor. The data type must be float16 or float32.
L
liuxiao 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590

    Outputs:
        Tensor, has the same shape and dtype as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
        >>> erf = P.Erf()
        >>> erf(input_x)
        [-0.8427168, 0., 0.8427168, 0.99530876, 0.99997765]
    """

    @prim_attr_register
    def __init__(self):
        """init Erf"""
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
        validator.check_tensor_type_same({"x": x_type}, [mstype.float16, mstype.float32], self.name)
        return x_type


J
jiangjinsheng 已提交
1591 1592 1593 1594 1595
class Erfc(PrimitiveWithInfer):
    r"""
    Computes the complementary error function of `input_x` element-wise.

    Inputs:
S
simson 已提交
1596
        - **input_x** (Tensor) - The input tensor. The data type must be float16 or float32.
J
jiangjinsheng 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620

    Outputs:
        Tensor, has the same shape and dtype as the `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
        >>> erfc = P.Erfc()
        >>> erfc(input_x)
        [1.8427168, 0., 0.1572832, 0.00469124, 0.00002235]
    """

    @prim_attr_register
    def __init__(self):
        """init Erfc"""
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
        validator.check_tensor_type_same({"x": x_type}, [mstype.float16, mstype.float32], self.name)
        return x_type


Z
zhunaipan 已提交
1621 1622 1623 1624
class Minimum(_MathBinaryOp):
    """
    Computes the element-wise minimum of input tensors.

1625
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1626
    The inputs must be two tensors or one tensor and one scalar.
1627
    When the inputs are two tensors,
1628
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1629
    When the inputs are one tensor and one scalar,
S
simson 已提交
1630
    the scalar could only be a constant.
Z
zhunaipan 已提交
1631 1632

    Inputs:
1633 1634 1635 1636
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1637 1638

    Outputs:
S
simson 已提交
1639
        Tensor, the shape is the same as the one after broadcasting,
1640
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1641 1642 1643 1644

    Examples:
        >>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
万万没想到 已提交
1645
        >>> minimum = P.Minimum()
Z
zhunaipan 已提交
1646 1647 1648 1649
        >>> minimum(input_x, input_y)
        [1.0, 2.0, 3.0]
    """

G
gong chen 已提交
1650 1651 1652 1653 1654 1655 1656 1657 1658
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = np.minimum(x, y)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None

Z
zhunaipan 已提交
1659 1660 1661 1662 1663

class Maximum(_MathBinaryOp):
    """
    Computes the element-wise maximum of input tensors.

1664
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1665
    The inputs must be two tensors or one tensor and one scalar.
1666
    When the inputs are two tensors,
1667
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1668
    When the inputs are one tensor and one scalar,
S
simson 已提交
1669
    the scalar could only be a constant.
Z
zhunaipan 已提交
1670 1671

    Inputs:
1672 1673 1674 1675
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1676 1677

    Outputs:
S
simson 已提交
1678
        Tensor, the shape is the same as the one after broadcasting,
1679
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1680 1681 1682 1683

    Examples:
        >>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
万万没想到 已提交
1684
        >>> maximum = P.Maximum()
Z
zhunaipan 已提交
1685 1686 1687 1688
        >>> maximum(input_x, input_y)
        [4.0, 5.0, 6.0]
    """

G
gong chen 已提交
1689 1690 1691 1692 1693 1694 1695 1696
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = np.maximum(x, y)
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None
Z
zhunaipan 已提交
1697

1698

Z
zhunaipan 已提交
1699 1700 1701 1702
class RealDiv(_MathBinaryOp):
    """
    Divide the first input tensor by the second input tensor in floating-point type element-wise.

1703
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1704
    The inputs must be two tensors or one tensor and one scalar.
1705
    When the inputs are two tensors,
1706
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1707
    When the inputs are one tensor and one scalar,
S
simson 已提交
1708
    the scalar could only be a constant.
Z
zhunaipan 已提交
1709 1710

    Inputs:
1711 1712 1713 1714
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1715 1716

    Outputs:
S
simson 已提交
1717
        Tensor, the shape is the same as the one after broadcasting,
1718
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1719 1720 1721 1722

    Examples:
        >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
万万没想到 已提交
1723
        >>> realdiv = P.RealDiv()
Z
zhunaipan 已提交
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
        >>> realdiv(input_x, input_y)
        [0.25, 0.4, 0.5]
    """

    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = x / y
            out = np.array(out, x.dtype)
            return Tensor(out)
        return None


class Div(_MathBinaryOp):
    """
    Computes the quotient of dividing the first input tensor by the second input tensor element-wise.

1742
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1743
    The inputs must be two tensors or one tensor and one scalar.
1744
    When the inputs are two tensors,
1745
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1746
    When the inputs are one tensor and one scalar,
S
simson 已提交
1747
    the scalar could only be a constant.
Z
zhunaipan 已提交
1748 1749

    Inputs:
1750 1751
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
J
jiangjinsheng 已提交
1752
        - **input_y** (Union[Tensor, Number, bool]) - When the first input is a tensor, The second input
S
simson 已提交
1753
          could be a number, a bool, or a tensor whose data type is number or bool. When the first input
J
jiangjinsheng 已提交
1754
          is a number or a bool, the second input should be a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1755 1756

    Outputs:
S
simson 已提交
1757
        Tensor, the shape is the same as the one after broadcasting,
1758
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1759 1760

    Raises:
S
simson 已提交
1761
        ValueError: When `input_x` and `input_y` do not have the same dtype.
Z
zhunaipan 已提交
1762 1763 1764 1765

    Examples:
        >>> input_x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
万万没想到 已提交
1766
        >>> div = P.Div()
Z
zhunaipan 已提交
1767
        >>> div(input_x, input_y)
L
lihongkang 已提交
1768
        [-1.3, 2.5, 2.0]
Z
zhunaipan 已提交
1769 1770 1771 1772 1773 1774
    """

    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
G
geekun 已提交
1775 1776
            out = np.array(x / y, x.dtype)
            return Tensor(out)
Z
zhunaipan 已提交
1777 1778 1779
        return None


F
fangzehua 已提交
1780 1781 1782 1783
class DivNoNan(_MathBinaryOp):
    """
    Computes a safe divide which returns 0 if the y is zero.

1784
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
F
fangzehua 已提交
1785
    The inputs must be two tensors or one tensor and one scalar.
1786
    When the inputs are two tensors,
1787
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1788
    When the inputs are one tensor and one scalar,
S
simson 已提交
1789
    the scalar could only be a constant.
F
fangzehua 已提交
1790 1791

    Inputs:
1792 1793 1794 1795
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
F
fangzehua 已提交
1796 1797

    Outputs:
S
simson 已提交
1798
        Tensor, the shape is the same as the one after broadcasting,
1799
        and the data type is the one with high precision or high digits among the two inputs.
F
fangzehua 已提交
1800 1801

    Raises:
S
simson 已提交
1802
        ValueError: When `input_x` and `input_y` do not have the same dtype.
F
fangzehua 已提交
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822

    Examples:
        >>> input_x = Tensor(np.array([-1.0, 0., 1.0, 5.0, 6.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([0., 0., 0., 2.0, 3.0]), mindspore.float32)
        >>> div_no_nan = P.DivNoNan()
        >>> div_no_nan(input_x, input_y)
        [0., 0., 0., 2.5, 2.0]
    """

    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            with np.errstate(divide='ignore', invalid='ignore'):
                out = np.true_divide(x, y)
                out[~np.isfinite(out)] = 0
            return out
        return None


Z
zhunaipan 已提交
1823 1824
class FloorDiv(_MathBinaryOp):
    """
S
simson 已提交
1825
    Divide the first input tensor by the second input tensor element-wise and round down to the closest integer.
Z
zhunaipan 已提交
1826

1827
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
1828
    The inputs must be two tensors or one tensor and one scalar.
1829
    When the inputs are two tensors,
1830
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1831
    When the inputs are one tensor and one scalar,
S
simson 已提交
1832
    the scalar could only be a constant.
Z
zhunaipan 已提交
1833 1834

    Inputs:
1835 1836 1837 1838
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
1839 1840

    Outputs:
S
simson 已提交
1841
        Tensor, the shape is the same as the one after broadcasting,
1842
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhunaipan 已提交
1843 1844 1845 1846

    Examples:
        >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
        >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
万万没想到 已提交
1847
        >>> floor_div = P.FloorDiv()
Z
zhunaipan 已提交
1848 1849 1850 1851 1852
        >>> floor_div(input_x, input_y)
        [0, 1, -1]
    """


1853 1854 1855 1856 1857
class TruncateDiv(_MathBinaryOp):
    """
    Divide the first input tensor by the second input tensor element-wise for integer types, negative numbers will
    round fractional quantities towards zero.

1858
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
1859 1860
    The inputs must be two tensors or one tensor and one scalar.
    When the inputs are two tensors,
L
liuxiao93 已提交
1861
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1862
    When the inputs are one tensor and one scalar,
S
simson 已提交
1863
    the scalar could only be a constant.
1864 1865 1866 1867 1868 1869 1870 1871

    Inputs:
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.

    Outputs:
S
simson 已提交
1872
        Tensor, the shape is the same as the one after broadcasting,
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
        and the data type is the one with high precision or high digits among the two inputs.

    Examples:
        >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
        >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
        >>> truncate_div = P.TruncateDiv()
        >>> truncate_div(input_x, input_y)
        [0, 1, 0]
    """


class TruncateMod(_MathBinaryOp):
    """
    Returns element-wise remainder of division.

1888
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
1889 1890
    The inputs must be two tensors or one tensor and one scalar.
    When the inputs are two tensors,
L
liuxiao93 已提交
1891
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
1892
    When the inputs are one tensor and one scalar,
S
simson 已提交
1893
    the scalar could only be a constant.
1894 1895 1896 1897 1898 1899 1900 1901

    Inputs:
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.

    Outputs:
S
simson 已提交
1902
        Tensor, the shape is the same as the one after broadcasting,
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
        and the data type is the one with high precision or high digits among the two inputs.

    Examples:
        >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
        >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
        >>> truncate_mod = P.TruncateMod()
        >>> truncate_mod(input_x, input_y)
        [2, 1, -1]
    """


J
jiangjinsheng 已提交
1914 1915 1916 1917
class Mod(_MathBinaryOp):
    """
    Computes the remainder of dividing the first input tensor by the second input tensor element-wise.

1918
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
J
jiangjinsheng 已提交
1919 1920
    The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors,
    both dtypes cannot be bool, and the shapes of them could be broadcast. When the inputs are one tensor
S
simson 已提交
1921
    and one scalar, the scalar could only be a constant.
J
jiangjinsheng 已提交
1922 1923 1924 1925 1926 1927 1928 1929

    Inputs:
        - **input_x** (Union[Tensor, Number]) - The first input is a number or a tensor whose data type is number.
        - **input_y** (Union[Tensor, Number]) - When the first input is a tensor, The second input
          could be a number or a tensor whose data type is number. When the first input is a number,
          the second input should be a tensor whose data type is number.

    Outputs:
S
simson 已提交
1930
        Tensor, the shape is the same as the one after broadcasting,
J
jiangjinsheng 已提交
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
        and the data type is the one with high precision or high digits among the two inputs.

    Raises:
        ValueError: When `input_x` and `input_y` are not the same dtype.

    Examples:
        >>> input_x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
        >>> input_y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
        >>> mod = P.Mod()
        >>> mod(input_x, input_y)
    """

    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            return Tensor(np.fmod(x, y))
        return None


Z
zhunaipan 已提交
1951 1952 1953 1954 1955
class Floor(PrimitiveWithInfer):
    """
    Round a tensor down to the closest integer element-wise.

    Inputs:
S
simson 已提交
1956
        - **input_x** (Tensor) - The input tensor. Its element data type must be float.
Z
zhunaipan 已提交
1957 1958 1959 1960 1961 1962

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
万万没想到 已提交
1963
        >>> floor = P.Floor()
Z
zhunaipan 已提交
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
        >>> floor(input_x)
        [1.0, 2.0, -2.0]
    """

    @prim_attr_register
    def __init__(self):
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
1976
        validator.check_tensor_type_same({"x": x_dtype}, mstype.float_type, self.name)
Z
zhunaipan 已提交
1977 1978 1979
        return x_dtype


Z
zhangz0911gm 已提交
1980 1981
class FloorMod(_MathBinaryOp):
    """
S
simson 已提交
1982
    Compute the remainder of division element-wise.
Z
zhangz0911gm 已提交
1983

1984
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhangz0911gm 已提交
1985
    The inputs must be two tensors or one tensor and one scalar.
1986
    When the inputs are two tensors,
1987
    dtypes of them cannot be both bool , and the shapes of them could be broadcast.
1988
    When the inputs are one tensor and one scalar,
S
simson 已提交
1989
    the scalar could only be a constant.
Z
zhangz0911gm 已提交
1990 1991

    Inputs:
1992 1993 1994 1995
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhangz0911gm 已提交
1996 1997

    Outputs:
S
simson 已提交
1998
        Tensor, the shape is the same as the one after broadcasting,
1999
        and the data type is the one with high precision or high digits among the two inputs.
Z
zhangz0911gm 已提交
2000 2001 2002 2003

    Examples:
        >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
        >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
2004
        >>> floor_mod = P.FloorMod()
Z
zhangz0911gm 已提交
2005 2006 2007 2008 2009
        >>> floor_mod(input_x, input_y)
        [2, 1, 2]
    """


2010 2011 2012 2013 2014
class Ceil(PrimitiveWithInfer):
    """
    Round a tensor up to the closest integer element-wise.

    Inputs:
2015
        - **input_x** (Tensor) - The input tensor. It's element data type must be float16 or float32.
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> input_x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
        >>> ceil_op = P.Ceil()
        >>> ceil_op(input_x)
        [2.0, 3.0, -1.0]
    """

    @prim_attr_register
    def __init__(self):
        self.init_prim_io_names(inputs=['x'], outputs=['y'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
2035
        validator.check_tensor_type_same({"x": x_dtype}, [mstype.float16, mstype.float32], self.name)
2036 2037 2038
        return x_dtype


L
liuxiao93 已提交
2039 2040 2041 2042
class Xdivy(_MathBinaryOp):
    """
    Divide the first input tensor by the second input tensor element-wise. Returns zero when `x` is zero.

2043
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
L
liuxiao93 已提交
2044 2045
    The inputs must be two tensors or one tensor and one scalar.
    When the inputs are two tensors,
L
liuxiao93 已提交
2046
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
L
liuxiao93 已提交
2047
    When the inputs are one tensor and one scalar,
S
simson 已提交
2048
    the scalar could only be a constant.
L
liuxiao93 已提交
2049 2050 2051 2052 2053 2054 2055 2056

    Inputs:
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is float16, float32 or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is float16, float32 or bool.

    Outputs:
S
simson 已提交
2057
        Tensor, the shape is the same as the one after broadcasting,
L
liuxiao93 已提交
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
        and the data type is the one with high precision or high digits among the two inputs.

    Examples:
        >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.float32)
        >>> input_y = Tensor(np.array([2, 2, 2]), mindspore.float32)
        >>> xdivy = P.Xdivy()
        >>> xdivy(input_x, input_y)
        [1.0, 2.0, -0.5]
    """

    def infer_dtype(self, x_dtype, y_dtype):
        return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, [mstype.float16, mstype.float32], self.name)


class Xlogy(_MathBinaryOp):
    """
    Computes first input tensor multiplied by the logarithm of second input tensor element-wise.
    Returns zero when `x` is zero.

2077
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
L
liuxiao93 已提交
2078 2079
    The inputs must be two tensors or one tensor and one scalar.
    When the inputs are two tensors,
L
liuxiao93 已提交
2080
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
L
liuxiao93 已提交
2081
    When the inputs are one tensor and one scalar,
S
simson 已提交
2082
    the scalar could only be a constant.
L
liuxiao93 已提交
2083 2084 2085 2086 2087 2088 2089 2090 2091

    Inputs:
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is float16, float32 or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is float16, float32 or bool.
          The value must be positive.

    Outputs:
S
simson 已提交
2092
        Tensor, the shape is the same as the one after broadcasting,
L
liuxiao93 已提交
2093 2094 2095 2096
        and the data type is the one with high precision or high digits among the two inputs.

    Examples:
        >>> input_x = Tensor(np.array([-5, 0, 4]), mindspore.float32)
2097
        >>> input_y = Tensor(np.array([2, 2, 2]), mindspore.float32)
L
liuxiao93 已提交
2098
        >>> xlogy = P.Xlogy()
2099
        >>> xlogy(input_x, input_y)
L
liuxiao93 已提交
2100 2101 2102 2103 2104 2105 2106
        [-3.465736, 0.0, 2.7725887]
    """

    def infer_dtype(self, x_dtype, y_dtype):
        return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, [mstype.float16, mstype.float32], self.name)


Z
zhangz0911gm 已提交
2107 2108
class Acosh(PrimitiveWithInfer):
    """
S
simson 已提交
2109
    Compute inverse hyperbolic cosine of the input element-wise.
Z
zhangz0911gm 已提交
2110 2111

    Inputs:
2112
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
Z
zhangz0911gm 已提交
2113 2114 2115 2116 2117

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
2118 2119 2120
        >>> acosh = P.Acosh()
        >>> input_x = Tensor(np.array([1.0, 1.5, 3.0, 100.0]), mindspore.float32)
        >>> output = acosh(input_x)
Z
zhangz0911gm 已提交
2121 2122 2123 2124 2125 2126
    """

    @prim_attr_register
    def __init__(self):
        """init Acosh"""

2127 2128
    def infer_shape(self, x_shape):
        return x_shape
Z
zhangz0911gm 已提交
2129

2130 2131 2132 2133 2134
    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype


L
lihongkang 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
class Cosh(PrimitiveWithInfer):
    """
    Computes hyperbolic cosine of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> cosh = P.Cosh()
        >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
        >>> output = cosh(input_x)
        [1.0289385 1.364684 1.048436 1.4228927]
    """

    @prim_attr_register
    def __init__(self):
        """init Cosh"""

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype


2164 2165
class Asinh(PrimitiveWithInfer):
    """
S
simson 已提交
2166
    Compute inverse hyperbolic sine of the input element-wise.
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> asinh = P.Asinh()
        >>> input_x = Tensor(np.array([-5.0, 1.5, 3.0, 100.0]), mindspore.float32)
        >>> output = asinh(input_x)
        [-2.3212, 1.1976, 1.8184, 5.2983]
    """

    @prim_attr_register
    def __init__(self):
        """init Asinh"""

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype
Z
zhangz0911gm 已提交
2191 2192


L
lihongkang 已提交
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
class Sinh(PrimitiveWithInfer):
    """
    Computes hyperbolic sine of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> sinh = P.Sinh()
        >>> input_x = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), mindspore.float32)
        >>> output = sinh(input_x)
        [0.6604918 0.28367308 0.44337422 0.6604918]
    """

    @prim_attr_register
    def __init__(self):
        """init Sinh"""

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype


Z
zhunaipan 已提交
2222 2223 2224 2225 2226 2227
class _LogicBinaryOp(_BinaryOp):
    """
    Define logic binary operators.
    """

    @staticmethod
2228 2229 2230
    def do_infer_dtype(x_dtype, y_dtype, valid_type=mstype.number_type, prim_name=None):
        args_dtype = {"x": x_dtype, "y": y_dtype}
        validator.check_tensor_type_same(args_dtype, valid_type, prim_name)
Z
zhunaipan 已提交
2231 2232 2233
        return mstype.tensor_type(mstype.bool_)

    def infer_dtype(self, x_dtype, y_dtype):
2234
        return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, prim_name=self.name)
Z
zhunaipan 已提交
2235 2236 2237 2238 2239 2240


class Equal(_LogicBinaryOp):
    """
    Computes the equivalence between two tensors element-wise.

2241
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
2242
    The inputs must be two tensors or one tensor and one scalar.
2243
    When the inputs are two tensors, the shapes of them could be broadcast.
S
simson 已提交
2244
    When the inputs are one tensor and one scalar, the scalar could only be a constant.
Z
zhunaipan 已提交
2245 2246

    Inputs:
L
lihongkang 已提交
2247 2248 2249 2250
        - **input_x** (Union[Tensor, Number]) - The first input is a number or
          a tensor whose data type is number.
        - **input_y** (Union[Tensor, Number]) - The second input is a number
          when the first input is a tensor or a tensor whose data type is number.
Z
zhunaipan 已提交
2251 2252

    Outputs:
S
simson 已提交
2253
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2254 2255 2256

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
万万没想到 已提交
2257
        >>> equal = P.Equal()
Z
zhunaipan 已提交
2258 2259 2260 2261 2262
        >>> equal(input_x, 2.0)
        [False, True, False]
        >>>
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
万万没想到 已提交
2263
        >>> equal = P.Equal()
Z
zhunaipan 已提交
2264 2265 2266 2267 2268
        >>> equal(input_x, input_y)
        [True, True, False]
    """

    def infer_dtype(self, x_dtype, y_dtype):
2269
        return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type + (mstype.bool_,), self.name)
Z
zhunaipan 已提交
2270 2271


2272 2273
class ApproximateEqual(_LogicBinaryOp):
    """
S
simson 已提交
2274
    Returns true if abs(x1-x2) is smaller than tolerance element-wise, otherwise false.
2275

2276 2277 2278 2279 2280
    Inputs of `x1` and `x2` comply with the implicit type conversion rules to make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

2281 2282 2283 2284 2285 2286 2287 2288
    Args:
        tolerance (float): The maximum deviation that two elements can be considered equal. Default: 1e-05.

    Inputs:
        - **x1** (Tensor) - A tensor. Must be one of the following types: float32, float16.
        - **x2** (Tensor) - A tensor of the same type and shape as 'x1'.

    Outputs:
2289
        Tensor, the shape is the same as the shape of 'x1', and the data type is bool.
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314

    Examples:
        >>> x1 = Tensor(np.array([1, 2, 3]), mindspore.float32)
        >>> x2 = Tensor(np.array([2, 4, 6]), mindspore.float32)
        >>> approximate_equal = P.ApproximateEqual(2.)
        >>> result = approximate_equal(x1, x2)
        [True  True  False]
    """

    @prim_attr_register
    def __init__(self, tolerance=1e-05):
        """Init ApproximateEqual"""
        validator.check_value_type("tolerance", tolerance, [float], self.name)

    def infer_shape(self, x_shape, y_shape):
        validator.check("x_shape", x_shape, "y_shape", y_shape, Rel.EQ, self.name)
        return x_shape

    def infer_dtype(self, x_dtype, y_dtype):
        args_dtype = {"x": x_dtype, "y": y_dtype}
        valid_type = [mstype.float32, mstype.float16]
        validator.check_tensor_type_same(args_dtype, valid_type, prim_name=self.name)
        return mstype.tensor_type(mstype.bool_)


Z
zhunaipan 已提交
2315 2316 2317 2318
class EqualCount(PrimitiveWithInfer):
    """
    Computes the number of the same elements of two tensors.

S
simson 已提交
2319
    The two input tensors should have the same data type and shape.
Z
zhunaipan 已提交
2320 2321 2322 2323 2324 2325

    Inputs:
        - **input_x** (Tensor) - The first input tensor.
        - **input_y** (Tensor) - The second input tensor.

    Outputs:
J
jiangjinsheng 已提交
2326
        Tensor, with the type same as input tensor and size as (1,).
Z
zhunaipan 已提交
2327 2328 2329 2330

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
万万没想到 已提交
2331
        >>> equal_count = P.EqualCount()
Z
zhunaipan 已提交
2332 2333 2334 2335 2336 2337 2338 2339 2340
        >>> equal_count(input_x, input_y)
        [2]
    """

    @prim_attr_register
    def __init__(self):
        """init EqualCount"""
        self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])

2341
    def infer_shape(self, x_shape, y_shape):
V
VectorSL 已提交
2342
        validator.check("x_shape", x_shape, "y_shape", y_shape, Rel.EQ, self.name)
Z
zhunaipan 已提交
2343 2344 2345
        output_shape = (1,)
        return output_shape

2346 2347
    def infer_dtype(self, x_dtype, y_dtype):
        args = {'x': x_dtype, 'y': y_dtype}
2348
        validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), self.name)
Z
zhunaipan 已提交
2349 2350 2351 2352 2353 2354 2355
        return x_dtype


class NotEqual(_LogicBinaryOp):
    """
    Computes the non-equivalence of two tensors element-wise.

2356
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
2357
    The inputs must be two tensors or one tensor and one scalar.
2358
    When the inputs are two tensors, the shapes of them could be broadcast.
S
simson 已提交
2359
    When the inputs are one tensor and one scalar, the scalar could only be a constant.
Z
zhunaipan 已提交
2360 2361

    Inputs:
2362 2363 2364 2365
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
2366 2367

    Outputs:
S
simson 已提交
2368
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2369 2370 2371

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
万万没想到 已提交
2372
        >>> not_equal = P.NotEqual()
Z
zhunaipan 已提交
2373 2374 2375 2376 2377
        >>> not_equal(input_x, 2.0)
        [True, False, True]
        >>>
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
万万没想到 已提交
2378
        >>> not_equal = P.NotEqual()
Z
zhunaipan 已提交
2379 2380 2381 2382 2383
        >>> not_equal(input_x, input_y)
        [False, False, True]
    """

    def infer_dtype(self, x_dtype, y_dtype):
2384
        return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type + (mstype.bool_,), self.name)
Z
zhunaipan 已提交
2385 2386 2387 2388 2389 2390


class Greater(_LogicBinaryOp):
    """
    Computes the boolean value of :math:`x > y` element-wise.

2391
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
2392
    The inputs must be two tensors or one tensor and one scalar.
2393
    When the inputs are two tensors,
2394
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
2395
    When the inputs are one tensor and one scalar,
S
simson 已提交
2396
    the scalar could only be a constant.
Z
zhunaipan 已提交
2397 2398

    Inputs:
2399 2400 2401 2402
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
2403 2404

    Outputs:
S
simson 已提交
2405
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2406 2407 2408 2409

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
万万没想到 已提交
2410
        >>> greater = P.Greater()
Z
zhunaipan 已提交
2411 2412 2413
        >>> greater(input_x, input_y)
        [False, True, False]
    """
2414

G
gong chen 已提交
2415 2416 2417 2418 2419 2420 2421
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = np.array(np.greater(x, y))
            return Tensor(out)
        return None
Z
zhunaipan 已提交
2422 2423 2424 2425 2426 2427


class GreaterEqual(_LogicBinaryOp):
    """
    Computes the boolean value of :math:`x >= y` element-wise.

2428
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
2429
    The inputs must be two tensors or one tensor and one scalar.
2430
    When the inputs are two tensors,
2431
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
2432
    When the inputs are one tensor and one scalar,
S
simson 已提交
2433
    the scalar could only be a constant.
Z
zhunaipan 已提交
2434 2435

    Inputs:
2436 2437 2438 2439
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
2440 2441

    Outputs:
S
simson 已提交
2442
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2443 2444 2445 2446

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
万万没想到 已提交
2447
        >>> greater_equal = P.GreaterEqual()
Z
zhunaipan 已提交
2448 2449 2450
        >>> greater_equal(input_x, input_y)
        [True, True, False]
    """
2451

G
gong chen 已提交
2452 2453 2454 2455 2456 2457 2458
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = np.array(np.greater_equal(x, y))
            return Tensor(out)
        return None
Z
zhunaipan 已提交
2459 2460 2461 2462 2463 2464


class Less(_LogicBinaryOp):
    """
    Computes the boolean value of :math:`x < y` element-wise.

2465
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
2466
    The inputs must be two tensors or one tensor and one scalar.
2467
    When the inputs are two tensors,
2468
    dtypes of them cannot be both bool, and the shapes of them could be broadcast.
2469
    When the inputs are one tensor and one scalar,
S
simson 已提交
2470
    the scalar could only be a constant.
Z
zhunaipan 已提交
2471 2472

    Inputs:
2473 2474 2475 2476
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
2477 2478

    Outputs:
S
simson 已提交
2479
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2480 2481 2482 2483

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
万万没想到 已提交
2484
        >>> less = P.Less()
Z
zhunaipan 已提交
2485 2486 2487
        >>> less(input_x, input_y)
        [False, False, True]
    """
2488

G
gong chen 已提交
2489 2490 2491 2492 2493 2494 2495
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = np.array(np.less(x, y))
            return Tensor(out)
        return None
Z
zhunaipan 已提交
2496 2497 2498 2499 2500 2501


class LessEqual(_LogicBinaryOp):
    """
    Computes the boolean value of :math:`x <= y` element-wise.

2502
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
Z
zhunaipan 已提交
2503
    The inputs must be two tensors or one tensor and one scalar.
2504
    When the inputs are two tensors,
2505
    dtypes of them cannot be both bool , and the shapes of them could be broadcast.
2506
    When the inputs are one tensor and one scalar,
S
simson 已提交
2507
    the scalar could only be a constant.
Z
zhunaipan 已提交
2508 2509

    Inputs:
2510 2511 2512 2513
        - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
          a bool or a tensor whose data type is number or bool.
        - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
          a bool when the first input is a tensor or a tensor whose data type is number or bool.
Z
zhunaipan 已提交
2514 2515

    Outputs:
S
simson 已提交
2516
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2517 2518 2519 2520

    Examples:
        >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
        >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
万万没想到 已提交
2521
        >>> less_equal = P.LessEqual()
Z
zhunaipan 已提交
2522 2523 2524
        >>> less_equal(input_x, input_y)
        [True, False, True]
    """
2525

G
gong chen 已提交
2526 2527 2528 2529 2530 2531 2532
    def infer_value(self, x, y):
        if x is not None and y is not None:
            x = x.asnumpy()
            y = y.asnumpy()
            out = np.array(np.less_equal(x, y))
            return Tensor(out)
        return None
Z
zhunaipan 已提交
2533 2534 2535 2536 2537 2538 2539


class LogicalNot(PrimitiveWithInfer):
    """
    Computes the "logical NOT" of a tensor element-wise.

    Inputs:
2540
        - **input_x** (Tensor) - The input tensor whose dtype is bool.
Z
zhunaipan 已提交
2541 2542

    Outputs:
2543
        Tensor, the shape is the same as the `input_x`, and the dtype is bool.
Z
zhunaipan 已提交
2544 2545 2546

    Examples:
        >>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
万万没想到 已提交
2547
        >>> logical_not = P.LogicalNot()
Z
zhunaipan 已提交
2548 2549 2550 2551 2552 2553 2554
        >>> logical_not(input_x)
        [False, True, False]
    """

    @prim_attr_register
    def __init__(self):
        """init LogicalNot"""
V
VectorSL 已提交
2555
        self.init_prim_io_names(inputs=['x'], outputs=['output'])
Z
zhunaipan 已提交
2556 2557 2558 2559 2560

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
2561
        validator.check_tensor_type_same({"x": x_dtype}, [mstype.bool_], self.name)
Z
zhunaipan 已提交
2562 2563 2564 2565 2566 2567 2568
        return mstype.tensor_type(mstype.bool_)


class LogicalAnd(_LogicBinaryOp):
    """
    Computes the "logical AND" of two tensors element-wise.

2569
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
2570
    The inputs must be two tensors or one tensor and one bool.
Z
zhunaipan 已提交
2571 2572
    When the inputs are two tensors, the shapes of them could be broadcast,
    and the data types of them should be bool.
S
simson 已提交
2573
    When the inputs are one tensor and one bool, the bool object could only be a constant,
Z
zhunaipan 已提交
2574 2575 2576
    and the data type of the tensor should be bool.

    Inputs:
2577 2578
        - **input_x** (Union[Tensor, bool]) - The first input is a bool or a tensor whose data type is bool.
        - **input_y** (Union[Tensor, bool]) - The second input is a bool when the first input is a tensor or
B
buxue 已提交
2579
          a tensor whose data type is bool.
Z
zhunaipan 已提交
2580 2581

    Outputs:
S
simson 已提交
2582
        Tensor, the shape is the same as the one after broadcasting, and the data type is bool.
Z
zhunaipan 已提交
2583 2584 2585 2586

    Examples:
        >>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
        >>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
万万没想到 已提交
2587
        >>> logical_and = P.LogicalAnd()
Z
zhunaipan 已提交
2588 2589 2590 2591 2592
        >>> logical_and(input_x, input_y)
        [True, False, False]
    """

    def infer_dtype(self, x_dtype, y_dtype):
2593
        return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, (mstype.bool_,), self.name)
Z
zhunaipan 已提交
2594 2595 2596 2597 2598 2599


class LogicalOr(_LogicBinaryOp):
    """
    Computes the "logical OR" of two tensors element-wise.

2600
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
2601
    The inputs must be two tensors or one tensor and one bool.
Z
zhunaipan 已提交
2602 2603
    When the inputs are two tensors, the shapes of them could be broadcast,
    and the data types of them should be bool.
S
simson 已提交
2604
    When the inputs are one tensor and one bool, the bool object could only be a constant,
Z
zhunaipan 已提交
2605 2606 2607
    and the data type of the tensor should be bool.

    Inputs:
2608 2609
        - **input_x** (Union[Tensor, bool]) - The first input is a bool or a tensor whose data type is bool.
        - **input_y** (Union[Tensor, bool]) - The second input is a bool when the first input is a tensor or
B
buxue 已提交
2610
          a tensor whose data type is bool.
Z
zhunaipan 已提交
2611 2612

    Outputs:
S
simson 已提交
2613
        Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
Z
zhunaipan 已提交
2614 2615 2616 2617

    Examples:
        >>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
        >>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
万万没想到 已提交
2618
        >>> logical_or = P.LogicalOr()
Z
zhunaipan 已提交
2619 2620 2621 2622 2623
        >>> logical_or(input_x, input_y)
        [True, True, True]
    """

    def infer_dtype(self, x_dtype, y_dtype):
2624
        return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, (mstype.bool_,), self.name)
Z
zhunaipan 已提交
2625

2626

V
VectorSL 已提交
2627 2628
class IsNan(PrimitiveWithInfer):
    """
S
simson 已提交
2629
    Judge which elements are nan for each position.
V
VectorSL 已提交
2630 2631 2632 2633 2634 2635

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape of input, and the dtype is bool.
2636 2637 2638 2639 2640

    Examples:
        >>> is_nan = P.IsNan()
        >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
        >>> result = is_nan(input_x)
V
VectorSL 已提交
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
    """

    @prim_attr_register
    def __init__(self):
        """init IsNan"""
        self.init_prim_io_names(inputs=['x'], outputs=['output'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        return mstype.bool_

2654

V
VectorSL 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663
class IsInf(PrimitiveWithInfer):
    """
    Judging which elements are inf or -inf for each position

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape of input, and the dtype is bool.
2664 2665 2666 2667 2668

    Examples:
        >>> is_inf = P.IsInf()
        >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
        >>> result = is_inf(input_x)
V
VectorSL 已提交
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
    """

    @prim_attr_register
    def __init__(self):
        """init IsInf"""
        self.init_prim_io_names(inputs=['x'], outputs=['output'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        return mstype.bool_

2682

V
VectorSL 已提交
2683 2684
class IsFinite(PrimitiveWithInfer):
    """
S
simson 已提交
2685
    Judge which elements are finite for each position.
V
VectorSL 已提交
2686 2687 2688 2689 2690 2691

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape of input, and the dtype is bool.
2692 2693 2694 2695 2696 2697

    Examples:
        >>> is_finite = P.IsFinite()
        >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
        >>> result = is_finite(input_x)
        [False   True   False]
V
VectorSL 已提交
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
    """

    @prim_attr_register
    def __init__(self):
        """init IsFinite"""
        self.init_prim_io_names(inputs=['x'], outputs=['output'])

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
Y
yanzhenxiang2020 已提交
2709 2710
        validator.check_subclass("x", x_dtype, mstype.tensor, self.name)
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type + (mstype.bool_,), self.name)
V
VectorSL 已提交
2711 2712
        return mstype.bool_

2713

V
VectorSL 已提交
2714 2715
class FloatStatus(PrimitiveWithInfer):
    """
S
simson 已提交
2716
    Determine if the elements contain Not a Number(NaN), infinite or negative infinite. 0 for normal, 1 for overflow.
V
VectorSL 已提交
2717 2718

    Inputs:
2719
        - **input_x** (Tensor) - The input tensor. The data type must be float16 or float32.
V
VectorSL 已提交
2720 2721 2722 2723

    Outputs:
        Tensor, has the shape of `(1,)`, and has the same dtype of input `mindspore.dtype.float32` or
        `mindspore.dtype.float16`.
2724 2725 2726 2727 2728

    Examples:
        >>> float_status = P.FloatStatus()
        >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
        >>> result = float_status(input_x)
V
VectorSL 已提交
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
    """

    @prim_attr_register
    def __init__(self):
        """init FloatStatus"""
        self.init_prim_io_names(inputs=['x'], outputs=['output'])

    def infer_shape(self, x_shape):
        return [1]

    def infer_dtype(self, x_dtype):
V
VectorSL 已提交
2740
        validator.check_tensor_type_same({'x': x_dtype}, [mstype.float32, mstype.float16], self.name)
V
VectorSL 已提交
2741
        return x_dtype
Z
zhunaipan 已提交
2742

2743

Z
zhunaipan 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
class NPUAllocFloatStatus(PrimitiveWithInfer):
    """
    Allocates a flag to store the overflow status.

    The flag is a tensor whose shape is `(8,)` and data type is `mindspore.dtype.float32`.

    Note:
        Examples: see `NPUGetFloatStatus`.

    Outputs:
        Tensor, has the shape of `(8,)`.

    Examples:
万万没想到 已提交
2757
        >>> alloc_status = P.NPUAllocFloatStatus()
Z
zhunaipan 已提交
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
        >>> init = alloc_status()
        Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)
    """

    @prim_attr_register
    def __init__(self):
        """init NPUAllocFloatStatus"""
        self.add_prim_attr("_side_effect_flag", True)

    def infer_shape(self):
        return [8]

    def infer_dtype(self):
        return mstype.float32


class NPUGetFloatStatus(PrimitiveWithInfer):
    """
    Updates the flag which is the output tensor of `NPUAllocFloatStatus` with latest overflow status.

    The flag is a tensor whose shape is `(8,)` and data type is `mindspore.dtype.float32`.
    If the sum of the flag equals 0, there is no overflow happened. If the sum of the flag is bigger than 0, there
    is overflow happened.

    Inputs:
        - **input_x** (Tensor) - The output tensor of `NPUAllocFloatStatus`.
2784
          The data type must be float16 or float32.
Z
zhunaipan 已提交
2785 2786 2787 2788 2789

    Outputs:
        Tensor, has the same shape as `input_x`. All the elements in the tensor will be zero.

    Examples:
万万没想到 已提交
2790 2791
        >>> alloc_status = P.NPUAllocFloatStatus()
        >>> get_status = P.NPUGetFloatStatus()
Z
zhunaipan 已提交
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
        >>> init = alloc_status()
        >>> flag = get_status(init)
        Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)
    """

    @prim_attr_register
    def __init__(self):
        """init NPUGetFloatStatus"""
        self.add_prim_attr("_side_effect_flag", True)

    def infer_shape(self, x_shape):
2803
        cls_name = self.name
2804 2805
        validator.check_integer("len(x_shape)", len(x_shape), 1, Rel.EQ, cls_name)
        validator.check_integer("x_shape[0]", x_shape[0], 8, Rel.EQ, cls_name)
Z
zhunaipan 已提交
2806 2807 2808
        return [8]

    def infer_dtype(self, x_dtype):
2809
        validator.check_tensor_type_same({'x': x_dtype}, [mstype.float16, mstype.float32], self.name)
Z
zhunaipan 已提交
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
        return mstype.float32


class NPUClearFloatStatus(PrimitiveWithInfer):
    """
    Clear the flag which stores the overflow status.

    Note:
        The flag is in the register on the `Ascend` device. It will be reset and can not be reused again after the
        `NPUClearFloatStatus` is called.

        Examples: see `NPUGetFloatStatus`.

    Inputs:
        - **input_x** (Tensor) - The output tensor of `NPUAllocFloatStatus`.
2825
          The data type must be float16 or float32.
Z
zhunaipan 已提交
2826 2827 2828 2829 2830

    Outputs:
        Tensor, has the same shape as `input_x`. All the elements in the tensor will be zero.

    Examples:
万万没想到 已提交
2831 2832 2833
        >>> alloc_status = P.NPUAllocFloatStatus()
        >>> get_status = P.NPUGetFloatStatus()
        >>> clear_status = P.NPUClearFloatStatus()
Z
zhunaipan 已提交
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
        >>> init = alloc_status()
        >>> flag = get_status(init)
        >>> clear = clear_status(init)
        Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)
    """

    @prim_attr_register
    def __init__(self):
        """init NPUClearFloatStatus"""
        self.add_prim_attr("_side_effect_flag", True)

    def infer_shape(self, x_shape):
2846
        cls_name = self.name
2847 2848
        validator.check_integer("len(x_shape)", len(x_shape), 1, Rel.EQ, cls_name)
        validator.check_integer("x_shape[0]", x_shape[0], 8, Rel.EQ, cls_name)
Z
zhunaipan 已提交
2849 2850 2851
        return [8]

    def infer_dtype(self, x_dtype):
2852
        validator.check_tensor_type_same({'x': x_dtype}, [mstype.float16, mstype.float32], self.name)
Z
zhunaipan 已提交
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
        return mstype.float32


class Cos(PrimitiveWithInfer):
    """
    Computes cosine of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
万万没想到 已提交
2867
        >>> cos = P.Cos()
2868 2869
        >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
        >>> output = cos(input_x)
Z
zhunaipan 已提交
2870 2871 2872 2873 2874 2875
    """

    @prim_attr_register
    def __init__(self):
        """init Cos"""

2876 2877
    def infer_shape(self, x_shape):
        return x_shape
Z
zhunaipan 已提交
2878

2879 2880 2881
    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype
Z
zhunaipan 已提交
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894


class ACos(PrimitiveWithInfer):
    """
    Computes arccosine of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
万万没想到 已提交
2895
        >>> acos = P.ACos()
2896 2897
        >>> input_x = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), mindspore.float32)
        >>> output = acos(input_x)
Z
zhunaipan 已提交
2898 2899 2900 2901 2902 2903
    """

    @prim_attr_register
    def __init__(self):
        """init ACos"""

2904 2905
    def infer_shape(self, x_shape):
        return x_shape
Z
zhunaipan 已提交
2906

2907 2908 2909
    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype
Z
zhunaipan 已提交
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922


class Sin(PrimitiveWithInfer):
    """
    Computes sine of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
万万没想到 已提交
2923
        >>> sin = P.Sin()
2924
        >>> input_x = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), mindspore.float32)
万万没想到 已提交
2925
        >>> output = sin(input_x)
Z
zhunaipan 已提交
2926 2927 2928 2929 2930 2931
    """

    @prim_attr_register
    def __init__(self):
        """Init Sin."""

2932 2933
    def infer_shape(self, x_shape):
        return x_shape
Z
zhunaipan 已提交
2934

2935 2936 2937 2938 2939 2940 2941
    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype


class Asin(PrimitiveWithInfer):
    """
2942
    Computes arcsine of input element-wise.
2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> asin = P.Asin()
        >>> input_x = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), mindspore.float32)
        >>> output = asin(input_x)
        [0.8331, 0.0400, 0.3047, 0.5944]
    """

    @prim_attr_register
    def __init__(self):
        """init Asin"""

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
        return x_dtype
Z
zhunaipan 已提交
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986


class NMSWithMask(PrimitiveWithInfer):
    """
    Select some bounding boxes in descending order of score.

    Args:
        iou_threshold (float): Specifies the threshold of overlap boxes with respect to
            IOU. Default: 0.5.

    Raises:
        ValueError: If the iou_threshold is not a float number, or if the first dimension
            of input Tensor is less than or equal to 0, or if the data type of the input
            Tensor is not float16 or float32.

    Inputs:
        - **bboxes** (Tensor) - The shape of tensor is :math:`(N, 5)`. Input bounding boxes.
          `N` is the number of input bounding boxes. Every bounding box
          contains 5 values, the first 4 values are the coordinates of bounding
          box, and the last value is the score of this bounding box.
2987
          The data type must be float16 or float32.
Z
zhunaipan 已提交
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002

    Outputs:
        tuple[Tensor], tuple of three tensors, they are selected_boxes, selected_idx and selected_mask.

        - **selected_boxes** (Tensor) - The shape of tensor is :math:`(N, 5)`. Bounding boxes
          list after non-max suppression calculation.
        - **selected_idx** (Tensor) - The shape of tensor is :math:`(N,)`. The indexes list of
          valid input bounding boxes.
        - **selected_mask** (Tensor) - The shape of tensor is :math:`(N,)`. A mask list of
          valid output bounding boxes.

    Examples:
        >>> bbox = np.random.rand(128, 5)
        >>> bbox[:, 2] += bbox[:, 0]
        >>> bbox[:, 3] += bbox[:, 1]
S
simson 已提交
3003
        >>> inputs = Tensor(bbox, mindspore.float32)
万万没想到 已提交
3004
        >>> nms = P.NMSWithMask(0.5)
Z
zhunaipan 已提交
3005 3006 3007 3008 3009 3010
        >>> output_boxes, indices, mask = nms(inputs)
    """

    @prim_attr_register
    def __init__(self, iou_threshold=0.5):
        """Init NMSWithMask"""
3011
        validator.check_value_type("iou_threshold", iou_threshold, [float], self.name)
Z
zhunaipan 已提交
3012
        self.init_prim_io_names(inputs=['bboxes'], outputs=['selected_boxes', 'selected_idx', 'selected_mask'])
Z
zhaozhenlong 已提交
3013
        self.is_ge = context.get_context("enable_ge")
Z
zhunaipan 已提交
3014 3015

    def infer_shape(self, bboxes_shape):
3016
        cls_name = self.name
3017
        validator.check_integer("bboxes rank", len(bboxes_shape), 2, Rel.EQ, cls_name)
3018 3019
        validator.check_integer("bboxes.shape[0]", bboxes_shape[0], 0, Rel.GT, cls_name)
        validator.check_integer("bboxes.shape[1]", bboxes_shape[1], 5, Rel.EQ, cls_name)
Z
zhunaipan 已提交
3020 3021 3022 3023
        num = bboxes_shape[0]
        return (bboxes_shape, (num,), (num,))

    def infer_dtype(self, bboxes_dtype):
3024
        validator.check_tensor_type_same({"bboxes": bboxes_dtype}, [mstype.float16, mstype.float32], self.name)
Z
zhunaipan 已提交
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
        return (bboxes_dtype, mstype.int32, mstype.bool_)


class Abs(PrimitiveWithInfer):
    """
    Returns absolute value of a tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor. The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as the `input_x`.

    Examples:
         >>> input_x = Tensor(np.array([-1.0, 1.0, 0.0]), mindspore.float32)
万万没想到 已提交
3040
         >>> abs = P.Abs()
Z
zhunaipan 已提交
3041 3042 3043 3044 3045 3046 3047
         >>> abs(input_x)
         [1.0, 1.0, 0.0]
    """

    @prim_attr_register
    def __init__(self):
        """init Abs"""
G
gong chen 已提交
3048
        self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
Z
zhunaipan 已提交
3049 3050 3051 3052 3053

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
3054
        validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
Z
zhunaipan 已提交
3055 3056 3057 3058 3059
        return x_type

    def infer_value(self, x):
        if x is not None:
            x = x.asnumpy()
H
huangdongrun 已提交
3060
            out = np.array(np.abs(x, dtype=x.dtype))
Z
zhunaipan 已提交
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
            return Tensor(out)
        return None


class Sign(PrimitiveWithInfer):
    r"""
    Perform :math:`sign` on tensor element-wise.

    Note:
        .. math::
            sign(x) = \begin{cases} -1, &if\ x < 0 \cr
            0, &if\ x == 0 \cr
            1, &if\ x > 0\end{cases}

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape and type as the `input_x`.

    Examples:
         >>> input_x = Tensor(np.array([[2.0, 0.0, -1.0]]), mindspore.float32)
万万没想到 已提交
3083
         >>> sign = P.Sign()
Z
zhunaipan 已提交
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
         >>> output = sign(input_x)
         [[1.0, 0.0, -1.0]]
    """

    @prim_attr_register
    def __init__(self):
        pass

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
3096
        validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
Z
zhunaipan 已提交
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111
        return x_dtype


class Round(PrimitiveWithInfer):
    """
    Returns half to even of a tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The input tensor.

    Outputs:
        Tensor, has the same shape and type as the `input_x`.

    Examples:
         >>> input_x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
万万没想到 已提交
3112
         >>> round = P.Round()
Z
zhunaipan 已提交
3113 3114 3115 3116 3117 3118
         >>> round(input_x)
         [1.0, 2.0, 2.0, 2.0, -4.0]
    """

    @prim_attr_register
    def __init__(self):
G
gong chen 已提交
3119 3120
        """init Round"""
        self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
Z
zhunaipan 已提交
3121 3122 3123 3124 3125

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
3126
        validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
Z
zhunaipan 已提交
3127
        return x_type
Z
zhaozhenlong 已提交
3128 3129


3130 3131
class Tan(PrimitiveWithInfer):
    """
L
liuxiao93 已提交
3132
    Computes tangent of `input_x` element-wise.
3133 3134

    Inputs:
3135 3136
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Data type should be
          float16, float32 or int32.
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> tan = P.Tan()
        >>> input_x = Tensor(np.array([-1.0, 0.0, 1.0]), mindspore.float32)
        >>> output = tan(input_x)
    """

    @prim_attr_register
    def __init__(self):
        """init Tan"""

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
3155 3156
        valid_types = [mstype.float16, mstype.float32, mstype.int32]
        validator.check_tensor_type_same({'x': x_type}, valid_types, self.name)
3157 3158 3159
        return x_type


Z
zhouneng 已提交
3160 3161
class Atan(PrimitiveWithInfer):
    """
S
simson 已提交
3162
    Computes the trigonometric inverse tangent of the input element-wise.
Z
zhouneng 已提交
3163 3164 3165 3166 3167

    Inputs:
        - **input_x** (Tensor): The input tensor.

    Outputs:
S
simson 已提交
3168
        A Tensor, has the same type as the input.
Z
zhouneng 已提交
3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192

    Examples:
        >>> input_x = Tensor(np.array([1.047, 0.785]), mindspore.float32)
        >>> tan = P.Tan()
        >>> output_y = tan(input_x)
        >>> atan = P.Atan()
        >>> atan(output_y)
        [[1.047, 07850001]]
    """

    @prim_attr_register
    def __init__(self):
        pass

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
        validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
        return x_type


class Atanh(PrimitiveWithInfer):
    """
S
simson 已提交
3193
    Computes inverse hyperbolic tangent of the input element-wise.
Z
zhouneng 已提交
3194 3195 3196 3197 3198

    Inputs:
        - **input_x** (Tensor): The input tensor.

    Outputs:
S
simson 已提交
3199
        A Tensor, has the same type as the input.
Z
zhouneng 已提交
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219

    Examples:
        >>> input_x = Tensor(np.array([1.047, 0.785]), mindspore.float32)
        >>> atanh = P.Atanh()
        >>> atanh(input_x)
        [[1.8869909 1.058268]]
    """

    @prim_attr_register
    def __init__(self):
        pass

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_type):
        validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
        return x_type


Z
zhaozhenlong 已提交
3220 3221 3222 3223
class Atan2(_MathBinaryOp):
    r"""
    Returns arctangent of input_x/input_y element-wise.

Z
zhaozhenlong 已提交
3224
    It returns :math:`\theta\ \in\ [-\pi, \pi]`
Z
zhaozhenlong 已提交
3225 3226
    such that :math:`x = r*\sin(\theta), y = r*\cos(\theta)`, where :math:`r = \sqrt{x^2 + y^2}`.

3227 3228 3229 3230 3231
    Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

Z
zhaozhenlong 已提交
3232 3233 3234 3235 3236
    Inputs:
        - **input_x** (Tensor) - The input tensor.
        - **input_y** (Tensor) - The input tensor.

    Outputs:
S
simson 已提交
3237
        Tensor, the shape is the same as the one after broadcasting,and the data type is same as `input_x`.
Z
zhaozhenlong 已提交
3238 3239

    Examples:
3240 3241
         >>> input_x = Tensor(np.array([[0, 1]]), mindspore.float32)
         >>> input_y = Tensor(np.array([[1, 1]]), mindspore.float32)
万万没想到 已提交
3242
         >>> atan2 = P.Atan2()
Z
zhaozhenlong 已提交
3243 3244 3245
         >>> atan2(input_x, input_y)
         [[0. 0.7853982]]
    """
Z
zhaojichen 已提交
3246

3247

Z
zhaojichen 已提交
3248 3249 3250 3251 3252
class SquareSumAll(PrimitiveWithInfer):
    """
    Returns square sum all of a tensor element-wise

    Inputs:
3253
        - **input_x1** (Tensor) - The input tensor. The data type must be float16 or float32.
Z
zhaojichen 已提交
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
        - **input_x2** (Tensor) - The input tensor same type and shape as the `input_x1`.

    Note:
        SquareSumAll only supports float16 and float32 data type.

    Outputs:
        - **output_y1** (Tensor) - The same type as the `input_x1`.
        - **output_y2** (Tensor) - The same type as the `input_x1`.

    Examples:
Z
zhaojichen 已提交
3264 3265
         >>> input_x1 = Tensor(np.random.randint([3, 2, 5, 7]), mindspore.float32)
         >>> input_x2 = Tensor(np.random.randint([3, 2, 5, 7]), mindspore.float32)
Z
zhaojichen 已提交
3266 3267 3268 3269 3270 3271 3272
         >>> square_sum_all = P.SquareSumAll()
         >>> square_sum_all(input_x1, input_x2)
    """

    @prim_attr_register
    def __init__(self):
        """init SquareSumAll"""
G
gong chen 已提交
3273

Z
zhaojichen 已提交
3274 3275 3276 3277 3278 3279 3280 3281
    def infer_shape(self, x_shape, y_shape):
        validator.check("x1_shape", x_shape, "x2_shape", y_shape, Rel.EQ, self.name)
        return [], []

    def infer_dtype(self, x_type, y_type):
        validator.check_tensor_type_same({'x1_type': x_type}, [mstype.float16, mstype.float32], self.name)
        validator.check_tensor_type_same({'x2_type': y_type}, [mstype.float16, mstype.float32], self.name)
        return x_type, y_type
3282 3283 3284 3285 3286 3287


class BitwiseAnd(_BitwiseBinaryOp):
    """
    Returns bitwise `and` of two tensors element-wise.

3288 3289 3290 3291 3292 3293
    Inputs of `input_x1` and `input_x2` comply with the implicit type conversion rules to
    make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

3294
    Inputs:
L
liuxiao93 已提交
3295
        - **input_x1** (Tensor) - The input tensor with int16, int32 or uint16 data type.
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
        - **input_x2** (Tensor) - The input tensor with same type as the `input_x1`.

    Outputs:
        - **y** (Tensor) - The same type as the `input_x1`.

    Examples:
         >>> input_x1 = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mstype.int16)
         >>> input_x2 = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mstype.int16)
         >>> bitwise_and = P.BitwiseAnd()
         >>> bitwise_and(input_x1, input_x2)
         [0, 0, 1, -1, 1, 0, 1]
    """


class BitwiseOr(_BitwiseBinaryOp):
    """
    Returns bitwise `or` of two tensors element-wise.

3314 3315 3316 3317 3318 3319
    Inputs of `input_x1` and `input_x2` comply with the implicit type conversion rules to
    make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

3320
    Inputs:
L
liuxiao93 已提交
3321
        - **input_x1** (Tensor) - The input tensor with int16, int32 or uint16 data type.
3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
        - **input_x2** (Tensor) - The input tensor with same type as the `input_x1`.

    Outputs:
        - **y** (Tensor) - The same type as the `input_x1`.

    Examples:
         >>> input_x1 = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mstype.int16)
         >>> input_x2 = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mstype.int16)
         >>> bitwise_or = P.BitwiseOr()
         >>> bitwise_or(input_x1, input_x2)
         [0, 1, 1, -1, -1, 3, 3]
    """


class BitwiseXor(_BitwiseBinaryOp):
    """
    Returns bitwise `xor` of two tensors element-wise.

3340 3341 3342 3343 3344 3345
    Inputs of `input_x1` and `input_x2` comply with the implicit type conversion rules to
    make the data types consistent.
    If they have different data types, lower priority data type will be converted to
    relatively highest priority data type.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.

3346
    Inputs:
L
liuxiao93 已提交
3347
        - **input_x1** (Tensor) - The input tensor with int16, int32 or uint16 data type.
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
        - **input_x2** (Tensor) - The input tensor with same type as the `input_x1`.

    Outputs:
        - **y** (Tensor) - The same type as the `input_x1`.

    Examples:
         >>> input_x1 = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mstype.int16)
         >>> input_x2 = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mstype.int16)
         >>> bitwise_xor = P.BitwiseXor()
         >>> bitwise_xor(input_x1, input_x2)
         [0, 1, 0, 0, -2, 3, 2]
    """
J
jiangjinsheng 已提交
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369


class BesselI0e(PrimitiveWithInfer):
    """
    Computes BesselI0e of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
L
liuxiao93 已提交
3370
        Tensor, has the same shape as `input_x`. Data type should be float16 or float32.
J
jiangjinsheng 已提交
3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398

    Examples:
        >>> bessel_i0e = P.BesselI0e()
        >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
        >>> output = bessel_i0e(input_x)
        [0.7979961, 0.5144438, 0.75117415, 0.9157829]
    """

    @prim_attr_register
    def __init__(self):
        """init BesselI0e"""

    def infer_shape(self, x):
        return x

    def infer_dtype(self, x):
        validator.check_tensor_type_same({'x': x}, mstype.number_type, self.name)
        return x


class BesselI1e(PrimitiveWithInfer):
    """
    Computes BesselI1e of input element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
L
liuxiao93 已提交
3399
        Tensor, has the same shape as `input_x`. Data type should be float16 or float32.
J
jiangjinsheng 已提交
3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417

    Examples:
        >>> bessel_i1e = P.BesselI1e()
        >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
        >>> output = bessel_i1e(input_x)
        [0.09507662, 0.19699717, 0.11505538, 0.04116856]
    """

    @prim_attr_register
    def __init__(self):
        """init BesselI1e"""

    def infer_shape(self, x):
        return x

    def infer_dtype(self, x):
        validator.check_tensor_type_same({'x': x}, mstype.number_type, self.name)
        return x
Z
zhaojichen 已提交
3418 3419 3420 3421 3422 3423 3424 3425


class Inv(PrimitiveWithInfer):
    """
    Computes Inv(Reciprocal) of input tensor element-wise.

    Inputs:
        - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
J
fix Inv  
jiangjinsheng 已提交
3426
          Must be one of the following types: float16, float32, int32.
Z
zhaojichen 已提交
3427 3428

    Outputs:
J
fix Inv  
jiangjinsheng 已提交
3429
        Tensor, has the same shape and data type as `input_x`.
Z
zhaojichen 已提交
3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446

    Examples:
        >>> inv = P.Inv()
        >>> input_x = Tensor(np.array([0.25, 0.4, 0.31, 0.52]), mindspore.float32)
        >>> output = inv(input_x)
        [4., 2.5, 3.2258065, 1.923077]
    """

    @prim_attr_register
    def __init__(self):
        pass

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x_dtype': x_dtype}, [mstype.float16, mstype.float32,
J
fix Inv  
jiangjinsheng 已提交
3447
                                                                mstype.int32], self.name)
Z
zhaojichen 已提交
3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
        return x_dtype


class Invert(PrimitiveWithInfer):
    """
    Flips all bits of input tensor element-wise.

    Inputs:
        - **input_x** (Tensor[int16], Tensor[uint16]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.

    Outputs:
        Tensor, has the same shape as `input_x`.

    Examples:
        >>> invert = P.Invert()
        >>> input_x = Tensor(np.array([25, 4, 13, 9]), mindspore.int16)
        >>> output = invert(input_x)
        [-26, -5, -14, -10]
    """

    @prim_attr_register
    def __init__(self):
        pass

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        validator.check_tensor_type_same({'x_dtype': x_dtype}, [mstype.int16, mstype.uint16], self.name)
        return x_dtype
G
gong chen 已提交
3478 3479 3480 3481 3482 3483 3484


class Eps(PrimitiveWithInfer):
    """
    Creates a tensor filled with `input_x` dtype minimum val.

    Inputs:
3485
        - **input_x** (Tensor) - Input tensor. The data type must be float16 or float32.
G
gong chen 已提交
3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515

    Outputs:
        Tensor, has the same type and shape as `input_x`, but filled with `input_x` dtype minimum val.

    Examples:
        >>> out = P.Eps()(input_x)
    """

    @prim_attr_register
    def __init__(self):
        """init Eps"""
        self.init_prim_io_names(inputs=['input_x'], outputs=['y'])

    def __infer__(self, input_x):
        valid_types = [mstype.float16, mstype.float32]
        validator.check_tensor_type_same({'input_x': input_x['dtype']}, valid_types, self.name)

        x_nptype = mstype.dtype_to_nptype(input_x['dtype'].element_type())
        if x_nptype == np.float16:
            min_val = 2 ** (-14)
        else:
            min_val = 2 ** (-16)

        res = np.full(input_x['shape'], min_val, x_nptype)
        out = {
            'value': Tensor(res),
            'shape': input_x['shape'],
            'dtype': input_x['dtype'],
        }
        return out