RTDETR更換Lion優化器
論文:https://arxiv.org/abs/2302.06675
代碼:https://github.com/google/automl/blob/master/lion/lion_pytorch.py
簡介:
Lion優化器是一種基于梯度的優化算法,旨在提高梯度下降法在深度學習中的優化效果。Lion優化器具有以下幾個特點:
-
自適應學習率:Lion優化器能夠自動調整學習率,根據每個參數的梯度情況來自適應地更新學習率。這使得模型能夠更快地收斂,并且不易陷入局部最優點。
-
動量加速:Lion優化器引入了動量概念,通過積累歷史梯度的一部分來加速梯度更新。這樣可以增加參數更新的穩定性,避免陷入震蕩或振蕩狀態。
-
參數分布均衡:Lion優化器通過分析模型參數的梯度分布情況,對梯度進行動態調整,以實現參數分布的均衡。這有助于避免某些參數過于稀疏或過于密集的問題,提高模型的泛化能力。
與AdamW 和各種自適應優化器需要同時保存一階和二階矩相比,Lion 只需要動量,將額外的內存占用減半;
由于 Lion 的簡單性,Lion 在我們的實驗中具有更快的運行時間(step/s),通常比 AdamW 和 Adafactor 提速 2-15%;
優化器代碼:
# Copyright 2023 Google Research. All Rights Reserved.
#
# 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.
# ==============================================================================
"""PyTorch implementation of the Lion optimizer."""
import torch
from torch.optim.optimizer import Optimizerclass Lion(Optimizer):r"""Implements Lion algorithm."""def __init__(self, params, lr=1e-4, betas=(0.9, 0.99), weight_decay=0.0):"""Initialize the hyperparameters.Args:params (iterable): iterable of parameters to optimize or dicts definingparameter groupslr (float, optional): learning rate (default: 1e-4)betas (Tuple[float, float], optional): coefficients used for computingrunning averages of gradient and its square (default: (0.9, 0.99))weight_decay (float, optional): weight decay coefficient (default: 0)"""if not 0.0 <= lr:raise ValueError('Invalid learning rate: {}'.format(lr))if not 0.0 <= betas[0] < 1.0:raise ValueError('Invalid beta parameter at index 0: {}'.format(betas[0]))if not 0.0 <= betas[1] < 1.0:raise ValueError('Invalid beta parameter at index 1: {}'.format(betas[1]))defaults = dict(lr=lr, betas=betas, weight_decay=weight_decay)super().__init__(params, defaults)@torch.no_grad()def step(self, closure=None):"""Performs a single optimization step.Args:closure (callable, optional): A closure that reevaluates the modeland returns the loss.Returns:the loss."""loss = Noneif closure is not None:with torch.enable_grad():loss = closure()for group in self.param_groups:for p in group['params']:if p.grad is None:continue# Perform stepweight decayp.data.mul_(1 - group['lr'] * group['weight_decay'])grad = p.gradstate = self.state[p]# State initializationif len(state) == 0:# Exponential moving average of gradient valuesstate['exp_avg'] = torch.zeros_like(p)exp_avg = state['exp_avg']beta1, beta2 = group['betas']# Weight updateupdate = exp_avg * beta1 + grad * (1 - beta1)p.add_(update.sign_(), alpha=-group['lr'])# Decay the momentum running average coefficientexp_avg.mul_(beta2).add_(grad, alpha=1 - beta2)return loss
將上述代碼復制粘貼在ultralytics/engine下創建lion_pytorch.py文件。
在ultralytics/engine/trainer.py中導入Lion
from ultralytics.engine.lion_pytorch import Lion
然后在def build_optimizer(self)函數中加入下列代碼
elif name == 'Lion':optimizer = Lion(g[2])
之后就可以在訓練時使用Lion優化器了
results = model.train(data="ultralytics/cfg/datasets/coco.yaml", epochs=500, batch=16, workers=8,resume=False,close_mosaic=10, name='cfg', patience=500, pretrained=False, cos_lr=True,optimizer ='Lion',device=1) # 訓練模型