← phi · docs

Pruning a model

phi_prune prunes a trained PyTorch model by output channels, fine-tunes it with the pruned weights held at zero, checks every mask, and saves the result as a checkpoint the phi-prune command can check again. This page is that interface, from phi_prune/api.py, cli.py and export. The figure below runs prune's choice of layers on two model shapes.

from phi_prune import prune, finetune, check, evaluate
from phi_prune.export import save_checkpoint

pruned, masks = prune(model)                       # a deep copy, one mask per pruned weight
finetune(pruned, train_loader, epochs=40, masks=masks, val_loader=test_loader)
report = check(pruned, masks)
assert report["_summary"]["all_masks_valid"] and report["_summary"]["all_zeros_enforced"]
save_checkpoint(pruned, masks, "pruned.pt")

Channel scores are drawn at random in the page, so the kept counts are those of one draw; which weights get a mask, and why the others stay dense, is prune's rule exactly. The density in the stats counts every weight of the selected module types, the dense ones included, and no bias.

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 weight in a module of layer_types gets a mask, apart from three cases that stay dense: the model's last weight layer, the last Conv2d, Linear or layer_types module in registration order, unless prune_head=True; the modules named in exclude; and a weight with fewer than min_dim positions along axis.
  • 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 with phi_mask, pattern="2:4" with two_four_mask; The masks shows both. A density below 0.5 reaches phi_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 raises ValueError.
  • The weights are multiplied by their masks. With inplace=False a 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, density and sparsity, counted over every weight of the layer_types modules, the dense ones included. check and save_checkpoint read 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_loader it scores every epoch with evaluate and at the end restores the weights of the epoch that scored best, when any epoch scored above 0%.
  • amp=True runs forward passes under fp16 autocast with loss scaling on a CUDA device; on any other device training stays in fp32.
  • verbose prints the loss and accuracies every max(1, epochs // 4) epochs.
  • It returns history, one dict per epoch with epoch, loss, train_acc and val_acc, best_val_acc, which is None without val_loader, and final_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
  • check reads every mask of a checkpoint through mask_stats, along the axis the file records, and checks that each pruned weight in its state dict is within 1e-10 of zero. It prints Loading and the file's name, one line per mask with its density, valid and zeros, 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.
  • info prints 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 no masks; check also exits 1 when a mask or a pruned weight fails. A command line argparse cannot read exits 2.
  • A file with no pattern is read as holding φ masks and one with no axis as 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.