Segment Sums and Segmented Softmax

A segment sum adds up the rows of a tensor that share a label. Its inputs are a data tensor and a vector of segment IDs, one per row, and row s of the output is the sum of the data rows whose ID is s:

out[s] = sum of data[i] for every i where segment_ids[i] == s

The same pattern works with other reductions, such as max, min and mean. Frameworks expose it under different names. TensorFlow has tf.math.unsorted_segment_sum, JAX has jax.ops.segment_sum, and PyTorch has index_add_ and scatter_reduce_.

A small example

Six values in three segments:

import torch

data = torch.tensor([1., 2., 3., 4., 5., 6.])
ids = torch.tensor([0, 0, 1, 1, 1, 2])
torch.zeros(3).index_add_(0, ids, data)
# tensor([ 3., 12.,  6.])

The segment IDs label rows, so a 2D input needs one ID per row, not one per element. Each row is reduced as a whole:

x = torch.tensor([[1., 2.], [3., 4.], [5., 6.]])
rid = torch.tensor([0, 0, 1])
torch.zeros(2, 2).index_add_(0, rid, x)
# tensor([[4., 6.],
#         [5., 6.]])

The number of segments sets the output shape. tf.math.segment_sum infers it from the largest ID and requires sorted IDs. The unsorted TensorFlow variant and the JAX function take num_segments as an argument. A compiled graph needs a fixed output shape, so code that will be compiled passes num_segments explicitly.

Segmented softmax

A softmax over each segment needs two segment reductions, a max for numerical stability and a sum for the denominator:

m[s]   = max of scores[i] in segment s
e[i]   = exp(scores[i] - m[segment_ids[i]])
out[i] = e[i] / (sum of e[j] in segment s)

Each segment’s outputs sum to 1, and the segments do not affect each other.

LLM serving with continuous batching produces this situation. The tokens or KV cache blocks of several sequences are packed along one dimension of a single tensor, and the attention softmax for each sequence must cover only that sequence’s entries. Here the segment ID of an entry is the sequence it belongs to.

transformers-neuronx, the AWS Neuron library for LLM inference, has a blockwise_softmax function for its paged KV cache. The function is in layers/attention_utils.py, published in December 2024. The logits have one row per active cache block, and block_to_seq maps each block to its sequence. The function first reduces within each block, then calls blockwise_reduce_max and blockwise_reduce_sum to combine the blocks of each sequence. Those two functions are segment reductions with block_to_seq as the segment IDs.

Three ways to write it

The three versions below compute the same result. They differ in how many operations they put into the graph and which hardware units do the work.

A loop over segments

The direct version masks out every other segment, reduces, and writes the result back to the rows of the current segment:

def softmax_loop(scores, ids, num_segments):
    out = torch.empty_like(scores)
    for s in range(num_segments):
        mask = ids == s
        m = torch.where(mask, scores, float("-inf")).max()
        e = torch.where(mask, torch.exp(scores - m), 0.0)
        out = torch.where(mask, e / e.sum(), out)
    return out

The two transformers-neuronx functions follow this structure. Each one loops over range(num_seqs), and each iteration emits a constant, a compare, a masked select, a reduction, a broadcast and a second masked select:

for seq_id in range(num_seqs):
    seq_full = hlo.full(seq_id, s32, o_sizes)
    seq_mask = hlo.equal(seq_iota, seq_full)
    masked_logits = hlo.masked_select(seq_mask, logits, zero)
    output_br = hlo.broadcast(hlo.reduce_sum(masked_logits, dim=0, keepdim=True), o_sizes, [0, 1, 2])
    output = hlo.masked_select(seq_mask, output_br, output)

This Python loop runs while the graph is being traced, so the compiled graph contains one copy of the body per sequence. With a maximum of 64 sequences, the two reductions together emit 768 HLO instructions where a fixed-size formulation needs a handful. The graph and its compile time grow with the batch size. Every copy also reads the full logits tensor, so the memory traffic grows with the number of sequences too.

Scatter and gather

A scatter with a reduction writes each entry into the slot of its segment and combines collisions with max or add. A gather with the segment IDs then reads each segment’s result back to its entries:

def softmax_scatter(scores, ids, num_segments):
    m = torch.full((num_segments,), float("-inf")).scatter_reduce(
        0, ids, scores, reduce="amax")
    e = torch.exp(scores - m[ids])
    denom = torch.zeros(num_segments).index_add_(0, ids, e)
    return e / denom[ids]

The graph has the same number of operations for any number of segments. XLA’s scatter instruction takes the combining function as an argument, so both the max and the sum map onto it. How fast scatter and gather run depends on the backend and on how well it handles data-dependent addresses.

One-hot matrix multiplication

A one-hot matrix onehot[i, s] is 1 when entry i belongs to segment s. Multiplying by its transpose sums each segment, and multiplying by the matrix itself broadcasts each segment’s value back to its entries:

def softmax_onehot(scores, ids, num_segments):
    onehot = torch.nn.functional.one_hot(ids, num_segments).to(scores.dtype)
    m = torch.where(onehot.bool(), scores[:, None], float("-inf")).amax(dim=0)
    e = torch.exp(scores - onehot @ m)
    return e / (onehot @ (onehot.T @ e))

The sums and broadcasts become matrix multiplications, which run on the matrix units of an accelerator. A max cannot be written as a matmul, so the max uses a masked reduction over an [entries, segments] tensor. That tensor is the cost of this version. Its size is the number of entries times the number of segments, times the size of any trailing dimensions. Many of the multiplications are by zero, which is acceptable when the matrix units would otherwise sit idle.

Checking the versions

The three functions agree, and each segment of the result sums to 1:

torch.manual_seed(0)
scores = torch.randn(10)
ids = torch.tensor([0, 0, 0, 1, 1, 2, 2, 2, 2, 3])
a = softmax_loop(scores, ids, 4)
b = softmax_scatter(scores, ids, 4)
c = softmax_onehot(scores, ids, 4)
assert torch.allclose(a, b) and torch.allclose(a, c)
assert torch.allclose(torch.zeros(4).index_add_(0, ids, a), torch.ones(4))

Choosing an approach

For a compiled graph, a loop whose trip count is a tensor size or a batch limit makes the graph grow with that size. The scatter and one-hot versions keep the operation count fixed. Scatter does the least arithmetic. The one-hot version runs on the matrix units and uses no data-dependent addressing, at the price of an [entries, segments] intermediate. Which one is faster depends on the backend, so the choice comes from measuring both at the batch sizes the server runs.

A fused attention kernel can avoid the segmented softmax altogether. If the kernel receives a mask that marks which cached positions each query may attend to, it can run an ordinary softmax with the masked positions set to a large negative value. The mask then keeps the sequences apart.

References


If you found this useful, please cite this post using

Senthilkumar Gopal. (Jan 2025). Segment Sums and Segmented Softmax. sengopal.me. https://sengopal.me/posts/segment-sums-and-segmented-softmax

or

@article{gopal2025segmentsumssegmented,
  title   = {Segment Sums and Segmented Softmax},
  author  = {Senthilkumar Gopal},
  journal = {sengopal.me},
  year    = {2025},
  month   = {Jan},
  url     = {https://sengopal.me/posts/segment-sums-and-segmented-softmax}
}