位置: IT常识 - 正文

网络模型的参数量和FLOPs的计算 Pytorch(网络模型参数方法)

编辑:rootadmin
网络模型的参数量和FLOPs的计算 Pytorch

目录

1、torchstat 

2、thop

3、fvcore 

4、flops_counter

5、自定义统计函数


推荐整理分享网络模型的参数量和FLOPs的计算 Pytorch(网络模型参数方法),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:网络模型的参数量是一层不变的吗,网络模型的参数设置,网络模型的参数是什么,网络模型参数量如何计算,网络模型的参数量,网络模型的参数是什么,网络模型的参数量是一层不变的吗,网络模型的参数有哪些,内容如对您有帮助,希望把文章链接给更多的朋友!

FLOPS和FLOPs的区别:

FLOPS:注意全大写,是floating point operations per second的缩写,意指每秒浮点运算次数,理解为计算速度。是一个衡量硬件性能的指标。FLOPs:注意s小写,是floating point operations的缩写(s表复数),意指浮点运算数,理解为计算量。可以用来衡量算法/模型的复杂度。

在介绍torchstat包和thop包之前,先总结一下:

torchstat包可以统计卷积神经网络和全连接神经网络的参数和计算量。thop包可以统计统计卷积神经网络、全连接神经网络以及循环神经网络的参数和计算量,程序示例等详见下文。1、torchstat pip install torchstat -i https://pypi.tuna.tsinghua.edu.cn/simple

在实际操作中,我们可以调用torchstat包,帮助我们统计模型的parameters和FLOPs。如果不修改这个包里面的一些代码,那么这个包只适用于输入为3通道的图像的模型。

import torchimport torch.nn as nnfrom torchstat import statclass Simple(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 16, 3, 1, padding=1, bias=False) self.conv2 = nn.Conv2d(16, 32, 3, 1, padding=1, bias=False) def forward(self, x): x = self.conv1(x) x = self.conv2(x) return xmodel = Simple()stat(model, (3, 244, 244)) # 统计模型的参数量和FLOPs,(3,244,244)是输入图像的size

 如果把torchstat包中的一行程序进行一点点改动,那么这个包可以用来统计全连接神经网络的参数量和计算量。当然手动计算全连接神经网络的参数量和计算量也很快 =_= 。进入torchstat源代码之后,如下图所示,注释掉圈红的地方,就可以用torchstat包统计全连接神经网络的参数量和计算量了。

网络模型的参数量和FLOPs的计算 Pytorch(网络模型参数方法)

2、thoppip install thop -i https://pypi.tuna.tsinghua.edu.cn/simpleimport torchimport torch.nn as nnfrom thop import profileclass Simple(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10, 10) def forward(self, x): x = self.fc1(x) return xnet = Simple()input = torch.randn(1, 10) # batchsize=1, 输入向量长度为10macs, params = profile(net, inputs=(input, ))print(' FLOPs: ', macs*2) # 一般来讲,FLOPs是macs的两倍print('params: ', params)3、fvcore pip install fvcore -i https://pypi.tuna.tsinghua.edu.cn/simple

用它比较好

import torchfrom torchvision.models import resnet50from fvcore.nn import FlopCountAnalysis, parameter_count_table# 创建resnet50网络model = resnet50(num_classes=1000)# 创建输入网络的tensortensor = (torch.rand(1, 3, 224, 224),)# 分析FLOPsflops = FlopCountAnalysis(model, tensor)print("FLOPs: ", flops.total())# 分析parametersprint(parameter_count_table(model))

 终端输出结果如下,FLOPs为4089184256,模型参数数量约为25.6M(这里的参数数量和我自己计算的有些出入,主要是在BN模块中,这里只计算了beta和gamma两个训练参数,没有统计moving_mean和moving_var两个参数),具体可以看下我在官方提的issue。 通过终端打印的信息我们可以发现在计算FLOPs时并没有包含BN层,池化层还有普通的add操作(我发现计算FLOPs时并没有统一的规定,在github上看的计算FLOPs项目基本每个都不同,但计算出来的结果大同小异)。

注意:在使用fvcore模块计算模型的flops时,遇到了问题,记录一下解决方案。首先是在jit_analysis.py的589行出错。经过调试发现,op_counts.values()的类型是int32,但是计算要求的类型只能是int、float、np.float64和np.int64,因此需要手动进行强制转换。修改如下:

4、flops_counterpip install ptflops -i https://pypi.tuna.tsinghua.edu.cn/simple

用它也很好,结果和fvcore一样

