统计神经网络参数量、MAC、FLOPs等信息

0、基础提示

1、FLOPS是用来衡量硬件算力的指标,FLOPs用来衡量模型复杂度。

2、MAC 一般为 FLOPs的2倍

3、并非FLOPs越小在硬件上就一定运行更快,还与模型占用的内存,带宽,等有关

1、FLOPs计算

神经网络参数量。用于衡量模型大小。一般卷积计算方式为:
F L O P s = 2 ∗ H W ( K h ∗ K w ∗ C i n + 1 ) C o u t FLOPs = 2*HW(Kh*Kw*Cin+1)Cout FLOPs=2∗HW(Kh∗Kw∗Cin+1)Cout

其中,

H,W表示该层卷积的高和宽

Kh,Kw表示卷积核的高和宽

2 表示一次乘操作 + 一次加操作

+1 表示bias操作

2、统计工具-THOP

源代码链接

2.1 安装

python 复制代码
pip install thop

python 复制代码
pip install --upgrade git+https://github.com/Lyken17/pytorch-OpCounter.git

2.2 基础使用

python 复制代码
from torchvision.models import resnet50
from thop import profile
model = resnet50()
input = torch.randn(1, 3, 224, 224)
macs, params = profile(model, inputs=(input, ))

2.3 定义自己的规则

python 复制代码
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})

2.4 模型包含多个输入

修改input就好

python 复制代码
from torchvision.models import resnet50
from thop import profile
model = resnet50()
input1 = input2 = torch.randn(1, 3, 224, 224)
macs, params = profile(model, inputs=(input1, input2,))

3、 统计工具-torchstat

这个是我更中意的,因为他统计信息更加丰富,包含params,memory, Madd, FLOPs等。缺点在于已经不更新了,且不支持多输入,好在我们可以修改代码支持。
源代码链接

3.1 安装

python 复制代码
pip install torchstat

3.2 基础使用

python 复制代码
from torchstat import stat
import torchvision.models as models
model = models.resnet18()
stat(model, (3, 224, 224))

3.3 输入多个Input

将torchstat 库安装目录下的 torchstat/statistics.py 中按如下修改:

python 复制代码
class ModelStat(object):
	def __init__(self, model, input_size, query_granularity=1):
 		assert isinstance(model, nn.Module)
		# 删除输入长度为3的限制
		# assert isinstance(input_size, (tuple, list)) and len(input_size) == 3
		assert isinstance(input_size, (tuple, list))
		self._model = model
		self._input_size = input_size
		self._query_granularity = query_granularity

将torchstat 库安装目录下的 torchstat/model_hook.py 中按如下修改:

python 复制代码
class ModelHook(object):
	def __init__(self, model, input_size):
		assert isinstance(model, nn.Module)
		assert isinstance(input_size, (list, tuple))
		self._model = model
		# 原始是通过单个输入的尺寸,再构建输入tensor,我们可以修改为在网络外构建输入tensor后直接送入网络
		# self._input_size = input_size
		self._origin_call = dict() # sub module call hook
		self._hook_model()
		# x = torch.rand(1, *self._input_size) # add module duration time
		self._model.eval()
		# self._model(x)
		self._model(*self._input_size)

使用时候测试代码

python 复制代码
from torchstat import stat
import torchvision.models as models
model = models.resnet18()
input1, input2 = torch.rand(1, 3, 224, 224), torch.rand(1, 3, 224, 224)
stat(model, (input1, input2))

大致改动就是这样了,还有什么bug可以自己稍微修改一下哈。另外找修改地方可以看报错提示torchstat安装路径修改。

4、fvcore

stat有个很麻烦的问题是,他不支持transformer,因此包含transformer的网络可以使用fvcore,他是Facebook开源的一个轻量级的核心库。

4.1、 安装

python 复制代码
pip install fvcore

4.2、 基础使用

python 复制代码
from fvcore.nn import FlopCountAnalysis, parameter_count_table
# 创建网络
model = MobileViTBlock(in_channels=32, transformer_dim=64, ffn_dim=256)

# 创建输入网络的tensor
tensor = (torch.rand(1, 32, 64, 64),)

# 分析FLOPs
flops = FlopCountAnalysis(model, tensor)
print("FLOPs: ", flops.total())

# 分析parameters
print(parameter_count_table(model))

参考来自:https://zhuanlan.zhihu.com/p/583106030

欢迎交流补充

相关推荐
Terry Cao 漕河泾20 分钟前
SRT3D: A Sparse Region-Based 3D Object Tracking Approach for the Real World
人工智能·计算机视觉·3d·目标跟踪
多猫家庭25 分钟前
宠物毛发对人体有什么危害?宠物空气净化器小米、希喂、352对比实测
人工智能·宠物
AI完全体29 分钟前
AI小项目4-用Pytorch从头实现Transformer(详细注解)
人工智能·pytorch·深度学习·机器学习·语言模型·transformer·注意力机制
AI知识分享官29 分钟前
智能绘画Midjourney AIGC在设计领域中的应用
人工智能·深度学习·语言模型·chatgpt·aigc·midjourney·llama
程序小旭1 小时前
Objects as Points基于中心点的目标检测方法CenterNet—CVPR2019
人工智能·目标检测·计算机视觉
阿利同学1 小时前
yolov8多任务模型-目标检测+车道线检测+可行驶区域检测-yolo多检测头代码+教程
人工智能·yolo·目标检测·计算机视觉·联系 qq1309399183·yolo多任务检测·多检测头检测
CV-King1 小时前
计算机视觉硬件知识点整理(三):镜头
图像处理·人工智能·python·opencv·计算机视觉
Alluxio官方1 小时前
Alluxio Enterprise AI on K8s FIO 测试教程
人工智能·机器学习
AI大模型知识分享1 小时前
Prompt最佳实践|指定输出的长度
人工智能·gpt·机器学习·语言模型·chatgpt·prompt·gpt-3
十有久诚1 小时前
TaskRes: Task Residual for Tuning Vision-Language Models
人工智能·深度学习·提示学习·视觉语言模型