Params and FLOPs
原文链接:https://blog.csdn.net/mzpmzk/article/details/82976871
参数数量(Params)
指模型含有多少参数,直接决定模型的大小,也影响推断时对内存的占用量
单位通常为M,通常参数用 float32 表示,所以模型大小是参数数量的4倍左右
参数数量与模型大小转换示例:10M float32 bit = 10M × 4 Byte = 40MB (注意位 bit 和字节 Byte 的区别)
理论计算量(FLOPs)
指模型推断时需要多少计算次数,是floating point operations的缩写(注意 s 小写),可以用来衡量算法/模型的复杂度,这关系到算法速度,大模型的单位通常为 G(GFLOPs:10亿次浮点运算),小模型单位通常为 M
通常只考虑**乘加操作(Multi-Adds)**的数量,而且只考虑 CONV 和 FC 等参数层的计算量,忽略 BN 和 PReLU 等等。一般情况,CONV 和 FC 层也会忽略仅纯加操作的计算量,如 bias 偏置加和 shotcut 残差加等,目前有 BN 的卷积层可以不加 bias
PS:也有用 MAC(Memory Access Cost) 表示的
Examples
假设卷积核大小为$K_h \times K_w$,输入通道数为$C_{in}$,输出通道数为$C_{out}$,输出特征图的宽和高分别为$W$ 和$H$,这里忽略偏置项
CONV标准卷积层
Params: $K_h \times K_w \times C_{in} \times C_{out}$
FLOPs: $K_h \times K_w \times C_{in} \times C_{out} \times H \times W = params \times H \times W$
FC 全连接层(相当于 k=1)
Params: $C_{in} \times C_{out}$
FLOPs: $C_{in} \times C_{out}$
参数量与计算量参考网址:https://github.com/Lyken17/pytorch-OpCounter
How to install
pip install thop
or pip install --upgrade git+https://github.com/Lyken17/pytorch-OpCounter.git
How to use
basic usage
from torchvision.models import resnet50
from thop import profile
model = resnet50()
input = torch.randn(1, 3, 224, 224)
macs, params = profile(model, inputs=(input, ))
Define the rule for 3rd party module.
class YourModule(nn.Module):
# your definition
def count_your_model(model, x, y):
# your rule here
input = torch.randn(1, 3, 224, 224)
macs, params = profile(model, inputs=(input, ),
custom_ops={YourModule: count_your_model})
Improve the output readability
Call thop.clever_format
to give a better format of the output.
from thop import clever_format
macs, params = clever_format([macs, params], "%.3f")