def compute_sparsity(tensor):
    """
    Compute L1 sparsity of the input tensor.

    Parameters
    ----------
    tensor : torch.Tensor
        (N,) or (B, N) tensor array.

    Returns
    -------
    sparsity : torch.Tensor
        Mean L1 sparsity of `tensor`, scalar.

    """
    if tensor.ndim == 1:
        # make a batch of size 1
        tensor = tensor.unsqueeze(dim=0)
    sparsity = tensor.norm(p=1, dim=1).mean() / tensor.shape[1]
    return sparsity.squeeze()