Prune weights to 2:4 structured sparsity
Why it matters 2:4 sparsity is supported by sparse tensor cores, and pruning LLM weights to it is a common way to speed up inference.
Some GPUs run matmuls about twice as fast when every group of 4 consecutive weights has at most 2 non-zeros. Magnitude pruning to this 2:4 pattern keeps the 2 largest-magnitude weights in each group.
Write prune_2_4(W). W has shape (rows, cols) with cols divisible by 4; raise ValueError otherwise. In each group of 4 consecutive entries along a row, keep the two with the largest absolute value (ties go to the lower index) and zero the others. Return (pruned W as float, mask as bool array).
def prune_2_4(W)Example
W [[1, -5, 3, 2, 0, 0, 7, -7]] gives pruned [[0, -5, 3, 0, 0, 0, 7, -7]].
Understand the idea
2:4 sparsity is a strict budget: in every group of four seats, only two people may sit. Hardware can then skip the empty seats in a fixed, predictable way, which is why it gives real speedups unlike random sparsity. Pruning by magnitude keeps the two weights with the biggest absolute value, because they change the output the most. Worked example: group [1, -5, 3, 2]. Absolute values are [1, 5, 3, 2], so keep -5 and 3 and zero the rest: [0, -5, 3, 0]. Rule: per group of 4 along a row, keep the top 2 by |w|, ties to the lower index. In practice the pruned model is usually fine-tuned briefly or corrected with a few calibration steps to recover accuracy.
Shapes and data flow
W (r, c) -> groups (r, c/4, 4) -> mask (r, c/4, 4) -> (r, c)