prune
prune(model, density=0.5, axis=0, layer_types=(nn.Conv2d, nn.Linear), min_dim=8, inplace=False, score_fn="magnitude", prune_head=False, exclude=(), pattern="phi") returns the pruned model and a dict from each pruned parameter's name to its mask.
- Every parameter whose name holds
weightin a module oflayer_typesgets a mask, apart from three cases that stay dense: the model's last weight layer, the last Conv2d, Linear orlayer_typesmodule in registration order, unlessprune_head=True; the modules named inexclude; and a weight with fewer thanmin_dimpositions alongaxis. - The last weight layer is usually the classifier head. Along axis 0 its positions are the classes, the φ mask would keep at most (n + 1) // 2 of them, and a class left out would get a logit that is its bias alone.
pattern="phi"builds each mask withphi_mask,pattern="2:4"withtwo_four_mask; The masks shows both. A density below 0.5 reachesphi_mask(density=...), and at 0.5 or above each φ mask is the heaviest set the constraint allows. With"2:4", a density below 0.5 raisesValueError.- The weights are multiplied by their masks. With
inplace=Falsea deep copy is pruned and the model passed in is left as it was. - The pruned model carries
_phi_prune_stats:pattern,axis,total_params,active_params,pruned_layers,densityandsparsity, counted over every weight of thelayer_typesmodules, the dense ones included.checkandsave_checkpointread the pattern and axis from it.
finetune and evaluate
finetune(model, train_loader, epochs=40, masks=None, lr=0.01, momentum=0.9, weight_decay=1e-4, device=None, val_loader=None, verbose=True, criterion=None, amp=False) trains with SGD and a cosine learning-rate schedule over all epochs, with cross-entropy unless criterion is given. It is fine-tuning with a fixed mask: after each backward pass every masked weight's gradient is multiplied by its mask, and after each step the weight is, so pruned weights end every step at zero. With no masks every weight trains, which is how a dense model is fine-tuned before pruning.
- With
val_loaderit scores every epoch withevaluateand at the end restores the weights of the epoch that scored best, when any epoch scored above 0%. amp=Trueruns forward passes under fp16 autocast with loss scaling on a CUDA device; on any other device training stays in fp32.verboseprints the loss and accuracies everymax(1, epochs // 4)epochs.- It returns
history, one dict per epoch withepoch,loss,train_accandval_acc,best_val_acc, which isNonewithoutval_loader, andfinal_train_acc.
evaluate(model, loader, device=None, amp=False, fp32_fallback=True) returns top-1 accuracy in percent. Under amp on CUDA, a batch whose fp16 logits are not all finite runs again in fp32, since an activation past 65504, fp16's largest value, makes a logit inf or NaN and argmax over a row of NaN gives class 0.
check
check(model, masks, pattern=None, axis=None) reports, for each masked parameter, the fields of mask_stats and zeros_enforced, whether every pruned weight is within 1e-10 of zero. The pattern and axis come from the stats prune attached, or default to "phi" and 0. Its "_summary" holds all_masks_valid, all_zeros_enforced, n_layers, pattern and axis.
Saving and exporting
phi_prune.export.save_checkpoint(model, masks, path, encoder=None, scales=None, metadata=None) writes a PyTorch checkpoint holding state_dict, masks, pattern, axis, format "phi-prune", version, the release of phi_prune that wrote it, and prune_stats, the mask_stats of each mask. Given an encoder it adds encoding with n_digits, n_levels and max_value; given scales it adds each layer's scale and quantization offset, as a float or a float64 tensor; and it stores metadata as given.
The file loads with torch.load(path, weights_only=True), which runs no code from it, as long as metadata holds only strings, numbers, booleans, None, lists, tuples, dicts and tensors:
data = torch.load("pruned.pt", weights_only=True)
model.load_state_dict(data["state_dict"])
masks = data["masks"]
export_onnx(model, path, input_shape=(1, 3, 32, 32), opset=17) exports through torch.onnx.export, traced on a random input of input_shape, with the first axis of the input and output named batch and dynamic. The pruned weights stay in the graph as zeros, so the graph is as dense as the model. It needs the export extra, which installs onnx, onnxruntime and onnxscript, and raises ImportError without onnx.
The quantized weights' own file, export_bitstream, is on Quantization and the code.
The phi-prune command
phi-prune check pruned.pt
phi-prune info pruned.pt
checkreads every mask of a checkpoint throughmask_stats, along the axis the file records, and checks that each pruned weight in its state dict is within 1e-10 of zero. It printsLoadingand the file's name, one line per mask with its density,validandzeros, then either one line saying every mask and pruned weight holds or one line for each kind of failure, and exits 0 when every mask holds and every pruned weight is zero. A mask whose weight the state dict lacks, or holds in another shape, fails.infoprints how many weights each mask keeps and the total over all of them, and exits 0.- Both read the file with
torch.load(weights_only=True), with the numpy array types a checkpoint of per-channel scales may hold allowed, and exit 1 for a file that load refuses or that holds nomasks;checkalso exits 1 when a mask or a pruned weight fails. A command line argparse cannot read exits 2. - A file with no
patternis read as holding φ masks and one with noaxisas pruned along axis 0, and the pattern value"zeckendorf"that earlier releases wrote reads as"phi". - The command neither prunes nor exports. A model's class cannot be rebuilt from saved weights, so pruning and fine-tuning go through the Python interface.
Source: phi_prune/cli.py; the command is the phi-prune script that [project.scripts] of pyproject.toml declares.
Installing
pip install "git+https://github.com/ezexe/phi.git#subdirectory=lbiza"
pip install "phi-prune[export] @ git+https://github.com/ezexe/phi.git#subdirectory=lbiza"
phi needs Python 3.11 or later, torch 2.4.1 or later and numpy 1.24 or later.