参考:

  1. https://mp.weixin.qq.com/s?__biz=MzI4MDYzNzg4Mw==&mid=2247546551&idx=2&sn=f198b6365e11f0a18832ff1203302632&chksm=ebb70e63dcc0877569d1838b2391744be628bf6cbb6e203a49f855e0769ecbbbf5a9929fe2db&scene=27

  1. https://www.cnblogs.com/king-lps/p/10904552.html

  1. https://zhuanlan.zhihu.com/p/337810633

在测试一个模型时,我们经常会用到FLOPS,FLOPs,Params↓

FLOPS

注意S大写,是floating point operations per second的缩写,意指每秒浮点运算次数,理解为计算速度。是一个衡量硬件性能的指标。

计算公式:

对卷积层:(K_h * K_w * C_in * C_out) * (H_out * W_out)

对全连接层:C_in * C_out

FLOPs

注意s小写,是floating point operations的缩写(s表复数),意指浮点运算数,理解为计算量。可以用来衡量算法/模型的复杂度

GFLOPS

GFLOPS 就是 Giga Floating-point Operations Per Second,即每秒10亿次的浮点运算数,常作为GPU性能参数但不一定代表GPU的实际表现,因为还要考虑具体如何拆分多边形和像素、以及纹理填充,理论上该数值越高越好。1GFlops = 1,000MFlops

一点常用的换算关系:

一个 MFLOPS (megaFLOPS) 等于每秒1百万 (=10^6) 次的浮点运算,

一个 GFLOPS (gigaFLOPS) 等于每秒10亿 (=10^9) 次的浮点运算,

一个 TFLOPS (teraFLOPS) 等于每秒1万亿 (=10^12) 次的浮点运算,

一个 PFLOPS (petaFLOPS) 等于每秒1千万亿 (=10^15) 次的浮点运算。

Params

是指模型训练中需要训练的参数总数

模型参数量计算公式为:

对卷积层:(K_h * K_w * C_in)* C_out

对全连接层:C_in * C_out

注意:

1.params只与你定义的网络结构有关,和forward的任何操作无关。即定义好了网络结构,参数就已经决定了。FLOPs和不同的层运算结构有关。如果forward时在同一层(同一名字命名的层)多次运算,FLOPs不会增加

  1. Model_size = 4*params 模型大小约为参数量的4倍

计算方法

方法1-使用thop库

import torch
from thop import profile
from models.yolo_nano import YOLONano

device = torch.device("cpu")
#input_shape of model,batch_size=1
net = YOLONano(num_classes=20, image_size=416) ##定义好的网络模型

input = torch.randn(1, 3, 416, 416)
flops, params = profile(net, inputs=(input, ))

print("FLOPs=", str(flops/1e9) +'{}'.format("G"))
print("params=", str(params/1e6)+'{}'.format("M")

方法2-使用torchstat库

torchstat这个库来查看网络模型的一些信息,包括总的参数量params、MAdd、显卡内存占用量和FLOPs等

from torchstat import stat
from torchvision.models import resnet50
model = resnet50()
stat(model, (3, 224, 224))

方法3-使用 ptflops:https://github.com/sovrasov/flops-counter.pytorch

from ptflops import get_model_complexity_info
from torchvision.models import resnet50
model = resnet50()
flops, params = get_model_complexity_info(model, (3, 224, 224), as_strings=True, print_per_layer_stat=True)
print('Flops:  ' + flops)
print('Params: ' + params)

方法4-使用 pytorch-OpCounter (pytorch版本>=1.0)

from torchvision.models import resnet50
from thop import profile
model = resnet50()
flops, params = profile(model, input_size=(1, 3, 224,224))

方法5自己计算

print('Total params: %.2fM' % (sum(p.numel() for p in net.parameters())/1000000.0))

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