"test/vscode:/vscode.git/clone" did not exist on "5bafb63780f94db0fb52d5bcc489c293d7e197df"
optimization_test.py 3.83 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import unittest

thomwolf's avatar
thomwolf committed
21
22
import torch

thomwolf's avatar
thomwolf committed
23
24
25
from pytorch_transformers import BertAdam
from pytorch_transformers import OpenAIAdam
from pytorch_transformers.optimization import ConstantLR, WarmupLinearSchedule, WarmupConstantSchedule, \
lukovnikov's avatar
lukovnikov committed
26
    WarmupCosineWithWarmupRestartsSchedule, WarmupCosineWithHardRestartsSchedule, WarmupCosineSchedule
lukovnikov's avatar
lukovnikov committed
27
import numpy as np
28

lukovnikov's avatar
lukovnikov committed
29

30
31
32
33
34
35
36
37
38
class OptimizationTest(unittest.TestCase):

    def assertListAlmostEqual(self, list1, list2, tol):
        self.assertEqual(len(list1), len(list2))
        for a, b in zip(list1, list2):
            self.assertAlmostEqual(a, b, delta=tol)

    def test_adam(self):
        w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True)
thomwolf's avatar
thomwolf committed
39
        target = torch.tensor([0.4, 0.2, -0.5])
thomwolf's avatar
thomwolf committed
40
        criterion = torch.nn.MSELoss()
thomwolf's avatar
thomwolf committed
41
        # No warmup, constant schedule, no gradient clipping
thomwolf's avatar
thomwolf committed
42
        optimizer = BertAdam(params=[w], lr=2e-1,
thomwolf's avatar
thomwolf committed
43
                                          weight_decay=0.0,
thomwolf's avatar
thomwolf committed
44
                                          max_grad_norm=-1)
45
        for _ in range(100):
thomwolf's avatar
thomwolf committed
46
            loss = criterion(w, target)
47
48
            loss.backward()
            optimizer.step()
thomwolf's avatar
thomwolf committed
49
50
            w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves.
            w.grad.zero_()
51
52
53
        self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2)


lukovnikov's avatar
lukovnikov committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class ScheduleInitTest(unittest.TestCase):
    def test_bert_sched_init(self):
        m = torch.nn.Linear(50, 50)
        optim = BertAdam(m.parameters(), lr=0.001, warmup=.1, t_total=1000, schedule=None)
        self.assertTrue(isinstance(optim.param_groups[0]["schedule"], ConstantLR))
        optim = BertAdam(m.parameters(), lr=0.001, warmup=.1, t_total=1000, schedule="none")
        self.assertTrue(isinstance(optim.param_groups[0]["schedule"], ConstantLR))
        optim = BertAdam(m.parameters(), lr=0.001, warmup=.01, t_total=1000)
        self.assertTrue(isinstance(optim.param_groups[0]["schedule"], WarmupLinearSchedule))
        # shouldn't fail

    def test_openai_sched_init(self):
        m = torch.nn.Linear(50, 50)
        optim = OpenAIAdam(m.parameters(), lr=0.001, warmup=.1, t_total=1000, schedule=None)
        self.assertTrue(isinstance(optim.param_groups[0]["schedule"], ConstantLR))
        optim = OpenAIAdam(m.parameters(), lr=0.001, warmup=.1, t_total=1000, schedule="none")
        self.assertTrue(isinstance(optim.param_groups[0]["schedule"], ConstantLR))
        optim = OpenAIAdam(m.parameters(), lr=0.001, warmup=.01, t_total=1000)
        self.assertTrue(isinstance(optim.param_groups[0]["schedule"], WarmupLinearSchedule))
        # shouldn't fail


lukovnikov's avatar
lukovnikov committed
76
77
class WarmupCosineWithRestartsTest(unittest.TestCase):
    def test_it(self):
lukovnikov's avatar
lukovnikov committed
78
        m = WarmupCosineWithWarmupRestartsSchedule(warmup=0.05, t_total=1000., cycles=5)
lukovnikov's avatar
lukovnikov committed
79
80
        x = np.arange(0, 1000)
        y = [m.get_lr(xe) for xe in x]
lukovnikov's avatar
lukovnikov committed
81
82
83
84
85
86
87
        y = np.asarray(y)
        expected_zeros = y[[0, 200, 400, 600, 800]]
        print(expected_zeros)
        expected_ones = y[[50, 250, 450, 650, 850]]
        print(expected_ones)
        self.assertTrue(np.allclose(expected_ones, 1))
        self.assertTrue(np.allclose(expected_zeros, 0))
lukovnikov's avatar
lukovnikov committed
88
89


90
91
if __name__ == "__main__":
    unittest.main()