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

"""Other operators."""
K
kingfo 已提交
17
import functools
W
Wei Luning 已提交
18
from .. import signature as sig
19
from ..._checkparam import Validator as validator, Rel
Z
zhunaipan 已提交
20 21 22 23
from ...common import dtype as mstype
from ..primitive import Primitive, PrimitiveWithInfer, prim_attr_register


24
class Assign(Primitive):
Z
zhunaipan 已提交
25 26
    """
    Assign `Parameter` with a value.
27 28 29 30 31

    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.
    RuntimeError exception will be thrown when the data type conversion of Parameter is required.
Z
zhunaipan 已提交
32 33 34

    Inputs:
        - **variable** (Parameter) - The `Parameter`.
S
simson 已提交
35
        - **value** (Tensor) - The value to be assigned.
Z
zhunaipan 已提交
36 37 38 39 40 41 42 43 44 45 46

    Outputs:
        Tensor, has the same type as original `variable`.

    Examples:
        >>> class Net(nn.Cell):
        >>>     def __init__(self):
        >>>         super(Net, self).__init__()
        >>>         self.y = mindspore.Parameter(Tensor([1.0], mindspore.float32), name="y")
        >>>
        >>>     def construct(self, x):
万万没想到 已提交
47
        >>>         P.Assign()(self.y, x)
Z
zhunaipan 已提交
48 49 50 51 52 53
        >>>         return x
        >>> x = Tensor([2.0], mindspore.float32)
        >>> net = Net()
        >>> net(x)
    """
    __mindspore_signature__ = (
W
Wei Luning 已提交
54 55
        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 已提交
56
    )
J
jiangjinsheng 已提交
57

Z
zhunaipan 已提交
58 59
    @prim_attr_register
    def __init__(self):
G
gong chen 已提交
60
        self.init_prim_io_names(inputs=['ref', 'value'], outputs=['output'])
Z
zhunaipan 已提交
61 62 63 64 65

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

    def infer_dtype(self, variable, value):
L
liuxiao93 已提交
66 67 68
        if variable != mstype.type_refkey:
            validator.check_tensor_type_same({"variable": variable}, mstype.number_type, self.name)
        validator.check_scalar_or_tensor_type_same({"value": value}, mstype.number_type, self.name)
Z
zhunaipan 已提交
69 70 71 72 73 74 75 76 77
        return variable


class BoundingBoxEncode(PrimitiveWithInfer):
    """
    Encode bounding boxes locations.

    Args:
        means (tuple): Means for encoding bounding boxes calculation. Default: (0.0, 0.0, 0.0, 0.0).
S
simson 已提交
78
        stds (tuple): The standard deviations of deltas calculation. Default: (1.0, 1.0, 1.0, 1.0).
Z
zhunaipan 已提交
79 80

    Inputs:
F
fangzehua 已提交
81 82
        - **anchor_box** (Tensor) - Anchor boxes. The shape of anchor_box must be (n, 4).
        - **groundtruth_box** (Tensor) - Ground truth boxes. Which has the same shape with anchor_box.
Z
zhunaipan 已提交
83 84 85 86 87

    Outputs:
        Tensor, encoded bounding boxes.

    Examples:
88 89
        >>> anchor_box = Tensor([[4,1,2,1],[2,2,2,3]],mindspore.float32)
        >>> groundtruth_box = Tensor([[3,1,2,2],[1,2,1,4]],mindspore.float32)
90
        >>> boundingbox_encode = P.BoundingBoxEncode(means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0))
91 92 93 94
        >>> boundingbox_encode(anchor_box, groundtruth_box)
        [[5.0000000e-01  5.0000000e-01  -6.5504000e+04  6.9335938e-01]
         [-1.0000000e+00  2.5000000e-01  0.0000000e+00  4.0551758e-01]]

Z
zhunaipan 已提交
95 96 97 98
    """

    @prim_attr_register
    def __init__(self, means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0)):
F
fangzehua 已提交
99 100
        validator.check_value_type('means', means, (tuple), self.name)
        validator.check_value_type('stds', stds, (tuple), self.name)
101 102 103 104
        for i, value in enumerate(means):
            validator.check_value_type("means[%d]" % i, value, [float], self.name)
        for i, value in enumerate(stds):
            validator.check_value_type("stds[%d]" % i, value, [float], self.name)
105 106
        validator.check_integer("means len", len(means), 4, Rel.EQ, self.name)
        validator.check_integer("stds len", len(stds), 4, Rel.EQ, self.name)
