-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
77 lines (60 loc) · 3.11 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import torch
from torch import nn
flops = 0
def count_flops(m, i, o):
global flops
x = i[0]
flops += (2 * x.nelement() - 1) * m.weight.nelement()
def count_parameters(model, data):
hooks = []
for name, module in model.named_modules():
if isinstance(module,nn.Sequential):
for name, layer in module._modules.items():
if isinstance(layer, nn.Conv3d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.Linear):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.ConvTranspose3d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.BatchNorm3d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.Conv2d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.ConvTranspose2d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.Conv1d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.ConvTranspose1d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.BatchNorm1d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.BatchNorm2d):
hooks.append(layer.register_forward_hook(count_flops))
if isinstance(layer, nn.BatchNorm3d):
hooks.append(layer.register_forward_hook(count_flops))
else:
if isinstance(module, nn.Conv3d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.Linear):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.ConvTranspose3d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.Conv2d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.ConvTranspose2d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.Conv1d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.ConvTranspose1d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.BatchNorm1d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.BatchNorm2d):
hooks.append(module.register_forward_hook(count_flops))
if isinstance(module, nn.BatchNorm3d):
hooks.append(module.register_forward_hook(count_flops))
with torch.no_grad():
model(data)
for hook in hooks:
hook.remove()
print(f"FLOPs: {flops/10**9}")