import torch


def torch_intersection(segments1, segments2):
    """Compute pairwise intersection length between segments.

    Args:
        segments1 (torch tensor): shape [N, 2] holding N segments
        segments2 (torch tensor): shape [M, 2] holding M segments
    Returns:
        a torch tensor with shape [N, M] representing pairwise intersection length
    """
    [t_min1, t_max1] = torch.chunk(segments1, 2, dim=1)
    [t_min2, t_max2] = torch.chunk(segments2, 2, dim=1)
    # t_max1 and t_max2 are not contigous, does it matter?

    # it seems that t_*_[1-2] share memory with segments[1-2], thus I don't
    # transpose in-place
    all_pairs_min_tmax = torch.min(t_max1, t_max2.transpose(0, 1))
    all_pairs_max_tmin = torch.max(t_min1, t_min2.transpose(0, 1))
    intersect_length = torch.max(torch.zeros_like(all_pairs_max_tmin),
                                 all_pairs_min_tmax - all_pairs_max_tmin)
    return intersect_length