import torch


def avg_disp(y_pred, y_true):
    """ Average displacement error. """
    y_true, masks = y_true

    seq_lengths = masks.sum(1)
    batch_size = len(seq_lengths)

    squared_dist = (y_true - y_pred)**2
    l2_dist = masks * torch.sqrt(squared_dist.sum(2))

    avg_l2_dist = (1./batch_size) * ((1./seq_lengths) * l2_dist.sum(1)).sum()
    return avg_l2_dist.item()