Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
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: 2 additions & 0 deletions python/paddle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@
matrix_transpose,
mv,
norm,
permute,
t,
t_,
transpose,
Expand Down Expand Up @@ -1091,6 +1092,7 @@
'tanh_',
'transpose',
'transpose_',
'permute',
'cauchy_',
'geometric_',
'randn',
Expand Down
2 changes: 2 additions & 0 deletions python/paddle/tensor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
norm,
ormqr,
pca_lowrank,
permute,
pinv,
qr,
solve,
Expand Down Expand Up @@ -710,6 +711,7 @@
'strided_slice',
'transpose',
'transpose_',
'permute',
'cauchy_',
'geometric_',
'tan_',
Expand Down
35 changes: 34 additions & 1 deletion python/paddle/tensor/linalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 of 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]

>>> x.permute(1, 0, 2)
>>> print(x.shape)
[3, 2, 4]
"""
return transpose(x=input, perm=dims)


def matrix_transpose(
x: paddle.Tensor,
name: str | None = None,
Expand Down
16 changes: 16 additions & 0 deletions python/paddle/utils/decorator_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
85 changes: 85 additions & 0 deletions test/legacy_test/test_permute_op.py
Original file line number Diff line number Diff line change
@@ -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()
Loading