딥러닝 모델의 계산량
MACs (Multiply-ACcumulate)
- 현대 하드웨어는 tensor를 다루는 연산을 할 때 FMA (Floating Point Multiply and Add Operation) 라고 하는 명령어 셋을 사용한다. 이는 a∗x+b를 하나의 연산으로 처리한다. FMA 연산이 몇번 실행되었는지를 세는 것이 MAC이다.
FLOPs (FLoating point OPerations)
- 연산을 수행한 횟수를 말하며 연산에는 root, log, exponential, add, multiply 등을 각각 1회로 센다.
MACs와 FLOPs의 관계
- MACs는 multiply와 add를 묶어서 하나로 카운트하지만 FLOPs는 이 둘을 각각 1회로 카운트하기 때문에 대게 MACs * 2 = FLOPs라고 할 수 있다.
딥러닝 모듈별 MACs 계산방법(Pytorch)
nn.Conv2d

MACs=K2×Cin×Cout×OH×OW
nn.Batchnorm2d

MACs=OH×OW×2
nn.ReLU

MACs=OH×OW
Pytorch MACs 계산 라이브러리
ptflops https://github.com/sovrasov/flops-counter.pytorch
- MACs 계산 과정
- 미리 정해진 module(nn.Conv2d, nn.Batchnorm2d,,,)에 forward_hook을 붙인다.
- forward_hook은 input, output, module이 인자로 들어오기 때문에 input, output 크기를 데이터에 따라 자동으로 받을 수 있고 module을 활용하여 in_channels와 out_channels를 이용하여 MACs를 계산한다.
- forward_hook을 제거한다.