Add Axon.Pruning with magnitude-based unstructured pruning - #666
Open
seanmor5 wants to merge 2 commits into
Open
Add Axon.Pruning with magnitude-based unstructured pruning#666seanmor5 wants to merge 2 commits into
seanmor5 wants to merge 2 commits into
Conversation
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
function_exported?/3 accepted module_info/0, which then failed with a FunctionClauseError inside Polaris.Updates.stateful/3 instead of the documented ArgumentError. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
polvalente
reviewed
Aug 24, 2026
|
|
||
| defp optimizer_fns(optimizer) when is_atom(optimizer) do | ||
| if Code.ensure_loaded?(Polaris.Optimizers) and | ||
| {optimizer, 0} in Polaris.Optimizers.__info__(:functions) do |
Member
There was a problem hiding this comment.
Suggested change
| {optimizer, 0} in Polaris.Optimizers.__info__(:functions) do | |
| function_exported?(Polaris.Optimizers, optimizer, 0) do |
polvalente
reviewed
Aug 24, 2026
| end | ||
|
|
||
| defp zero_count(tensor) do | ||
| tensor |> Nx.equal(0) |> Nx.sum() |> Nx.to_number() |
Member
There was a problem hiding this comment.
Suggested change
| tensor |> Nx.equal(0) |> Nx.sum() |> Nx.to_number() | |
| tensor |> Nx.equal(0) |> Nx.as_type(:u64) |> Nx.sum() |> Nx.to_number() |
Otherwise there will be overflows happening
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #120.
Pruning is a standard compression step alongside quantization, but Axon had nothing for it: there was no way to zero out low-magnitude weights, no way to keep them at zero while fine-tuning, and no way to report how sparse a model state is. This PR adds
Axon.Pruning, a sibling ofAxon.Quantizationthat works purely on anAxon.ModelStateand leaves the model graph untouched.Design
This is a first, deliberately narrow increment: unstructured magnitude pruning. The parameters with the smallest absolute values are set to zero, either against one global threshold (
scope: :global, the default, so some tensors end up sparser than others) or per tensor (scope: :tensor, every selected tensor is pruned to exactly the requested sparsity). Pruning always produces a mask alongside the pruned state: a nested map mirroring the model state data with a{:u, 8}tensor (1= keep,0= pruned) for every pruned parameter. Parameters that were not selected are simply absent from the mask.The public API is:
magnitude_mask/3computes the mask without touching the state. Candidates come from theparameterstree only, so batch-norm running statistics (which live instate) are never pruned. Tied parameters (Axon.ModelState.SharedParameter), quantized parameters (Axon.Quantization.QTensor) and non-float tensors are skipped. The:filteroption receives the same access paths asAxon.ModelState.freeze/2(e.g.["dense_0", "kernel"]or["lstm_0", "input_kernel", "wii"]); the default keeps any path with a name ending in"kernel", which covers dense/conv/embedding kernels and the composite RNN kernels while leaving biases and normalization parameters alone.apply_mask/2zeroes the masked entries of a model state or a plain parameter map usingNx.select/3, so dtypes are preserved andNaN/Infdon't leak through a multiply.prune/3ismagnitude_mask/3+apply_mask/2and returns{pruned_state, mask}.masked_optimizer/2wraps anythingAxon.Loop.trainer/4accepts (aPolaris.Optimizersatom or an{init_fn, update_fn}tuple) viaPolaris.Updates.stateful/3. The mask is stored in the optimizer state, and the final update is zeroed at pruned positions, so a weight that starts at zero stays exactly zero regardless of momentum or weight decay. This composes with the existing loop and needs no changes toAxon.Loop. Mask entries for parameters that are not trained (e.g. frozen ones) are ignored.sparsity/1andglobal_sparsity/1report the fraction of exactly-zero entries per parameter (nested maps for composite parameters) and size-weighted across the whole state.The mask computation ranks magnitudes with a double
Nx.argsort(stable), so exactlyround(sparsity * n)entries are pruned even when magnitudes tie, and it works insidedefnon any backend.magnitude_mask/3,apply_mask/2andprune/3aredeftransforms so they can be called fromdefn; the sparsity reporting functions callNx.to_number/1and are eager only.Usage
Limitations
"kernel"; anything else needs an explicit:filter.masked_optimizer/2copies the mask to the binary backend so it can be embedded in the traced optimizer init; from then on it travels as ordinary optimizer state (and is therefore checkpointed with it).Tests
test/axon/pruning_test.exscovers per-tensor and global masks against hand-computed expectations, exact counts under ties, the sparsity0/1short-circuits, the default filter on dense + batch norm (state untouched) and LSTM (composite kernels masked, biases not), custom filters, skipping of tied, quantized and integer parameters, argument validation,apply_mask/2on model states and plain parameter maps (ignoring mask keys that are absent), all three transforms insidedefn,sparsity/1/global_sparsity/1including composite parameters and empty states, andmasked_optimizer/2with both:adamand an{init_fn, update_fn}tuple through a realAxon.Looprun (pruned entries stay exactly zero, unmasked entries train, and a control run without the wrapper does not keep them at zero). The suite passes on the default backend and withUSE_EXLA=1.🤖 Generated with Claude Code