From 3b0dd5f620e0565a3886fac53bf6c2cf5e7d802d Mon Sep 17 00:00:00 2001 From: Zhou Wei <52485244+zhouwei25@users.noreply.github.com> Date: Fri, 20 Nov 2020 15:34:34 +0800 Subject: [PATCH] fix bug that to_tensor not support paddle.Place (#28717) --- paddle/fluid/pybind/imperative.cc | 5 ++++- python/paddle/fluid/tests/unittests/test_var_base.py | 3 +++ python/paddle/tensor/creation.py | 6 +++--- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/paddle/fluid/pybind/imperative.cc b/paddle/fluid/pybind/imperative.cc index 7c36efcaf3..d7959c6997 100644 --- a/paddle/fluid/pybind/imperative.cc +++ b/paddle/fluid/pybind/imperative.cc @@ -69,9 +69,12 @@ static const platform::Place PyObjectToPlace(const py::object &place_obj) { return place_obj.cast(); } else if (py::isinstance(place_obj)) { return place_obj.cast(); + } else if (py::isinstance(place_obj)) { + return place_obj.cast(); } else { PADDLE_THROW(platform::errors::InvalidArgument( - "Place should be one of CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace")); + "Place should be one of " + "Place/CPUPlace/XPUPlace/CUDAPlace/CUDAPinnedPlace")); } } diff --git a/python/paddle/fluid/tests/unittests/test_var_base.py b/python/paddle/fluid/tests/unittests/test_var_base.py index 511813fc1c..7d3e09a7dd 100644 --- a/python/paddle/fluid/tests/unittests/test_var_base.py +++ b/python/paddle/fluid/tests/unittests/test_var_base.py @@ -40,6 +40,9 @@ class TestVarBase(unittest.TestCase): self.assertTrue(np.array_equal(x.numpy(), [1])) self.assertNotEqual(x.dtype, core.VarDesc.VarType.FP32) + y = paddle.to_tensor(2, place=x.place) + self.assertEqual(str(x.place), str(y.place)) + # set_default_dtype should not take effect on numpy x = paddle.to_tensor( np.array([1.2]).astype('float16'), diff --git a/python/paddle/tensor/creation.py b/python/paddle/tensor/creation.py index 622ae3c584..b46e1c7946 100644 --- a/python/paddle/tensor/creation.py +++ b/python/paddle/tensor/creation.py @@ -126,10 +126,10 @@ def to_tensor(data, dtype=None, place=None, stop_gradient=True): if place is None: place = _current_expected_place() - elif not isinstance(place, - (core.CPUPlace, core.CUDAPinnedPlace, core.CUDAPlace)): + elif not isinstance(place, (core.Place, core.CPUPlace, core.CUDAPinnedPlace, + core.CUDAPlace)): raise ValueError( - "'place' must be any of paddle.Place, paddle.CUDAPinnedPlace, paddle.CUDAPlace" + "'place' must be any of paddle.Place, paddle.CPUPlace, paddle.CUDAPinnedPlace, paddle.CUDAPlace" ) #Todo(zhouwei): Support allocate tensor on any other specified card -- GitLab