import torch


def euclidean_dist(x, y, squared=False):
    """
    Compute (Squared) Euclidean distance between two tensors.
    Args:
        x: input tensor with size N x D.
        y: input tensor with size M x D.
        return: distance matrix with size N x M.
    """
    n = x.size(0)
    m = y.size(0)
    d = x.size(1)
    if d != y.size(1):
        raise Exception('Invalid input shape.')

    x = x.unsqueeze(1).expand(n, m, d)
    y = y.unsqueeze(0).expand(n, m, d)
    dist = torch.pow(x - y, 2).sum(2)

    if squared:
        return dist
    else:
        return torch.sqrt(dist+1e-12)