Compute a matmul with split-K partial sums

Why it matters Split-K is used for skinny matmuls such as decode-time projections, where there are too few output tiles to keep every SM busy.

When M and N are small but K is large, a matmul has too few output tiles to fill the GPU. Split-K cuts the K dimension into chunks, lets different blocks compute partial products, then sums them.

Write split_k_matmul(A, B, splits). A is (M, K), B is (K, N). Chunk size is c = ceil(K / splits); split s covers k from s * c up to min(K, (s + 1) * c) (a split may be empty). Return (C, partials) where partials has shape (splits, M, N) with each split's partial product (zeros for empty splits) and C is their sum.

Signaturedef split_k_matmul(A, B, splits)

Example

A [[1, 2, 3]], B [[1], [1], [1]], splits 2 gives C [[6]] and partials [[[3]], [[3]]].

Understand the idea

Adding a long column of numbers goes faster if several people each add part of it and then you add their subtotals. A matmul output C[m, n] is exactly such a long sum over k, so the K dimension can be split. Worked example: A = [1, 2, 3], B = ones, splits 2. Chunk size ceil(3 / 2) = 2. Split 0 covers k = 0, 1: 1 + 2 = 3. Split 1 covers k = 2: 3. Total 6. Rule: c = ceil(K / S), C = sum_s A[:, sc:(s+1)c] B[sc:(s+1)c]. On a GPU the partial results are added with atomics or a second small reduction kernel. It pays off when the output has few tiles, for example one decode token times a big weight matrix with a large K.

Shapes and data flow

A (M, K) B (K, N)  split s: A[:, lo:hi] (M, c) @ B[lo:hi] (c, N) -> (M, N)  partials (S, M, N)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplesplit_k_matmul([[1, 2, 3]], [[1], [1], [1]], 2)
  • Sample 2: randomsplit_k_matmul(_A, _B, 3)