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

[Torch] fix cross_entropy_loss decomposition #3839

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
17 changes: 16 additions & 1 deletion lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8896,6 +8896,12 @@ class DecomposeAtenCrossEntropyLossOp
op, "Unimplemented: unranked target tensor");
unsigned targetRank = maybeRank.value();

Value reduction = op.getReduction();
int64_t reductionInt;
if (!matchPattern(reduction, m_TorchConstantInt(&reductionInt))) {
return rewriter.notifyMatchFailure(op,
"reduction should be a constant int!");
}
// When the input is 2-d i.e. of the form [minibatch, C] and target is 1-d
// of the form [minibatch] the cross entropy loss decomposes to the
// combination of softmax and nll loss as follows:
Expand Down Expand Up @@ -8925,10 +8931,19 @@ class DecomposeAtenCrossEntropyLossOp
loc, rewriter.getI64IntegerAttr(1));
Value logSoftmax = rewriter.create<AtenLogSoftmaxIntOp>(
loc, self.getType(), self, dim, /*dtype=*/noneVal);

Type secondType;
if (reductionInt == 0) {
secondType = target.getType();
} else {
auto targetType = dyn_cast<BaseTensorType>(target.getType());
secondType = targetType.getWithSizesAndDtype({}, targetType.getDtype());
}

Comment on lines +8934 to +8942
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
Type secondType;
if (reductionInt == 0) {
secondType = target.getType();
} else {
auto targetType = dyn_cast<BaseTensorType>(target.getType());
secondType = targetType.getWithSizesAndDtype({}, targetType.getDtype());
}
Type secondType = target.getType();
if (reductionInt != 0) {
auto targetType = dyn_cast<BaseTensorType>(target.getType());
secondType = targetType.getWithSizesAndDtype({}, targetType.getDtype());
}

Value nllLoss =
rewriter
.create<AtenNllLossForwardOp>(
loc, op.getType(), target.getType(), logSoftmax, target,
loc, op.getType(), secondType, logSoftmax, target,
op.getWeight(), op.getReduction(), op.getIgnoreIndex())
->getResult(0);
rewriter.replaceOp(op, nllLoss);
Expand Down
Loading