import torch


def collate_fn(data):
    """Sorts the input(the mini-batch) by length and truncates all the data points to the max length of the input"""
    sorted_data = sorted(data, key=lambda x: x[2], reverse=True)
    max_len = sorted_data[0][2]
    x = torch.stack([x_i[:max_len] for x_i, y_i, l_i in sorted_data])
    y = torch.stack([y_i[:max_len] for x_i, y_i, l_i in sorted_data])
    l = [l_i for _, _, l_i in sorted_data]
    return x, y, l