paddlenlp

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

15
import copy
16
import sys
17
from collections import defaultdict
18

19
import paddle
20
from paddle.optimizer.lr import LRScheduler
21
from ppfleetx.utils.log import logger
22

23
from .grad_clip import *
24
from .lr_scheduler import *
25
from .optimizer import *
26

27

28
def build_lr_scheduler(lr_config):
29
    if "name" in lr_config:
30
        lr_name = lr_config.pop("name")
31
        lr = eval(lr_name)(**lr_config)
32
        if isinstance(lr, LRScheduler):
33
            return lr
34
        else:
35
            return lr()
36
    else:
37
        lr = lr_config.learning_rate
38

39
    logger.debug("build lr ({}) success..".format(lr))
40
    return lr
41

42

43
def build_grad_clip(grad_clip_config):
44
    if grad_clip_config is not None:
45
        grad_clip_name = grad_clip_config.pop("name", "ClipGradByGlobalNorm")
46
        clip_norm = grad_clip_config.get("clip_norm", 1.0)
47
        grad_clip = eval(grad_clip_name)(**grad_clip_config) if clip_norm != 0.0 else None
48
        return grad_clip
49
    else:
50
        return None
51

52

53
def build_optimizer(config, model, lr_scheduler=None):
54
    config = copy.deepcopy(config)
55
    if lr_scheduler is not None:
56
        config.pop("lr")
57

58
    multi_precision = config.get("multi_precision", False)
59
    if multi_precision:
60
        paddle.nn.clip._clip_by_global_norm_using_mp_type(True)
61

62
    grad_clip_config = config.pop("grad_clip", None)
63
    grad_clip = build_grad_clip(grad_clip_config)
64

65
    optim_name = config.pop("name")
66
    optim = eval(optim_name)(learning_rate=lr_scheduler, parameters=model.parameters(), grad_clip=grad_clip, **config)
67

68
    logger.debug("build optimizer ({}) success..".format(optim))
69
    return optim
70

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

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

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

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