Z
zhunaipan 已提交
107 108

    def infer_shape(self, anchor_box, groundtruth_box):
109 110
        validator.check('anchor_box shape[0]', anchor_box[0], 'groundtruth_box shape[0]', groundtruth_box[0], Rel.EQ,
                        self.name)
L
linqingke 已提交
111 112
        validator.check("anchor_box rank", len(anchor_box), "", 2, Rel.EQ, self.name)
        validator.check("groundtruth_box rank", len(groundtruth_box), "", 2, Rel.EQ, self.name)
113 114
        validator.check_integer('anchor_box shape[1]', anchor_box[1], 4, Rel.EQ, self.name)
        validator.check_integer('groundtruth_box shape[1]', groundtruth_box[1], 4, Rel.EQ, self.name)
Z
zhunaipan 已提交
115 116 117
        return anchor_box

    def infer_dtype(self, anchor_box, groundtruth_box):
118 119
        args = {"anchor_box": anchor_box, "groundtruth_box": groundtruth_box}
        validator.check_tensor_type_same(args, mstype.number_type, self.name)
Z
zhunaipan 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133
        return anchor_box


class BoundingBoxDecode(PrimitiveWithInfer):
    """
    Decode bounding boxes locations.

    Args:
        means (tuple): The means of deltas calculation. Default: (0.0, 0.0, 0.0, 0.0).
        stds (tuple): The standard deviations of deltas calculation. Default: (1.0, 1.0, 1.0, 1.0).
        max_shape (tuple): The max size limit for decoding box calculation.
        wh_ratio_clip (float): The limit of width and height ratio for decoding box calculation. Default: 0.016.

    Inputs:
S
simson 已提交
134 135
        - **anchor_box** (Tensor) - Anchor boxes. The shape of `anchor_box` must be (n, 4).
        - **deltas** (Tensor) - Delta of boxes. Which has the same shape with `anchor_box`.
Z
zhunaipan 已提交
136 137 138 139 140

    Outputs:
        Tensor, decoded boxes.

    Examples:
141 142
        >>> anchor_box = Tensor([[4,1,2,1],[2,2,2,3]],mindspore.float32)
        >>> deltas = Tensor([[3,1,2,2],[1,2,1,4]],mindspore.float32)
143
        >>> boundingbox_decode = P.BoundingBoxDecode(means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0),
144
        >>>                                          max_shape=(768, 1280), wh_ratio_clip=0.016)
145 146 147 148
        >>> boundingbox_decode(anchor_box, deltas)
        [[4.1953125  0.  0.  5.1953125]
         [2.140625  0.  3.859375  60.59375]]

Z
zhunaipan 已提交
149 150 151 152
    """

    @prim_attr_register
    def __init__(self, max_shape, means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0), wh_ratio_clip=0.016):
F
fangzehua 已提交
153 154
        validator.check_value_type('means', means, (tuple), self.name)
        validator.check_value_type('stds', stds, (tuple), self.name)
155 156 157 158
        for i, value in enumerate(means):
            validator.check_value_type("means[%d]" % i, value, [float], self.name)
        for i, value in enumerate(stds):
            validator.check_value_type("stds[%d]" % i, value, [float], self.name)
159 160 161
        validator.check_value_type('wh_ratio_clip', wh_ratio_clip, [float], self.name)
        validator.check_integer("means len", len(means), 4, Rel.EQ, self.name)
        validator.check_integer("stds len", len(stds), 4, Rel.EQ, self.name)
Z
zhunaipan 已提交
162
        if max_shape is not None:
163 164
            validator.check_value_type('max_shape', max_shape, [tuple], self.name)
            validator.check_integer("max_shape len", len(max_shape), 2, Rel.EQ, self.name)
Z
zhunaipan 已提交
165 166

    def infer_shape(self, anchor_box, deltas):
167
        validator.check('anchor_box shape[0]', anchor_box[0], 'deltas shape[0]', deltas[0], Rel.EQ, self.name)
L
linqingke 已提交
168 169
        validator.check("anchor_box rank", len(anchor_box), "", 2, Rel.EQ, self.name)
        validator.check("deltas rank", len(deltas), "", 2, Rel.EQ, self.name)
170 171
        validator.check_integer('anchor_box shape[1]', anchor_box[1], 4, Rel.EQ, self.name)
        validator.check_integer('deltas shape[1]', deltas[1], 4, Rel.EQ, self.name)
