Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

count_normalization is only correct for batch_norm. wrong flops count for layernorm #220

Open
pzpzpzp2 opened this issue Mar 13, 2024 · 1 comment

Comments

@pzpzpzp2
Copy link

nn.LayerNorm: count_normalization,

The same count_normalization function is used for every norm-esque module but batchnorms store an estimate mean and stdev, while layernorms calculate them at inference time. Shouldn't layernorms account for the cost of evaluating mean and stdev? The difference is pretty significant:
The mean is n flops, stdev is 2n more flops? and thats before the rest of the norm module which is another 2n.
Is there a reason layernorms should be estimateable as only 2n flops by re-using batchnorm's estimate?

@dyhBUPT
Copy link

dyhBUPT commented Jul 3, 2024

I think you are right.
BTW, I think the MACs of BN (eval, no affine) should be n, not 2n in codes.

def count_normalization(m: nn.modules.batchnorm._BatchNorm, x, y):
# TODO: add test cases
# https://github.com/Lyken17/pytorch-OpCounter/issues/124
# y = (x - mean) / sqrt(eps + var) * weight + bias
x = x[0]
# bn is by default fused in inference
flops = calculate_norm(x.numel())
if (getattr(m, 'affine', False) or getattr(m, 'elementwise_affine', False)):
flops *= 2
m.total_ops += flops

def calculate_norm(input_size):
"""input is a number not a array or tensor"""
return torch.DoubleTensor([2 * input_size])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants