From e199b9202a39eca135197958a2dec2acf1621217 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Thu, 14 Aug 2025 17:37:40 +0800 Subject: [PATCH 01/23] Support more construction method for paddle.Tensor --- python/paddle/__init__.py | 94 +++++++++++++-------- test/legacy_test/test_tensor_constructor.py | 52 ++++++++++++ 2 files changed, 109 insertions(+), 37 deletions(-) create mode 100644 test/legacy_test/test_tensor_constructor.py diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 4ebc15fdc9753c..60ae58a2944ff6 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -50,43 +50,6 @@ monkey_patch_program() monkey_patch_dtype() -from .base.dataset import * # noqa: F403 -from .framework import ( - disable_signal_handler, - disable_static, - enable_static, - get_flags, - in_dynamic_mode, - set_flags, -) -from .framework.dtype import ( - bfloat16, - bool, - complex64, - complex128, - dtype, - finfo, - float8_e4m3fn, - float8_e5m2, - float16, - float32, - float64, - iinfo, - int8, - int16, - int32, - int64, - pstring, - raw, - uint8, -) - -if typing.TYPE_CHECKING: - from .tensor.tensor import Tensor -else: - Tensor = framework.core.eager.Tensor - Tensor.__qualname__ = 'Tensor' - import paddle.distributed.fleet import paddle.text import paddle.vision @@ -136,6 +99,7 @@ no_grad, set_grad_enabled, ) +from .base.dataset import * # noqa: F403 from .device import ( # noqa: F401 device_guard, get_cudnn_version, @@ -161,10 +125,37 @@ XPUPlace, async_save, clear_async_save_task_queue, + disable_signal_handler, + disable_static, + enable_static, get_default_dtype, + get_flags, + in_dynamic_mode, load, save, set_default_dtype, + set_flags, +) +from .framework.dtype import ( + bfloat16, + bool, + complex64, + complex128, + dtype, + finfo, + float8_e4m3fn, + float8_e5m2, + float16, + float32, + float64, + iinfo, + int8, + int16, + int32, + int64, + pstring, + raw, + uint8, ) from .framework.random import ( get_cuda_rng_state, @@ -604,6 +595,35 @@ to_dlpack, ) +if typing.TYPE_CHECKING: + from .tensor.tensor import Tensor +else: + + class Tensor(framework.core.eager.Tensor): + def __init__(self, *args, **kwargs): + kwargs_cnt = len(kwargs.keys()) + if kwargs_cnt: + super().__init__(*args, **kwargs) + return + if len(args) == 0: + super().__init__(empty(shape=[0], dtype="float32")) + return + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + super().__init__(to_tensor(args[0], dtype="float32")) + return + create_random_tensor = True + for arg in args: + if not isinstance(arg, int): + create_random_tensor = False + break + if create_random_tensor: + super().__init__(randn(list(args), dtype="float32")) + return + else: + super().__init__(*args, **kwargs) + + Tensor.__qualname__ = 'Tensor' + # CINN has to set a flag to include a lib if is_compiled_with_cinn(): import os diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py new file mode 100644 index 00000000000000..44067616fa8f5d --- /dev/null +++ b/test/legacy_test/test_tensor_constructor.py @@ -0,0 +1,52 @@ +# Copyright (c) 2025 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. + +import unittest + +import numpy as np + +import paddle + + +class TestTensorConstructor(unittest.TestCase): + def setUp(self): + np.random.seed(2025) + paddle.seed(2025) + self.shape = [10, 20, 30] + + def test_construct_random_tensor_with_float32(self): + res = paddle.Tensor(*self.shape) + self.assertEqual(res.dtype, paddle.float32) + self.assertEqual(res.shape, self.shape) + + def test_construct_from_list(self): + x = np.random.random(size=self.shape) + res = paddle.Tensor(list(x)) + np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(res.dtype, paddle.float32) + + def test_construct_from_tuple(self): + x = np.random.random(size=self.shape) + res = paddle.Tensor(tuple(x)) + np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(res.dtype, paddle.float32) + + def test_empty_construct(self): + target = paddle.empty([0]) + res = paddle.Tensor() + self.assertEqual(res.shape, target.shape) + + +if __name__ == "__main__": + unittest.main() From 584e6837d4d2dcb84ad250ad2051fbb3c4093d8d Mon Sep 17 00:00:00 2001 From: zeroRains Date: Thu, 14 Aug 2025 22:10:27 +0800 Subject: [PATCH 02/23] fix the bug in stub --- python/paddle/__init__.py | 95 +++++++++++++------------------- python/paddle/tensor/creation.py | 28 ++++++++++ 2 files changed, 66 insertions(+), 57 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 60ae58a2944ff6..0b71bb5be215f3 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -50,6 +50,43 @@ monkey_patch_program() monkey_patch_dtype() +from .base.dataset import * # noqa: F403 +from .framework import ( + disable_signal_handler, + disable_static, + enable_static, + get_flags, + in_dynamic_mode, + set_flags, +) +from .framework.dtype import ( + bfloat16, + bool, + complex64, + complex128, + dtype, + finfo, + float8_e4m3fn, + float8_e5m2, + float16, + float32, + float64, + iinfo, + int8, + int16, + int32, + int64, + pstring, + raw, + uint8, +) + +if typing.TYPE_CHECKING: + from .tensor.tensor import Tensor +else: + Tensor = framework.core.eager.Tensor + Tensor.__qualname__ = 'Tensor' + import paddle.distributed.fleet import paddle.text import paddle.vision @@ -99,7 +136,6 @@ no_grad, set_grad_enabled, ) -from .base.dataset import * # noqa: F403 from .device import ( # noqa: F401 device_guard, get_cudnn_version, @@ -125,37 +161,10 @@ XPUPlace, async_save, clear_async_save_task_queue, - disable_signal_handler, - disable_static, - enable_static, get_default_dtype, - get_flags, - in_dynamic_mode, load, save, set_default_dtype, - set_flags, -) -from .framework.dtype import ( - bfloat16, - bool, - complex64, - complex128, - dtype, - finfo, - float8_e4m3fn, - float8_e5m2, - float16, - float32, - float64, - iinfo, - int8, - int16, - int32, - int64, - pstring, - raw, - uint8, ) from .framework.random import ( get_cuda_rng_state, @@ -184,6 +193,7 @@ ) from .tensor.creation import ( MmapStorage, + Tensor, arange, assign, cauchy_, @@ -595,35 +605,6 @@ to_dlpack, ) -if typing.TYPE_CHECKING: - from .tensor.tensor import Tensor -else: - - class Tensor(framework.core.eager.Tensor): - def __init__(self, *args, **kwargs): - kwargs_cnt = len(kwargs.keys()) - if kwargs_cnt: - super().__init__(*args, **kwargs) - return - if len(args) == 0: - super().__init__(empty(shape=[0], dtype="float32")) - return - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - super().__init__(to_tensor(args[0], dtype="float32")) - return - create_random_tensor = True - for arg in args: - if not isinstance(arg, int): - create_random_tensor = False - break - if create_random_tensor: - super().__init__(randn(list(args), dtype="float32")) - return - else: - super().__init__(*args, **kwargs) - - Tensor.__qualname__ = 'Tensor' - # CINN has to set a flag to include a lib if is_compiled_with_cinn(): import os diff --git a/python/paddle/tensor/creation.py b/python/paddle/tensor/creation.py index 55432ea9adcbaa..4de72f325cf410 100644 --- a/python/paddle/tensor/creation.py +++ b/python/paddle/tensor/creation.py @@ -987,6 +987,34 @@ def to_tensor( return _to_tensor_static(data, dtype, stop_gradient) +class Tensor(paddle.framework.core.eager.Tensor): + def __init__(self, *args, **kwargs): + kwargs_cnt = len(kwargs.keys()) + if kwargs_cnt: + super().__init__(*args, **kwargs) + return + if len(args) == 0: + super().__init__(paddle.empty(shape=[0], dtype="float32")) + return + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + super().__init__(paddle.to_tensor(args[0], dtype="float32")) + return + create_random_tensor = True + for arg in args: + if not isinstance(arg, int): + create_random_tensor = False + break + if create_random_tensor: + super().__init__(paddle.randn(list(args), dtype="float32")) + return + else: + super().__init__(*args, **kwargs) + + +Tensor.__qualname__ = 'Tensor' +Tensor.__doc__ = paddle.framework.core.eager.Tensor.__doc__ + + class MmapStorage(paddle.base.core.MmapStorage): """ This class will use mmap to load a file. From 1192f3d68487f65943f9958117f2662aa8b07945 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Sat, 16 Aug 2025 15:13:14 +0800 Subject: [PATCH 03/23] update the constructor --- python/paddle/__init__.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index a8aacecec62c64..de45df577521a5 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -86,6 +86,31 @@ else: Tensor = framework.core.eager.Tensor Tensor.__qualname__ = 'Tensor' + super_init = Tensor.__init__ + + def new_init(self, *args, **kwargs): + kwargs_cnt = len(kwargs.keys()) + if kwargs_cnt: + super_init(self, *args, **kwargs) + return + if len(args) == 0: + super_init(self, paddle.empty(shape=[0], dtype="float32")) + return + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + super_init(self, paddle.to_tensor(args[0], dtype="float32")) + return + create_random_tensor = True + for arg in args: + if not isinstance(arg, int): + create_random_tensor = False + break + if create_random_tensor: + super_init(self, paddle.randn(list(args), dtype="float32")) + return + else: + super_init(self, *args, **kwargs) + + Tensor.__init__ = new_init import paddle.distributed.fleet import paddle.text @@ -199,7 +224,6 @@ ) from .tensor.creation import ( MmapStorage, - Tensor, arange, assign, cauchy_, From 89267025c4ff8a8fd041de20f2c65f8c4bfd6ec4 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Sat, 16 Aug 2025 17:55:16 +0800 Subject: [PATCH 04/23] fix the bug in kwargs --- paddle/fluid/pybind/eager.cc | 2 +- python/paddle/tensor/creation.py | 28 ---------------------------- 2 files changed, 1 insertion(+), 29 deletions(-) diff --git a/paddle/fluid/pybind/eager.cc b/paddle/fluid/pybind/eager.cc index 1067c4e6854e3b..265e87343d4670 100644 --- a/paddle/fluid/pybind/eager.cc +++ b/paddle/fluid/pybind/eager.cc @@ -830,7 +830,7 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { SetPythonStack(); // set a flag to record use kwargs or not bool flag_kwargs = false; - if (kwargs) flag_kwargs = true; + if (kwargs && PyList_Size(PyDict_Keys(kwargs))) flag_kwargs = true; // all kwargs PyObject* kw_zero_copy = nullptr; diff --git a/python/paddle/tensor/creation.py b/python/paddle/tensor/creation.py index a3097d5a89a610..c537ef45d50984 100644 --- a/python/paddle/tensor/creation.py +++ b/python/paddle/tensor/creation.py @@ -987,34 +987,6 @@ def to_tensor( return _to_tensor_static(data, dtype, stop_gradient) -class Tensor(paddle.framework.core.eager.Tensor): - def __init__(self, *args, **kwargs): - kwargs_cnt = len(kwargs.keys()) - if kwargs_cnt: - super().__init__(*args, **kwargs) - return - if len(args) == 0: - super().__init__(paddle.empty(shape=[0], dtype="float32")) - return - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - super().__init__(paddle.to_tensor(args[0], dtype="float32")) - return - create_random_tensor = True - for arg in args: - if not isinstance(arg, int): - create_random_tensor = False - break - if create_random_tensor: - super().__init__(paddle.randn(list(args), dtype="float32")) - return - else: - super().__init__(*args, **kwargs) - - -Tensor.__qualname__ = 'Tensor' -Tensor.__doc__ = paddle.framework.core.eager.Tensor.__doc__ - - class MmapStorage(paddle.base.core.MmapStorage): """ This class will use mmap to load a file. From ad7803bcb3b60897e49bb6c37882306188ccc52f Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 18 Aug 2025 12:35:17 +0800 Subject: [PATCH 05/23] update --- python/paddle/__init__.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 13e6f5d675f9c4..6253ed0c58e241 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -110,13 +110,13 @@ def new_init(self, *args, **kwargs): elif len(args) == 1 and isinstance(args[0], (list, tuple)): super_init(self, paddle.to_tensor(args[0], dtype="float32")) return - create_random_tensor = True + with_shape_empty = True for arg in args: if not isinstance(arg, int): - create_random_tensor = False + with_shape_empty = False break - if create_random_tensor: - super_init(self, paddle.randn(list(args), dtype="float32")) + if with_shape_empty: + super_init(self, paddle.empty(list(args), dtype="float32")) return else: super_init(self, *args, **kwargs) From 48fe324a552e35172221d8a577efd2776888efbc Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 18 Aug 2025 20:32:17 +0800 Subject: [PATCH 06/23] change the flag name --- python/paddle/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 6253ed0c58e241..2b38170d66bb92 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -110,12 +110,12 @@ def new_init(self, *args, **kwargs): elif len(args) == 1 and isinstance(args[0], (list, tuple)): super_init(self, paddle.to_tensor(args[0], dtype="float32")) return - with_shape_empty = True + is_all_int = True for arg in args: if not isinstance(arg, int): - with_shape_empty = False + is_all_int = False break - if with_shape_empty: + if is_all_int: super_init(self, paddle.empty(list(args), dtype="float32")) return else: From c8cd7c10fee5032ba3e126c25e23bff8b643487d Mon Sep 17 00:00:00 2001 From: zeroRains Date: Tue, 19 Aug 2025 12:07:38 +0800 Subject: [PATCH 07/23] add [dtype]Tensor test --- test/legacy_test/test_tensor_constructor.py | 137 +++++++++++++++++++- 1 file changed, 132 insertions(+), 5 deletions(-) diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py index 44067616fa8f5d..c76159985732e7 100644 --- a/test/legacy_test/test_tensor_constructor.py +++ b/test/legacy_test/test_tensor_constructor.py @@ -25,11 +25,6 @@ def setUp(self): paddle.seed(2025) self.shape = [10, 20, 30] - def test_construct_random_tensor_with_float32(self): - res = paddle.Tensor(*self.shape) - self.assertEqual(res.dtype, paddle.float32) - self.assertEqual(res.shape, self.shape) - def test_construct_from_list(self): x = np.random.random(size=self.shape) res = paddle.Tensor(list(x)) @@ -47,6 +42,138 @@ def test_empty_construct(self): res = paddle.Tensor() self.assertEqual(res.shape, target.shape) + target = paddle.empty(self.shape, dtype=paddle.float32) + res = paddle.Tensor(*self.shape) + self.assertEqual(res.dtype, paddle.float32) + self.assertEqual(res.shape, self.shape) + + +class TestFloatTensor(unittest.TestCase): + def setUp(self): + np.random.seed(2025) + paddle.seed(2025) + self.shape = [10, 20, 30] + self.set_api_and_type() + + def set_api_and_type(self): + self.dtype = paddle.float32 + self.np_dtype = "float32" + self.api = paddle.FloatTensor + + def test_empty_construct(self): + target = paddle.empty([0], dtype=self.dtype) + res = self.api() + self.assertEqual(res.shape, target.shape) + + target = paddle.empty(self.shape, dtype=self.dtype) + res = self.api(*self.shape) + self.assertEqual(res.dtype, self.dtype) + self.assertEqual(res.shape, self.shape) + + def test_construct_from_list_and_tuple(self): + x = np.random.random(size=self.shape).astype(self.np_dtype) + res = self.api(tuple(x)) + np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(res.dtype, self.dtype) + res = self.api(list(x)) + np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(res.dtype, self.dtype) + + def test_construct_from_tensor_and_numpy(self): + x = np.random.random(size=self.shape).astype(self.np_dtype) + x_tensor = paddle.to_tensor(x, dtype=self.dtype) + res = self.api(x_tensor) + np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(res.dtype, self.dtype) + res = self.api(x) + np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(res.dtype, self.dtype) + + +class TestDoubleTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.float64 + self.np_dtype = "float64" + self.api = paddle.DoubleTensor + + +class TestHalfTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.float16 + self.np_dtype = "float16" + self.api = paddle.HalfTensor + + +class TestBFloat16Tensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.bfloat16 + self.np_dtype = "float16" + self.api = paddle.BFloat16Tensor + + def test_construct_from_list_and_tuple(self): + x = np.random.random(size=self.shape).astype(self.np_dtype) + x_target = paddle.to_tensor(x, dtype=self.dtype) + res = self.api(tuple(x)) + np.testing.assert_allclose( + x_target.numpy(), res.numpy(), rtol=1e-6, atol=1e-6 + ) + self.assertEqual(res.dtype, self.dtype) + res = self.api(list(x)) + np.testing.assert_allclose( + x_target.numpy(), res.numpy(), rtol=1e-6, atol=1e-6 + ) + self.assertEqual(res.dtype, self.dtype) + + def test_construct_from_tensor_and_numpy(self): + x_tensor = paddle.randn(self.shape, dtype=self.dtype) + res = self.api(x_tensor) + np.testing.assert_allclose( + x_tensor.numpy(), res.numpy(), rtol=1e-6, atol=1e-6 + ) + self.assertEqual(res.dtype, self.dtype) + + +class TestByteTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.uint8 + self.np_dtype = "uint8" + self.api = paddle.ByteTensor + + +class TestCharTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.int8 + self.np_dtype = "int8" + self.api = paddle.CharTensor + + +class TestShortTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.int16 + self.np_dtype = "int16" + self.api = paddle.ShortTensor + + +class TestIntTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.int32 + self.np_dtype = "int32" + self.api = paddle.IntTensor + + +class TestLongTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.int64 + self.np_dtype = "int64" + self.api = paddle.LongTensor + + +class TestBoolTensor(TestFloatTensor): + def set_api_and_type(self): + self.dtype = paddle.bool + self.np_dtype = "bool" + self.api = paddle.BoolTensor + if __name__ == "__main__": unittest.main() From 0755a40e876114b687b67066e9ab5c97b0344e77 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Wed, 20 Aug 2025 19:22:54 +0800 Subject: [PATCH 08/23] update --- python/paddle/__init__.py | 9 +++++---- python/paddle/tensor/creation.py | 11 ++--------- test/legacy_test/test_tensor_constructor.py | 5 +---- 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 31c4ea85156031..c11b64e407e983 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -101,14 +101,15 @@ def new_init(self, *args, **kwargs): kwargs_cnt = len(kwargs.keys()) - if kwargs_cnt: + default_dtype = kwargs.get("dtype", "float32") + if kwargs_cnt and not (kwargs_cnt == 1 and "dtype" in kwargs): super_init(self, *args, **kwargs) return if len(args) == 0: - super_init(self, paddle.empty(shape=[0], dtype="float32")) + super_init(self, paddle.empty(shape=[0], dtype=default_dtype)) return elif len(args) == 1 and isinstance(args[0], (list, tuple)): - super_init(self, paddle.to_tensor(args[0], dtype="float32")) + super_init(self, paddle.tensor(args[0], dtype=default_dtype)) return is_all_int = True for arg in args: @@ -116,7 +117,7 @@ def new_init(self, *args, **kwargs): is_all_int = False break if is_all_int: - super_init(self, paddle.empty(list(args), dtype="float32")) + super_init(self, paddle.empty(list(args), dtype=default_dtype)) return else: super_init(self, *args, **kwargs) diff --git a/python/paddle/tensor/creation.py b/python/paddle/tensor/creation.py index 83a8f050d60afd..4486e0944a07ce 100644 --- a/python/paddle/tensor/creation.py +++ b/python/paddle/tensor/creation.py @@ -4101,15 +4101,8 @@ def dtype_tensor_factory(dtype): class _DtypeTensorFactory: def __new__(cls, *args, **kwargs): - if len(args) == 0: - return paddle.empty(shape=[0], dtype=dtype) - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - return paddle.to_tensor(args[0], dtype=dtype) - elif all(isinstance(arg, int) for arg in args): - return paddle.empty(shape=list(args), dtype=dtype) - else: - kwargs.setdefault('dtype', dtype) - return paddle.Tensor(*args, **kwargs) + kwargs.setdefault('dtype', dtype) + return paddle.Tensor(*args, **kwargs) return _DtypeTensorFactory diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py index c76159985732e7..45d1b7f7a1fff6 100644 --- a/test/legacy_test/test_tensor_constructor.py +++ b/test/legacy_test/test_tensor_constructor.py @@ -25,14 +25,11 @@ def setUp(self): paddle.seed(2025) self.shape = [10, 20, 30] - def test_construct_from_list(self): + def test_construct_from_list_and_tuple(self): x = np.random.random(size=self.shape) res = paddle.Tensor(list(x)) np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) self.assertEqual(res.dtype, paddle.float32) - - def test_construct_from_tuple(self): - x = np.random.random(size=self.shape) res = paddle.Tensor(tuple(x)) np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) self.assertEqual(res.dtype, paddle.float32) From 7eb9d513a70b981f7f271095f1e683efa5fd3986 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Wed, 20 Aug 2025 21:21:58 +0800 Subject: [PATCH 09/23] update --- python/paddle/__init__.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index c11b64e407e983..ffa25b8854f139 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -102,25 +102,21 @@ def new_init(self, *args, **kwargs): kwargs_cnt = len(kwargs.keys()) default_dtype = kwargs.get("dtype", "float32") - if kwargs_cnt and not (kwargs_cnt == 1 and "dtype" in kwargs): - super_init(self, *args, **kwargs) - return - if len(args) == 0: - super_init(self, paddle.empty(shape=[0], dtype=default_dtype)) - return - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - super_init(self, paddle.tensor(args[0], dtype=default_dtype)) - return is_all_int = True for arg in args: if not isinstance(arg, int): is_all_int = False break - if is_all_int: + if kwargs_cnt and not (kwargs_cnt == 1 and "dtype" in kwargs): + super_init(self, *args, **kwargs) + elif len(args) == 0: + super_init(self, paddle.empty(shape=[0], dtype=default_dtype)) + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + super_init(self, paddle.tensor(args[0], dtype=default_dtype)) + elif is_all_int: super_init(self, paddle.empty(list(args), dtype=default_dtype)) - return else: - super_init(self, *args, **kwargs) + super_init(self, *args) Tensor.__init__ = new_init From 8e161d64a97ac750293df4cffddb9850bc90d222 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Thu, 21 Aug 2025 21:12:52 +0800 Subject: [PATCH 10/23] change to try except --- python/paddle/__init__.py | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index ffa25b8854f139..675b3ce8ea3a31 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -100,23 +100,25 @@ super_init = Tensor.__init__ def new_init(self, *args, **kwargs): - kwargs_cnt = len(kwargs.keys()) - default_dtype = kwargs.get("dtype", "float32") - is_all_int = True - for arg in args: - if not isinstance(arg, int): - is_all_int = False - break - if kwargs_cnt and not (kwargs_cnt == 1 and "dtype" in kwargs): + try: super_init(self, *args, **kwargs) - elif len(args) == 0: - super_init(self, paddle.empty(shape=[0], dtype=default_dtype)) - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - super_init(self, paddle.tensor(args[0], dtype=default_dtype)) - elif is_all_int: - super_init(self, paddle.empty(list(args), dtype=default_dtype)) - else: - super_init(self, *args) + except Exception as e: + default_dtype = kwargs.get("dtype", "float32") + if len(args) == 0: + super_init(self, paddle.empty(shape=[0], dtype=default_dtype)) + return + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + super_init(self, paddle.tensor(args[0], dtype=default_dtype)) + return + is_all_int = True + for arg in args: + if not isinstance(arg, int): + is_all_int = False + break + if is_all_int: + super_init(self, paddle.empty(list(args), dtype=default_dtype)) + return + raise ValueError(e) Tensor.__init__ = new_init From 37806b9771300506dda775880248cdc88ca52919 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Fri, 22 Aug 2025 11:20:09 +0800 Subject: [PATCH 11/23] add the test case in raise --- test/legacy_test/test_tensor_constructor.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py index 45d1b7f7a1fff6..56f4ba9ddca3e6 100644 --- a/test/legacy_test/test_tensor_constructor.py +++ b/test/legacy_test/test_tensor_constructor.py @@ -44,6 +44,11 @@ def test_empty_construct(self): self.assertEqual(res.dtype, paddle.float32) self.assertEqual(res.shape, self.shape) + def test_error_construct(self): + with self.assertRaises(ValueError): + a = paddle.tensor([1]) + paddle.Tensor(1, 2, 3, a) + class TestFloatTensor(unittest.TestCase): def setUp(self): @@ -86,6 +91,11 @@ def test_construct_from_tensor_and_numpy(self): np.testing.assert_allclose(x, res.numpy(), rtol=1e-6, atol=1e-6) self.assertEqual(res.dtype, self.dtype) + def test_error_construct(self): + with self.assertRaises(ValueError): + a = paddle.tensor([1]) + self.api(1, 2, 3, a) + class TestDoubleTensor(TestFloatTensor): def set_api_and_type(self): From 3789759a187076bcb8bacef34b6f9036deee94b3 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 11:05:29 +0800 Subject: [PATCH 12/23] update name --- python/paddle/__init__.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 675b3ce8ea3a31..40e28c6da78388 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -97,18 +97,20 @@ else: Tensor = framework.core.eager.Tensor Tensor.__qualname__ = 'Tensor' - super_init = Tensor.__init__ + original_init = Tensor.__init__ def new_init(self, *args, **kwargs): try: - super_init(self, *args, **kwargs) + original_init(self, *args, **kwargs) except Exception as e: default_dtype = kwargs.get("dtype", "float32") if len(args) == 0: - super_init(self, paddle.empty(shape=[0], dtype=default_dtype)) + original_init( + self, paddle.empty(shape=[0], dtype=default_dtype) + ) return elif len(args) == 1 and isinstance(args[0], (list, tuple)): - super_init(self, paddle.tensor(args[0], dtype=default_dtype)) + original_init(self, paddle.tensor(args[0], dtype=default_dtype)) return is_all_int = True for arg in args: @@ -116,7 +118,9 @@ def new_init(self, *args, **kwargs): is_all_int = False break if is_all_int: - super_init(self, paddle.empty(list(args), dtype=default_dtype)) + original_init( + self, paddle.empty(list(args), dtype=default_dtype) + ) return raise ValueError(e) From 6da909f1e24c12cbcc8dc6165149993204e06bb0 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 14:33:07 +0800 Subject: [PATCH 13/23] fix the bug in new construct --- python/paddle/__init__.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 24fd2d6419dede..db97fcbf7fd50f 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -103,6 +103,9 @@ def new_init(self, *args, **kwargs): try: original_init(self, *args, **kwargs) except Exception as e: + kwargs_cnt = len(kwargs) - int("dtype" in kwargs) + if kwargs_cnt: + raise ValueError(e) default_dtype = kwargs.get("dtype", "float32") if len(args) == 0: original_init( From 2632d10bfd75b57ee6ed3fd1303daccb5018e0ef Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 19:40:37 +0800 Subject: [PATCH 14/23] change to origin method --- python/paddle/__init__.py | 44 +++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index e9710ffa4b665f..b3f53c9bdb47a4 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -100,32 +100,26 @@ original_init = Tensor.__init__ def new_init(self, *args, **kwargs): - try: + kwargs_cnt = len(kwargs.keys()) - int("dtype" in kwargs) + if kwargs_cnt > 1: original_init(self, *args, **kwargs) - except Exception as e: - kwargs_cnt = len(kwargs) - int("dtype" in kwargs) - if kwargs_cnt: - raise ValueError(e) - default_dtype = kwargs.get("dtype", "float32") - if len(args) == 0: - original_init( - self, paddle.empty(shape=[0], dtype=default_dtype) - ) - return - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - original_init(self, paddle.tensor(args[0], dtype=default_dtype)) - return - is_all_int = True - for arg in args: - if not isinstance(arg, int): - is_all_int = False - break - if is_all_int: - original_init( - self, paddle.empty(list(args), dtype=default_dtype) - ) - return - raise ValueError(e) + return + default_dtype = kwargs.get("dtype", "float32") + if len(args) == 0: + original_init(self, paddle.empty(shape=[0], dtype=default_dtype)) + return + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + original_init(self, paddle.tensor(args[0], dtype=default_dtype)) + return + is_all_int = True + for arg in args: + if not isinstance(arg, int): + is_all_int = False + break + if is_all_int: + original_init(self, paddle.empty(list(args), dtype=default_dtype)) + else: + original_init(self, *args) Tensor.__init__ = new_init From 63f28b8f3bb65cfb82e9f16507388ec230f4ad7d Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 20:18:46 +0800 Subject: [PATCH 15/23] fix bug --- python/paddle/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index b3f53c9bdb47a4..a369029c19d7b5 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -101,7 +101,7 @@ def new_init(self, *args, **kwargs): kwargs_cnt = len(kwargs.keys()) - int("dtype" in kwargs) - if kwargs_cnt > 1: + if kwargs_cnt: original_init(self, *args, **kwargs) return default_dtype = kwargs.get("dtype", "float32") From 822fadb7773bf5d4bff2c3049c0f564e277b5e16 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 21:13:27 +0800 Subject: [PATCH 16/23] update --- paddle/fluid/pybind/eager.cc | 9 ++++++--- python/paddle/__init__.py | 19 +++++++------------ python/paddle/tensor/creation.py | 11 +++++++++-- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/paddle/fluid/pybind/eager.cc b/paddle/fluid/pybind/eager.cc index 265e87343d4670..c2970e9b2d235a 100644 --- a/paddle/fluid/pybind/eager.cc +++ b/paddle/fluid/pybind/eager.cc @@ -845,6 +845,7 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { PyObject* kw_type = nullptr; PyObject* kw_process_mesh = nullptr; PyObject* kw_placements = nullptr; + PyObject* kw_device = nullptr; // the keywords argument static char* kwlist[] = {const_cast("value"), // NOLINT @@ -858,6 +859,7 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { const_cast("type"), const_cast("process_mesh"), const_cast("placements"), + const_cast("device"), nullptr}; // 'O' Store a Python object (without any conversion) in a C object pointer, @@ -868,7 +870,7 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { // which enhance case2, case3, case4, case5, case6, case7. bool flag_ = PyArg_ParseTupleAndKeywords(args, kwargs, - "|OOOOOOOOOOO", + "|OOOOOOOOOOOO", kwlist, &kw_value, &kw_place, @@ -880,8 +882,9 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { &kw_dtype, &kw_type, &kw_process_mesh, - &kw_placements); - + &kw_placements, + &kw_device); + kw_place = kw_place ? kw_place : kw_device; // helper map std::unordered_map kws_map{ {"value", kw_value}, diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index a369029c19d7b5..b565bd88b236e4 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -100,24 +100,19 @@ original_init = Tensor.__init__ def new_init(self, *args, **kwargs): - kwargs_cnt = len(kwargs.keys()) - int("dtype" in kwargs) - if kwargs_cnt: - original_init(self, *args, **kwargs) - return - default_dtype = kwargs.get("dtype", "float32") - if len(args) == 0: - original_init(self, paddle.empty(shape=[0], dtype=default_dtype)) + if len(args) + len(kwargs.keys()) == 0: + original_init(self, paddle.empty(shape=[0], dtype="float32")) return elif len(args) == 1 and isinstance(args[0], (list, tuple)): - original_init(self, paddle.tensor(args[0], dtype=default_dtype)) + original_init(self, paddle.tensor(args[0], dtype="float32")) return - is_all_int = True + args_is_all_int = True for arg in args: if not isinstance(arg, int): - is_all_int = False + args_is_all_int = False break - if is_all_int: - original_init(self, paddle.empty(list(args), dtype=default_dtype)) + if args_is_all_int: + original_init(self, paddle.empty(list(args), dtype="float32")) else: original_init(self, *args) diff --git a/python/paddle/tensor/creation.py b/python/paddle/tensor/creation.py index 26e56f7397da70..ec9346e5cf8ce6 100644 --- a/python/paddle/tensor/creation.py +++ b/python/paddle/tensor/creation.py @@ -3926,8 +3926,15 @@ def resize_( def dtype_tensor_factory(dtype): class _DtypeTensorFactory: def __new__(cls, *args, **kwargs): - kwargs.setdefault('dtype', dtype) - return paddle.Tensor(*args, **kwargs) + if len(args) == 0: + return paddle.empty(shape=[0], dtype=dtype) + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + return paddle.to_tensor(args[0], dtype=dtype) + elif all(isinstance(arg, int) for arg in args): + return paddle.empty(shape=list(args), dtype=dtype) + else: + kwargs.setdefault('dtype', dtype) + return paddle.Tensor(*args, **kwargs) return _DtypeTensorFactory From 52d8b99b4a05513e1e43f6ab525058dfcd9b02de Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 21:18:10 +0800 Subject: [PATCH 17/23] update --- python/paddle/__init__.py | 2 +- test/legacy_test/test_tensor_constructor.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index b565bd88b236e4..bad0542ba853c5 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -114,7 +114,7 @@ def new_init(self, *args, **kwargs): if args_is_all_int: original_init(self, paddle.empty(list(args), dtype="float32")) else: - original_init(self, *args) + original_init(self, *args, **kwargs) Tensor.__init__ = new_init diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py index 56f4ba9ddca3e6..11c981a0454922 100644 --- a/test/legacy_test/test_tensor_constructor.py +++ b/test/legacy_test/test_tensor_constructor.py @@ -25,6 +25,10 @@ def setUp(self): paddle.seed(2025) self.shape = [10, 20, 30] + def test_device(self): + x = paddle.Tensor([1, 2, 3], device="cpu") + self.assertEqual(x.place, paddle.CPUPlace()) + def test_construct_from_list_and_tuple(self): x = np.random.random(size=self.shape) res = paddle.Tensor(list(x)) From 912c5c355fa856c7240048f6105903bd271155f3 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 21:38:22 +0800 Subject: [PATCH 18/23] update --- python/paddle/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index bad0542ba853c5..f14d738e06d175 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -101,10 +101,14 @@ def new_init(self, *args, **kwargs): if len(args) + len(kwargs.keys()) == 0: - original_init(self, paddle.empty(shape=[0], dtype="float32")) + original_init( + self, paddle.empty(shape=[0], dtype="float32"), **kwargs + ) return elif len(args) == 1 and isinstance(args[0], (list, tuple)): - original_init(self, paddle.tensor(args[0], dtype="float32")) + original_init( + self, paddle.tensor(args[0], dtype="float32"), **kwargs + ) return args_is_all_int = True for arg in args: @@ -112,7 +116,9 @@ def new_init(self, *args, **kwargs): args_is_all_int = False break if args_is_all_int: - original_init(self, paddle.empty(list(args), dtype="float32")) + original_init( + self, paddle.empty(list(args), dtype="float32"), **kwargs + ) else: original_init(self, *args, **kwargs) From e89929b15479aa4c1c2ebdbae687a2b196c88800 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Mon, 25 Aug 2025 23:18:11 +0800 Subject: [PATCH 19/23] remove device --- paddle/fluid/pybind/eager.cc | 9 +++------ python/paddle/__init__.py | 12 +++--------- test/legacy_test/test_tensor_constructor.py | 4 ---- 3 files changed, 6 insertions(+), 19 deletions(-) diff --git a/paddle/fluid/pybind/eager.cc b/paddle/fluid/pybind/eager.cc index c2970e9b2d235a..265e87343d4670 100644 --- a/paddle/fluid/pybind/eager.cc +++ b/paddle/fluid/pybind/eager.cc @@ -845,7 +845,6 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { PyObject* kw_type = nullptr; PyObject* kw_process_mesh = nullptr; PyObject* kw_placements = nullptr; - PyObject* kw_device = nullptr; // the keywords argument static char* kwlist[] = {const_cast("value"), // NOLINT @@ -859,7 +858,6 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { const_cast("type"), const_cast("process_mesh"), const_cast("placements"), - const_cast("device"), nullptr}; // 'O' Store a Python object (without any conversion) in a C object pointer, @@ -870,7 +868,7 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { // which enhance case2, case3, case4, case5, case6, case7. bool flag_ = PyArg_ParseTupleAndKeywords(args, kwargs, - "|OOOOOOOOOOOO", + "|OOOOOOOOOOO", kwlist, &kw_value, &kw_place, @@ -882,9 +880,8 @@ int TensorInit(PyObject* self, PyObject* args, PyObject* kwargs) { &kw_dtype, &kw_type, &kw_process_mesh, - &kw_placements, - &kw_device); - kw_place = kw_place ? kw_place : kw_device; + &kw_placements); + // helper map std::unordered_map kws_map{ {"value", kw_value}, diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index f14d738e06d175..bad0542ba853c5 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -101,14 +101,10 @@ def new_init(self, *args, **kwargs): if len(args) + len(kwargs.keys()) == 0: - original_init( - self, paddle.empty(shape=[0], dtype="float32"), **kwargs - ) + original_init(self, paddle.empty(shape=[0], dtype="float32")) return elif len(args) == 1 and isinstance(args[0], (list, tuple)): - original_init( - self, paddle.tensor(args[0], dtype="float32"), **kwargs - ) + original_init(self, paddle.tensor(args[0], dtype="float32")) return args_is_all_int = True for arg in args: @@ -116,9 +112,7 @@ def new_init(self, *args, **kwargs): args_is_all_int = False break if args_is_all_int: - original_init( - self, paddle.empty(list(args), dtype="float32"), **kwargs - ) + original_init(self, paddle.empty(list(args), dtype="float32")) else: original_init(self, *args, **kwargs) diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py index 11c981a0454922..56f4ba9ddca3e6 100644 --- a/test/legacy_test/test_tensor_constructor.py +++ b/test/legacy_test/test_tensor_constructor.py @@ -25,10 +25,6 @@ def setUp(self): paddle.seed(2025) self.shape = [10, 20, 30] - def test_device(self): - x = paddle.Tensor([1, 2, 3], device="cpu") - self.assertEqual(x.place, paddle.CPUPlace()) - def test_construct_from_list_and_tuple(self): x = np.random.random(size=self.shape) res = paddle.Tensor(list(x)) From dd0e6762a93dc85c147612453689686b905e0bc8 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Tue, 26 Aug 2025 12:48:34 +0800 Subject: [PATCH 20/23] fix the bug in args_is_all_int --- python/paddle/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index bad0542ba853c5..488e341c28464e 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -111,7 +111,7 @@ def new_init(self, *args, **kwargs): if not isinstance(arg, int): args_is_all_int = False break - if args_is_all_int: + if args_is_all_int and len(kwargs) == 0: original_init(self, paddle.empty(list(args), dtype="float32")) else: original_init(self, *args, **kwargs) From d0ae7b6387844c36ec37a2c534ebfd1e87c907a6 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Tue, 26 Aug 2025 22:22:04 +0800 Subject: [PATCH 21/23] support new constructor use kwargs --- python/paddle/__init__.py | 57 ++++++++++++++++----- test/legacy_test/test_tensor_constructor.py | 16 ++++++ 2 files changed, 60 insertions(+), 13 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 488e341c28464e..4bcc5f9b391944 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -95,26 +95,57 @@ if typing.TYPE_CHECKING: from .tensor.tensor import Tensor else: + import builtins + Tensor = framework.core.eager.Tensor Tensor.__qualname__ = 'Tensor' original_init = Tensor.__init__ def new_init(self, *args, **kwargs): - if len(args) + len(kwargs.keys()) == 0: - original_init(self, paddle.empty(shape=[0], dtype="float32")) - return - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - original_init(self, paddle.tensor(args[0], dtype="float32")) + """ + New Usage Example: + 1. paddle.Tensor() + 2. paddle.Tensor(device="cpu") + 3. paddle.Tensor(1,2,3) + 4. paddle.Tensor(1,2,3, device="cpu") + 5. paddle.Tensor([1,2,3]) + 6. paddle.Tensor([1,2,3], device="cpu") + 7. paddle.Tensor(data=[1,2,3]) + 8. paddle.Tensor(data=[1,2,3], device="cpu") + Original Usage Example: + 9. paddle.Tensor(value=data, place="cpu", persistable=False, zero_copy=False, name=None, stop_gradient=True) + """ + device = "cpu" + if 'device' in kwargs: + device = kwargs.pop('device') + device = framework._get_paddle_place(device) + if len(args) == 0 and len(kwargs) == 0: # case 1, 2 + original_init( + self, paddle.empty(shape=[0], dtype='float32'), place=device + ) return - args_is_all_int = True - for arg in args: - if not isinstance(arg, int): - args_is_all_int = False - break - if args_is_all_int and len(kwargs) == 0: - original_init(self, paddle.empty(list(args), dtype="float32")) - else: + try: original_init(self, *args, **kwargs) + except Exception as e: + if 'data' in kwargs: # case 7,8 + data = kwargs.pop('data') + original_init( + self, paddle.tensor(data, dtype='float32'), place=device + ) + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + # case 5, 6 + original_init( + self, paddle.tensor(args[0], dtype='float32'), place=device + ) + elif builtins.all(isinstance(arg, int) for arg in args): + # case 3, 4 + original_init( + self, + paddle.empty(shape=list(args), dtype='float32'), + place=device, + ) + else: + raise e Tensor.__init__ = new_init diff --git a/test/legacy_test/test_tensor_constructor.py b/test/legacy_test/test_tensor_constructor.py index 56f4ba9ddca3e6..25b1d0633284df 100644 --- a/test/legacy_test/test_tensor_constructor.py +++ b/test/legacy_test/test_tensor_constructor.py @@ -49,6 +49,22 @@ def test_error_construct(self): a = paddle.tensor([1]) paddle.Tensor(1, 2, 3, a) + def test_kwargs(self): + x1 = paddle.Tensor(device="cpu") + self.assertEqual(x1.place, paddle.CPUPlace()) + x2 = paddle.Tensor(*self.shape, device="cpu") + self.assertEqual(x2.place, paddle.CPUPlace()) + + x = np.random.random(size=self.shape) + x3 = paddle.Tensor(data=x) + np.testing.assert_allclose(x, x3.numpy(), rtol=1e-6, atol=1e-6) + x4 = paddle.Tensor(list(x), device="cpu") + x5 = paddle.Tensor(data=list(x), device="cpu") + np.testing.assert_allclose(x4.numpy(), x5.numpy(), rtol=1e-6, atol=1e-6) + np.testing.assert_allclose(x, x4.numpy(), rtol=1e-6, atol=1e-6) + self.assertEqual(x4.place, x5.place) + self.assertEqual(x4.place, paddle.CPUPlace()) + class TestFloatTensor(unittest.TestCase): def setUp(self): From 40739c31e7629b75ddbab4dbde0ef6639fe69d1d Mon Sep 17 00:00:00 2001 From: zeroRains Date: Wed, 27 Aug 2025 09:47:38 +0800 Subject: [PATCH 22/23] update --- python/paddle/__init__.py | 42 +++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index 4bcc5f9b391944..a1d68d9e0d77ef 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -124,28 +124,28 @@ def new_init(self, *args, **kwargs): self, paddle.empty(shape=[0], dtype='float32'), place=device ) return - try: + if 'data' in kwargs: # case 7,8 + data = kwargs.pop('data') + original_init( + self, paddle.tensor(data, dtype='float32'), place=device + ) + elif len(args) == 1 and isinstance(args[0], (list, tuple)): + # case 5, 6 + original_init( + self, paddle.tensor(args[0], dtype='float32'), place=device + ) + elif ( + builtins.all(isinstance(arg, int) for arg in args) + and len(kwargs) == 0 + ): + # case 3, 4 + original_init( + self, + paddle.empty(shape=list(args), dtype='float32'), + place=device, + ) + else: original_init(self, *args, **kwargs) - except Exception as e: - if 'data' in kwargs: # case 7,8 - data = kwargs.pop('data') - original_init( - self, paddle.tensor(data, dtype='float32'), place=device - ) - elif len(args) == 1 and isinstance(args[0], (list, tuple)): - # case 5, 6 - original_init( - self, paddle.tensor(args[0], dtype='float32'), place=device - ) - elif builtins.all(isinstance(arg, int) for arg in args): - # case 3, 4 - original_init( - self, - paddle.empty(shape=list(args), dtype='float32'), - place=device, - ) - else: - raise e Tensor.__init__ = new_init From a50e23b89fe4c98403fe0a6a2e5c3eedd9fcd083 Mon Sep 17 00:00:00 2001 From: zeroRains Date: Wed, 27 Aug 2025 15:48:43 +0800 Subject: [PATCH 23/23] update --- python/paddle/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index a1d68d9e0d77ef..f180e0a1fde0c0 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -115,9 +115,10 @@ def new_init(self, *args, **kwargs): Original Usage Example: 9. paddle.Tensor(value=data, place="cpu", persistable=False, zero_copy=False, name=None, stop_gradient=True) """ - device = "cpu" if 'device' in kwargs: device = kwargs.pop('device') + else: + device = "cpu" device = framework._get_paddle_place(device) if len(args) == 0 and len(kwargs) == 0: # case 1, 2 original_init(