最近看了很多关于FLOPs计算的实现方法,也自己尝试了一些方法,发现最好用的还是PyTorch中的thop库(代码如下):

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = 模型的名字().to(device)
inputs = torch.randn(1,3,512,1024)   ####(360,640)
inputs=inputs.to(device)
macs, params = profile(model,inputs=(inputs,))   ##verbose=False
print('The number of MACs is %s'%(macs/1e9))   ##### MB
print('The number of params is %s'%(params/1e6))   ##### MB

实现起来确实很简单,那么问题来了,这里面算出来的macs到底是MACs还是FLOPs呢?先说我自己探索得到的结论,这里计算出的macs其实就是FLOPs(每秒钟浮点运算次数),前提是:不计算卷积层的bias,原因如下:

自己手动计算ResNet18的FLOPs,对于512*1024*3的输入尺寸。

(1)ResNet18的代码:

class BasicBlock(nn.Module):expansion = 1def __init__(self, inplanes, planes, r=1, stride=1, downsample=None, norm_layer=nn.BatchNorm2d):super(BasicBlock, self).__init__()# Both self.conv1 and self.downsample layers downsample the input when stride != 1self.conv1 = conv3x3(inplanes, planes, stride)self.bn1 = norm_layer(planes)self.relu = nn.ReLU(inplace=True)self.conv2 = conv3x3(planes, planes, dilation=r)self.bn2 = norm_layer(planes)self.downsample = downsampleself.stride = stridedef forward(self, x):identity = xout = self.conv1(x)out = self.bn1(out)out = self.relu(out)out = self.conv2(out)out = self.bn2(out)if self.downsample is not None:identity = self.downsample(x)out += identityout = self.relu(out)return outclass ResNet18(nn.Module):def __init__(self, block=BasicBlock, layers=[2,2,2,2], zero_init_residual=False, norm_layer=nn.BatchNorm2d):super(ResNet18, self).__init__()self.inplanes = 64self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,bias=False)self.bn1 = norm_layer(64)self.relu = nn.ReLU(inplace=True)self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)self.layer1 = self._make_layer(block, 64, layers[0], r=2, norm_layer=norm_layer)self.layer2 = self._make_layer(block, 128, layers[1], stride=2, r=2, norm_layer=norm_layer)self.layer3 = self._make_layer(block, 256, layers[2], stride=2, r=2, norm_layer=norm_layer)self.layer4 = self._make_layer(block, 512, layers[3], stride=2, r=2, norm_layer=norm_layer)for m in self.modules():if isinstance(m, nn.Conv2d):nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')elif isinstance(m, nn.BatchNorm2d):nn.init.constant_(m.weight, 1)nn.init.constant_(m.bias, 0)# Zero-initialize the last BN in each residual branch,# so that the residual branch starts with zeros, and each residual block behaves like an identity.# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677if zero_init_residual:for m in self.modules():if isinstance(m, Bottleneck):nn.init.constant_(m.bn3.weight, 0)elif isinstance(m, BasicBlock):nn.init.constant_(m.bn2.weight, 0)def _make_layer(self, block, planes, blocks, stride=1, r=1, norm_layer=nn.BatchNorm2d):downsample = Noneif stride != 1 or self.inplanes != planes * block.expansion:downsample = nn.Sequential(conv1x1(self.inplanes, planes * block.expansion, stride),norm_layer(planes * block.expansion),)layers = []layers.append(block(self.inplanes, planes, r, stride, downsample))self.inplanes = planes * block.expansionfor _ in range(1, blocks):layers.append(block(self.inplanes, planes))return nn.Sequential(*layers)def forward(self, x):x = self.conv1(x)x = self.bn1(x)x = self.relu(x)x = self.maxpool(x)x = self.layer1(x)x = self.layer2(x)x_downsampling_8 = x       ###(h/8,128)x = self.layer3(x)x_downsampling_16 = x      ###(h/16,256)x = self.layer4(x)         ###(h/32,512)return x, x_downsampling_8, x_downsampling_16

(2)用profile函数计算得到的macs值为 19.0GB

(3)自己手动计算FLOPs ≈ 20GB

因此,在不统计卷积层bias计算次数的前提下,profile函数计算得到的macs值其实就是FLOPs。

(PS:个人理解,欢迎批评纠正)

