Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions python/paddle/fluid/dygraph/math_op_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from ..framework import Variable, convert_np_dtype_to_dtype_, _varbase_creator
from ..layers.layer_function_generator import OpProtoHolder
from . import no_grad
import paddle

import numpy as np
import six
Expand Down Expand Up @@ -209,12 +210,17 @@ def __impl__(self, other_var):
# 2. create varbase for scalar
lhs_dtype = self.dtype
if not isinstance(other_var, core.VarBase):
if reverse:
other_var = create_tensor(
other_var, dtype=lhs_dtype, shape=self.shape)
if isinstance(other_var, complex):
global paddle
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

global paddle? 为什么这么用

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不加global paddle的话,会报 "NameError: free variable 'paddle' referenced before assignment in enclosing scope" 的错误。
如果from ...tensor.creation import to_tensor 这样引用的话,则会报
ImportError: cannot import name '_unpack_saved_dict' from 'paddle.fluid.io' 错误。

other_var = paddle.to_tensor(other_var, dtype='complex64')
else:
# add fill_op
other_var = create_scalar(value=other_var, dtype=lhs_dtype)
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)

# 3. promote types or unify right var type to left var
rhs_dtype = other_var.dtype
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,13 @@ def test_tensor_patch_method(self):
self.assertTrue(inspect.ismethod(a.std))
self.assertTrue(inspect.ismethod(a.numel))

def test_complex_scalar(self):
a_np = np.random.random(self.shape).astype(self.dtype)
with fluid.dygraph.guard():
a = fluid.dygraph.to_variable(a_np)
res = 1J * a
self.assertTrue(np.array_equal(res.numpy(), 1J * a_np))


if __name__ == '__main__':
unittest.main()