import torch


def dist_nd_pytorch(anchors: torch.Tensor,
                    targets: torch.Tensor,
                    dim=None) -> torch.Tensor:
    """
    :param anchors:  [N, (y1,x1,y2,x2) | (y1,x1,z1,y2,x2,z2)]
    :param targets:  [M, (y1,x1,y2,x2) | (y1,x1,z1,y2,x2,z2)]
    :param dim: dimension of bbox
    :return:   IoU:  [N,M]
    """
    if not dim:
        dim = targets.shape[-1] // 2
        assert dim in (2, 3)

    anchors = anchors[..., :2 * dim]
    targets = targets[..., :2 * dim]

    # expand dim
    anchors = torch.unsqueeze(anchors, dim=1)  # [N, 1, 2*dim]
    targets = torch.unsqueeze(targets, dim=0)  # [1, M, 2*dim]

    # center on each dim
    anchors = (anchors[..., :dim] + anchors[..., dim:]) / 2  # [N, 1, dim]
    targets = (targets[..., :dim] + targets[..., dim:]) / 2  # [1, M, dim]

    # distance
    distance = torch.pow(anchors - targets, 2).float()  # [N, M, dim]
    distance = torch.sqrt(torch.sum(distance, dim=-1))

    return distance