def cosine_similarity_matrix(samples, eps=1e-8):
    """Calculate the cosine similarity between all sample pairs.
    
    Args:
        samples (~torch.Tensor): Tensor of shape :math:`(*, N, F)` where
            :math:`*` means any number of additional dimensions,
            :math:`N` is the number of samples and :math:`F` is the number
            of features per sample.
    
    Returns:
        ~torch.Tensor: Cosine similarity matrix of shape :math:`(*, N, N)`
        where :math:`*` and math:`N` are the same as for the input.
    """
    assert samples.dim() >= 2, \
        'Shape of input should be (*, num_samples, num_features)'
    w = samples.norm(dim=-1, keepdim=True)
    return samples.matmul(samples.transpose(-1, -2)) / (w * w.transpose(-1, -2)).clamp(min=eps)