from ptflops import get_model_complexity_infomacs, params = get_model_complexity_info(model, (112, 9, 9), as_strings=True, print_per_layer_stat=True, verbose=True)print('{:<30} {:<8}'.format('Computational complexity: ', macs))print('{:<30} {:<8}'.format('Number of parameters: ', params))

5、自定义统计函数import torchimport numpy as npdef calc_flops(model, input): def conv_hook(self, input, output): batch_size, input_channels, input_height, input_width = input[0].size() output_channels, output_height, output_width = output[0].size() kernel_ops = self.kernel_size[0] * self.kernel_size[1] * (self.in_channels / self.groups) * ( 2 if multiply_adds else 1) bias_ops = 1 if self.bias is not None else 0 params = output_channels * (kernel_ops + bias_ops) flops = batch_size * params * output_height * output_width list_conv.append(flops) def linear_hook(self, input, output): batch_size = input[0].size(0) if input[0].dim() == 2 else 1 num_steps = input[0].size(0) weight_ops = self.weight.nelement() * (2 if multiply_adds else 1) bias_ops = self.bias.nelement() if self.bias is not None else 0 flops = batch_size * (weight_ops + bias_ops) flops *= num_steps list_linear.append(flops) def fsmn_hook(self, input, output): batch_size = input[0].size(0) if input[0].dim() == 2 else 1 weight_ops = self.filter.nelement() * (2 if multiply_adds else 1) num_steps = input[0].size(0) flops = num_steps * weight_ops flops *= batch_size list_fsmn.append(flops) def gru_cell(input_size, hidden_size, bias=True): total_ops = 0 # r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ # z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ state_ops = (hidden_size + input_size) * hidden_size + hidden_size if bias: state_ops += hidden_size * 2 total_ops += state_ops * 2 # n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\ total_ops += (hidden_size + input_size) * hidden_size + hidden_size if bias: total_ops += hidden_size * 2 # r hadamard : r * (~) total_ops += hidden_size # h' = (1 - z) * n + z * h # hadamard hadamard add total_ops += hidden_size * 3 return total_ops def gru_hook(self, input, output): batch_size = input[0].size(0) if input[0].dim() == 2 else 1 if self.batch_first: batch_size = input[0].size(0) num_steps = input[0].size(1) else: batch_size = input[0].size(1) num_steps = input[0].size(0) total_ops = 0 bias = self.bias input_size = self.input_size hidden_size = self.hidden_size num_layers = self.num_layers total_ops = 0 total_ops += gru_cell(input_size, hidden_size, bias) for i in range(num_layers - 1): total_ops += gru_cell(hidden_size, hidden_size, bias) total_ops *= batch_size total_ops *= num_steps list_lstm.append(total_ops) def lstm_cell(input_size, hidden_size, bias): total_ops = 0 state_ops = (input_size + hidden_size) * hidden_size + hidden_size if bias: state_ops += hidden_size * 2 total_ops += state_ops * 4 total_ops += hidden_size * 3 total_ops += hidden_size return total_ops def lstm_hook(self, input, output): batch_size = input[0].size(0) if input[0].dim() == 2 else 1 if self.batch_first: batch_size = input[0].size(0) num_steps = input[0].size(1) else: batch_size = input[0].size(1) num_steps = input[0].size(0) total_ops = 0 bias = self.bias input_size = self.input_size hidden_size = self.hidden_size num_layers = self.num_layers total_ops = 0 total_ops += lstm_cell(input_size, hidden_size, bias) for i in range(num_layers - 1): total_ops += lstm_cell(hidden_size, hidden_size, bias) total_ops *= batch_size total_ops *= num_steps list_lstm.append(total_ops) def bn_hook(self, input, output): list_bn.append(input[0].nelement()) def relu_hook(self, input, output): list_relu.append(input[0].nelement()) def pooling_hook(self, input, output): batch_size, input_channels, input_height, input_width = input[0].size() output_channels, output_height, output_width = output[0].size() kernel_ops = self.kernel_size * self.kernel_size bias_ops = 0 params = output_channels * (kernel_ops + bias_ops) flops = batch_size * params * output_height * output_width list_pooling.append(flops) def foo(net): childrens = list(net.children()) if not childrens: print(net) if isinstance(net, torch.nn.Conv2d) or isinstance(net, torch.nn.ConvTranspose2d): net.register_forward_hook(conv_hook) # print('conv_hook_ready') if isinstance(net, torch.nn.Linear): net.register_forward_hook(linear_hook) # print('linear_hook_ready') if isinstance(net, torch.nn.BatchNorm2d): net.register_forward_hook(bn_hook) # print('batch_norm_hook_ready') if isinstance(net, torch.nn.ReLU) or isinstance(net, torch.nn.PReLU): net.register_forward_hook(relu_hook) # print('relu_hook_ready') if isinstance(net, torch.nn.MaxPool2d) or isinstance(net, torch.nn.AvgPool2d): net.register_forward_hook(pooling_hook) # print('pooling_hook_ready') if isinstance(net, torch.nn.LSTM): net.register_forward_hook(lstm_hook) # print('lstm_hook_ready') if isinstance(net, torch.nn.GRU): net.register_forward_hook(gru_hook) # if isinstance(net, FSMNZQ): # net.register_forward_hook(fsmn_hook) # print('fsmn_hook_ready') return for c in childrens: foo(c) multiply_adds = False list_conv, list_bn, list_relu, list_linear, list_pooling, list_lstm, list_fsmn = [], [], [], [], [], [], [] foo(model) _ = model(input) total_flops = (sum(list_conv) + sum(list_linear) + sum(list_bn) + sum(list_relu) + sum(list_pooling) + sum( list_lstm) + sum(list_fsmn)) fsmn_flops = (sum(list_fsmn) + sum(list_linear)) lstm_flops = sum(list_lstm) model_parameters = filter(lambda p: p.requires_grad, model.parameters()) params = sum([np.prod(p.size()) for p in model_parameters]) print('The network has {} params.'.format(params)) print(total_flops, fsmn_flops, lstm_flops) print(' + Number of FLOPs: %.2f M' % (total_flops / 1000 ** 2)) return total_flopsif __name__ == '__main__': from torchvision.models import resnet18 model = resnet18(num_classes=1000) imput_size = torch.rand((1,3,224,224)) calc_flops(model, imput_size)

