A matmul kernel that picks its split-K factor from the batch size sums the same output row in a different order for different batch sizes, and floating-point addition is not associative, so a prompt's logits change with the batch it shares a step with. Write a split-K matmul whose reduction order depends only on K and the split factor you pass, never on M.
Required kernels and wrapper:
@triton.jit
def splitk_partial_kernel(a_ptr, b_ptr, part_ptr, M, N, K,
stride_am, stride_ak, stride_bk, stride_bn,
stride_ps, stride_pm, stride_pn,
K_PER_SPLIT: tl.constexpr, BLOCK_N: tl.constexpr):
@triton.jit
def splitk_reduce_kernel(part_ptr, out_ptr, M, N,
stride_ps, stride_pm, stride_pn, stride_om, stride_on,
SPLIT_K: tl.constexpr, BLOCK_N: tl.constexpr):
def matmul_splitk(a: torch.Tensor, b: torch.Tensor, split_k: int) -> torch.Tensor:
a is (M, K) and b is (K, N), both float32 on the GPU. K_PER_SPLIT = triton.cdiv(K, split_k).(M, cdiv(N, BLOCK_N), split_k). Program (m, n_block, s) accumulates a[m, k] * b[k, cols] for k from s * K_PER_SPLIT upward, one k at a time in increasing order, masking k >= K, and stores its partial row into part[s, m, cols], a (split_k, M, N) float32 buffer.(M, cdiv(N, BLOCK_N)) and adds the partials for s = 0, 1, ..., split_k - 1 in that order into the output.BLOCK_N = 128.The tests check that the result is close to torch.matmul and that every row's bits are identical whether it is computed alone, inside a bigger batch, or after a permutation of the rows.
tl.load(a_ptr + m * stride_am + k * stride_ak, mask=k < K, other=0.0) broadcasts against the column block; the masked tail keeps non-divisible K correct.[BLOCK_N] float32 block created with tl.zeros and loop with for kk in range(K_PER_SPLIT).M except the mask on the grid; that is the whole invariance argument.