FLOPS: 注意全大写, 是 floating point operations per second 的缩写, 意指每秒浮点运算次数, 理解为计算速度. 是一个衡量硬件性能的指标.
FLOPs: 注意 s 小写, 是 floating point operations 的缩写(s 表复数), 意指浮点运算数, 理解为计算量. 可以用来衡量算法 / 模型的复杂度.
网上打字很容易全小写, 造成混淆, 本问题针对模型, 应指的是 FLOPs.
以下答案不考虑 activation function 的运算.
卷积层:
Ci=input channel, k=kernel size, HW=output feature map size, Co=output channel.
2 是因为一个 Mac 算 2 个 operations.
不考虑 bias 时有 - 1, 有 bias 时没有 - 1.
上面针对一个 input feature map, 没考虑 batch size.
理解上面这个公式分两步, 括号内是第一步, 计算出 output feature map 的一个 pixel, 然后再乘以 HWCo 拓展到整个 output feature map. 括号内的部分又可以分为两步,
, 第一项是乘法运算数, 第二项是加法运算数, 因为 n 个数相加, 要加 n-1 次, 所以不考虑 bias, 会有一个 - 1, 如果考虑 bias, 刚好中和掉, 括号内变为
全联接层:
I=input neuron numbers, O=output neuron numbers.
2 是因为一个 Mac 算 2 个 operations.
不考虑 bias 时有 - 1, 有 bias 时没有 - 1.
分析同理, 括号内是一个输出神经元的计算量, 拓展到 O 了输出神经元.
参考: chen liu
对于一个卷积层, 假设其大小为 (其中 c 为 #input channel, n 为 #output channel), 输出的 feature map 尺寸为 , 则该卷积层的
- #paras =
- #FLOPS=
即 #FLOPS= #paras
参考: 李珂 https://www.zhihu.com/people/li-ke-26-99
Model_size = 4*params 模型大小为参数量的 4 倍
附: Pytorch 计算 FLOPs 的代码:
- http://link.zhihu.com/?target=https://github.com/Lyken17/pytorch-OpCounter
- https://github.com/sovrasov/flops-counter.pytorch
神器(pytorch):
https://github.com/Lyken17/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))
https://github.com/Swall0w/torchstat 用法:
- from torchstat import stat
- import torchvision.models as models
- model = model.alexnet()
- stat(model, (3, 224, 224))
https://github.com/vra/flopth 用法:
- from flopth import flopth
- print(flopth.NET, in_size=[3,112,112]))
ptflops https://github.com/sovrasov/flops-counter.pytorch 用法:
- from ptflops import get_model_complexity_info
- flops, params = get_model_complexity_info.NET, (3, 224, 224), as_strings=True, print_per_layer_stat=True)
- print('Flops:' + flops)
- print('Params:' + params)
自己计算参数量:
print('Total params: %.2fM' % (sum(p.numel() for p in.NET.parameters())/1000000.0))
需要注意的是: params 只与你定义的网络结构有关, 和 forward 的任何操作无关. 即定义好了网络结构, 参数就已经决定了. FLOPs 和不同的层运算结构有关. 如果 forward 时在同一层 (同一名字命名的层) 多次运算, FLOPs 不会增加.
来源: http://www.bubuko.com/infodetail-3297360.html