Estimating FLOPs (Floating Point Operations) is critical for calculating Model FLOPs Utilization (MFU). This notebook uses a method that counts actual FLOPs (not MACs), meaning matrix multiplications of $(B imes C) imes (C imes D)$ are calculated as $2 imes B imes C imes D$.
Key FLOP components:
- Attention: K/Q/V projection, attention score calculation, value reduction, and final projection.
- MLP: Feed-forward expansion and projection.
- Total Pass: The sum of forward and backward passes. A common estimate for the backward pass is $2 imes ext{forward pass}$ cost.
PaLM Formula: For a more standardized estimate, the PaLM paper formula can be used:
$mf_{ ext{per token}} = 6N + 12LHQ T$
where $N$ is non-embedding parameters, $L$ is layers, $H$ is heads, $Q$ is head dimension, and $T$ is block size.
def flops():
# ... (implementation details) ...
# 1) the projection to key, query, values
out['attention/kqv'] = 2 * block_size * (n_embd * 3*n_embd)
# 2) calculating the attention scores
out['attention/scores'] = 2 * block_size * block_size * n_embd
# 3) the reduction of the values
out['attention/reduce'] = 2 * n_head * (block_size * block_size * head_size)
# 4) the final linear projection
out['attention/proj'] = 2 * block_size * (n_embd * n_embd)
# ... (MLP and total calculations) ...
return out