diff --git a/python/paddle/__init__.py b/python/paddle/__init__.py index b1bdc05813d8c0..8bd0baefa63c7b 100644 --- a/python/paddle/__init__.py +++ b/python/paddle/__init__.py @@ -248,6 +248,7 @@ matrix_transpose, mv, norm, + permute, t, t_, transpose, @@ -1091,6 +1092,7 @@ 'tanh_', 'transpose', 'transpose_', + 'permute', 'cauchy_', 'geometric_', 'randn', diff --git a/python/paddle/tensor/__init__.py b/python/paddle/tensor/__init__.py index 824d8d681f4e59..fe4acca55695ef 100644 --- a/python/paddle/tensor/__init__.py +++ b/python/paddle/tensor/__init__.py @@ -98,6 +98,7 @@ norm, ormqr, pca_lowrank, + permute, pinv, qr, solve, @@ -710,6 +711,7 @@ 'strided_slice', 'transpose', 'transpose_', + 'permute', 'cauchy_', 'geometric_', 'tan_', diff --git a/python/paddle/tensor/linalg.py b/python/paddle/tensor/linalg.py index a22eda0d3ce21f..45b2d48e002f41 100644 --- a/python/paddle/tensor/linalg.py +++ b/python/paddle/tensor/linalg.py @@ -24,7 +24,10 @@ from paddle.base.libpaddle import DataType from paddle.common_ops_import import VarDesc from paddle.tensor.math import broadcast_shape -from paddle.utils.decorator_utils import ParamAliasDecorator +from paddle.utils.decorator_utils import ( + ParamAliasDecorator, + VariableArgsDecorator, +) from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only from ..base.data_feeder import ( @@ -191,6 +194,36 @@ def transpose_(x, perm, name=None): return _C_ops.transpose_(x, perm) +@VariableArgsDecorator('dims') +def permute(input: Tensor, dims: Sequence[int]) -> Tensor: + """ + Permute the dimensions of a tensor. + + Args: + input (Tensor): the input tensor. + *dims (tuple|list|int): The desired ordering of dimensions. Supports passing as variable-length + arguments (e.g., permute(x, 1, 0, 2)) or as a single list/tuple (e.g., permute(x, [1, 0, 2])). + + Returns: + Tensor: A tensor with permuted dimensions. + + Examples: + .. code-block:: python + + >>> import paddle + + >>> x = paddle.randn([2, 3, 4]) + >>> y = paddle.permute(x, (1, 0, 2)) + >>> print(y.shape) + [3, 2, 4] + + >>> y = x.permute([1, 0, 2]) + >>> print(y.shape) + [3, 2, 4] + """ + return transpose(x=input, perm=dims) + + def matrix_transpose( x: paddle.Tensor, name: str | None = None, diff --git a/python/paddle/utils/decorator_utils.py b/python/paddle/utils/decorator_utils.py index bf870a73ff6dd5..f03e3619478fa8 100644 --- a/python/paddle/utils/decorator_utils.py +++ b/python/paddle/utils/decorator_utils.py @@ -241,6 +241,22 @@ def process( return args, kwargs +class VariableArgsDecorator(DecoratorBase): + def __init__(self, var: str) -> None: + super().__init__() + if not isinstance(var, str): + raise TypeError("var must be a string") + self.var = var + + def process( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + if len(args) >= 2 and isinstance(args[1], int): + kwargs[self.var] = list(args[1:]) + args = args[:1] + return args, kwargs + + """ Usage Example: paddle.view(x=tensor_x, shape_or_dtype=[-1, 1, 3], name=None) diff --git a/test/legacy_test/test_permute_op.py b/test/legacy_test/test_permute_op.py new file mode 100644 index 00000000000000..c1305992decbf5 --- /dev/null +++ b/test/legacy_test/test_permute_op.py @@ -0,0 +1,85 @@ +# 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 TestPermuteApi(unittest.TestCase): + def test_static(self): + paddle.enable_static() + with paddle.static.program_guard( + paddle.static.Program(), paddle.static.Program() + ): + x = paddle.static.data(name='x', shape=[2, 3, 4], dtype='float32') + + # function: list / tuple / varargs + y1 = paddle.permute(x, [1, 0, 2]) + y2 = paddle.permute(x, (2, 1, 0)) + y3 = paddle.permute(x, 1, 2, 0) + y4 = paddle.permute(x, dims=[1, 2, 0]) + + place = paddle.CPUPlace() + exe = paddle.static.Executor(place) + x_np = np.random.random([2, 3, 4]).astype("float32") + out1, out2, out3, out4 = exe.run( + feed={"x": x_np}, fetch_list=[y1, y2, y3, y4] + ) + + expected1 = np.transpose(x_np, [1, 0, 2]) + expected2 = np.transpose(x_np, (2, 1, 0)) + expected3 = np.transpose(x_np, [1, 2, 0]) + + np.testing.assert_array_equal(out1, expected1) + np.testing.assert_array_equal(out2, expected2) + np.testing.assert_array_equal(out3, expected3) + np.testing.assert_array_equal(out4, expected3) + + def test_dygraph(self): + paddle.disable_static() + x = paddle.randn([2, 3, 4]) + x_np = x.numpy() + + y1 = paddle.permute(x, [1, 0, 2]) + y2 = paddle.permute(x, (2, 1, 0)) + y3 = paddle.permute(x, 1, 2, 0) + y4 = paddle.permute(x, dims=[1, 2, 0]) + + m1 = x.permute([1, 0, 2]) + m2 = x.permute((2, 1, 0)) + m3 = x.permute(1, 2, 0) + m4 = x.permute(dims=[1, 2, 0]) + + expected1 = np.transpose(x_np, [1, 0, 2]) + expected2 = np.transpose(x_np, (2, 1, 0)) + expected3 = np.transpose(x_np, [1, 2, 0]) + + np.testing.assert_array_equal(y1.numpy(), expected1) + np.testing.assert_array_equal(y2.numpy(), expected2) + np.testing.assert_array_equal(y3.numpy(), expected3) + np.testing.assert_array_equal(y4.numpy(), expected3) + + np.testing.assert_array_equal(m1.numpy(), expected1) + np.testing.assert_array_equal(m2.numpy(), expected2) + np.testing.assert_array_equal(m3.numpy(), expected3) + np.testing.assert_array_equal(m4.numpy(), expected3) + + paddle.enable_static() + + +if __name__ == '__main__': + unittest.main()