Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix softmax_cross_entropy to handle -inf logits correctly when corresponding label is 0. #898

Merged
merged 1 commit into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion optax/losses/_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ def softmax_cross_entropy(
distributions, with shape `[...]`.
"""
chex.assert_type([logits], float)
return -jnp.sum(labels * jax.nn.log_softmax(logits, axis=-1), axis=-1)
log_probs = jax.nn.log_softmax(logits, axis=-1)
return -jnp.where(labels == 0, 0, labels * log_probs).sum(axis=-1)


def softmax_cross_entropy_with_integer_labels(
Expand Down
24 changes: 21 additions & 3 deletions optax/losses/_classification_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,28 @@ class SoftmaxCrossEntropyTest(parameterized.TestCase):

def setUp(self):
super().setUp()
self.ys = np.array([[10., 1., -2.], [1., 4., 0.2]], dtype=np.float32)
self.ts = np.array([[0., 1., 0.], [1., 0., 0.]], dtype=np.float32)
self.ys = np.array([
[10., 1., -2.],
[1., 4., 0.2],
[-np.inf, 0., 0.],
[-np.inf, 0., 0.],
[-np.inf, 0., -np.inf],
], dtype=np.float32)
self.ts = np.array([
[0., 1., 0.],
[1., 0., 0.],
[0., 0.5, 0.5],
[0.4, 0.3, 0.3],
[0., 1., 0.],
], dtype=np.float32)
# taken expected outputs from rlax.
self.exp = np.array([9.00013, 3.0696733], dtype=np.float32)
self.exp = np.array([
9.00013,
3.0696733,
0.693147,
np.inf,
0.,
], dtype=np.float32)

@chex.all_variants
def test_scalar(self):
Expand Down
Loading