Z
zhunaipan 已提交
172 173 174
        return anchor_box

    def infer_dtype(self, anchor_box, deltas):
175 176
        args = {"anchor_box": anchor_box, "deltas": deltas}
        validator.check_tensor_type_same(args, mstype.number_type, self.name)
Z
zhunaipan 已提交
177 178 179 180 181 182 183
        return anchor_box


class CheckValid(PrimitiveWithInfer):
    """
    Check bounding box.

S
simson 已提交
184
    Check whether the bounding box cross data and data border are valid.
Z
zhunaipan 已提交
185 186

    Inputs:
187
        - **bboxes** (Tensor) - Bounding boxes tensor with shape (N, 4). Data type should be float16 or float32.
S
simson 已提交
188
        - **img_metas** (Tensor) - Raw image size information with the format of (height, width, ratio).
189
          Data type should be float16 or float32.
Z
zhunaipan 已提交
190 191 192

    Outputs:
        Tensor, the valided tensor.
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

    Examples:
        >>> import mindspore
        >>> import mindspore.nn as nn
        >>> import numpy as np
        >>> from mindspore import Tensor
        >>> from mindspore.ops import operations as P
        >>> class Net(nn.Cell):
        >>>     def __init__(self):
        >>>         super(Net, self).__init__()
        >>>         self.check_valid = P.CheckValid()
        >>>     def construct(self, x, y):
        >>>         valid_result = self.check_valid(x, y)
        >>>         return valid_result
        >>>
        >>> bboxes = Tensor(np.linspace(0, 6, 12).reshape(3, 4), mindspore.float32)
        >>> img_metas = Tensor(np.array([2, 1, 3]), mindspore.float32)
        >>> net = Net()
        >>> result = net(bboxes, img_metas)
        [True   False   False]
Z
zhunaipan 已提交
213 214 215 216 217 218 219
    """

    @prim_attr_register
    def __init__(self):
        self.init_prim_io_names(inputs=['bboxes', 'img_metas'], outputs=['output'])

    def infer_shape(self, bboxes_shape, metas_shape):
Z
zhaozhenlong 已提交
220 221 222 223
        validator.check("bboxes rank", len(bboxes_shape), "", 2, Rel.EQ, self.name)
        validator.check("bboxes_shape[-1]", bboxes_shape[-1], "", 4, Rel.EQ, self.name)
        validator.check("img_metas rank", len(metas_shape), "", 1, Rel.EQ, self.name)
        validator.check("img_metas shape[0]", metas_shape[0], "", 3, Rel.EQ, self.name)
Z
zhunaipan 已提交
224 225 226
        return bboxes_shape[:-1]

    def infer_dtype(self, bboxes_type, metas_type):
227
        valid_type = [mstype.float32, mstype.float16, mstype.int16, mstype.uint8]
228 229
        validator.check_tensor_type_same({"bboxes_type": bboxes_type}, valid_type, self.name)
        validator.check_tensor_type_same({"metas_type": metas_type}, valid_type, self.name)
Z
zhunaipan 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        return mstype.bool_


class IOU(PrimitiveWithInfer):
    r"""
    Calculate intersection over union for boxes.

    Compute the intersection over union (IOU) or the intersection over foreground (IOF) based on the ground-truth and
    predicted regions.

    .. math::
        \text{IOU} = \frac{\text{Area of Overlap}}{\text{Area of Union}}

        \text{IOF} = \frac{\text{Area of Overlap}}{\text{Area of Ground Truth}}

    Args:
        mode (string): The mode is used to specify the calculation method,
S
simson 已提交
247
                       now supporting 'iou' (intersection over union) or 'iof'
Z
zhunaipan 已提交
248 249 250 251
                       (intersection over foreground) mode. Default: 'iou'.

    Inputs:
        - **anchor_boxes** (Tensor) - Anchor boxes, tensor of shape (N, 4). "N" indicates the number of anchor boxes,
L
linqingke 已提交
252
          and the value "4" refers to "x0", "y0", "x1", and "y1". Data type must be float16 or float32.
Z
zhunaipan 已提交
253
        - **gt_boxes** (Tensor) - Ground truth boxes, tensor of shape (M, 4). "M" indicates the number of ground
L
linqingke 已提交
254
          truth boxes, and the value "4" refers to "x0", "y0", "x1", and "y1". Data type must be float16 or float32.
Z
zhunaipan 已提交
255 256

    Outputs:
257
        Tensor, the 'iou' values, tensor of shape (M, N), with the same data type as `anchor_boxes`.
Z
zhunaipan 已提交
258 259 260 261 262

    Raises:
        KeyError: When `mode` is not 'iou' or 'iof'.

    Examples:
263
        >>> iou = P.IOU()
J
jiangjinsheng 已提交
264 265
        >>> anchor_boxes = Tensor(np.random.randint(1.0, 5.0, [3, 4]), mindspore.float16)
        >>> gt_boxes = Tensor(np.random.randint(1.0, 5.0, [3, 4]), mindspore.float16)
Z
zhunaipan 已提交
266
        >>> iou(anchor_boxes, gt_boxes)
L
lihongkang 已提交
267 268 269
        [[0.0, 65504, 65504],
         [0.0, 0.0, 0.0],
         [0.22253, 0.0, 0.0]]
Z
zhunaipan 已提交
270 271 272 273 274 275 276 277 278
    """

    @prim_attr_register
    def __init__(self, mode='iou'):
        if mode not in {'iou', 'iof'}:
            raise KeyError("Mode only support 'iou' or 'iof'.")
        self.init_prim_io_names(inputs=['anchor_boxes', 'gt_boxes'], outputs=['overlap'])

    def infer_shape(self, anchor_boxes, gt_boxes):
