manipulation.py 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
from paddle import _C_ops, _legacy_C_ops
from paddle.fluid.data_feeder import check_variable_and_dtype
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
from paddle.fluid.framework import _in_legacy_dygraph, in_dygraph_mode
from paddle.fluid.layer_helper import LayerHelper

__all__ = []


# TODO(qili93): remove this op after custom op and custom device
# integrated and then move this op along with its code to plugin.
def _npu_identity(x, format=-1):
    """

    This OP takes in the Tensor :attr:`x` and change it to ouptut with
    aclFormat with int value. This API is only used for Ascend NPU.

    Args:
        x(Tensor): An input N-D Tensor with data type bool, float16,
                   float32, float64, int32, int64, int16, int8, uint8.
        format(int): Storage data format of the output in aclFormat,
                     default value is -1.

    Returns:
        Tensor: A Tensor with acl storage format on Ascend NPU.

    Examples:
        .. code-block:: python

            # required: npu
            import paddle

            x = paddle.ones(shape=[6])
            y = paddle.incubate._npu_identity(x, 3) # ACL_FORMAT_NC1HWC0 = 3
            # y.shape = [1, 1, 1, 1, 16]
    """
    if in_dygraph_mode():
        return _C_ops.npu_identity(x, format)

    if _in_legacy_dygraph():
54
        return _legacy_C_ops.npu_identity(x, 'format', format)
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

    check_variable_and_dtype(
        x,
        'x',
        [
            'bool',
            'int8',
            'uint8',
            'int16',
            'int32',
            'int64',
            'float16',
            'float32',
            'float64',
        ],
        'npu_identity',
    )

    helper = LayerHelper('npu_identity', **locals())
    out = helper.create_variable_for_type_inference(
        dtype=x.dtype, stop_gradient=x.stop_gradient
    )
    helper.append_op(
        type='npu_identity',
        inputs={'x': [x]},
        outputs={'out': [out]},
        attrs={'format': format},
    )
    return out