Use logsumexp to avoid big exponentials.