Skip to content

Commit

Permalink
Fix Python IndexError of case8: paddle.static.nn.nce (#49989)
Browse files Browse the repository at this point in the history
* add dimension check for nce

* add unittest

* fix incorrect type in test_nce
  • Loading branch information
RedContritio authored Feb 2, 2023
1 parent 24e395f commit c8548af
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
7 changes: 7 additions & 0 deletions python/paddle/fluid/tests/unittests/test_nce.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,13 @@ def test_errors(self):
TypeError, paddle.static.nn.nce, input4, label4, 5
)

input5 = paddle.static.data(name='x', shape=[1], dtype='float32')
label5 = paddle.static.data(name='label', shape=[1], dtype='int64')

self.assertRaises(
ValueError, paddle.static.nn.nce, input5, label5, 1
)


if __name__ == '__main__':
unittest.main()
5 changes: 5 additions & 0 deletions python/paddle/static/nn/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,11 @@ def nce(
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'nce')
check_variable_and_dtype(label, 'label', ['int64'], 'nce')

if input.ndim != 2:
raise ValueError(
f'The rank of `input` must be 2, but received {input.ndim}.'
)

dim = input.shape[1]
num_true_class = label.shape[1]
w = helper.create_parameter(
Expand Down

0 comments on commit c8548af

Please sign in to comment.