Skip to content

Commit

Permalink
Fix Python IndexError of case4: paddle.optimizer.lr.PiecewiseDecay (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
RedContritio authored Feb 2, 2023
1 parent a34ecad commit 3e65641
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
11 changes: 11 additions & 0 deletions python/paddle/fluid/tests/unittests/test_lr_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,17 @@ def test_scheduler(self):
step_size_down=-1,
scale_mode='test',
)
# check empty boundaries
with self.assertRaises(ValueError):
paddle.optimizer.lr.PiecewiseDecay(boundaries=[], values=[])
# check non-empty boundaries but empty values
with self.assertRaises(ValueError):
paddle.optimizer.lr.PiecewiseDecay(boundaries=[100, 200], values=[])
# check boundaries and values has same length
with self.assertRaises(ValueError):
paddle.optimizer.lr.PiecewiseDecay(
boundaries=[100, 200], values=[0.5, 0.1]
)

func_api_kwargs = [
(
Expand Down
8 changes: 8 additions & 0 deletions python/paddle/optimizer/lr.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,14 @@ class PiecewiseDecay(LRScheduler):
"""

def __init__(self, boundaries, values, last_epoch=-1, verbose=False):
if len(boundaries) == 0:
raise ValueError('The boundaries cannot be empty.')

if len(values) <= len(boundaries):
raise ValueError(
f'The values have one more element than boundaries, but received len(values) [{len(values)}] < len(boundaries) + 1 [{len(boundaries) + 1}].'
)

self.boundaries = boundaries
self.values = values
super().__init__(last_epoch=last_epoch, verbose=verbose)
Expand Down
2 changes: 1 addition & 1 deletion python/paddle/tests/test_callback_reduce_lr_on_plateau.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def test_warn_or_error(self):

optim = paddle.optimizer.Adam(
learning_rate=paddle.optimizer.lr.PiecewiseDecay(
[0.001, 0.0001], [5, 10]
[0.001, 0.0001], [5, 10, 10]
),
parameters=net.parameters(),
)
Expand Down

0 comments on commit 3e65641

Please sign in to comment.