Pytorch mixed precision 概述(混合精度)
程序员大白
共 3611字,需浏览 8分钟
· 2021-04-17
点击上方“程序员大白”,选择“星标”公众号
重磅干货,第一时间送达
01
import torchvision
import torch
import torch.cuda.amp
import gc
import time
# Timing utilities
start_time = None
def start_timer():
global start_time
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.synchronize() # 同步后得出的时间才是实际运行的时间
start_time = time.time()
def end_timer_and_print(local_msg):
torch.cuda.synchronize()
end_time = time.time()
print("\n" + local_msg)
print("Total execution time = {:.3f} sec".format(end_time - start_time))
print("Max memory used by tensors = {} bytes".format(torch.cuda.max_memory_allocated()))
num_batches = 50
batch_size = 70
epochs = 3
# 随机创建训练数据
data = [torch.randn(batch_size, 3, 224, 224, device="cuda") for _ in range(num_batches)]
targets = [torch.randint(0, 1000, size=(batch_size, ), device='cuda') for _ in range(num_batches)]
# 创建一个模型
net = torchvision.models.resnext50_32x4d().cuda()
# 定义损失函数
loss_fn = torch.nn.CrossEntropyLoss().cuda()
# 定义优化器
opt = torch.optim.SGD(net.parameters(), lr=0.001)
# 是否使用混合精度训练
use_amp = True
# Constructs scaler once, at the beginning of the convergence run, using default args.
# If your network fails to converge with default GradScaler args, please file an issue.
# The same GradScaler instance should be used for the entire convergence run.
# If you perform multiple convergence runs in the same script, each run should use
# a dedicated fresh GradScaler instance. GradScaler instances are lightweight.
scaler = torch.cuda.amp.GradScaler(enabled=use_amp)
start_timer()
for epoch in range(epochs):
for input, target in zip(data, targets):
with torch.cuda.amp.autocast(enabled=use_amp):
output = net(input)
loss = loss_fn(output, target)
# 放大loss Calls backward() on scaled loss to create scaled gradients.
scaler.scale(loss).backward()
# scaler.step() first unscales the gradients of the optimizer's assigned params.
# If these gradients do not contain infs or NaNs, optimizer.step() is then called,
# otherwise, optimizer.step() is skipped.
scaler.step(opt)
# Updates the scale for next iteration.
scaler.update()
opt.zero_grad(set_to_none=True) # set_to_none=True here can modestly improve performance
end_timer_and_print("Mixed precision:")
02
混合精度测试
推荐阅读
关于程序员大白
程序员大白是一群哈工大,东北大学,西湖大学和上海交通大学的硕士博士运营维护的号,大家乐于分享高质量文章,喜欢总结知识,欢迎关注[程序员大白],大家一起学习进步!
评论
人工智能周刊#17:Llama3、微调 LLMs 的 PyTorch 原生库、李彦宏内部讲话、900 个最受欢迎的AI 工具
在内部讲话中,李彦宏对大模型开源与闭源的路线选择,以及 AI 创业者应该专注模型还是应用等业界焦点话题,发表了自己的看法。人工智能周刊:关注Python、机器学习、深度学习、大模型等硬核技术本期目录:1、Meta 最新发布 Llama 3 80 亿和 700 亿参数版本2、「抱抱脸」公
机器学习算法与Python实战
10
精度最高降幅60%!SOTA只是假象?CVPR2024 Highlight为你揭示CLIP和LLaVA-Next等模型“骗局”
作者丨派派星来源丨CVHub编辑丨极市平台导读 这篇论文提出了利用diffusion model作为data source来测评模型鲁棒性。提出的ImageNet-D数据集有效地降低state-of-art模型的测试准确率,降低幅度最高达60%,其中便包括了 CLIP,MiniGPT-4和
AI算法与图像处理
10
系统调优助手,PyTorch Profiler TensorBoard 插件教程
0x1. 前言使用PyTorch Profiler进行性能分析已经一段时间了,毕竟是PyTorch提供的原生profile工具,个人感觉做系统性能分析时感觉比Nsys更方便一些,并且画的图也比较直观。这里翻译一下PyTorch Profiler TensorBoard Plugin的教程并分享一些使
GiantPandaCV
6
扩散模型的原理及实现(Pytorch)
来源:机器学习算法那些事本文约6500字,建议阅读13分钟本文完整的介绍了有关扩散模型的必要知识,并且使用Pytorch进行了完整的实现。扩散模型的导火索,是始于2020 年所提出的DDPM(Denoising Diffusion Probabilis...
数据派THU
0
LoRA及其变体概述:LoRA, DoRA, AdaLoRA, Delta-LoRA
来源:Deephub Imba本文约4000字,建议阅读6分钟本文我们将解释LoRA本身的基本概念,然后介绍一些以不同的方式改进LoRA的功能的变体。LoRA可以说是针对特定任务高效训练大型语言模型的重大突破。它被广泛应用于许多...
数据派THU
0
全新SOTA骨干网络HIRI-ViT | 大力出奇迹,高分辨率+双路径设计,让Backbone卖力生产精度
点击下方卡片,关注「集智书童」公众号点击加入?「集智书童」交流群视觉Transformer(ViT)与卷积神经网络(CNN)的混合深度模型已经成为视觉任务中的一类强大的基础架构。扩大这类混合基础架构的输入分辨率自然会增...
AI人工智能初学者
0
Unet++(pytorch实现)
向AI转型的程序员都关注了这个号??? Unet++网络 Dense connection Unet++继承了Unet的结构,同时又借鉴了DenseNet的稠密连接方式(图1中各种分支)。 作者通过各层之间的稠密连接,互相连接起来,就像Denset那样,前...
机器学习AI算法工程
0
深度学习在股市的应用概述
【导读】大家好,我是泳鱼。一个乐于探索和分享AI知识的码农! 股票市场预测由于其非线性、高度波动性和复杂性,一直是个复杂的问题。近年来,深度学习在许多领域占据了主导地位,在股市预测方面取得了巨大的 成功...
算法进阶
0