Counting FLOPs: What Matrix Products Cost in a Model
Count the arithmetic in dense, convolution and attention layers, and learn why the FLOP total alone does not tell you the running time.
Key takeaways
- An (m, k) by (k, n) matrix product needs mkn multiply-adds, or about 2mkn FLOPs.
- A dense layer costs roughly two FLOPs per weight per example in the forward pass.
- The order in which you multiply a chain of matrices can change the cost by orders of magnitude.
- Training a layer costs about three times its forward pass: one forward and two backward matrix products.
- Running time also depends on memory bandwidth, data types, batch size and how well the hardware is used.
A FLOP is one floating-point operation, such as one addition or one multiplication. Multiplying an m by k matrix by a k by n matrix with the standard method takes about 2mkn FLOPs. Since matrix products make up most of the arithmetic in many neural networks, that one rule lets you estimate a model's cost on the back of an envelope.
The estimate tells you how much arithmetic there is. It does not tell you how long it will take, because moving numbers through memory often costs more than computing with them.
The basic count
Let A have shape (m, k) and B have shape (k, n). The product C has shape (m, n). Each entry of C is a dot product of length k: k multiplications and k − 1 additions.
entries in C = m · n
multiplications = m · n · k
additions = m · n · (k − 1)
total FLOPs ≈ 2 · m · k · n A multiplication followed by an addition is called a multiply-accumulate, or MAC. One MAC is usually counted as 2 FLOPs. Some tools report MACs and label them FLOPs, so a factor of two often separates two published figures for the same model. Check which convention is in use.
Also keep FLOPs, a count of work, apart from FLOP/s, the rate at which hardware performs it.
Dense layers
A dense (fully connected) layer multiplies a batch of inputs X, shape (B, d_in), by weights W, shape (d_in, d_out). The cost is about 2 · B · d_in · d_out FLOPs, plus B · d_out for the bias and a similar small amount for a simple activation.
Take a small network for 28 by 28 grayscale images, with layer widths 784, 256, 128 and 10.
| Layer | MACs per example | Parameters (with bias) |
|---|---|---|
| 784 → 256 | 200,704 | 200,960 |
| 256 → 128 | 32,768 | 32,896 |
| 128 → 10 | 1,280 | 1,290 |
| Total | 234,752 | 235,146 |
The forward pass is therefore about 470,000 FLOPs per image. The first layer accounts for roughly 85% of it. Notice that MACs and weight counts nearly match: in a dense layer each weight is used exactly once per example.
Hypothetical example: the numbers are made up to show the method, not a quote or an average.
Multiplication order matters
Matrix multiplication is associative: (AB)v and A(Bv) give the same result, apart from rounding. Their costs can be very different.
Let A be 1,000 by 10, B be 10 by 1,000 and v be a vector of length 1,000.
(AB)v: AB = 1000 · 10 · 1000 = 10,000,000 MACs
then 1000 · 1000 = 1,000,000 MACs
total 11,000,000 MACs
A(Bv): Bv = 10 · 1000 = 10,000 MACs
then 1000 · 10 = 10,000 MACs
total 20,000 MACs The second order is 550 times cheaper and never builds the large intermediate matrix. The same idea explains why reverse-mode differentiation passes vectors backward through a network, and why a low-rank factorization saves work only if you keep the two thin matrices separate.
Convolutions
A standard two-dimensional convolution with a K by K kernel, C_in input channels, C_out output channels and an H by W output costs about K² · C_in · C_out · H · W MACs.
For a 3 by 3 convolution from 64 to 128 channels with a 56 by 56 output:
3 · 3 · 64 · 128 · 56 · 56 = 231,211,008 MACs A depthwise separable convolution splits this into one 3 by 3 filter per input channel, then a 1 by 1 convolution that mixes channels.
depthwise: 3 · 3 · 64 · 56 · 56 = 1,806,336
pointwise: 64 · 128 · 56 · 56 = 25,690,112
total 27,496,448 MACs That is about 8.4 times less arithmetic. The two layers do not compute the same family of functions, so accuracy must be checked separately. Note also that the weight count of a convolution is small while its MAC count is large, because every weight is reused at each spatial position.
Attention and transformers
For one self-attention layer with sequence length n and model width d, split across heads whose widths add to d, count the main matrix products.
queries, keys, values, output projections: 4 · n · d² MACs
scores Q Kᵀ across all heads: n² · d
weights times V across all heads: n² · d With n = 1,000 and d = 512, the projections cost about 1.05 billion MACs and the two n² products about 1.02 billion. Double n and the projections double while the attention products quadruple. This is the quadratic cost of attention.
For large language models at moderate context lengths, most weights sit in matrices applied once per token. A widely used rule of thumb is therefore about 2N FLOPs per token for a forward pass of a dense model with N parameters. Treat it as a first approximation that omits the attention products, which grow with context length. Estimating training compute builds on the same idea.
What training adds
For a layer Y = XW, the backward pass receives G, the gradient of the loss with respect to Y, and forms two more products.
gradient for the weights: Xᵀ G same MAC count as the forward product
gradient for the input: G Wᵀ same MAC count as the forward product So one training step costs about three forward passes, or roughly 6N FLOPs per token under the rule above. Optimizer updates add work proportional to the number of parameters once per step, which is usually minor when batches are large. Some memory-saving techniques recompute activations and add to the total.
Memory is a separate budget
The same shapes tell you how much storage a layer needs. Multiply the number of values by the bytes per value: 4 for 32-bit floats and 2 for 16-bit formats.
| Quantity in the example network | Count | At 32 bits |
|---|---|---|
| Parameters | 235,146 | about 0.94 MB |
| Activations for a batch of 128, including inputs | 128 · 1,178 = 150,784 | about 0.6 MB |
Here 1,178 is the sum of the widths 784, 256, 128 and 10. Training needs more than the parameters: gradients take as much space as the weights, and an optimizer such as Adam keeps two further values per parameter. In 32-bit form that is roughly 16 bytes per parameter before any activations.
Parameter memory does not depend on batch size, while activation memory grows with it. In attention layers, explicitly stored score matrices grow with the square of the sequence length. Some optimized kernels avoid storing them, which lowers memory without lowering the arithmetic count. Estimating GPU memory works through a full training budget.
FLOPs and bytes can pull in opposite directions. Recomputing a value saves memory and adds arithmetic; caching it does the reverse.
Why FLOPs are not seconds
Every number must travel from memory to the arithmetic units. Arithmetic intensity is the number of FLOPs performed per byte moved. Hardware can only reach its peak rate when intensity is high enough.
Consider a hypothetical device that peaks at 10 trillion FLOP/s and reads memory at 100 billion bytes per second. A matrix-vector product with 16-bit weights does 2 FLOPs for each 2-byte weight, an intensity of 1 FLOP per byte. Memory then limits it to about 100 billion FLOP/s, or 1% of peak.
Process many vectors together and each weight read serves many multiplications. Intensity rises with the batch size until arithmetic becomes the limit. This is why generating text one token at a time for a single user tends to be memory-bound, while large training batches can keep processors busy.
Other factors move the result as well: transfer between devices, tiny operations with high overhead, padding that wastes work, and the numeric format. Lower precision usually reduces bytes moved and can raise throughput, with effects on accuracy that you must verify.
Counting and measuring in practice
A short function covers a stack of dense layers.
def dense_cost(widths, batch=1):
pairs = list(zip(widths[:-1], widths[1:]))
macs = sum(a * b for a, b in pairs) * batch
params = sum(a * b + b for a, b in pairs)
return macs, 2 * macs, params
macs, flops, params = dense_cost([784, 256, 128, 10])
print(macs, flops, params) # 234752 469504 235146 Then compare with reality:
- Write down the FLOP estimate for your model and batch size.
- Time a warmed-up run, synchronizing the accelerator so that queued work has finished.
- Divide FLOPs by seconds to get an achieved rate.
- Compare that rate with the hardware's documented peak for the same data type.
- If the fraction is small, use a profiler to look for memory, transfer or input pipeline limits.
Profiling tools in major libraries can count operations for you, but their coverage differs, and custom operations may be skipped. Check a simple layer by hand to learn the tool's convention.
Common questions
Do activation functions count?
They add FLOPs proportional to the number of activations, which is usually small next to the matrix products. Very narrow layers or expensive element-wise functions are the exception.
Does a faster matrix algorithm change the rule?
Algorithms such as Strassen's use fewer multiplications asymptotically. Mainstream deep learning libraries generally rely on carefully tuned versions of the standard method, so 2mkn remains the practical estimate.
Can I compare two architectures by FLOPs alone?
Only roughly. Two models with equal counts can differ widely in speed and energy use. Measure on the target hardware before you decide.