import torch


def unravel_index(input, size):
    """Unravel the index of tensor given size
    Args:
        input: LongTensor
        size: a tuple of integers

    Outputs: output,
        - **output**: the unraveled new tensor

    Examples::
        <<< value = torch.LongTensor(4,5,7,9)
        <<< max_val, flat_index = torch.max(value.view(4, 5, -1), dim=-1)
        <<< index = unravel_index(flat_index, (7, 9))
        <<< # output is a tensor with size (4, 5, 2)

    """
    idx = []
    for adim in size[::-1]:
        idx.append((input % adim).unsqueeze(dim=-1))
        input = input / adim
    idx = idx[::-1]
    return torch.cat(idx, -1)