import torch


def pairwise_distance(u, v=None):
    """
    Euclidean pairwise dist. similar to scipy.spatial.distance.pdist.
    Args:
        u (tensor): 2d tensor
        v (tensor): 2d tensor (if none, computes pairwise distance with the same vector)
    """
    if v is None:
        v = u

    n = u.size(0)
    m = v.size(0)
    assert u.size(1) == v.size(1)
    d = u.size(1)

    x = u.unsqueeze(1).expand(n, m, d)
    y = v.unsqueeze(0).expand(n, m, d)

    return torch.sqrt(torch.pow(x - y, 2).sum(2))