# 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.fromtypingimportSequencefromtripyimportconstraints,exportfromtripy.common.exceptionimportraise_error
[docs]@export.public_api(document_under="operations/functions")@constraints.dtypes(constraints={"tensors":"T1",constraints.RETURN_VALUE:"T1"},variables={"T1":["float32","float16","bfloat16","float8","int4","int8","int32","int64","bool"],},)defstack(tensors:Sequence["tripy.Tensor"],dim:int=0)->"tripy.Tensor":""" Stacks multiple tensors of same shape along a given dimension. Args: tensors: Sequence of tensors of the same shape. dim: The dimension to insert. Returns: A tensor with a new dimension inserted at the specified position. .. code-block:: python :linenos: :caption: Example a = tp.iota((2, 3), dtype=tp.float32) b = tp.iota((2, 3), dtype=tp.float32) output = tp.stack([a, b], dim=0) assert np.array_equal(cp.from_dlpack(output).get(), np.stack((cp.from_dlpack(a).get(), cp.from_dlpack(b).get()), axis=0)) """fromtripy.frontend.ops.unsqueezeimportunsqueezefromtripy.frontend.trace.ops.concatenateimportconcatenateifnottensors:raise_error(f"Expected a non-empty list of tensors, got {tensors}")# Check if all tensors have the same rankiflen(set(tensor.rankfortensorintensors))>1:ranks=", ".join(str(tensor.rank)fortensorintensors)raise_error(f"Expected all input tensors to have the same rank.",[f"Note: Got tensors of multiple ranks: {ranks}."])expanded_tensors=[unsqueeze(tensor,dim=dim)fortensorintensors]# Concatenate along the new dimensionreturnconcatenate(expanded_tensors,dim=dim)