import torch


def compute_ranking(x: torch.Tensor) -> torch.Tensor:
    """ Given a vector of shape: (*, n) compute the ranking along the last dimension.

        Note:
            It works for arbitrary leading dimension. Each leading dimension will be treated independently.
    """
    indices = torch.sort(x, dim=-1, descending=False)[1]

    # this is the fast way which uses indexing on the left
    src = torch.arange(start=0, end=x.shape[-1], step=1, dtype=indices.dtype, device=indices.device).expand_as(indices)
    rank = torch.zeros_like(indices)
    rank.scatter_(dim=-1, index=indices, src=src)
    return rank