PyTorch中FLOPs计算问题相关推荐

  1. 深度学习中FLOPs计算

    深度学习中FLOPs计算 定义:FLOPs(floating point operations),即浮点数运算次数,是一个计算量,所以可以用来衡量一个算法/模型等的复杂度 FLOPs是用来计算整个网络 ...

  2. pytorch 中 glu计算

    1. glu 计算 原理 demo dropout 原理 训练过程中,输入张量的一些元素按从伯努利分布中采样的概率p随机置零.在每个前向调用过程中每个通道都能被独立置零. Dropout方法证明被证明 ...

  3. pytorch梯度的计算过程

    1.基础知识: 与numpy中的基本操作相似, pytorch 的作用是引入GPU加快运算, 增加图形界面, 适合大数据运算, 尤其是deep learning gradient 梯度类似于求导, 找 ...

  4. 【深度学习理论】一文搞透pytorch中的tensor、autograd、反向传播和计算图

    转载:https://zhuanlan.zhihu.com/p/145353262 前言 本文的主要目标: 一遍搞懂反向传播的底层原理,以及其在深度学习框架pytorch中的实现机制.当然一遍搞不定两 ...

  5. CNN中parameters和FLOPs计算

    CNN中parameters和FLOPs计算 以AlexNet为例,先注意观察每层编注的通道数的变化. 1. 卷积网络的参数量的计算(parameters) CNN中的parameters分为两种:W ...

  6. Pytorch中的向前计算(autograd)、梯度计算以及实现线性回归操作

    在整个Pytorch框架中, 所有的神经网络本质上都是一个autograd package(自动求导工具包) autograd package提供了一个对Tensors上所有的操作进行自动微分的功能. ...

  7. 神经网络中参数量parameters和FLOPs计算

    一.神经网络中参数量parameters和FLOPs计算 CNN中的parameters分为两种:W和b,对于某一个卷积层,它的parameters的个数为: (Kh∗Kw∗Cin)∗Cout+Cou ...

  8. 如何利用PyTorch中的Moco-V2减少计算约束

    介绍 SimCLR论文(http://cse.iitkgp.ac.in/~arastogi/papers/simclr.pdf)解释了这个框架如何从更大的模型和更大的批处理中获益,并且如果有足够的计算 ...

  9. pytorch 模型可视化_PyTorch Tips(FLOPs计算/参数量/计算图可视化/相关性分析)

    最近在做Research Project的时候,发现有些小工具很好用,记录在此. 1. 准确的FLOPS 计算 网上开源的很多计算flops的工具只支持计算PyTorch内置层的flops,不能有效计 ...

最新文章

  1. python文本处理实例_Python 文件处理的简单示例
  2. 技嘉主板万能网卡驱动_技嘉Z490系列主板来袭:16相供电/钽电容,堆料更进一步...
  3. springmvc 前端传给后台中文数据时,会产生乱码
  4. hiredis(Synchronous API)
  5. Oracle Enterprises Manager 12C安装
  6. python考试有什么用_Python有什么用?2020年学习Python的10个理由
  7. Sublime Text 3 搭建 React.js 开发环境
  8. sql sum 结果集不为零_sql语句分类练习题
  9. 获得1.5亿区块链投资后,矩阵元怎么做区块链?
  10. zabbix 监控percona
  11. Python入门之经典练习题
  12. 欧拉角Yaw、Pitch、Roll
  13. ClassCastException: XXX are in unnamed module of loader ‘app‘异常分析
  14. 用计算机处理表格说课稿,信息技术《电子表格的特点及应用》的说课稿
  15. 黑马主播单场带货千万,抖音直播市场还有哪些新机遇?
  16. [人工智能-深度学习-61]:生成对抗网络GAN - 图像融合的基本原理与案例
  17. 网络七层协议地图,报文格式一览无遗。绝对是干货,值得收藏
  18. linux模拟usb发包,Linux下USB模拟ps2鼠标驱动
  19. LSM-tree基本原理及应用
  20. thymeleaf 调用后台方法

热门文章

  1. 分享到微信,qq空间,微博
  2. Linux系统的定时任务
  3. 中维带你揭秘倾斜摄影三维实景
  4. Python爬虫(6):比Selenium快100倍的方法爬东方财富网财务报表
  5. 怎样设置计算机默认字体及语言,电脑中默认输入法如何设置 Win7系统设置默认输入法技巧...
  6. 机器学习实战——决策树Python实现问题记录
  7. 华为nova8pro和荣耀60pro哪个好
  8. 弘辽科技:拼多多新手该如何提升直通车权重?
  9. MySQL——————表的查询
  10. 【论文研读】Similarity of Neural Network Representations Revisited (ICML2019)