位置: 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前端视频教程全套)

  • 有目标的人,就会有路(有目标的人就是不一样)

    有目标的人,就会有路(有目标的人就是不一样)

  • 华为nova9pro怎么连接电脑(华为nova9pro怎么分屏操作)

    华为nova9pro怎么连接电脑(华为nova9pro怎么分屏操作)

  • 真我gtneo2t屏幕材质(真我gtneo2T屏幕刷新率)

    真我gtneo2t屏幕材质(真我gtneo2T屏幕刷新率)

  • 手机微信清理了缓存,聊天记录还在吗(手机微信清理了怎么恢复)

    手机微信清理了缓存,聊天记录还在吗(手机微信清理了怎么恢复)

  • 华为p40pro手电筒快捷键是什么(华为mate50手电筒)

    华为p40pro手电筒快捷键是什么(华为mate50手电筒)

  • 手机号可以卖吗(手机号可以卖吗什么样的号码比较贵)

    手机号可以卖吗(手机号可以卖吗什么样的号码比较贵)

  • OTG为什么连不上

    OTG为什么连不上

  • 苹果手机换国产屏影响使用吗(苹果手机换国产屏有原彩吗)

    苹果手机换国产屏影响使用吗(苹果手机换国产屏有原彩吗)

  • 电脑开机黑屏主机风扇一直响(电脑开机黑屏主板亮黄灯)

    电脑开机黑屏主机风扇一直响(电脑开机黑屏主板亮黄灯)

  • 通过qq号可以查到手机号码吗(通过qq号可以查到什么社交软件)

    通过qq号可以查到手机号码吗(通过qq号可以查到什么社交软件)

  • oppor11截图怎么截(oppo r11s 截图)

    oppor11截图怎么截(oppo r11s 截图)

  • 斐讯运动闪退解决方法(斐讯运动闪退解决方案)

    斐讯运动闪退解决方法(斐讯运动闪退解决方案)

  • 机械硬盘隔一会响一次(机械硬盘隔一会咔一声)

    机械硬盘隔一会响一次(机械硬盘隔一会咔一声)

  • 为什么连蓝牙网络变差(为什么连蓝牙网易云自动弹出来)

    为什么连蓝牙网络变差(为什么连蓝牙网易云自动弹出来)

  • iphone11发热严重怎么解决(iphone11发热严重耗电快)

    iphone11发热严重怎么解决(iphone11发热严重耗电快)

  • 苹果手机怎么唤醒小爱音箱(苹果手机怎么唤醒密码解锁)

    苹果手机怎么唤醒小爱音箱(苹果手机怎么唤醒密码解锁)

  • 未开售怎么加入购物车(未开售商品先加购物车)

    未开售怎么加入购物车(未开售商品先加购物车)

  • 超长视频怎么微信发送(过长的视频微信怎么发送给朋友)

    超长视频怎么微信发送(过长的视频微信怎么发送给朋友)

  • 防蹭网怎么设置(随身wifi防蹭网怎么设置)

    防蹭网怎么设置(随身wifi防蹭网怎么设置)

  • vivo浏览器的热点关闭(vivo浏览器热门下载怎么关闭)

    vivo浏览器的热点关闭(vivo浏览器热门下载怎么关闭)

  • qq音乐有访客记录吗(qq音乐有访客记录但是看不到是谁)

    qq音乐有访客记录吗(qq音乐有访客记录但是看不到是谁)

  • 途牛旅游如何分期付款(途牛旅游分期怎么样)

    途牛旅游如何分期付款(途牛旅游分期怎么样)

  • Linux中使用ln命令在文件之间建立连接的用法讲解(linux命令“ln file1 file2”的含义是)

    Linux中使用ln命令在文件之间建立连接的用法讲解(linux命令“ln file1 file2”的含义是)

  • stable diffusion webui安装与使用(官方超简单教程)(stable diffusion webul)

    stable diffusion webui安装与使用(官方超简单教程)(stable diffusion webul)

  • 什么时候要计提坏账准备
  • 支付的运输费用计入什么科目
  • 小规模纳税人进货分录
  • 审计助理是做什么工作的
  • 银行日记账期初余额写在什么科目
  • 承兑汇票怎么做假
  • 每天现金日记账登记完以后应怎么对账
  • 税务登记法人变更后多久生效
  • 税务局代开的劳务费发票可以入账吗
  • 行政事业单位资产管理工作总结
  • 回拨工费经费怎么做会计分录?
  • 出口没有退税的发票
  • 新成立公司注资流程
  • 合作开发项目收益怎么算
  • 船运费发票抵扣多少税
  • 企业发票税收编码是什么
  • 未给对方开票对方举报情况怎么写
  • 建房子的公司
  • 资产损失税前扣除备查资料
  • 合伙创业如何分配财产
  • 进口商品买卖的关键环节
  • 本年利润余额负数表示什么意思
  • 上月开的发票本月作废怎么处理
  • 金税盘服务费计入什么会计科目
  • 增值税普通发票有什么用
  • 什么叫资金预算
  • 综合资金成本是
  • 增值税附税的计算公式
  • win11系统打不出顿号
  • 零售环节的金银首饰需征收增值税吗
  • 对于个体工商户不需要满足累计经营三个月以上的条件
  • 宣告分配现金股利和股票股利的区别
  • 购买电脑固定资产怎么记账
  • 你知道怎么训练
  • 2021年前端还火吗
  • 27岁零基础转行做网络工程师
  • yii2高级应用之自定义组件实现全局使用图片上传功能的方法
  • 物料最低库存
  • wordpress限制下载次数
  • 怎么开电子专用增值税发票
  • 工会经费与教育经费比例
  • 土地使用权使用寿命不确定要摊销吗
  • 新版电子税务局怎么增加办税人员
  • 待处理财产损益期末余额在哪方
  • 资产负债表是面子
  • 收货和入库的区别
  • 合并报表中的抵消分录是什么意思?
  • 文化事业建设费会计分录
  • 挂靠的项目如何做账?
  • 有限合伙企业如何报税
  • 销售未开票怎么做分录
  • 开办费计入期间费用明细表
  • 汇算清缴帐务处理
  • 企业营改增后的会计处理有何变化
  • 记账凭证的基本要素包括哪些
  • navicat不能创建string类型
  • win8语言栏不见了 怎么调出来
  • 安装sqlserver2016步骤
  • windows导航栏在左边
  • 将SP2整合进Office 2007的安装包中的方法
  • linux系统中的用户大体可分为三组
  • freebsd ports安装
  • win10访问局域网电脑需要用户名和密码
  • ubuntu的root
  • linux中的ssh命令
  • dvd rom drive bbs priorities
  • 如何手动设置定位
  • 新买的笔记本电脑需要做什么
  • unityshader怎么用
  • preorder遍历
  • python appium 微信
  • vue wepack
  • javascript HTML+CSS实现经典橙色导航菜单
  • Unity multiplayer
  • 重庆市国家税务局电子税务局官网
  • 河南商丘医疗保险在微信上怎么交
  • 什么是委托代征专用账户管理
  • 财务报表盖章位置
  • 地方税务局发票管理所
  • 混凝土税率是多少2021
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设