本文链接地址:https://www.jiuchutong.com/zhishi/299382.html 转载请保留说明!

上一篇:c++STL急急急(c++stl详解)

下一篇:40个web前端实战项目,练完即可就业,从入门到进阶,基础到框架,html_css【附视频+源码】(web前端视频教程全套)

  • 成都月饼包装免费设计_成都月饼包装设计公司_成都中秋节月饼包装设计(成都哪里有月饼盒批发)

    成都月饼包装免费设计_成都月饼包装设计公司_成都中秋节月饼包装设计(成都哪里有月饼盒批发)

  • 腾讯课堂怎么关闭麦克风权限(腾讯课堂怎么关闭麦克风和摄像头)

    腾讯课堂怎么关闭麦克风权限(腾讯课堂怎么关闭麦克风和摄像头)

  • 华为如何设置永不休眠(华为如何设置永不熄灭屏幕)

    华为如何设置永不休眠(华为如何设置永不熄灭屏幕)

  • 华为荣耀20青春版怎么设置返回键(华为荣耀20青春版有没有nfc功能)

    华为荣耀20青春版怎么设置返回键(华为荣耀20青春版有没有nfc功能)

  • 小米lot模组是什么

    小米lot模组是什么

  • 华为mate30充电时手机发热

    华为mate30充电时手机发热

  • 为什么抖音关注了后还显示没有关注(为什么抖音关注了却不显示)

    为什么抖音关注了后还显示没有关注(为什么抖音关注了却不显示)

  • 公众号有哪些类型呢(公众号有哪些类型)

    公众号有哪些类型呢(公众号有哪些类型)

  • 红包能退回去吗(微信抢了红包能退回去吗)

    红包能退回去吗(微信抢了红包能退回去吗)

  • 雷电3接口和typec通用吗(雷电3接口和typec什么区别)

    雷电3接口和typec通用吗(雷电3接口和typec什么区别)

  • iphone账户详情不可用(iphone账户详情不可用是什么意思)

    iphone账户详情不可用(iphone账户详情不可用是什么意思)

  • 怎么把图片变成png格式(怎么把图片变成高清图)

    怎么把图片变成png格式(怎么把图片变成高清图)

  • 苹果支持快充的机型(苹果支持快充的机型有哪些)

    苹果支持快充的机型(苹果支持快充的机型有哪些)

  • 淘宝匿名评价买家能看到吗(淘宝匿名评价显示是什么样)

    淘宝匿名评价买家能看到吗(淘宝匿名评价显示是什么样)

  • vivo手机关机闹钟会响吗(vivo手机关机闹钟还会响起来吗)

    vivo手机关机闹钟会响吗(vivo手机关机闹钟还会响起来吗)

  • 抖音心愿单在哪里看(抖音心愿单在哪里弄)

    抖音心愿单在哪里看(抖音心愿单在哪里弄)

  • html5的优势(HTML5的优势主要体现在)

    html5的优势(HTML5的优势主要体现在)

  • 华为手机怎么添加铃声(华为手机怎么添加时间和天气)

    华为手机怎么添加铃声(华为手机怎么添加时间和天气)

  • 苹果电脑怎么拖动文件(苹果电脑怎么拖动图标)

    苹果电脑怎么拖动文件(苹果电脑怎么拖动图标)

  • 电脑怎么安装(电脑怎么安装win10系统)

    电脑怎么安装(电脑怎么安装win10系统)

  • 淘宝短视频制作方法有哪些(淘宝短视频制作及上传)

    淘宝短视频制作方法有哪些(淘宝短视频制作及上传)

  • vivox27左边的按键是干什么的(vivox27左侧面的按键)

    vivox27左边的按键是干什么的(vivox27左侧面的按键)

  • vivo手机怎么在首页显示时间(vivo手机怎么在电视上投屏)

    vivo手机怎么在首页显示时间(vivo手机怎么在电视上投屏)

  • 时间财富成立多久了(时间财富app)

    时间财富成立多久了(时间财富app)

  • 打印凭证怎么设置纸张(打印凭证怎么设置成信封c5)

    打印凭证怎么设置纸张(打印凭证怎么设置成信封c5)

  • Stable Diffusion 准确绘制人物动作及手脚细节(需ControlNet扩展)

    Stable Diffusion 准确绘制人物动作及手脚细节(需ControlNet扩展)

  • 延期缴税申请需要先申报吗?
  • 买车交的保险
  • 个税由公司承担的账务处理
  • 支付宝理财提现到银行卡有费用吗
  • 小规模电子发票一张可以开多少金额
  • 税收的三个基本要素是
  • 经纪代理服务怎么做分录
  • 上月暂估收入本月开票增值税实操
  • 出口抵内销产品应纳税额分录
  • 股权转让资产怎么清算
  • 两所工资所得怎么扣税
  • 总公司调到子公司
  • 水利建设基金有优惠政策吗
  • 增值税发票过期了税金怎么办
  • 企业所得税纳税申报表A类
  • 应交税费的期初余额是借还是贷
  • 其他综合收益可以转损益的情况
  • 京挑客怎么赚钱
  • 预付的费用没有还没有收到发票
  • 免抵退转免税
  • 企业银行保证金账户怎么查询
  • 哪些工资薪酬可以进行税前扣除?
  • 税基式减免的内容有哪些?
  • 给员工购买的意外保险可以税前扣除
  • 分公司与总公司的关系
  • linux attached
  • regsync.exe - regsync是什么进程 有什么用
  • 营改增后租金如何交税
  • 行政事业单位捐款支出怎么记账
  • 外贸企业出口免抵退
  • php rediscluster
  • 数字马力前端笔试题rgb
  • PHP:imagealphablending()的用法_GD库图像处理函数
  • php exit绕过
  • uniapp控制硬件设备
  • 预缴的附加税怎么填表抵减
  • echarts地图参数设置
  • 债务重组利得计入其他收益还是营业外收入
  • 可以抵扣的项目有哪些
  • 什么是进项票什么是成本票
  • ctrl ate del
  • 政府补助的会计准则
  • php上传视频到服务器
  • 工业企业成本核算的一般程序
  • 500元以下开收据要交税吗
  • 现金零星支出大还是小
  • 劳务报酬根据什么确定
  • 瀑布流样式
  • python smtpd
  • 税额和税款是一回事吗
  • 企业注销其他应收款有数,要交税吗?
  • 个人所得税专项附加扣除2023
  • 固定制造费用属于固定成本吗
  • 出口免税申报流程视频
  • 无形资产的摊销年限及摊销方法
  • 利润分配未分配利润期末有余额吗
  • 另一种收到企业信息英文
  • 公司应该怎么记账
  • 对于审核后的凭证可直接修改对吗
  • 暂估入库后发票来不了会计分录
  • 品种法案例分析
  • 旅行社的代订机票产品能报销吗
  • centos安装编译环境
  • winxp系统如何设置禁用磁盘检测功能
  • Ubuntu安装ssh
  • centos7配置免密登录
  • win10预览版21301bug
  • linux find . -name命令
  • win10快捷键合集
  • 如何在linux中添加环境变量
  • win7系统如何给文件夹加密
  • win8 设置
  • bass表示什么
  • eval()方法
  • js不重复集合
  • javascript定义数组的方法
  • duck有鸭肉的意思吗
  • 市直单位正职是市单位一把手吗
  • 独生子女补贴和退休金一起发吗
  • 税审工作流程
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设