use logsumexp for better numerical properties