import torch


def to_thinnest_padded_tensor(tensor, PAD=0):
    """
    Given an 2D padded tensor of shape (batch_size, padded_length),
    resize it to (batch_size, maximum_unpadded_length).
    :param tensor: input 2D tensor
    :param PAD: value of pad id
    :return: resized tensor, and the true maximum unpadded length.
    """
    mask = (torch.ones_like(tensor) * PAD != tensor).float()
    lengths = mask.sum(dim=1)
    max_len = int(lengths.max().item())
    resized_tensor = tensor[:, :max_len]
    return resized_tensor, max_len