Pytorch统计网络参数计算工具、模型 FLOPs, MACs, MAdds 关系

Pytorch统计网络参数

#网络参数数量
def get_parameter_number(net):
    total_num = sum(p.numel() for p in net.parameters())
    trainable_num = sum(p.numel() for p in net.parameters() if p.requires_grad)
    return {'Total': total_num, 'Trainable': trainable_num}
#查看网络参数
print(model.state_dict())

FLOPs, MACs, MAdds 关系

在这里插入图片描述
见文章:CNN模型复杂度(FLOPs、MAC)、参数量与运行速度

计算工具:

地址备注
https://github.com/Lyken17/pytorch-OpCounterPytorch
https://github.com/sovrasov/flops-counter.pytorchPytorch
https://stackoverflow.com/questions/45085938/tensorflow-is-there-a-way-to-measure-flops-for-a-modelTensorFlow: 自带tf.RunMetadata()

另:在PyTorch中,可以使用torchstat这个库来查看网络模型的一些信息,包括总的参数量params、MAdd、显卡内存占用量和FLOPs等。

!pip install torchstat
from torchstat import stat
from torchvision.models import resnet50, resnet101, resnet152, resnext101_32x8d
 
model = resnet50()
# stat打印完整信息
stat(model, (3, 224, 224))
# 模型的总参数量
total = sum([param.nelement() for param in model.parameters()])
print("Number of parameters: %.2fM" % (total/1e6))

也可以使用torchsummary

!pip install torchsummary
from torchsummary import summary
summary(model, input_size=(ch, h, w), batch_size=-1)
#ch是指输入张量的channel数量,h表示输入张量的高,w表示输入张量的宽。
  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用下面的代码计算PyTorch模型FLOPs(浮点操作次数): ```python import torch from torch.autograd import Variable def print_model_parm_flops(model, input_size, custom_layers): multiply_adds = 1 params = 0 flops = 0 input = Variable(torch.rand(1, *input_size)) def register_hook(module): def hook(module, input, output): class_name = str(module.__class__).split(".")[-1].split("'")[0] if class_name == 'Conv2d': out_h, out_w = output.size()[2:] kernel_h, kernel_w = module.kernel_size in_channels = module.in_channels out_channels = module.out_channels if isinstance(module.padding, int): pad_h = pad_w = module.padding else: pad_h, pad_w = module.padding if isinstance(module.stride, int): stride_h = stride_w = module.stride else: stride_h, stride_w = module.stride params += out_channels * (in_channels // module.groups) * kernel_h * kernel_w flops += out_channels * (in_channels // module.groups) * kernel_h * kernel_w * out_h * out_w / (stride_h * stride_w) elif class_name == 'Linear': weight_flops = module.weight.nelement() * input[0].nelement() // module.weight.size(1) bias_flops = module.bias.nelement() flops = weight_flops + bias_flops params = weight_flops + bias_flops elif class_name in custom_layers: custom_flops, custom_params = custom_layers[class_name](module, input, output) flops += custom_flops params += custom_params else: print(f"Warning: module {class_name} not implemented") if not isinstance(module, torch.nn.Sequential) and \ not isinstance(module, torch.nn.ModuleList) and \ not (module == model): hooks.append(module.register_forward_hook(hook)) # loop through the model architecture and register hooks for each layer hooks = [] model.apply(register_hook) # run the input through the model model(input) # remove the hooks for hook in hooks: hook.remove() print(f"Number of parameters: {params}") print(f"Number of FLOPs: {flops}") return flops, params ``` 调用这个函数需要传入模型、输入大小和一个自定义图层字典,其中字典的键是自定义层的名称,值是一个函数,该函数接受模块,输入和输出,返回FLOPs参数数量。例如,如果您的模型包含一个名为MyLayer的自定义层,则可以将以下内容添加到字典中: ```python def my_layer_impl(module, input, output): # compute FLOPs and params for MyLayer flops = ... params = ... return flops, params custom_layers = {'MyLayer': my_layer_impl} ``` 使用示例: ```python import torchvision.models as models model = models.resnet18() input_size = (3, 224, 224) custom_layers = {} flops, params = print_model_parm_flops(model, input_size, custom_layers) ``` 该函数将打印出模型参数数量和FLOPs
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值