transformers

Форк
0
/
test_optimization.py 
186 строк · 6.7 Кб
1
# coding=utf-8
2
# Copyright 2020 The HuggingFace Team. All rights reserved.
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15

16

17
import os
18
import tempfile
19
import unittest
20

21
from transformers import is_torch_available
22
from transformers.testing_utils import require_torch
23

24

25
if is_torch_available():
26
    import torch
27
    from torch import nn
28

29
    from transformers import (
30
        Adafactor,
31
        AdamW,
32
        get_constant_schedule,
33
        get_constant_schedule_with_warmup,
34
        get_cosine_schedule_with_warmup,
35
        get_cosine_with_hard_restarts_schedule_with_warmup,
36
        get_inverse_sqrt_schedule,
37
        get_linear_schedule_with_warmup,
38
        get_polynomial_decay_schedule_with_warmup,
39
    )
40

41

42
def unwrap_schedule(scheduler, num_steps=10):
43
    lrs = []
44
    for _ in range(num_steps):
45
        lrs.append(scheduler.get_lr()[0])
46
        scheduler.step()
47
    return lrs
48

49

50
def unwrap_and_save_reload_schedule(scheduler, num_steps=10):
51
    lrs = []
52
    for step in range(num_steps):
53
        lrs.append(scheduler.get_lr()[0])
54
        scheduler.step()
55
        if step == num_steps // 2:
56
            with tempfile.TemporaryDirectory() as tmpdirname:
57
                file_name = os.path.join(tmpdirname, "schedule.bin")
58
                torch.save(scheduler.state_dict(), file_name)
59

60
                state_dict = torch.load(file_name)
61
                scheduler.load_state_dict(state_dict)
62
    return lrs
63

64

65
@require_torch
66
class OptimizationTest(unittest.TestCase):
67
    def assertListAlmostEqual(self, list1, list2, tol):
68
        self.assertEqual(len(list1), len(list2))
69
        for a, b in zip(list1, list2):
70
            self.assertAlmostEqual(a, b, delta=tol)
71

72
    def test_adam_w(self):
73
        w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True)
74
        target = torch.tensor([0.4, 0.2, -0.5])
75
        criterion = nn.MSELoss()
76
        # No warmup, constant schedule, no gradient clipping
77
        optimizer = AdamW(params=[w], lr=2e-1, weight_decay=0.0)
78
        for _ in range(100):
79
            loss = criterion(w, target)
80
            loss.backward()
81
            optimizer.step()
82
            w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
83
            w.grad.zero_()
84
        self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2)
85

86
    def test_adafactor(self):
87
        w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True)
88
        target = torch.tensor([0.4, 0.2, -0.5])
89
        criterion = nn.MSELoss()
90
        # No warmup, constant schedule, no gradient clipping
91
        optimizer = Adafactor(
92
            params=[w],
93
            lr=1e-2,
94
            eps=(1e-30, 1e-3),
95
            clip_threshold=1.0,
96
            decay_rate=-0.8,
97
            beta1=None,
98
            weight_decay=0.0,
99
            relative_step=False,
100
            scale_parameter=False,
101
            warmup_init=False,
102
        )
103
        for _ in range(1000):
104
            loss = criterion(w, target)
105
            loss.backward()
106
            optimizer.step()
107
            w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
108
            w.grad.zero_()
109
        self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2)
110

111

112
@require_torch
113
class ScheduleInitTest(unittest.TestCase):
114
    m = nn.Linear(50, 50) if is_torch_available() else None
115
    optimizer = AdamW(m.parameters(), lr=10.0) if is_torch_available() else None
116
    num_steps = 10
117

118
    def assertListAlmostEqual(self, list1, list2, tol, msg=None):
119
        self.assertEqual(len(list1), len(list2))
120
        for a, b in zip(list1, list2):
121
            self.assertAlmostEqual(a, b, delta=tol, msg=msg)
122

123
    def test_schedulers(self):
124
        common_kwargs = {"num_warmup_steps": 2, "num_training_steps": 10}
125
        # schedulers doct format
126
        # function: (sched_args_dict, expected_learning_rates)
127
        scheds = {
128
            get_constant_schedule: ({}, [10.0] * self.num_steps),
129
            get_constant_schedule_with_warmup: (
130
                {"num_warmup_steps": 4},
131
                [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
132
            ),
133
            get_linear_schedule_with_warmup: (
134
                {**common_kwargs},
135
                [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
136
            ),
137
            get_cosine_schedule_with_warmup: (
138
                {**common_kwargs},
139
                [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
140
            ),
141
            get_cosine_with_hard_restarts_schedule_with_warmup: (
142
                {**common_kwargs, "num_cycles": 2},
143
                [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
144
            ),
145
            get_polynomial_decay_schedule_with_warmup: (
146
                {**common_kwargs, "power": 2.0, "lr_end": 1e-7},
147
                [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156],
148
            ),
149
            get_inverse_sqrt_schedule: (
150
                {"num_warmup_steps": 2},
151
                [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714],
152
            ),
153
        }
154

155
        for scheduler_func, data in scheds.items():
156
            kwargs, expected_learning_rates = data
157

158
            scheduler = scheduler_func(self.optimizer, **kwargs)
159
            self.assertEqual(len([scheduler.get_lr()[0]]), 1)
160
            lrs_1 = unwrap_schedule(scheduler, self.num_steps)
161
            self.assertListAlmostEqual(
162
                lrs_1,
163
                expected_learning_rates,
164
                tol=1e-2,
165
                msg=f"failed for {scheduler_func} in normal scheduler",
166
            )
167

168
            scheduler = scheduler_func(self.optimizer, **kwargs)
169
            if scheduler_func.__name__ != "get_constant_schedule":
170
                LambdaScheduleWrapper.wrap_scheduler(scheduler)  # wrap to test picklability of the schedule
171
            lrs_2 = unwrap_and_save_reload_schedule(scheduler, self.num_steps)
172
            self.assertListEqual(lrs_1, lrs_2, msg=f"failed for {scheduler_func} in save and reload")
173

174

175
class LambdaScheduleWrapper:
176
    """See https://github.com/huggingface/transformers/issues/21689"""
177

178
    def __init__(self, fn):
179
        self.fn = fn
180

181
    def __call__(self, *args, **kwargs):
182
        return self.fn(*args, **kwargs)
183

184
    @classmethod
185
    def wrap_scheduler(self, scheduler):
186
        scheduler.lr_lambdas = list(map(self, scheduler.lr_lambdas))
187

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.