Apply a numerically stable softmax inside each group of a flat array

Packed batches and graph attention store scores for many groups in one flat array, with a group id per entry. You need a softmax within each group, not across the whole array, and it must not overflow when scores are large.

Write segment_softmax(scores, seg_ids, num_segments). scores is a 1D float array of length n. seg_ids is an int array of length n with values in [0, num_segments), in any order. Return a float array of length n where the entries of each group sum to 1.

Stability is required: scores can be as large as 1000 or as small as -1000, and different groups can live at very different scales. Subtract each group's own maximum before exponentiating. Groups with no entries are simply ignored. Avoid Python loops over entries; np.maximum.at and np.add.at help.

Signaturedef segment_softmax(scores, seg_ids, num_segments)

Example

scores [1, 1, 5], seg_ids [0, 0, 1], num_segments 2 gives [0.5, 0.5, 1.0].

Understand the idea

Segment softmax runs a separate softmax inside each group of a flat array, where every entry has a group id. Each group's entries must sum to 1 on their own. For stability, subtract each group's own maximum, not the global one: a group far below the global max would underflow to all zeros and give 0 / 0. Worked example: scores [1000, 1001, -1000, -1000], seg_ids [0, 0, 1, 1]. Group 0 max is 1001: exp(-1) = 0.368 and exp(0) = 1, sum 1.368, so [0.269, 0.731]. Group 1 max is -1000: exp(0) and exp(0), giving [0.5, 0.5]. Subtracting the global max 1001 from group 1 would give exp(-2001) = 0 for both. Without loops: start a max array at -inf, fill it with np.maximum.at, subtract max[seg_ids], exponentiate, sum per group with np.add.at, then divide by sums[seg_ids]. Rule: out_i = exp(s_i - max_g) / sum over the group of exp(s_j - max_g). Graph attention and packed-sequence models need this.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplesegment_softmax([1.0, 1.0, 5.0], [0, 0, 1], 2)
  • Sample 2: random unsorted groupssegment_softmax(_s, _g, 5)