Install phi-prune, prune a small model, check its masks, write its kept weights as a Fibonacci-coded bitstream, and run the tests. Each step below ran once on Python 3.14 with torch 2.15 on a CPU, and each output is what it printed. The three Python steps run in one session, each using the names the one before it set.
phi-prune needs Python 3.11 or later, torch 2.4.1 or later, and numpy. Install the package and its phi-prune command from GitHub:
pip install "git+https://github.com/ezexe/phi#subdirectory=lbiza"
To work on the code and run its tests, clone it and install it in editable mode with the dev extra, which adds pytest:
git clone https://github.com/ezexe/phi
cd phi/lbiza
pip install -e ".[dev]"
pip installs torch when it is missing. For torch's CPU-only wheels, install torch first from https://download.pytorch.org/whl/cpu, as the tests workflow does.
prune gives each eligible Conv2d and Linear weight a φ mask over its output channels, which keeps the heaviest set of channels with no two adjacent, and zeroes the rest. It prunes a copy and returns it with the masks.
import torch
import torch.nn as nn
from phi_prune import prune
torch.manual_seed(0)
model = nn.Sequential(
nn.Conv2d(3, 16, 3), nn.ReLU(),
nn.Conv2d(16, 32, 3), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Linear(32, 10),
)
pruned, masks = prune(model)
for name, mask in masks.items():
print(name, tuple(mask.shape), f"keeps {mask.float().mean():.1%}")
print(f"density {pruned._phi_prune_stats['density']:.1%}")
Output
0.weight (16, 3, 3, 3) keeps 50.0% 2.weight (32, 16, 3, 3) keeps 50.0% density 53.0%
The last weight layer, here the Linear classifier head, stays dense, and the density counts its weights too. A trained model is fine-tuned next with the masks held fixed, through finetune, which Pruning a model covers.
check reads every mask against its pattern and checks that every pruned weight is zero. Its summary counts the masked layers. save_checkpoint writes the model with its masks, so the phi-prune command can check the file again.
from phi_prune import check
from phi_prune.export import save_checkpoint
report = check(pruned, masks)
summary = report["_summary"]
print(summary["n_layers"], summary["all_masks_valid"], summary["all_zeros_enforced"])
save_checkpoint(pruned, masks, "pruned.pt")
Output
2 True True
phi-prune check pruned.pt
phi-prune info pruned.pt
Output
Loading pruned.pt... ✓ 0.weight: density=0.500 valid=True zeros=True ✓ 2.weight: density=0.500 valid=True zeros=True ✓ All masks satisfy the (1,∞)-RLL constraint, and every pruned weight is zero. 0.weight: 216/432 (50.0%) 2.weight: 2304/4608 (50.0%) Overall: 2520/5040, 50.0% density
phi-prune check exits 1 when a mask breaks its pattern or a pruned weight is not zero. info counts only the masked weights.
FibonacciEncoder rounds each kept weight to the nearest of its quantization levels, with a scale and an offset per output channel when axis=0. export_bitstream writes each level as a Fibonacci codeword, and load_bitstream reads the file back into the kept positions.
from phi_prune import FibonacciEncoder
from phi_prune.export import export_bitstream, load_bitstream
encoder = FibonacciEncoder(n_digits=8)
scales = {}
for name, param in pruned.named_parameters():
if name in masks:
encoded, scale, rmse, offset = encoder.encode_tensor(
param.data, mask=masks[name], return_offset=True, axis=0)
param.data.copy_(encoded)
scales[name] = (scale, offset)
print(name, f"rmse {rmse:.4f}")
stats = export_bitstream(pruned, masks, encoder, scales, "pruned.phi")
print(stats["n_weights"], "weights,", f"{stats['bits_per_weight']:.2f} bits per weight")
encoded = {name: p.detach().clone() for name, p in pruned.named_parameters()}
for p in pruned.parameters():
p.data.zero_()
load_bitstream(pruned, masks, "pruned.phi")
for name in masks:
error = (pruned.get_parameter(name) - encoded[name]).abs().max().item()
print(name, f"read back, largest error {error:.1e}")
Output
0.weight rmse 0.0018 2.weight rmse 0.0009 2520 weights, 7.55 bits per weight 0.weight read back, largest error 0.0e+00 2.weight read back, largest error 0.0e+00
Eight digits give 55 quantization levels. The bits per weight count the payload alone, and the file's JSON header line holds each layer's shape, kept count, scales and offsets.
From lbiza/ in the clone, the folder that holds pyproject.toml, with the dev extra installed:
python -m pytest
Last line of the output, at commit 49b36ab
================ 203 passed, 13 skipped, 4 warnings in 18.64s =================
A test that needs a package, git or the p4-phi plugin where this machine lacks it is skipped, and -ra in pyproject.toml prints why. In this run 12 tests skipped for the p4-phi plugin, which a checkout of ezexe/p4 beside the clone or P4_RECALL_PLUGIN_ROOT supplies, and one for onnx, which the export extra installs. Outside CI, tests/test_suite.py fails a run that takes longer than the budget_seconds that pyproject.toml sets.
prune, finetune, check and the saved checkpoint in full..phid file of a model's delta.