K-Iwa's picture
Refresh all files
2f28361 verified
Raw
History Blame Contribute Delete
1.05 kB
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
from typing import List
import torch
def left_pad_and_stack_1d(tensors: List[torch.Tensor]) -> torch.Tensor:
"""Left-pad variable-length 1D tensors with NaN and stack them into a batch."""
if not tensors:
raise ValueError("At least one tensor is required.")
max_len = max(len(c) for c in tensors)
padded = []
for index, c in enumerate(tensors):
if not isinstance(c, torch.Tensor):
raise TypeError(f"Item {index} is not a torch.Tensor.")
if c.ndim != 1:
raise ValueError(f"Item {index} must be 1D; got shape {tuple(c.shape)}.")
padding = torch.full(
size=(max_len - len(c),),
fill_value=torch.nan,
dtype=c.dtype,
device=c.device,
)
padded.append(torch.concat((padding, c), dim=-1))
return torch.stack(padded)
left_pad_and_stack_1D = left_pad_and_stack_1d