Merge split-KV partial attention results

Why it matters Split-KV decoding kernels use this merge to parallelize one long sequence across many SMs, and it must give exactly the same result as one big softmax.

For long-context decoding, one query's keys are split across several thread blocks. Each block returns its local max m_j, local softmax denominator l_j = sum exp(s - m_j), and its locally normalized output o_j. A final step merges them exactly.

Write merge_partials(ms, ls, os). ms and ls have length S, os has shape (S, D). Let M = max over splits with l_j > 0 of m_j. Weight w_j = l_j * exp(m_j - M) (0 for splits with l_j = 0, which may have m_j = -inf). Return (o, lse) where o = sum_j w_j o_j / sum_j w_j and lse = M + log(sum_j w_j). If every split is empty raise ValueError.

Signaturedef merge_partials(ms, ls, os)

Example

ms [1, 3], ls [2, 1], os [[1, 0], [0, 1]] gives o [0.2130, 0.7870] and lse 3.2395 (rounded to 4 places).

Understand the idea

Imagine three cashiers each counting part of a pile of foreign coins, each converting to rupees at their own exchange rate. To get the true total you must convert all three counts to one common rate first. In split attention the exchange rate is exp(m_j), the local max each block subtracted for safety. Worked example: split 1 has max 1 and sum 2, split 2 has max 3 and sum 1. Global M = 3. Weights: 2 x exp(1 - 3) = 0.271 and 1 x exp(0) = 1. Output = (0.271 [1, 0] + 1 [0, 1]) / 1.271 = [0.213, 0.787]. lse = 3 + log(1.271) = 3.24. Rule: w_j = l_j exp(m_j - M), o = sum w_j o_j / sum w_j. This lets long-context decode spread one query's keys over many blocks and still give the exact softmax result.

Shapes and data flow

ms (S,)  ls (S,)  os (S, D)  ->  o (D,)  lse scalar
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplemerge_partials([1, 3], [2, 1], [[1, 0], [0, 1]])
  • Sample 2: matches full softmax_check()