279 280 281 282
        validator.check_integer('gt_boxes shape[1]', gt_boxes[1], 4, Rel.EQ, self.name)
        validator.check_integer('anchor_boxes shape[1]', anchor_boxes[1], 4, Rel.EQ, self.name)
        validator.check_integer('anchor_boxes rank', len(anchor_boxes), 2, Rel.EQ, self.name)
        validator.check_integer('gt_boxes rank', len(gt_boxes), 2, Rel.EQ, self.name)
Z
zhunaipan 已提交
283 284 285 286
        iou = [gt_boxes[0], anchor_boxes[0]]
        return iou

    def infer_dtype(self, anchor_boxes, gt_boxes):
287 288 289
        valid_type = [mstype.float32, mstype.float16]
        validator.check_tensor_type_same({"anchor_boxes": anchor_boxes}, valid_type, self.name)
        validator.check_tensor_type_same({"gt_boxes": gt_boxes}, valid_type, self.name)
Z
zhunaipan 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        return anchor_boxes


class MakeRefKey(Primitive):
    """
    Make a RefKey instance by string. RefKey stores the name of Parameter, can be passed through the functions,
    and used for Assign target.

    Args:
        tag (str): Parameter name to make the RefKey.

    Inputs:
        No input.

    Outputs:
        RefKeyType, made from the Parameter name.

    Examples:
        >>> from mindspore.ops import functional as F
        >>> class Net(nn.Cell):
        >>>     def __init__(self):
        >>>         super(Net, self).__init__()
312 313
        >>>         self.y = mindspore.Parameter(Tensor(np.ones([6, 8, 10]), mindspore.int32), name="y")
        >>>         self.make_ref_key = P.MakeRefKey("y")
Z
zhunaipan 已提交
314 315 316 317 318 319
        >>>
        >>>     def construct(self, x):
        >>>         key = self.make_ref_key()
        >>>         ref = F.make_ref(key, x, self.y)
        >>>         return ref * x
        >>>
320
        >>> x = Tensor(np.ones([3, 4, 5]), mindspore.int32)
Z
zhunaipan 已提交
321 322 323 324 325 326
        >>> net = Net()
        >>> net(x)
    """

    @prim_attr_register
    def __init__(self, tag):
327
        validator.check_value_type('tag', tag, (str,), self.name)
K
kingfo 已提交
328 329 330

    def __call__(self):
        pass
P
panyifeng 已提交
331 332


K
kingfo 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
class Partial(Primitive):
    """
    Make a partial function instance, used for pynative mode.

    Inputs:
        - **args** (Union[FunctionType, Tensor]) - The function and bind arguments.

    Outputs:
        FunctionType, partial function binded with arguments.
    """

    @prim_attr_register
    def __init__(self):
        pass

    def __call__(self, *args):
        func = args[0].__call__
        partial_func = functools.partial(func, *args[1:])
        return partial_func

J
jiangjinsheng 已提交
353

K
kingfo 已提交
354 355
class Depend(Primitive):
    """
S
simson 已提交
356
    Depend is used for processing side-effect operations.
K
kingfo 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

    Inputs:
        - **value** (Tensor) - the real value to return for depend operator.
        - **expr** (Expression) - the expression to execute with no outputs.

    Outputs:
        Tensor, the value passed by last operator.
    """

    @prim_attr_register
    def __init__(self):
        pass

    def __call__(self, value, expr):
        return value


