Skip to content

Fix KL and Jensen-Shannon divergence returning NaN for -inf inputs with log_prob=True - #3674

Open
Ali-Tharwat wants to merge 1 commit into
Lightning-AI:masterfrom
Ali-Tharwat:fix/kld-jsd-log-prob-zero
Open

Ali-Tharwat wants to merge 1 commit into
Lightning-AI:masterfrom
Ali-Tharwat:fix/kld-jsd-log-prob-zero

Conversation

@Ali-Tharwat

Copy link
Copy Markdown

What does this PR do?

Fixes #3673

When log_prob=True, _kld_update previously computed p.exp() * (p - q), which produces 0.0 * -inf = NaN whenever an entry in p has -inf (log(0)). Because jensen_shannon_divergence(..., log_prob=True) calls kl_divergence(..., log_prob=True), both KLDivergence/kl_divergence and JensenShannonDivergence/jensen_shannon_divergence returned NaN for zero-probability inputs in log space.

  • src/torchmetrics/functional/regression/kl_divergence.py: Mask p - q with torch.where(p_prob == 0, zero, p - q) so zero-probability terms evaluate to 0.0 (while keeping autograd gradients finite when requires_grad=True).
  • tests/unittests/regression/test_kl_divergence.py & test_js_divergence.py: Add test_zero_probability_log_prob verifying parity with log_prob=False and finite gradients.
  • CHANGELOG.md: Document fix under ### Fixed.

Verified locally:
pytest tests/unittests/regression/test_kl_divergence.py tests/unittests/regression/test_js_divergence.py -m "not DDP" -v (41 passed, 8 skipped for CUDA, 8 DDP deselected).

Before submitting
  • Was this discussed/agreed via a Github issue? (no need for typos and docs improvements)
  • Did you read the contributor guideline, Pull Request section?
  • Did you make sure to update the docs?
  • Did you write any new necessary tests?

…th log_prob=True

Signed-off-by: Ali Tharwat <ali.tharwat@student.giu-uni.de>

@atishay-kasliwal atishay-kasliwal left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compared kl_divergence and jensen_shannon_divergence with log_prob=True against scipy.special.rel_entr and jensenshannon(...)**2, where p has a zero entry (log = -inf). Master returned nan for that row; here both match scipy and the probability-space results.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

kl_divergence and jensen_shannon_divergence return NaN for zero probabilities (-inf) when log_prob=True

2 participants