Skip to content

Commit

Permalink
[NPU] replace ce loss with nll loss (#3759) (#3782)
Browse files Browse the repository at this point in the history
  • Loading branch information
Birdylx authored Aug 23, 2024
1 parent 6758049 commit 4b37151
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions paddleseg/models/losses/cross_entropy_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

from paddleseg.cvlibs import manager

_IS_NPU = "npu" in paddle.get_device()


@manager.LOSSES.add_component
class CrossEntropyLoss(nn.Layer):
Expand Down Expand Up @@ -81,11 +83,20 @@ def forward(self, logit, label, semantic_weights=None):
logit = paddle.transpose(logit, [0, 2, 3, 1])
label = label.astype('int64')

loss = F.cross_entropy(logit,
label,
ignore_index=self.ignore_index,
reduction='none',
weight=self.weight)
if _IS_NPU:
logit = logit.transpose([0, 3, 1, 2])
logit = F.log_softmax(logit, axis=1)
loss = F.nll_loss(logit,
label,
weight=self.weight,
ignore_index=self.ignore_index,
reduction='none')
else:
loss = F.cross_entropy(logit,
label,
ignore_index=self.ignore_index,
reduction='none',
weight=self.weight)

return self._post_process_loss(logit, label, semantic_weights, loss)

Expand Down

0 comments on commit 4b37151

Please sign in to comment.