import torch


def seq_mask_by_lens(lengths:torch.Tensor, 
                     maxlen=None, 
                     dtype=torch.bool):
    """
    giving sequence lengths, return mask of the sequence.
    example:
        input: 
        lengths = torch.tensor([4, 5, 1, 3])

        output:
        tensor([[ True,  True,  True,  True, False],
                [ True,  True,  True,  True,  True],
                [ True, False, False, False, False],
                [ True,  True,  True, False, False]])
    """
    if maxlen is None:
        maxlen = lengths.max()
    row_vector = torch.arange(start=0, end=maxlen.item(), step=1)
    matrix = torch.unsqueeze(lengths, dim=-1)
    mask = row_vector < matrix

    mask.type(dtype)
    return mask