Build a global magnitude pruning mask
Why it matters Magnitude pruning is the baseline every sparsity method for LLMs (SparseGPT, Wanda) compares against.
The lottery ticket experiments prune the smallest weights by magnitude across all layers at once.
Write prune_mask(weights, sparsity). weights is a list of arrays. Find the threshold so that the fraction sparsity of all weights (counted globally) is removed: sort all |w|, k = int(sparsity * total), threshold = the k-th smallest |w| (0-based index k - 1), and keep weights with |w| > threshold. If k is 0 keep everything. Return a list of boolean masks.
def prune_mask(weights, sparsity)Example
prune_mask([[1, -3], [2, 0.5]], 0.5) removes 0.5 and 1, giving [[False, True], [True, False]].
Understand the idea
Magnitude pruning removes the weights closest to zero, on the idea that they matter least. Doing it globally means you pick one threshold across all layers together, so a layer full of tiny weights loses more of them than a layer with large ones. Worked example: weights [[0.2, -1.5, 0.7], [3.0, -0.1]], sparsity 0.4. There are 5 weights, so k = int(0.4 * 5) = 2. The sorted absolute values are [0.1, 0.2, 0.7, 1.5, 3.0], and the threshold is the value at index k - 1 = 1, which is 0.2. Keep |w| > 0.2: masks [[False, True, True], [True, False]]. Two weights (0.2 and -0.1) are removed. Rule: flatten all |w| from every array into one list and sort; k = int(sparsity * total); if k is 0, keep everything; else threshold = sorted[k - 1] and each mask is |w| > threshold, with the same shape as its array. Note that ties at the threshold are also removed. Compute the threshold from all layers, not just the first. Used in: lottery ticket experiments, compressing networks, and sparsity research on LLM weights.