881. Mean pooling over variable-length segments
Why it matters Packing variable-length sequences without padding is how fast training and embedding servers avoid wasted compute. Pooling over packed segments is the matching read-out.
segment_mean(emb, lengths) mean-pools packed sequences. The rows of emb are several sequences stored back to back: the first lengths[0] rows are sequence 0, the next lengths[1] rows are sequence 1, and so on. Return the mean row of each sequence. A sequence with length 0 gives a row of zeros.
Inputs: emb is a list or ndarray of shape (N, d). lengths is a list or ndarray of non-negative ints that sum to N.
Return an ndarray of floats with shape (len(lengths), d). No rounding.
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 50 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def segment_mean(emb, lengths)Example 1
Input: segment_mean([[1.0, 2.0], [3.0, 4.0], [10.0, 0.0]], [2, 1])
Output: [[2.0, 3.0], [10.0, 0.0]]
Example 2
Input: emb = [[5.0], [7.0]], lengths = [0, 2, 0]
Output: [[0.0], [6.0], [0.0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Prefix-sum the rows with a leading row of zeros.
Hint 2
Segment ends are np.cumsum(lengths); starts are ends - lengths.
Hint 3
Divide by np.maximum(lengths, 1)[:, None].
Common mistakes
- Using
np.add.reduceatwith zero-length segments, which returns the next row instead of zero. - Dividing by 0 for empty segments.
- Forgetting the leading zero row.
Understand the idea
A cumulative sum over rows turns every segment sum into one subtraction: sum of rows s .. e - 1 = c[e] - c[s], with a leading zero row in c. Dividing by the lengths (with 0 replaced by 1, so empty segments stay at zero) gives the means. np.add.reduceat is another route, but it mishandles empty segments.
Shapes and data flow
emb: (N, d). c: (N + 1, d). lengths, starts, ends: (S,). Output: (S, d).