Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
e199b92
Support more construction method for paddle.Tensor
zeroRains Aug 14, 2025
584e683
fix the bug in stub
zeroRains Aug 14, 2025
0ed5ade
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 15, 2025
1192f3d
update the constructor
zeroRains Aug 16, 2025
85eef13
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 16, 2025
8926702
fix the bug in kwargs
zeroRains Aug 16, 2025
ad7803b
update
zeroRains Aug 18, 2025
48fe324
change the flag name
zeroRains Aug 18, 2025
1b501a3
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 18, 2025
66fb8b1
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 19, 2025
c8cd7c1
add [dtype]Tensor test
zeroRains Aug 19, 2025
2efd947
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 20, 2025
0755a40
update
zeroRains Aug 20, 2025
7eb9d51
update
zeroRains Aug 20, 2025
12ed6fa
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 21, 2025
8e161d6
change to try except
zeroRains Aug 21, 2025
37806b9
add the test case in raise
zeroRains Aug 22, 2025
3789759
update name
zeroRains Aug 25, 2025
b8611a2
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 25, 2025
98859bb
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 25, 2025
6da909f
fix the bug in new construct
zeroRains Aug 25, 2025
0285607
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zeroRains Aug 25, 2025
2632d10
change to origin method
zeroRains Aug 25, 2025
63f28b8
fix bug
zeroRains Aug 25, 2025
822fadb
update
zeroRains Aug 25, 2025
52d8b99
update
zeroRains Aug 25, 2025
912c5c3
update
zeroRains Aug 25, 2025
e89929b
remove device
zeroRains Aug 25, 2025
dd0e676
fix the bug in args_is_all_int
zeroRains Aug 26, 2025
d0ae7b6
support new constructor use kwargs
zeroRains Aug 26, 2025
40739c3
update
zeroRains Aug 27, 2025
a50e23b
update
zeroRains Aug 27, 2025
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
2 changes: 1 addition & 1 deletion paddle/fluid/pybind/eager.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
52 changes: 52 additions & 0 deletions python/paddle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,60 @@
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):
"""
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)
"""
if 'device' in kwargs:
Copy link
Contributor

Choose a reason for hiding this comment

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

if 'device' in kwargs:
    place = kwargs.pop('device')
else:
    place = "cpu"

device = kwargs.pop('device')
else:
device = "cpu"
device = framework._get_paddle_place(device)
Copy link
Contributor

Choose a reason for hiding this comment

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

这个后面的函数都应该支持字符串的传入,如果不支持需要对后面API进行改造。这里节省一个操作吧

Copy link
Contributor Author

Choose a reason for hiding this comment

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

这个是最下层的Tensor了,original_init是c++ 的方法这个操作省不了

if len(args) == 0 and len(kwargs) == 0: # case 1, 2
original_init(
self, paddle.empty(shape=[0], dtype='float32'), place=device
)
return
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)

Tensor.__init__ = new_init

import paddle.distributed.fleet
import paddle.text
Expand Down
202 changes: 202 additions & 0 deletions test/legacy_test/test_tensor_constructor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
# 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_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)
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)

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)

def test_error_construct(self):
with self.assertRaises(ValueError):
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):
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)

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):
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()
Loading