MCPcopy Create free account
hub / github.com/PaddlePaddle/Paddle / _binary_creator_

Function _binary_creator_

python/paddle/base/layers/math_op_patch.py:638–800  ·  view source on GitHub ↗
(
        method_name, op_type, reverse=False, scalar_method=None
    )

Source from the content-addressed store, hash-verified

636 return _scalar_op_(var, 1.0 / value, 0.0)
637
638 def _binary_creator_(
639 method_name, op_type, reverse=False, scalar_method=None
640 ):
641 def __impl__(self, other_var):
642 # 1. scalar exists cases
643 # we need combine the tensor.dtype and scalar.dtype, cast correct object
644 if isinstance(other_var, float):
645 # in all cases(+, -, *, /, **, //, %), we need cast tensor.dtype to float
646 if self.dtype in _supported_int_dtype_:
647 self = astype(self, 'float32')
648 # here use `scale` replace `elementwise` to get better performance
649 # but only +, -, *, / can use this method
650 if scalar_method is not None:
651 return scalar_method(self, other_var)
652 elif isinstance(other_var, int):
653 # in all cases(+, -, *, /, **, //, %), we can cast it to float
654 # because the output tensor.dtype depend on the type of input tensor
655 other_var = float(other_var)
656 # division is a special case
657 # NOTE(chenweihang): because we cast tensor to float32 instead float64,
658 # the division result can only guarantee the numerical accuracy of 6 digits
659 # after the decimal point. The result of numpy calculation is of float64 type,
660 # so the calculation result here and the calculation result of numpy are
661 # different after 6 decimal point. If necessary, we can also use float64 here.
662 # torch's behavior here is consistent with ours
663 if (
664 op_type == 'elementwise_div'
665 and self.dtype in _supported_int_dtype_
666 ):
667 self = astype(self, 'float32')
668 # bool(tensor) + int(scalar) will do type promotion to int64
669 if self.dtype == core.VarDesc.VarType.BOOL:
670 self = astype(self, 'int64')
671 # here use `scale` replace `elementwise` to get better performance
672 # but only +, -, *, / can use this method
673 if scalar_method is not None:
674 return scalar_method(self, other_var)
675 elif isinstance(other_var, complex):
676 if self.dtype not in _supported_complex_dtype_:
677 self = astype(self, 'complex64')
678 other_var = create_new_tmp_var(
679 current_block(self), dtype='complex64'
680 )
681 else:
682 # do nothing
683 pass
684
685 # 2. create variable for scalar
686 lhs_dtype = safe_get_dtype(self)
687 if not isinstance(other_var, Variable):
688 if reverse:
689 for elem in self.shape:
690 if elem < 0:
691 other_var = create_tensor_with_batchsize(
692 self, other_var, lhs_dtype
693 )
694 break
695 else:

Callers 1

monkey_patch_variableFunction · 0.70

Calls 2

get_op_protoMethod · 0.80
instanceMethod · 0.45

Tested by

no test coverage detected