-
Notifications
You must be signed in to change notification settings - Fork 7.1k
feat: Added support of Poly Loss #6457
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
Draft
frgfm
wants to merge
5
commits into
pytorch:main
Choose a base branch
from
frgfm:poly-loss
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
from typing import Optional | ||
|
||
import torch | ||
from torch import Tensor | ||
|
||
from ..utils import _log_api_usage_once | ||
|
||
|
||
def poly_loss( | ||
x: Tensor, | ||
target: Tensor, | ||
eps: float = 2.0, | ||
weight: Optional[Tensor] = None, | ||
ignore_index: int = -100, | ||
reduction: str = "mean", | ||
frgfm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) -> Tensor: | ||
"""Implements the Poly1 loss from `"PolyLoss: A Polynomial Expansion Perspective of Classification Loss | ||
Functions" <https://arxiv.org/pdf/2204.12511.pdf>`_. | ||
|
||
Args: | ||
x (Tensor[N, K, ...]): predicted probability | ||
target (Tensor[N, K, ...]): target probability | ||
eps (float, optional): epsilon 1 from the paper | ||
weight (Tensor[K], optional): manual rescaling of each class | ||
ignore_index (int, optional): specifies target value that is ignored and do not contribute to gradient | ||
reduction (string): ``'none'`` | ``'mean'`` | ``'sum'`` | ||
``'none'``: No reduction will be applied to the output. | ||
``'mean'``: The output will be averaged. | ||
``'sum'``: The output will be summed. Default: ``'none'``. | ||
|
||
Returns: | ||
Tensor: loss reduced with `reduction` method | ||
""" | ||
# Original implementation from https://github.com/frgfm/Holocron/blob/main/holocron/nn/functional.py | ||
if not torch.jit.is_scripting() and not torch.jit.is_tracing(): | ||
_log_api_usage_once(poly_loss) | ||
# log(P[class]) = log_softmax(score)[class] | ||
logpt = F.log_softmax(x, dim=1) | ||
|
||
# Compute pt and logpt only for target classes (the remaining will have a 0 coefficient) | ||
logpt = logpt.transpose(1, 0).flatten(1).gather(0, target.view(1, -1)).squeeze() | ||
# Ignore index (set loss contribution to 0) | ||
valid_idxs = torch.ones(target.view(-1).shape[0], dtype=torch.bool, device=x.device) | ||
if ignore_index >= 0 and ignore_index < x.shape[1]: | ||
valid_idxs[target.view(-1) == ignore_index] = False | ||
|
||
# Get P(class) | ||
loss = -1 * logpt + eps * (1 - logpt.exp()) | ||
|
||
# Weight | ||
if weight is not None: | ||
# Tensor type | ||
if weight.type() != x.data.type(): | ||
weight = weight.type_as(x.data) | ||
logpt = weight.gather(0, target.data.view(-1)) * logpt | ||
|
||
# Loss reduction | ||
if reduction == "sum": | ||
loss = loss[valid_idxs].sum() | ||
elif reduction == "mean": | ||
loss = loss[valid_idxs].mean() | ||
elif reduction == "none": | ||
# if no reduction, reshape tensor like target | ||
loss = loss.view(*target.shape) | ||
else: | ||
raise ValueError(f"invalid value for arg 'reduction': {reduction}") | ||
|
||
return loss |
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.
Uh oh!
There was an error while loading. Please reload this page.