BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges10 of 14 in topic

881. Mean pooling over variable-length segments

HardOptimization challenges Pro

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.

Functiondef 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.reduceat with 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).
Topics
Optimization challenges
Similar questions
  • Vectorise pairwise Euclidean distancesMedium
  • Group-by mean without a Python loopMedium
  • Fast 2D valid convolutionMedium
  • Top-k indices for every rowMedium
All Optimization challenges problems
Report
881 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
​
def segment_mean(emb, lengths):
emb = np.asarray(emb, dtype=float)
out = np.zeros((len(lengths), emb.shape[1]))
start = 0
for i, n in enumerate(np.asarray(lengths, dtype=int).tolist()):
if n > 0:
out[i] = emb[start:start + n].mean(axis=0)
start += n
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS