def median_absolute_deviation(x, dim=-1, scale=1.):
    """
    Args:
        x: n-d torch.Tensor
    
    Returns:
        mad: median absolute deviation along dim of x, same shape with x
        median: median along dim of x, same shape with x
    """
    median = x.median(dim=dim)[0].unsqueeze(dim)
    mad = (x - median).abs().median(dim=dim)[0].unsqueeze(dim) * scale
    return mad, median