Math Fundamentals · lesson 10/15
Hadamard Product (Element-wise Op)
The Hadamard product multiplies two arrays entry by entry. It is written and keeps the shape, unlike the dot product or matrix product. Gates, masks, and per-parameter scaling are all Hadamard products, which makes its gradient the simplest one in the course.
The idea
For arrays of the same shape, . It is commutative, associative, and distributes over addition. The identity element is an array of all ones.
It is not the same operation as either cousin:
- Dot product of two vectors returns a scalar, — a contraction.
- Matrix product combines axes, .
- Hadamard touches nothing: times gives .
Shapes still have to match, or broadcast. A scalar broadcasts against everything: doubles every entry. A row vector broadcasts across the rows of a matrix, which is how a per-channel scale is applied.
The gradient is the reason this shows up everywhere. For :
In reverse mode, with upstream gradient of the same shape, the VJPs are
So each input's gradient is the other input acting as a mask. When one factor is a binary mask, the gradient flows exactly where the mask is 1 and is zeroed everywhere else — that is a gate.
Worked example
Let and . Then element by element.
Now let , a scalar built from a Hadamard product followed by a sum. Then and . Compare with the dot product alone: the forward value is the same scalar, , and the gradients are still the other vector — the sum never changed the local slopes.
In an LSTM, : the forget gate multiplies the old cell state entry by entry, so a value near 0 erases a dimension and a value near 1 preserves it.
In code
import torch
a = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
b = torch.tensor([4.0, -1.0, 0.5])
print(a * b) # tensor([ 4., -2., 1.5])
(a * b).sum().backward()
print(a.grad) # tensor([ 4., -1., 0.5]) == bIn PyTorch * on tensors is the Hadamard product and @ is the matrix product. Mixing them up is one of the most common sources of shape bugs in model code.
Check yourself
- How does differ from for two matrices of the same shape?
- Why is for an element-wise statement rather than a matrix?
- In attention, a mask of zeros is multiplied into the scores. What happens to the gradient through the masked positions?
Key takeaways
- Hadamard means element-wise, shape-preserving multiplication.
- Its gradient is the other operand, so it acts as a gate.
- Binary masks route gradients by zeroing the blocked positions.