torch 实现inverse-square-root scheduler

python 复制代码
import cv2
import torch.nn as nn
import torch
from torchvision.models import AlexNet
import matplotlib.pyplot as plt

from torch.optim.lr_scheduler import LambdaLR
def get_inverse_sqrt_scheduler(optimizer, num_warmup_steps, num_cooldown_steps, num_training_steps):
    # linearly warmup for the first args.warmup_updates
    lr_step = 1 / num_warmup_steps
    # then, decay prop. to the inverse square root of the update number
    decay_factor = num_warmup_steps**0.5
    decayed_lr = decay_factor * (num_training_steps - num_cooldown_steps) ** -0.5
    def lr_lambda(current_step: int):
        if current_step < num_warmup_steps:
            return float(current_step * lr_step)
        elif current_step > (num_training_steps - num_cooldown_steps):
            return max(0.0, float(decayed_lr * (num_training_steps - current_step) / num_cooldown_steps))
        else:
            return float(decay_factor * current_step**-0.5)

    return LambdaLR(optimizer, lr_lambda, last_epoch=-1)

#定义2分类网络
steps = []
lrs = []
model = AlexNet(num_classes=2)
lr = 0.1
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
#前10steps warmup ,中间70steps正常衰减,最后20个steps期间衰减到0
scheduler = get_inverse_sqrt_scheduler(optimizer,num_warmup_steps=10, num_cooldown_steps=20, num_training_steps=100)
for epoch in range(10):
    for batch in range(10):
        scheduler.step()
        lrs.append(scheduler.get_lr()[0])
        steps.append(epoch*10+batch)
 
 
plt.figure()
plt.legend()
plt.plot(steps, lrs, label='inverse_sqrt')
plt.savefig("dd.png")
相关推荐
仅此,7 分钟前
deep agent整合 DeepSeek 记录
python·langchain·agent·deep agent sdk
数智工坊12 分钟前
基于CLIP隐空间的层级文本条件图像生成:unCLIP核心原理与全链路解析
论文阅读·人工智能·深度学习·transformer·迁移学习
雪回14 分钟前
基于 Stable Diffusion-WebUI 实现 LandPPT 本地模型绘图配置指南(SDWebUI )
人工智能·深度学习·ai·ai作画·stable diffusion·ppt
ftpeak29 分钟前
AI开发之LangGraph教程6~自定义状态 (Custom State)
python·ai·langchain·langgraph
m0_7381207243 分钟前
渗透测试——Djinn1靶场详细渗透提权过程讲解(绕过黑名单限制,命令执行反弹shell,pyc反编译,代码白盒分析,python沙盒逃逸)
开发语言·python·php
Ares-Wang1 小时前
AI》》欧氏距离、曼哈顿距离 切比雪夫距离 等
人工智能·python
陈eaten1 小时前
windows上协调多版本python以及虚拟环境
开发语言·windows·python·pycharm·pip·虚拟环境·py
一晌小贪欢2 小时前
告别 `datetime` 混乱:使用 Python 类型注解构建健壮的时间处理管道
开发语言·python·时间·时间类型·时间模块
嘛?2507012 小时前
Python高阶基础
python
li星野2 小时前
哈希表通关八题:从两数之和到LRU缓存,手撕高频面试题(Python + C++)
python·缓存·散列表