import torch


def center(k: torch.Tensor) -> torch.Tensor:
    """Center features of a kernel by pre- and post-multiplying by the centering matrix H.

    In other words, if k_ij is dot(x_i, x_j), the result will be dot(x_i - mu_x, x_j - mu_x).

    :param k: a n by n Gram matrix of inner products between xs
    :return: a n by n centered matrix
    """
    n = k.size()[0]
    if k.size() != (n, n):
        raise ValueError(
            f"Expected k to be nxn square matrix, but it has size {k.size()}"
        )
    H = (
        torch.eye(n, device=k.device, dtype=k.dtype)
        - torch.ones((n, n), device=k.device, dtype=k.dtype) / n
    )
    return H @ k @ H