Mask a padded item before averaging
Read a complete operation before typing its result. · 150 words
In many neural networks, a batch contains sequences of different lengths. Shorter sequences are padded with zeros so every row has the same shape. A mask is a row of ones for real tokens and zeros for padding. To average token embeddings correctly, use masked_sum(m*x)/sum(m), where m is the mask and multiplication is elementwise. Multiplying by m removes padded values, while dividing by the number of real tokens keeps the average fair.
Consider two book reviews padded to two tokens. Review A, 'good read,' has embeddings [2,0] and [2,2]. With mask [1,1], its correct average is ([4,2]/2)=[2,1]. Review B, 'great,' has embedding [6,2] followed by a zero pad. If we divide its padded sum by two, we get [3,1], which is much closer to Review A. Using mask [1,0] instead gives ([6,2]+[0,0])/1=[6,2], the true average. Masking therefore prevents fake zero tokens from diluting short items and changing a downstream ranking.
Check your recall
What average does Review B receive without a mask, and what average does masked averaging produce?
Check your answer
Without a mask, Review B is averaged over two positions and becomes [3,1]. With mask [1,0], only its real token contributes, so the result is [6,2].
Sources and credits
Original KeyTouch lesson. Background reading · Google · Neural networks.