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

from __future__ import print_function

from .. import core
C
chentianyu03 已提交
18
from ..framework import Variable, convert_np_dtype_to_dtype_, _varbase_creator
19
from ..layers.layer_function_generator import OpProtoHolder
20
from . import no_grad
21

22
import numpy as np
23
import warnings
24

25 26 27 28 29 30
_supported_int_dtype_ = [
    core.VarDesc.VarType.UINT8,
    core.VarDesc.VarType.INT8,
    core.VarDesc.VarType.INT16,
    core.VarDesc.VarType.INT32,
    core.VarDesc.VarType.INT64,
31
    core.VarDesc.VarType.BOOL,
32 33
]

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
# NOTE(chenweihang): We currently do not fully support the type promotion 
# between tensors. Parting support here is because the interoperation of 
# real and complex numbers in paddle quantum is very frequent, such as the 
# binary operation between `float` and `complex64`, so we must support the 
# correct type promotion on the APIs paddle quantum used.
# Now only check in dygraph (paddle quantum based dygraph)
# Full type promotion support will need to be fully verified later.
_supported_promote_complex_types_ = [
    '__add__',
    '__radd__',
    '__sub__',
    '__rsub__',
    '__mul__',
    '__rmul__',
    '__truediv__',
    '__rtruediv__',
    '__matmul__',
]

53 54 55 56 57
_complex_dtypes = [
    core.VarDesc.VarType.COMPLEX64,
    core.VarDesc.VarType.COMPLEX128,
]

58 59
_already_patch_varbase = False

60 61 62 63 64 65 66

def monkey_patch_math_varbase():
    """
    Similar to monkey_patch_variable.
    The difference is, in dygraph mode, use auto-generated op functions for better performance.
    """

67
    @no_grad
68
    def create_tensor(value, dtype, shape):
69 70 71 72 73
        out = _varbase_creator(dtype=dtype)
        out = core.ops.fill_constant(out, 'dtype', dtype, 'shape', shape,
                                     'value', value, 'force_cpu', False)
        out.stop_gradient = True
        return out
74 75 76 77 78 79 80

    def create_scalar(value, dtype):
        return create_tensor(value, dtype, shape=[1])

    def astype(self, dtype):
        """

81
        Cast a Tensor to a specified data type.
82 83

        Args:
84
            dtype: The target data type.
85 86

        Returns:
87
            Tensor: a new Tensor with target dtype
88 89 90 91

        Examples:
            .. code-block:: python

92
                import paddle
93 94
                import numpy as np

95 96 97 98
                original_tensor = paddle.ones([2, 2])
                print("original tensor's dtype is: {}".format(original_tensor.dtype))
                new_tensor = original_tensor.astype('float32')
                print("new tensor's dtype is: {}".format(new_tensor.dtype))
99 100

        """
101 102 103
        if not isinstance(dtype, core.VarDesc.VarType):
            dtype = convert_np_dtype_to_dtype_(dtype)
        return core.ops.cast(self, 'in_dtype', self.dtype, 'out_dtype', dtype)
104 105

    def _scalar_elementwise_op_(var, scale, bias):
106
        return core.ops.scale(var, 'scale', scale, 'bias', bias)
107

108 109 110
    def _neg_(var):
        return _scalar_elementwise_op_(var, -1.0, 0.0)

111 112 113 114 115 116 117 118 119 120 121 122
    def _float_(var):
        numel = np.prod(var.shape)
        assert numel == 1, "only one element variable can be converted to float."
        tensor = var.value().get_tensor()
        assert tensor._is_initialized(), "variable's tensor is not initialized"
        return float(var.numpy().flatten()[0])

    def _long_(var):
        numel = np.prod(var.shape)
        assert numel == 1, "only one element variable can be converted to long."
        tensor = var.value().get_tensor()
        assert tensor._is_initialized(), "variable's tensor is not initialized"
T
tianshuo78520a 已提交
123
        return int(var.numpy().flatten()[0])
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    def _int_(var):
        numel = np.prod(var.shape)
        assert numel == 1, "only one element variable can be converted to int."
        tensor = var.value().get_tensor()
        assert tensor._is_initialized(), "variable's tensor is not initialized"
        return int(var.numpy().flatten()[0])

    def _len_(var):
        return var.shape[0]

    def _index_(var):
        numel = np.prod(var.shape)
        assert numel == 1, "only one element variable can be converted to python index."
        tensor = var.value().get_tensor()
        assert tensor._is_initialized(), "variable's tensor is not initialized"