P
panyifeng 已提交
374 375
class CheckBprop(PrimitiveWithInfer):
    """
S
simson 已提交
376
    Checks whether the data type and the shape of corresponding elements from tuples x and y are the same.
P
panyifeng 已提交
377 378

    Raises:
S
simson 已提交
379
        TypeError: If tuples x and y are not the same.
P
panyifeng 已提交
380 381

    Inputs:
S
simson 已提交
382 383
        - **input_x** (tuple[Tensor]) - The `input_x` contains the outputs of bprop to be checked.
        - **input_y** (tuple[Tensor]) - The `input_y` contains the inputs of bprop to check against.
P
panyifeng 已提交
384 385

    Outputs:
S
simson 已提交
386
        (tuple[Tensor]), the `input_x`,
P
panyifeng 已提交
387 388 389 390 391 392 393 394 395
        if data type and shape of corresponding elements from `input_x` and `input_y` are the same.

    Examples:
        >>> input_x = (Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32),)
        >>> input_y = (Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32),)
        >>> out = P.CheckBprop()(input_x, input_y)
    """

    @prim_attr_register
P
panyifeng 已提交
396
    def __init__(self, prim_to_check=""):
P
panyifeng 已提交
397
        """init CheckBprop"""
P
panyifeng 已提交
398
        self.prim_to_check = prim_to_check
P
panyifeng 已提交
399 400 401

    def infer_shape(self, xshapes, yshapes):
        tips = f'Bprop of {self.prim_to_check}'
P
panyifeng 已提交
402 403
        validator.check_value_type('grads', xshapes, (tuple,), tips)
        validator.check_value_type('params', yshapes, (tuple,), tips)
P
panyifeng 已提交
404
        if len(xshapes) < len(yshapes):
P
panyifeng 已提交
405 406
            raise ValueError(f"{tips}, the size of output should be {len(yshapes)},"
                             f" but got {len(xshapes)}.")
P
panyifeng 已提交
407 408 409 410 411 412 413
        checking_range = len(yshapes)
        for i in range(checking_range):
            xshape = xshapes[i]
            yshape = yshapes[i]
            if not xshape or not yshape:
                continue
            if xshape != yshape:
P
panyifeng 已提交
414 415
                raise ValueError(f"{tips}, the shape of {i}th output should be {yshape},"
                                 f" but got {xshape}.")
P
panyifeng 已提交
416 417 418 419
        return xshapes

    def infer_dtype(self, xdtypes, ydtypes):
        tips = f'Bprop of {self.prim_to_check}'
P
panyifeng 已提交
420 421
        validator.check_value_type('grads', xdtypes, (tuple,), tips)
        validator.check_value_type('params', ydtypes, (tuple,), tips)
P
panyifeng 已提交
422
        if len(xdtypes) < len(ydtypes):
P
panyifeng 已提交
423 424
            raise ValueError(f"{tips}, the size of output should be {len(ydtypes)},"
                             f" but got {len(xdtypes)}.")
P
panyifeng 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
        checking_range = len(ydtypes)
        for i in range(checking_range):
            xdtype = xdtypes[i]
            ydtype = ydtypes[i]
            if isinstance(xdtype, mstype.anything_type) or isinstance(ydtype, mstype.anything_type):
                continue
            if isinstance(ydtype, mstype.function_type):
                if not isinstance(xdtype, mstype.env_type_type):
                    raise TypeError(f"{tips}, the dtype of {i}th output should be {mstype.env_type_type},"
                                    f" but got {xdtype}.")
                continue
            if xdtype != ydtype:
                raise TypeError(f"{tips}, the dtype of {i}th output should be {ydtype},"
                                f" but got {xdtype}.")
        return xdtypes
440 441 442 443 444 445 446 447 448 449 450 451 452


