Fix LigerCrossEntropyLoss Reduction Behavior for "None" Mode #435
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.
Summary
Closes #421
This pull request addresses an issue in the
cross_entropy_forward
function where thereduction="none"
mode did not behave as expected.Previously, the function always returned a single scalar value, even when reduction="none" was specified. This update ensures that when reduction="none" is used, the function directly outputs the unreduced loss array (loss_1d) instead of summing it.
Changes Made:
reduction="none"
, ensuring the function outputs loss_1d directly.reduction="none"
Why we pass
gradient
tooutput.backward()
?Background on Gradients in PyTorch
Why reduction="none" Needs Explicit Gradients
When
reduction="none"
, the loss function does not reduce the per-example loss values into a single scalar. Instead, it outputs a vector of losses, with one value per example in the batch. This means that the loss tensor has multiple values, and PyTorch cannot assume what the gradient for each of these values should be unless explicitly provided.The Fix
By passing
gradient=torch.ones_like(loss)
tobackward()
:torch.ones_like(loss)
serves as the gradient tensor. It specifies that each element in the loss tensor contributes equally to the gradients during backpropagation.Testing Done
make test
pytest /home/jobuser/Liger-Kernel/test/transformers/test_cross_entropy.py
shows:make test
to ensure correctnessmake checkstyle
to ensure code stylemake test-convergence
to ensure convergence