Lesson 6 of 10
Global magnitude pruning
Magnitude pruning keeps the largest weights and zeros the rest. Global pruning ranks the weights of all layers together, so a layer full of tiny weights can lose most of them while a sensitive layer keeps more.
Implement global_masks(weights, sparsity): given a list of weight matrices and the fraction to remove, return one 0/1 mask per matrix (same shapes) that removes exactly round(sparsity * total) weights, the smallest in absolute value across all matrices.
Then the training loop multiplies weights by their mask after every step so pruned weights stay dead (lab/nn.py:MLP.apply_masks).
Your code
Tab indents. Press Esc, then Tab, to leave the editor. Ctrl or Cmd + Enter checks your code.
Pigeon's hint, 1 of 2
Concatenate abs(w).ravel() for every matrix, rank once, then split back by sizes.
Pigeon's hint, 2 of 2
np.argsort(...)[:k] gives the indices of the k smallest.
import numpy as np
def global_masks(weights, sparsity):
flat = np.concatenate([np.abs(w).ravel() for w in weights])
k = int(round(sparsity * flat.size))
drop = np.zeros(flat.size, bool)
drop[np.argsort(flat, kind="stable")[:k]] = True
masks, i = [], 0
for w in weights:
masks.append((~drop[i:i + w.size]).reshape(w.shape).astype(float))
i += w.size
return masks
Pigeon's tip
Pigeon's warning
Pigeon's note
Where this is used
- Magnitude pruningRuns hereSet the smallest weights to zero. Cheap and surprisingly effective, as long as you let the network recover afterwards.
- Lottery ticketsRuns hereTrain, prune, rewind the surviving weights to their early values, retrain. Tests whether the sparse network was trainable from the start.