Source code for tripy.frontend.trace.ops.permute

#
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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.
#

from dataclasses import dataclass
from typing import Sequence

from tripy import constraints, export
from tripy.common.exception import raise_error
from tripy.frontend.trace.ops import utils as op_utils
from tripy.frontend.trace.ops.base import BaseTraceOp


@dataclass(repr=False)
class Permute(BaseTraceOp):
    permutation: Sequence[int]

    infer_rank = op_utils.InferRankPolicies.same_as_input()

    def to_flat_ir(self, inputs, outputs):
        from tripy.flat_ir.ops import TransposeOp

        TransposeOp.build(inputs, outputs, perm=self.permutation)


[docs] @export.public_api(document_under="operations/functions") @constraints.dtypes( constraints={"input": "T1", constraints.RETURN_VALUE: "T1"}, variables={"T1": ["float32", "float16", "bfloat16", "float8", "int4", "int8", "int32", "int64", "bool"]}, ) def permute(input: "tripy.Tensor", perm: Sequence[int]) -> "tripy.Tensor": """ Returns a tensor with its dimensions permuted. Args: input: The input tensor. perm: The desired ordering of dimensions. It must contain all integers in :math:`[0..N-1]` exactly once, where :math:`N` is the rank of the input tensor. Returns: A new tensor. .. code-block:: python :linenos: :caption: Example input = tp.reshape(tp.arange(6, dtype=tp.float32), (2, 3)) output = tp.permute(input, (1, 0)) assert np.array_equal(cp.from_dlpack(output).get(), np.transpose(np.arange(6, dtype=np.float32).reshape(2, 3), (1, 0))) """ if len(perm) != input.rank: raise_error( "Invalid permutation.", [ "Permutation must have a number of elements equal to the number of dimensions in the input.\n" f"Note: Permutation was: {perm}, which has {len(perm)} element(s), but input has {input.rank} dimension(s)." ], ) if list(sorted(perm)) != list(range(input.rank)): raise_error( "Invalid permutation.", [ f"Permutation must contain every integer between 0 and {input.rank -1} exactly once, but permutation was: {perm}" ], ) return Permute.build([input], perm)