Average only the real tokens in a padded batch

Batches of sentences are padded to the same length. When you average token vectors to get a sentence vector, the padding must not count.

Write masked_mean(x, mask) where x has shape (batch, seq, d) and mask has shape (batch, seq) with 1 for real tokens and 0 for padding. Return shape (batch, d): the mean over real tokens only.

If a row has no real tokens, return zeros for that row instead of dividing by zero.

Signaturedef masked_mean(x, mask)

Understand the idea

Sentences in a batch have different lengths, so short ones are padded with filler tokens. When you average token vectors to get a sentence vector, the padding must not count, or the average gets pulled toward junk. Think of averaging test marks only for students who were present. Multiply x by the mask (adding a last axis so it broadcasts), sum over the sequence, then divide by the number of real tokens. Worked example, d = 1: a row with tokens [2], [4], [100] and mask [1, 1, 0]. Masked sum is 2 + 4 = 6, count is 2, mean 3. A naive mean would give 106 / 3 = 35.3. For a row with mask all zeros, the count is 0; clip the count to at least 1 so the result is 0 instead of nan. Rule: mean = sum(x * mask) / max(sum(mask), 1), per row. Sentence embedding models use masked mean pooling.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: padding ignoredmasked_mean(_x, _m)[0]
  • Sample 2: full row equals plain meanmasked_mean(_x, _m)[1]
  • Test 3: empty row is zerosmasked_mean(_x, _m)[2]
  • Test 4: shapelist(masked_mean(_x, _m).shape)