class ConfusionMatrix(PrimitiveWithInfer):
    r"""
    Calculate the confusion matrix from labels and predictions.

    Args:
        num_classes (int): The num of classes.
        dtype (str): Data type of confusion matrix. Default: 'int32'.

    Inputs:
        - **labels** (Tensor) - real labels, tensor of 1-D. the dtype must be non-negative Integer.
        - **predictions** (Tensor) - the labels from prediction, tensor of 1-D.
453
          the shape same as `labels` and the dtype must be non-negative Integer.
454 455 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 485 486
        - **weights** (Tensor) - tensor of 1-D. the shape same as `predictions`.

    Outputs:
        Tensor, the confusion matrix, with shape (`num_classes`, `num_classes`).

    Examples:
        >>> confusion_matrix = P.ConfusionMatrix(4)
        >>> labels = Tensor([0, 1, 1, 3], mindspore.int32)
        >>> predictions = Tensor([1, 2, 1, 3], mindspore.int32)
        >>> confusion_matrix(labels, predictions)
    """

    @prim_attr_register
    def __init__(self, num_classes, dtype="int32"):
        validator.check_value_type("num_classes", num_classes, [int], self.name)
        validator.check_value_type("dtype", dtype, [str], self.name)

    def infer_shape(self, labels, predictions, weights=None):
        validator.check('labels dimension', len(labels), '', 1, Rel.EQ, self.name)
        validator.check('labels shape', labels, 'predictions shape', predictions, Rel.EQ, self.name)
        if weights is not None:
            validator.check('labels shape', labels, 'weights shape', weights, Rel.EQ, self.name)
        ret = (self.num_classes, self.num_classes)
        return ret

    def infer_dtype(self, labels, predictions, weights=None):
        validator.check_subclass('labels', labels, mstype.tensor, self.name)
        validator.check_subclass('predictions', predictions, mstype.tensor, self.name)
        if weights is not None:
            validator.check_subclass('weights', weights, mstype.tensor, self.name)
        args = {"labels": labels, "predictions": predictions}
        validator.check_tensor_type_same(args, (mstype.number_type), self.name)
        return labels
J
jiangjinsheng 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515


class PopulationCount(PrimitiveWithInfer):
    r"""
    Calculate population count.

    Inputs:
        - **input** (Tensor) -  The data type should be int16 or uint16.

    Outputs:
        Tensor, with shape same as the input.

    Examples:
        >>> population_count = P.PopulationCount()
        >>> x_input = Tensor([0, 1, 3], mindspore.int16)
        >>> population_count(x_input)
    """

    @prim_attr_register
    def __init__(self):
        pass

    def infer_shape(self, x_shape):
        return x_shape

    def infer_dtype(self, x_dtype):
        args = {"x": x_dtype}
        validator.check_tensor_type_same(args, (mstype.int16, mstype.uint16,), self.name)
        return mstype.tensor_type(mstype.uint8)
Z
ZPaC 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

class Push(PrimitiveWithInfer):
    """
    Pushing the inputs of the corresponding optimizer to parameter server.

    Args:
        optim_type (string): The optimizer type. Default: 'ApplyMomentum'.
        only_shape_indices (list): The indices of input of which only shape
                                   will be pushed to parameter server. Default: None.

    Inputs:
        - **optim_inputs** (tuple) - The inputs for this kind of optimizer.
        - **optim_input_shapes** (tuple) - The shapes of the inputs.

    Outputs:
        Tensor, the key of the weight which needs to be updated.
    """

    @prim_attr_register
    def __init__(self, optim_type='ApplyMomentum', only_shape_indices=None):
        """init Push"""
J
jinyaohui 已提交
537
        self.add_prim_attr("primitive_target", "CPU")
538
        self.add_prim_attr("_side_effect", True)
Z
ZPaC 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
        self.init_prim_io_names(inputs=['optim_inputs', 'optim_input_shapes'], outputs=['key'])

    def infer_shape(self, inputs, shapes):
        return [1]

    def infer_dtype(self, inputs, shapes):
        return mstype.uint64

class Pull(PrimitiveWithInfer):
    """
    Pulling weight from parameter server.

    Inputs:
        - **key** (Tensor) - The key of the weight.
        - **weight** (Tensor) - The weight to be updated.

    Outputs:
        None.
    """

    @prim_attr_register
    def __init__(self):
        """init Pull"""
J
jinyaohui 已提交
562
        self.add_prim_attr("primitive_target", "CPU")
Z
ZPaC 已提交
563 564 565 566 567 568 569
        self.init_prim_io_names(inputs=['key', 'weight'], outputs=['output'])

    def infer_shape(self, key_shape, weight_shape):
        return [1]

    def infer_dtype(self, key_dtype, weight_dtype):
        return mstype.float32
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

class identity(Primitive):
    """
    Make a identify primitive, used for pynative mode.

    Inputs:
        - **x** (Any) - identity input value.

    Outputs:
        The same as input.
    """

    @prim_attr_register
    def __init__(self):
        pass

    def __call__(self, x):
        return x