import torch


def collate_sequences(samples, pad, align_right=False):
    """Collates 1D tensors of different length with padding."""
    lengths = [x.size(0) for x in samples]
    max_length = max(lengths)
    # initialize with batch_size * length first
    tensor = samples[0].new(len(samples), max_length).fill_(pad)

    def copy_tensor(src, dst):
        dst.copy_(src)

    for i, sample in enumerate(samples):
        copy_tensor(sample, tensor[i][max_length - lengths[i]:] if align_right else
                    tensor[i][:lengths[i]])

    return tensor, torch.tensor(lengths)