Correct p-norm computation in triplet_loss#3613
Merged
Merged
Conversation
zcbenz
approved these changes
Jun 2, 2026
zcbenz
left a comment
Collaborator
There was a problem hiding this comment.
Looks good to me, thanks for fixing this!
42ec0e7 to
b69b9dd
Compare
Contributor
Author
|
@zcbenz thnx again |
1 task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
nn.losses.triplet_lossexposes a configurable norm degree through thepargument and documents the distance term as a p-norm:However, the current distance computation is:
which only matches the documented p-norm when
p=2. For other values ofp, it can produce incorrect results and evenNaNvalues.This change updates the distance computation to use the standard p-norm:
which matches both the function documentation and MLX's
linalg.normbehavior.On a sidenote, I also noticed that the LayerNorm, GroupNorm, and BatchNorm docstrings in
normalization.pyhadepsilonoutside the square root (\sqrt{Var[x]} + \epsilon) which doesn't match the standard normalization formula, so I changed it to (\sqrt{Var[x] + \epsilon}) instead.Changes
nn.losses.triplet_losspvaluesTesting
cc @zcbenz