T
tianshuo78520a 已提交
140
        return int(var.numpy().flatten()[0])
141

142 143 144 145
    @property
    def _ndim_(var):
        return len(var.shape)

146 147 148 149
    @property
    def _size_(var):
        return np.prod(var.shape)

150
    def _scalar_add_(var, value):
151 152
        return _scalar_elementwise_op_(var, 1.0, value)

153
    def _scalar_sub_(var, value):
154 155
        return _scalar_elementwise_op_(var, 1.0, -value)

156
    def _scalar_rsub_(var, value):
157 158
        return _scalar_elementwise_op_(var, -1.0, value)

159
    def _scalar_mul_(var, value):
160 161
        return _scalar_elementwise_op_(var, value, 0.0)

162 163 164 165 166
    # for binary operator such as elementwise, compare
    def _binary_creator_(method_name,
                         op_type,
                         reverse=False,
                         scalar_method=None):
167
        def __impl__(self, other_var):
168 169 170 171 172 173 174 175 176
            # 1. scalar exists cases
            # we need combine the tensor.dtype and scalar.dtype, cast correct object
            if isinstance(other_var, float):
                # in all cases(+, -, *, /, **, //, %), we need cast tensor.dtype to float
                if self.dtype in _supported_int_dtype_:
                    self = astype(self, 'float32')
                # here use `scale` replace `elementwise` to get better performance
                # but only +, -, *, / can use this method
                if scalar_method is not None:
177
                    return scalar_method(self, other_var)
178 179 180 181 182 183 184 185 186 187 188 189 190 191
            elif isinstance(other_var, int):
                # in all cases(+, -, *, /, **, //, %), we can cast it to float
                # because the output tensor.dtype depend on the type of input tensor
                other_var = float(other_var)
                # division is a special case
                # NOTE(chenweihang): because we cast tensor to float32 instead float64,
                # the division result can only guarantee the numerical accuracy of 6 digits 
                # after the decimal point. The result of numpy calculation is of float64 type, 
                # so the calculation result here and the calculation result of numpy are 
                # different after 6 decimal point. If necessary, we can also use float64 here.
                # torch's behavior here is consistent with ours
                if op_type == 'elementwise_div' and self.dtype in _supported_int_dtype_:
                    self = astype(self, 'float32')
                # here use `scale` replace `elementwise` to get better performance
192 193 194 195
                # but only +, -, * can use this method
                # NOTE(chentianyu03): / can not use `scale` method,because the result of
                # `scale` method (self*(1/other_var)) do not exactly equal with the result 
                # of `elementwise_div` method.
196 197 198 199 200
                if scalar_method is not None:
                    return scalar_method(self, other_var)
            else:
                # do nothing
                pass
201

202
            # 2. create varbase for scalar
203
            lhs_dtype = self.dtype
204
            if not isinstance(other_var, core.VarBase):
205 206 207
                if isinstance(other_var, complex):
                    import paddle
                    other_var = paddle.to_tensor(other_var, dtype='complex64')
208
                else:
209 210 211 212 213 214 215
                    if reverse:
                        other_var = create_tensor(
                            other_var, dtype=lhs_dtype, shape=self.shape)
                    else:
                        # add fill_op
                        other_var = create_scalar(
                            value=other_var, dtype=lhs_dtype)
216

217
            # 3. promote types or unify right var type to left var
218
            rhs_dtype = other_var.dtype
219
            if lhs_dtype != rhs_dtype:
220 221 222
                if method_name in _supported_promote_complex_types_ and (
                        lhs_dtype in _complex_dtypes or
                        rhs_dtype in _complex_dtypes):
223 224 225 226 227 228 229 230 231 232
                    # only when lhs_dtype or rhs_dtype is complex type,
                    # the dtype will promote, in other cases, directly
                    # use lhs_dtype, this is consistent will original rule
                    promote_dtype = core._promote_types_if_complex_exists(
                        lhs_dtype, rhs_dtype)
                    self = self if lhs_dtype == promote_dtype else astype(
                        self, promote_dtype)
                    other_var = other_var if rhs_dtype == promote_dtype else astype(
                        other_var, promote_dtype)
                else:
233 234 235
                    warnings.warn(
                        'The dtype of left and right variables are not the same, left dtype is {}, but right dtype is {}, the right dtype will convert to {}'.
                        format(lhs_dtype, rhs_dtype, lhs_dtype))
