Keras -- no Dot layer with broadcasting?
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
Keras's Dot layer computes dot products along a specified axis but does not support broadcasting — both inputs must have the same batch size and compatible shapes. When you need a dot product with broadcasting (e.g., multiplying a batch of vectors by a single weight vector, or computing attention scores between tensors of different ranks), use tf.keras.layers.Lambda with tf.tensordot, tf.einsum, or the Multiply layer combined with tf.reduce_sum. These alternatives give you full control over which axes are contracted and how broadcasting is applied.
The Problem with Dot Layer
The Dot layer requires both inputs to have the same number of dimensions. It cannot broadcast a 2D tensor across a 3D tensor.
Solution 1: Lambda Layer with tf.einsum
tf.einsum is the most flexible and readable option:
einsum('bsf,bf->bs') means: for each batch b, multiply the (seq, features) matrix by the (features,) vector, producing a (seq,) result.
Common einsum Patterns for Broadcasting Dot Products
Solution 2: Multiply + Reduce Sum
Element-wise multiplication with broadcasting followed by sum reduction:
This is equivalent to the dot product but uses broadcasting explicitly.
Solution 3: Custom Layer
For reuse across models, create a custom layer:
Solution 4: tf.tensordot in a Lambda
tf.tensordot is powerful but does not handle the batch dimension implicitly. For batched operations, tf.einsum is usually a better choice.
Attention Score Example
A common use case is computing attention scores between queries and keys of different shapes:
When to Use the Built-in Dot Layer
The Dot layer works fine when both inputs have the same rank:
Common Pitfalls
- Assuming
Dotsupports broadcasting: TheDotlayer requires both inputs to have the same number of dimensions. For different ranks, useeinsum,Multiply+reduce_sum, or a custom layer. - Losing the batch dimension with
tf.tensordot:tf.tensordotcontracts all specified axes including batch if you are not careful. Prefertf.einsumfor batched operations because it explicitly names all dimensions. - Wrong axis in einsum string: A typo in the einsum subscript silently produces wrong shapes. Print
output.shapeafter each einsum operation to verify correctness. - Not using
get_configin custom layers: Custom layers withoutget_configcannot be serialized (saved/loaded). Always implementget_configin custom Keras layers. - Using
Lambdalayers for complex logic:Lambdalayers are hard to serialize and debug. For anything beyond a simple one-liner, create a proper custom layer subclassingtf.keras.layers.Layer.
Summary
- Keras
Dotlayer does not support broadcasting between tensors of different ranks - Use
tf.einsumin aLambdalayer for the most readable and flexible broadcasting dot products - Use
Multiply+Reshape+reduce_sumfor explicit element-wise broadcasting - Create a custom
BroadcastDotlayer for reusable broadcasting dot products - Prefer
tf.einsumovertf.tensordotfor batched operations to preserve the batch dimension
Related reading
- Keras - Add attention mechanism to an LSTM model
- keras - cannot import name Conv2D
- Keras - class_weight vs sample_weights in the fit_generator
- Keras - Difference between categorical_accuracy and sparse_categorical_accuracy
- Keras - Difference between categorical_accuracy and sparse_categorical_accuracy
- Keras - How are batches and epochs used in fit_generator?
- Keras - How to construct a shared Embedding Layer for each Input-Neuron
- Keras - how to get unnormalized logits instead of probabilities
.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.