tensorflow einsum vs. matmul vs. tensordot
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
tf.matmul, tf.tensordot, and tf.einsum all express tensor contraction, but they are not interchangeable from a readability point of view. The right choice depends on how standard the operation is, how many axes are involved, and whether the formula is easier to understand as axis lists or as equation notation.
Use matmul for Ordinary Matrix Products
If you are doing a normal matrix multiply, or a batched version of one, tf.matmul should usually be the default. It communicates intent immediately.
It also supports transpose flags, which covers many common model-building cases without reshaping tensors by hand.
For layers, projections, and batched matrix math, matmul is usually the clearest API.
Use tensordot When You Want to Name the Contracted Axes
tf.tensordot is useful when the operation is not a classic matrix multiply but still has a straightforward axis-contraction story.
Here the last axis of x is contracted with the first axis of y, producing shape (2, 3, 5). tensordot is especially readable when you want to say "sum over these axes" and nothing more.
You can also contract multiple axes at once:
Use einsum for Formulas with Several Axis Relationships
tf.einsum is the most expressive option. Instead of passing axis lists, you describe the relationship between dimensions with symbols.
That is mathematically compact and extremely powerful. It becomes especially useful for attention-style code and cases where multiplication, summation, and axis reordering all happen together.
In that example, the equation says more clearly what is being compared than a sequence of reshapes and transposes would.
Compare Equivalent Forms
Many operations can be written with more than one API.
All three operations produce the same result here. That does not mean they are equally readable. For a plain two-dimensional product, matmul is the strongest choice because it is obvious at a glance.
A Practical Decision Rule
Use matmul when the operation is fundamentally matrix multiplication.
Use tensordot when you need to contract specific axes and the mapping is still simple enough to explain with lists.
Use einsum when the expression has several axis relationships and equation notation is easier to read than a mix of transpose, reshape, and multiply calls.
That choice is mostly about maintainability, not just performance. In practice, shape bugs cost more time than tiny differences in API overhead.
Debug Shapes Before Optimizing
Most failures come from mismatched dimensions or incorrect assumptions about batch axes. Print shapes before the operation and verify the algebra on paper if necessary.
For einsum, check that each symbol means exactly one dimension and that repeated symbols are the axes you intend to sum over.
Profile Only with Realistic Tensor Shapes
Performance depends on tensor shapes, backend kernels, device type, and graph optimizations. Benchmark only if performance matters for your actual workload.
Do not assume einsum is always slower or always faster. TensorFlow may lower different forms to similar kernels.
Common Pitfalls
- Using
einsumfor a simple two-dimensional multiply and making the code harder to read. - Passing the wrong axis lists to
tensordotand silently producing an unexpected shape. - Forgetting that
matmultreats leading dimensions as batch dimensions. - Comparing performance on toy tensors and then generalizing the result to production workloads.
- Reading an
einsumequation incorrectly because the symbolic dimensions are not documented.
Summary
- Prefer
tf.matmulfor standard matrix and batched matrix multiplication. - Reach for
tf.tensordotwhen the job is explicit axis contraction. - Use
tf.einsumwhen equation notation makes a multi-axis formula clearer. - Validate shapes before assuming an API call is wrong.
- Benchmark only with realistic shapes and hardware if performance is important.
Related reading
- TensorFlow Embedding Lookup
- Tensorflow Enlarge images on Tensorboard embedding?
- Tensorflow Enqueue operation was cancelled
- TensorFlow equivalent of numpy.all
- Tensorflow equivalent to numpy.diff
- Tensorflow error DLL load failed The specified procedure could not be found
- TensorFlow Error found in Tutorial
- Tensorflow error in import tf.nn.rnn_cell
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.