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

Fix the slow running speed of kl_div when option 'reduction' is set #37283

Merged
merged 2 commits into from
Nov 18, 2021
Merged
Show file tree
Hide file tree
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
4 changes: 3 additions & 1 deletion python/paddle/fluid/tests/unittests/test_kldiv_loss_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ def test_kl_loss_static_api(self):
input = paddle.fluid.data(name='input', shape=[5, 20])
label = paddle.fluid.data(name='label', shape=[5, 20])

pred_loss = paddle.nn.functional.kl_div(input, label)
paddle.nn.functional.kl_div(input, label)
paddle.nn.functional.kl_div(input, label, 'sum')
paddle.nn.functional.kl_div(input, label, 'batchmean')


class TestKLDivLossTypePromotion(unittest.TestCase):
Expand Down
20 changes: 18 additions & 2 deletions python/paddle/nn/functional/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -903,7 +903,15 @@ def kl_div(input, label, reduction='mean', name=None):
label = paddle.cast(label, 'float64')

if paddle.in_dynamic_mode():
out = _C_ops.kldiv_loss(input, label, 'reduction', reduction)
out = _C_ops.kldiv_loss(input, label, 'reduction', 'none')
if reduction == 'mean':
out = paddle.mean(out)
elif reduction == 'sum':
out = paddle.sum(out)
elif reduction == 'batchmean':
if len(input.shape) > 0:
batch_size = input.shape[0]
out = paddle.sum(out) / batch_size
return out

helper = LayerHelper('kl_div', **locals())
Expand All @@ -920,7 +928,15 @@ def kl_div(input, label, reduction='mean', name=None):
inputs={'X': input,
'Target': label},
outputs={'Loss': loss},
attrs={'reduction': reduction})
attrs={'reduction': 'none'})

if reduction == 'mean':
loss = paddle.mean(loss)
elif reduction == 'sum':
loss = paddle.sum(loss)
elif reduction == 'batchmean':
batch_size = paddle.shape(input)[0]
loss = paddle.sum(loss) / batch_size
return loss


Expand Down