-
Notifications
You must be signed in to change notification settings - Fork 6k
[API compatibility] Add Tensor.is_cuda and paddle.Size #75043
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e345bdc
[API compatibility] Add Tensor.is_cuda and paddle.Size
zhanghonggeng 4e2cf72
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zhanghonggeng 272f1fb
update
zhanghonggeng 25ec0ad
Update python/paddle/pir/math_op_patch.py
zhanghonggeng 9f80941
add shape_wrapped
zhanghonggeng 750b967
Merge branch 'develop' of https://github.com/PaddlePaddle/Paddle into…
zhanghonggeng 5c675be
update
zhanghonggeng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| # 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 functools | ||
| from collections.abc import Iterable, Sequence | ||
|
|
||
|
|
||
| class Size(tuple): | ||
| """The result type of a call to ``paddle.Tensor.size()``. | ||
| It describes the size of all dimensions of the original tensor. As a subclass of tuple, | ||
| it supports all common sequence operations like indexing, slicing, concatenation, etc. | ||
|
|
||
| Args: | ||
| *args: Either a sequence of integers or multiple integer arguments representing dimensions. | ||
|
|
||
| Returns: | ||
| Size: A special tuple subclass representing tensor dimensions. | ||
|
|
||
| Examples: | ||
| .. code-block:: python | ||
|
|
||
| >>> import paddle | ||
| >>> size = paddle.Size([2, 3, 4]) | ||
| >>> print(size) | ||
| paddle.Size([2, 3, 4]) | ||
| """ | ||
|
|
||
| def __new__(cls, *args, **kwargs): | ||
| if len(args) == 1 and isinstance(args[0], Sequence): | ||
| seq = args[0] | ||
| else: | ||
| seq = args | ||
|
|
||
| if len(seq) == 1 and hasattr(seq[0], 'ndim') and seq[0].ndim == 1: | ||
| seq = seq[0].tolist() | ||
|
|
||
| converted = [] | ||
| for item in seq: | ||
| if hasattr(item, '__index__'): | ||
| converted.append(int(item.__index__())) | ||
| else: | ||
| raise TypeError( | ||
| f"paddle.Size() takes an iterable of 'int' (got {type(item).__name__})" | ||
| ) | ||
|
|
||
| return super().__new__(cls, converted) | ||
|
|
||
| def __repr__(self): | ||
| if not self: | ||
| return "paddle.Size([])" | ||
| return f"paddle.Size([{', '.join(map(str, self))}])" | ||
|
|
||
| def __add__(self, other: Iterable): | ||
| if isinstance(other, (tuple)): | ||
| return Size(super().__add__(tuple(other))) | ||
| raise TypeError( | ||
| f"can only concatenate tuple (not {type(other).__name__}) to Size" | ||
| ) | ||
|
|
||
| def __radd__(self, other: Iterable): | ||
| if isinstance(other, (tuple)): | ||
| return Size(tuple(other).__add__(self)) | ||
| raise TypeError( | ||
| f"can only concatenate tuple (not {type(other).__name__}) to Size" | ||
| ) | ||
|
|
||
| def __mul__(self, other: Iterable): | ||
| if isinstance(other, int): | ||
| return Size(super().__mul__(other)) | ||
| return NotImplemented | ||
|
|
||
| __rmul__ = __mul__ | ||
|
|
||
| def numel(self): | ||
| return functools.reduce(lambda x, y: x * y, self, 1) | ||
|
|
||
| def __reduce__(self): | ||
| return (Size, (tuple(self),)) | ||
|
|
||
| def __concat__(self, other: Iterable): | ||
| if not isinstance(other, (tuple, Size)): | ||
| raise TypeError( | ||
| f"can only concatenate tuple (not {type(other).__name__}) to paddle.Size" | ||
| ) | ||
| return self + other | ||
|
|
||
| def __getitem__(self, key): | ||
| from builtins import slice | ||
|
|
||
| result = super().__getitem__(key) | ||
| if isinstance(key, slice): | ||
| return Size(result) | ||
| return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| # 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 TestPaddleSize(unittest.TestCase): | ||
| # TODO: enable when paddle.Tensor.size() is implemented | ||
| # def test_tensor_size(self): | ||
| # x = paddle.empty(3, 4, 5) | ||
| # size = x.size() | ||
| # self.assertEqual(size, (3, 4, 5)) | ||
| # self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| # int_size = x.size(dim=1) | ||
| # self.assertEqual(int_size, 3) | ||
| # self.assertIsInstance(int_size, int) | ||
|
|
||
| def test_creation_size(self): | ||
| size = paddle.Size() | ||
| self.assertEqual(size, ()) | ||
| self.assertIsInstance(size, tuple) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| size = paddle.Size([2, 3, 4]) | ||
| self.assertEqual(size, (2, 3, 4)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| size = paddle.Size((2, 3, 4)) | ||
| self.assertEqual(size, (2, 3, 4)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| tensor1 = paddle.to_tensor(2) | ||
| tensor2 = paddle.to_tensor(3) | ||
| size = paddle.Size([tensor1, tensor2]) | ||
| self.assertEqual(size, (2, 3)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| tensor3 = paddle.to_tensor([2, 3]) | ||
| size = paddle.Size(tensor3) | ||
| self.assertEqual(size, (2, 3)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| size = paddle.Size([True, False]) | ||
| self.assertEqual(size, (1, 0)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| size = paddle.Size([np.int64(8), np.int64(8)]) | ||
| self.assertEqual(size, (8, 8)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| def test_creation_invalid_type(self): | ||
| with self.assertRaises(TypeError): | ||
| paddle.Size([1.5, 2.5]) # float not allowed | ||
| with self.assertRaises(TypeError): | ||
| paddle.Size(["a", "b"]) # string not allowed | ||
|
|
||
| def test_creation_from_mixed_types(self): | ||
| size = paddle.Size([1, paddle.to_tensor(2), 3]) | ||
| self.assertEqual(size, (1, 2, 3)) | ||
| self.assertIsInstance(size, paddle.Size) | ||
|
|
||
| def test_getitem_int(self): | ||
| size = paddle.Size([2, 3, 4]) | ||
| self.assertEqual(size[0], 2) | ||
| self.assertEqual(size[1], 3) | ||
| self.assertEqual(size[2], 4) | ||
| self.assertIsInstance(size[0], int) | ||
|
|
||
| def test_getitem_slice(self): | ||
| size = paddle.Size([2, 3, 4, 5]) | ||
| sliced = size[1:3] | ||
| self.assertEqual(sliced, (3, 4)) | ||
| self.assertIsInstance(sliced, paddle.Size) | ||
|
|
||
| def test_addition(self): | ||
| size1 = paddle.Size([2, 3]) | ||
| size2 = (4, 5) | ||
| result = size1 + size2 | ||
| self.assertEqual(result, (2, 3, 4, 5)) | ||
| self.assertIsInstance(result, paddle.Size) | ||
|
|
||
| def test_raddition(self): | ||
| size1 = paddle.Size([2, 3]) | ||
| size2 = (4, 5) | ||
| result = size2 + size1 | ||
| self.assertEqual(result, (4, 5, 2, 3)) | ||
| self.assertIsInstance(result, paddle.Size) | ||
|
|
||
| def test_addition_invalid_type(self): | ||
| size = paddle.Size([2, 3]) | ||
| with self.assertRaises(TypeError): | ||
| size + "abc" # string not allowed | ||
|
|
||
| def test_multiplication(self): | ||
| size = paddle.Size([2, 3]) | ||
| result = size * 2 | ||
| self.assertEqual(result, (2, 3, 2, 3)) | ||
| self.assertIsInstance(result, paddle.Size) | ||
|
|
||
| def test_rmultiplication(self): | ||
| size = paddle.Size([2, 3]) | ||
| result = 2 * size | ||
| self.assertEqual(result, (2, 3, 2, 3)) | ||
| self.assertIsInstance(result, paddle.Size) | ||
|
|
||
| def test_multiplication_invalid_type(self): | ||
| size = paddle.Size([2, 3]) | ||
| with self.assertRaises(TypeError): | ||
| size * 2.5 # float not allowed | ||
| with self.assertRaises(TypeError): | ||
| size * "a" # string not allowed | ||
|
|
||
| def test_repr(self): | ||
| size = paddle.Size([2, 3, 4]) | ||
| self.assertEqual(repr(size), "paddle.Size([2, 3, 4])") | ||
| self.assertEqual(str(size), "paddle.Size([2, 3, 4])") | ||
|
|
||
| def test_numel(self): | ||
| size = paddle.Size([2, 3, 4]) | ||
| self.assertEqual(size.numel(), 24) # 2*3*4=24 | ||
|
|
||
| def test_empty_size_numel(self): | ||
| size = paddle.Size([]) | ||
| self.assertEqual(size.numel(), 1) # Empty size has numel=1 | ||
|
|
||
| def test_concat_method(self): | ||
| size1 = paddle.Size([1, 2]) | ||
| size2 = (3, 4) | ||
| result = size1.__concat__(size2) | ||
| self.assertEqual(result, (1, 2, 3, 4)) | ||
| self.assertIsInstance(result, paddle.Size) | ||
|
|
||
| def test_concat_invalid_type(self): | ||
| size = paddle.Size([1, 2]) | ||
| with self.assertRaises(TypeError): | ||
| size.__concat__("invalid") # string not allowed | ||
|
|
||
| def test_reduce(self): | ||
| size = paddle.Size([2, 3]) | ||
| reduced = size.__reduce__() | ||
| self.assertEqual(reduced, (paddle.Size, ((2, 3),))) | ||
| # Test reconstruction | ||
| new_size = reduced[0](*reduced[1]) | ||
| self.assertEqual(new_size, size) | ||
| self.assertIsInstance(new_size, paddle.Size) | ||
|
|
||
| def test_count_index(self): | ||
| x = paddle.Size([2, 3]).count(2) | ||
| y = paddle.Size([2, 3]).index(3, 0) | ||
| self.assertEqual(x, 1) | ||
| self.assertEqual(y, 1) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.