236 237
                    other_var = astype(other_var, lhs_dtype)

238 239 240 241 242
            if reverse:
                tmp = self
                self = other_var
                other_var = tmp

243
            # 4. calculation
244
            axis = -1
245
            math_op = getattr(core.ops, op_type)
L
Leo Chen 已提交
246
            return math_op(self, other_var, 'axis', axis)
247 248 249 250 251 252

        comment = OpProtoHolder.instance().get_op_proto(op_type).comment

        __impl__.__doc__ = """
        {0}
        Args:
253
            other_var(Tensor|float|int): right hand Tensor
254 255

        Returns:
256
            Tensor
257 258 259 260
        """.format(comment)
        __impl__.__name__ = method_name
        return __impl__

261 262 263 264 265 266 267 268 269 270 271
    varbase_methods = [
        ('__neg__', _neg_),
        ('__float__', _float_),
        ('__long__', _long_),
        ('__int__', _int_),
        ('__len__', _len_),
        ('__index__', _index_),
        ('astype', astype),
        ('dim', lambda x: len(x.shape)),
        ('ndimension', lambda x: len(x.shape)),
        ('ndim', _ndim_),
272
        ('size', _size_),
273 274 275 276 277 278 279 280 281 282 283 284 285 286
        ('__add__',
         _binary_creator_('__add__', 'elementwise_add', False, _scalar_add_)),
        ##  a+b == b+a. Do not need to reverse explicitly
        ('__radd__',
         _binary_creator_('__radd__', 'elementwise_add', False, _scalar_add_)),
        ('__sub__', _binary_creator_('__sub__', 'elementwise_sub', False,
                                     _scalar_sub_)),
        ('__rsub__', _binary_creator_('__rsub__', 'elementwise_sub', True,
                                      _scalar_rsub_)),
        ('__mul__', _binary_creator_('__mul__', 'elementwise_mul', False,
                                     _scalar_mul_)),
        ## a*b == b*a. Do not need to reverse explicitly
        ('__rmul__',
         _binary_creator_('__rmul__', 'elementwise_mul', False, _scalar_mul_)),
S
ShenLiang 已提交
287
        ('__truediv__', _binary_creator_('__truediv__', 'elementwise_div',
288
                                         False, None)),
289 290 291 292 293 294
        ('__rtruediv__', _binary_creator_('rtruediv__', 'elementwise_div', True,
                                          None)),
        ('__pow__', _binary_creator_('__pow__', 'elementwise_pow', False,
                                     None)),
        ('__rpow__', _binary_creator_('__rpow__', 'elementwise_pow', True,
                                      None)),
S
ShenLiang 已提交
295 296 297 298
        ('__floordiv__', _binary_creator_('__floordiv__',
                                          'elementwise_floordiv', False, None)),
        ('__mod__', _binary_creator_('__mod__', 'elementwise_mod', False,
                                     None)),
299 300
        ('__matmul__', _binary_creator_('__matmul__', "matmul_v2", False,
                                        None)),
301 302 303 304 305 306 307
        ## for logical compare
        ('__eq__', _binary_creator_('__eq__', 'equal', False, None)),
        ('__ne__', _binary_creator_('__ne__', 'not_equal', False, None)),
        ('__lt__', _binary_creator_('__lt__', 'less_than', False, None)),
        ('__le__', _binary_creator_('__le__', 'less_equal', False, None)),
        ('__gt__', _binary_creator_('__gt__', 'greater_than', False, None)),
        ('__ge__', _binary_creator_('__ge__', 'greater_equal', False, None)),
308
        ('__array_ufunc__', None)
309 310 311 312 313 314 315 316 317 318
    ]

    global _already_patch_varbase
    if not _already_patch_varbase:
        for method in varbase_methods:
            method_name = method[0]
            method_impl = method[1]
            setattr(core.VarBase, method_name, method_impl)
    else:
        import paddle.tensor
319
        # Tensor method from module paddle.tensor
320
        for method_name in paddle.tensor.tensor_method_func:
321 322 323 324
            if hasattr(core.VarBase, method_name): continue
            method_impl = getattr(paddle.tensor, method_name, None)
            if method_impl: setattr(core.VarBase, method_name, method_impl)

325 326 327 328
        for magic_method, origin_method in paddle.tensor.magic_method_func:
            impl = getattr(paddle.tensor, origin_method, None)
            if impl: setattr(core.VarBase, magic_method, impl)

329
    _already_patch_varbase = True