Upload folder using huggingface_hub (part 22)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +25 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/activation_sparsifier.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/activation_sparsifier.py +482 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py +6 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py +199 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__init__.py +8 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/base_data_sparsifier.py +334 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py +204 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/_data_sparstity_utils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py +44 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py +181 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/quantization_utils.py +156 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py +95 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py +5 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py +314 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py +54 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py +65 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py +63 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py +485 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py +35 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/_mappings.py +23 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/base_scheduler.py +173 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py +114 -0
- .venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py +64 -0
.gitattributes
CHANGED
|
@@ -553,3 +553,28 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 553 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 554 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 555 |
.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 554 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 555 |
.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 556 |
+
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 557 |
+
.venv/lib/python3.12/site-packages/torch/bin/FileStoreTest filter=lfs diff=lfs merge=lfs -text
|
| 558 |
+
.venv/lib/python3.12/site-packages/torch/bin/HashStoreTest filter=lfs diff=lfs merge=lfs -text
|
| 559 |
+
.venv/lib/python3.12/site-packages/torch/bin/TCPStoreTest filter=lfs diff=lfs merge=lfs -text
|
| 560 |
+
.venv/lib/python3.12/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
| 561 |
+
.venv/lib/python3.12/site-packages/torch/bin/protoc-3.21.12.0 filter=lfs diff=lfs merge=lfs -text
|
| 562 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_aoti_abi_check filter=lfs diff=lfs merge=lfs -text
|
| 563 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_api filter=lfs diff=lfs merge=lfs -text
|
| 564 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_comms_id filter=lfs diff=lfs merge=lfs -text
|
| 565 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_cpp_rpc filter=lfs diff=lfs merge=lfs -text
|
| 566 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_dist_autograd filter=lfs diff=lfs merge=lfs -text
|
| 567 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_global_state_manager filter=lfs diff=lfs merge=lfs -text
|
| 568 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_jit filter=lfs diff=lfs merge=lfs -text
|
| 569 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_lazy filter=lfs diff=lfs merge=lfs -text
|
| 570 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_privateuse1_profiler filter=lfs diff=lfs merge=lfs -text
|
| 571 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_profiler_collection filter=lfs diff=lfs merge=lfs -text
|
| 572 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_profiler_global_callback_stale_session filter=lfs diff=lfs merge=lfs -text
|
| 573 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_shim filter=lfs diff=lfs merge=lfs -text
|
| 574 |
+
.venv/lib/python3.12/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 575 |
+
.venv/lib/python3.12/site-packages/torch/distributed/_local_tensor/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 576 |
+
.venv/lib/python3.12/site-packages/torch/distributed/_symmetric_memory/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 577 |
+
.venv/lib/python3.12/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 578 |
+
.venv/lib/python3.12/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 579 |
+
.venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 580 |
+
.venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (227 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/activation_sparsifier.cpython-312.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/activation_sparsifier.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import copy
|
| 3 |
+
import warnings
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import nn
|
| 9 |
+
from torch.ao.pruning.sparsifier.utils import fqn_to_module, module_to_fqn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = ["ActivationSparsifier"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ActivationSparsifier:
|
| 16 |
+
r"""
|
| 17 |
+
The Activation sparsifier class aims to sparsify/prune activations in a neural
|
| 18 |
+
network. The idea is to attach the sparsifier to a layer (or layers) and it
|
| 19 |
+
zeroes out the activations based on the mask_fn (or sparsification function)
|
| 20 |
+
input by the user.
|
| 21 |
+
The mask_fn is applied once all the inputs are aggregated and reduced i.e.
|
| 22 |
+
mask = mask_fn(reduce_fn(aggregate_fn(activations)))
|
| 23 |
+
|
| 24 |
+
Note::
|
| 25 |
+
The sparsification mask is computed on the input **before it goes through the attached layer**.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
model (nn.Module):
|
| 29 |
+
The model whose layers will be sparsified. The layers that needs to be
|
| 30 |
+
sparsified should be added separately using the register_layer() function
|
| 31 |
+
aggregate_fn (Optional, Callable):
|
| 32 |
+
default aggregate_fn that is used if not specified while registering the layer.
|
| 33 |
+
specifies how inputs should be aggregated over time.
|
| 34 |
+
The aggregate_fn should usually take 2 torch tensors and return the aggregated tensor.
|
| 35 |
+
Example
|
| 36 |
+
def add_agg_fn(tensor1, tensor2): return tensor1 + tensor2
|
| 37 |
+
reduce_fn (Optional, Callable):
|
| 38 |
+
default reduce_fn that is used if not specified while registering the layer.
|
| 39 |
+
reduce_fn will be called on the aggregated tensor i.e. the tensor obtained after
|
| 40 |
+
calling agg_fn() on all inputs.
|
| 41 |
+
Example
|
| 42 |
+
def mean_reduce_fn(agg_tensor): return agg_tensor.mean(dim=0)
|
| 43 |
+
mask_fn (Optional, Callable):
|
| 44 |
+
default mask_fn that is used to create the sparsification mask using the tensor obtained after
|
| 45 |
+
calling the reduce_fn(). This is used by default if a custom one is passed in the
|
| 46 |
+
register_layer().
|
| 47 |
+
Note that the mask_fn() definition should contain the sparse arguments that is passed in sparse_config
|
| 48 |
+
arguments.
|
| 49 |
+
features (Optional, list):
|
| 50 |
+
default selected features to sparsify.
|
| 51 |
+
If this is non-empty, then the mask_fn will be applied for each feature of the input.
|
| 52 |
+
For example,
|
| 53 |
+
mask = [mask_fn(reduce_fn(aggregated_fn(input[feature])) for feature in features]
|
| 54 |
+
feature_dim (Optional, int):
|
| 55 |
+
default dimension of input features. Again, features along this dim will be chosen
|
| 56 |
+
for sparsification.
|
| 57 |
+
sparse_config (Dict):
|
| 58 |
+
Default configuration for the mask_fn. This config will be passed
|
| 59 |
+
with the mask_fn()
|
| 60 |
+
|
| 61 |
+
Example:
|
| 62 |
+
>>> # xdoctest: +SKIP
|
| 63 |
+
>>> model = SomeModel()
|
| 64 |
+
>>> act_sparsifier = ActivationSparsifier(...) # init activation sparsifier
|
| 65 |
+
>>> # Initialize aggregate_fn
|
| 66 |
+
>>> def agg_fn(x, y):
|
| 67 |
+
>>> return x + y
|
| 68 |
+
>>>
|
| 69 |
+
>>> # Initialize reduce_fn
|
| 70 |
+
>>> def reduce_fn(x):
|
| 71 |
+
>>> return torch.mean(x, dim=0)
|
| 72 |
+
>>>
|
| 73 |
+
>>> # Initialize mask_fn
|
| 74 |
+
>>> def mask_fn(data):
|
| 75 |
+
>>> return torch.eye(data.shape).to(data.device)
|
| 76 |
+
>>>
|
| 77 |
+
>>>
|
| 78 |
+
>>> act_sparsifier.register_layer(
|
| 79 |
+
... model.some_layer,
|
| 80 |
+
... aggregate_fn=agg_fn,
|
| 81 |
+
... reduce_fn=reduce_fn,
|
| 82 |
+
... mask_fn=mask_fn,
|
| 83 |
+
... )
|
| 84 |
+
>>>
|
| 85 |
+
>>> # start training process
|
| 86 |
+
>>> for _ in [...]:
|
| 87 |
+
>>> # epoch starts
|
| 88 |
+
>>> # model.forward(), compute_loss() and model.backwards()
|
| 89 |
+
>>> # epoch ends
|
| 90 |
+
>>> act_sparsifier.step()
|
| 91 |
+
>>> # end training process
|
| 92 |
+
>>> sparsifier.squash_mask()
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
model: nn.Module,
|
| 98 |
+
aggregate_fn=None,
|
| 99 |
+
reduce_fn=None,
|
| 100 |
+
mask_fn=None,
|
| 101 |
+
features=None,
|
| 102 |
+
feature_dim=None,
|
| 103 |
+
**sparse_config,
|
| 104 |
+
):
|
| 105 |
+
self.model = model
|
| 106 |
+
self.defaults: dict[str, Any] = defaultdict()
|
| 107 |
+
self.defaults["sparse_config"] = sparse_config
|
| 108 |
+
|
| 109 |
+
# functions
|
| 110 |
+
self.defaults["aggregate_fn"] = aggregate_fn
|
| 111 |
+
self.defaults["reduce_fn"] = reduce_fn
|
| 112 |
+
self.defaults["mask_fn"] = mask_fn
|
| 113 |
+
|
| 114 |
+
# default feature and feature_dim
|
| 115 |
+
self.defaults["features"] = features
|
| 116 |
+
self.defaults["feature_dim"] = feature_dim
|
| 117 |
+
|
| 118 |
+
self.data_groups: dict[str, dict] = defaultdict(
|
| 119 |
+
dict
|
| 120 |
+
) # contains all relevant info w.r.t each registered layer
|
| 121 |
+
|
| 122 |
+
self.state: dict[str, Any] = defaultdict(dict) # layer name -> mask
|
| 123 |
+
|
| 124 |
+
@staticmethod
|
| 125 |
+
def _safe_rail_checks(args):
|
| 126 |
+
"""Makes sure that some of the functions and attributes are not passed incorrectly"""
|
| 127 |
+
|
| 128 |
+
# if features are not None, then feature_dim must not be None
|
| 129 |
+
features, feature_dim = args["features"], args["feature_dim"]
|
| 130 |
+
if features is not None:
|
| 131 |
+
if feature_dim is None:
|
| 132 |
+
raise AssertionError("need feature dim to select features")
|
| 133 |
+
|
| 134 |
+
# all the *_fns should be callable
|
| 135 |
+
fn_keys = ["aggregate_fn", "reduce_fn", "mask_fn"]
|
| 136 |
+
for key in fn_keys:
|
| 137 |
+
fn = args[key]
|
| 138 |
+
if not callable(fn):
|
| 139 |
+
raise AssertionError(f"{fn} must be callable")
|
| 140 |
+
|
| 141 |
+
def _aggregate_hook(self, name):
|
| 142 |
+
"""Returns hook that computes aggregate of activations passing through."""
|
| 143 |
+
|
| 144 |
+
# gather some data
|
| 145 |
+
feature_dim = self.data_groups[name]["feature_dim"]
|
| 146 |
+
features = self.data_groups[name]["features"]
|
| 147 |
+
agg_fn = self.data_groups[name]["aggregate_fn"]
|
| 148 |
+
|
| 149 |
+
def hook(module, input) -> None:
|
| 150 |
+
input_data = input[0]
|
| 151 |
+
|
| 152 |
+
data = self.data_groups[name].get("data") # aggregated data
|
| 153 |
+
if features is None:
|
| 154 |
+
# no features associated, data should not be a list
|
| 155 |
+
if data is None:
|
| 156 |
+
data = torch.zeros_like(input_data)
|
| 157 |
+
self.state[name]["mask"] = torch.ones_like(input_data)
|
| 158 |
+
out_data = agg_fn(data, input_data)
|
| 159 |
+
else:
|
| 160 |
+
# data should be a list [aggregated over each feature only]
|
| 161 |
+
if data is None:
|
| 162 |
+
out_data = [
|
| 163 |
+
0 for _ in range(len(features))
|
| 164 |
+
] # create one in case of 1st forward
|
| 165 |
+
self.state[name]["mask"] = [0 for _ in range(len(features))]
|
| 166 |
+
else:
|
| 167 |
+
out_data = data # a list
|
| 168 |
+
|
| 169 |
+
# compute aggregate over each feature
|
| 170 |
+
for feature_idx in range(len(features)):
|
| 171 |
+
# each feature is either a list or scalar, convert it to torch tensor
|
| 172 |
+
feature_tensor = (
|
| 173 |
+
torch.Tensor([features[feature_idx]])
|
| 174 |
+
.long()
|
| 175 |
+
.to(input_data.device)
|
| 176 |
+
)
|
| 177 |
+
data_feature = torch.index_select(
|
| 178 |
+
input_data, feature_dim, feature_tensor
|
| 179 |
+
)
|
| 180 |
+
if data is None:
|
| 181 |
+
curr_data = torch.zeros_like(data_feature)
|
| 182 |
+
self.state[name]["mask"][feature_idx] = torch.ones_like(
|
| 183 |
+
data_feature
|
| 184 |
+
)
|
| 185 |
+
else:
|
| 186 |
+
curr_data = data[feature_idx]
|
| 187 |
+
out_data[feature_idx] = agg_fn(curr_data, data_feature)
|
| 188 |
+
self.data_groups[name]["data"] = out_data
|
| 189 |
+
|
| 190 |
+
return hook
|
| 191 |
+
|
| 192 |
+
def register_layer(
|
| 193 |
+
self,
|
| 194 |
+
layer: nn.Module,
|
| 195 |
+
aggregate_fn=None,
|
| 196 |
+
reduce_fn=None,
|
| 197 |
+
mask_fn=None,
|
| 198 |
+
features=None,
|
| 199 |
+
feature_dim=None,
|
| 200 |
+
**sparse_config,
|
| 201 |
+
):
|
| 202 |
+
r"""
|
| 203 |
+
Registers a layer for sparsification. The layer should be part of self.model.
|
| 204 |
+
Specifically, registers a pre-forward hook to the layer. The hook will apply the aggregate_fn
|
| 205 |
+
and store the aggregated activations that is input over each step.
|
| 206 |
+
|
| 207 |
+
Note::
|
| 208 |
+
- There is no need to pass in the name of the layer as it is automatically computed as per
|
| 209 |
+
the fqn convention.
|
| 210 |
+
|
| 211 |
+
- All the functions (fn) passed as argument will be called at a dim, feature level.
|
| 212 |
+
"""
|
| 213 |
+
name = module_to_fqn(self.model, layer)
|
| 214 |
+
if name is None:
|
| 215 |
+
raise AssertionError("layer not found in the model")
|
| 216 |
+
|
| 217 |
+
if name in self.data_groups: # unregister layer if already present
|
| 218 |
+
warnings.warn(
|
| 219 |
+
"layer already attached to the sparsifier, deregistering the layer and registering with new config",
|
| 220 |
+
stacklevel=2,
|
| 221 |
+
)
|
| 222 |
+
self.unregister_layer(name=name)
|
| 223 |
+
|
| 224 |
+
local_args = copy.deepcopy(self.defaults)
|
| 225 |
+
update_dict = {
|
| 226 |
+
"aggregate_fn": aggregate_fn,
|
| 227 |
+
"reduce_fn": reduce_fn,
|
| 228 |
+
"mask_fn": mask_fn,
|
| 229 |
+
"features": features,
|
| 230 |
+
"feature_dim": feature_dim,
|
| 231 |
+
"layer": layer,
|
| 232 |
+
}
|
| 233 |
+
local_args.update(
|
| 234 |
+
(arg, val) for arg, val in update_dict.items() if val is not None
|
| 235 |
+
)
|
| 236 |
+
local_args["sparse_config"].update(sparse_config)
|
| 237 |
+
|
| 238 |
+
self._safe_rail_checks(local_args)
|
| 239 |
+
|
| 240 |
+
self.data_groups[name] = local_args
|
| 241 |
+
agg_hook = layer.register_forward_pre_hook(self._aggregate_hook(name=name))
|
| 242 |
+
|
| 243 |
+
self.state[name]["mask"] = (
|
| 244 |
+
None # mask will be created when model forward is called.
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# attach agg hook
|
| 248 |
+
self.data_groups[name]["hook"] = agg_hook
|
| 249 |
+
|
| 250 |
+
# for serialization purposes, we know whether aggregate_hook is attached
|
| 251 |
+
# or sparsify_hook()
|
| 252 |
+
self.data_groups[name]["hook_state"] = "aggregate" # aggregate hook is attached
|
| 253 |
+
|
| 254 |
+
def get_mask(self, name: str | None = None, layer: nn.Module | None = None):
|
| 255 |
+
"""
|
| 256 |
+
Returns mask associated to the layer.
|
| 257 |
+
|
| 258 |
+
The mask is
|
| 259 |
+
- a torch tensor is features for that layer is None.
|
| 260 |
+
- a list of torch tensors for each feature, otherwise
|
| 261 |
+
|
| 262 |
+
Note::
|
| 263 |
+
The shape of the mask is unknown until model.forward() is applied.
|
| 264 |
+
Hence, if get_mask() is called before model.forward(), an
|
| 265 |
+
error will be raised.
|
| 266 |
+
"""
|
| 267 |
+
if name is None and layer is None:
|
| 268 |
+
raise AssertionError("Need at least name or layer obj to retrieve mask")
|
| 269 |
+
|
| 270 |
+
if name is None:
|
| 271 |
+
if layer is None:
|
| 272 |
+
raise AssertionError("layer must be provided when name is None")
|
| 273 |
+
name = module_to_fqn(self.model, layer)
|
| 274 |
+
if name is None:
|
| 275 |
+
raise AssertionError("layer not found in the specified model")
|
| 276 |
+
|
| 277 |
+
if name not in self.state:
|
| 278 |
+
raise ValueError("Error: layer with the given name not found")
|
| 279 |
+
|
| 280 |
+
mask = self.state[name].get("mask", None)
|
| 281 |
+
|
| 282 |
+
if mask is None:
|
| 283 |
+
raise ValueError(
|
| 284 |
+
"Error: shape unknown, call layer() routine at least once to infer mask"
|
| 285 |
+
)
|
| 286 |
+
return mask
|
| 287 |
+
|
| 288 |
+
def unregister_layer(self, name):
|
| 289 |
+
"""Detaches the sparsifier from the layer"""
|
| 290 |
+
|
| 291 |
+
# detach any hooks attached
|
| 292 |
+
self.data_groups[name]["hook"].remove()
|
| 293 |
+
|
| 294 |
+
# pop from the state dict
|
| 295 |
+
self.state.pop(name)
|
| 296 |
+
|
| 297 |
+
# pop from the data groups
|
| 298 |
+
self.data_groups.pop(name)
|
| 299 |
+
|
| 300 |
+
def step(self):
|
| 301 |
+
"""Internally calls the update_mask() function for each layer"""
|
| 302 |
+
with torch.no_grad():
|
| 303 |
+
for name, configs in self.data_groups.items():
|
| 304 |
+
data = configs["data"]
|
| 305 |
+
self.update_mask(name, data, configs)
|
| 306 |
+
|
| 307 |
+
self.data_groups[name].pop("data") # reset the accumulated data
|
| 308 |
+
|
| 309 |
+
def update_mask(self, name, data, configs):
|
| 310 |
+
"""
|
| 311 |
+
Called for each registered layer and does the following-
|
| 312 |
+
1. apply reduce_fn on the aggregated activations
|
| 313 |
+
2. use mask_fn to compute the sparsification mask
|
| 314 |
+
|
| 315 |
+
Note:
|
| 316 |
+
the reduce_fn and mask_fn is called for each feature, dim over the data
|
| 317 |
+
"""
|
| 318 |
+
mask = self.get_mask(name)
|
| 319 |
+
sparse_config = configs["sparse_config"]
|
| 320 |
+
features = configs["features"]
|
| 321 |
+
reduce_fn = configs["reduce_fn"]
|
| 322 |
+
mask_fn = configs["mask_fn"]
|
| 323 |
+
if features is None:
|
| 324 |
+
data = reduce_fn(data)
|
| 325 |
+
mask.data = mask_fn(data, **sparse_config)
|
| 326 |
+
else:
|
| 327 |
+
for feature_idx in range(len(features)):
|
| 328 |
+
data_feature = reduce_fn(data[feature_idx])
|
| 329 |
+
mask[feature_idx].data = mask_fn(data_feature, **sparse_config)
|
| 330 |
+
|
| 331 |
+
def _sparsify_hook(self, name):
|
| 332 |
+
"""Returns hook that applies sparsification mask to input entering the attached layer"""
|
| 333 |
+
mask = self.get_mask(name)
|
| 334 |
+
features = self.data_groups[name]["features"]
|
| 335 |
+
feature_dim = self.data_groups[name]["feature_dim"]
|
| 336 |
+
|
| 337 |
+
def hook(module, input):
|
| 338 |
+
input_data = input[0]
|
| 339 |
+
if features is None:
|
| 340 |
+
# apply to all the features
|
| 341 |
+
return input_data * mask
|
| 342 |
+
else:
|
| 343 |
+
# apply per feature, feature_dim
|
| 344 |
+
for feature_idx in range(len(features)):
|
| 345 |
+
feature = (
|
| 346 |
+
torch.Tensor([features[feature_idx]])
|
| 347 |
+
.long()
|
| 348 |
+
.to(input_data.device)
|
| 349 |
+
)
|
| 350 |
+
sparsified = (
|
| 351 |
+
torch.index_select(input_data, feature_dim, feature)
|
| 352 |
+
* mask[feature_idx]
|
| 353 |
+
)
|
| 354 |
+
input_data.index_copy_(feature_dim, feature, sparsified)
|
| 355 |
+
return input_data
|
| 356 |
+
|
| 357 |
+
return hook
|
| 358 |
+
|
| 359 |
+
def squash_mask(self, attach_sparsify_hook=True, **kwargs):
|
| 360 |
+
"""
|
| 361 |
+
Unregisters aggregate hook that was applied earlier and registers sparsification hooks if
|
| 362 |
+
attach_sparsify_hook = True.
|
| 363 |
+
"""
|
| 364 |
+
for name, configs in self.data_groups.items():
|
| 365 |
+
# unhook agg hook
|
| 366 |
+
configs["hook"].remove()
|
| 367 |
+
configs.pop("hook")
|
| 368 |
+
self.data_groups[name]["hook_state"] = "None"
|
| 369 |
+
if attach_sparsify_hook:
|
| 370 |
+
configs["hook"] = configs["layer"].register_forward_pre_hook(
|
| 371 |
+
self._sparsify_hook(name)
|
| 372 |
+
)
|
| 373 |
+
configs["hook_state"] = (
|
| 374 |
+
"sparsify" # signals that sparsify hook is now attached
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
def _get_serializable_data_groups(self):
|
| 378 |
+
"""Exclude hook and layer from the config keys before serializing
|
| 379 |
+
|
| 380 |
+
TODO: Might have to treat functions (reduce_fn, mask_fn etc) in a different manner while serializing.
|
| 381 |
+
For time-being, functions are treated the same way as other attributes
|
| 382 |
+
"""
|
| 383 |
+
data_groups: dict[str, Any] = defaultdict()
|
| 384 |
+
for name, config in self.data_groups.items():
|
| 385 |
+
new_config = {
|
| 386 |
+
key: value
|
| 387 |
+
for key, value in config.items()
|
| 388 |
+
if key not in ["hook", "layer"]
|
| 389 |
+
}
|
| 390 |
+
data_groups[name] = new_config
|
| 391 |
+
return data_groups
|
| 392 |
+
|
| 393 |
+
def _convert_mask(self, states_dict, sparse_coo=True):
|
| 394 |
+
r"""Converts the mask to sparse coo or dense depending on the `sparse_coo` argument.
|
| 395 |
+
If `sparse_coo=True`, then the mask is stored as sparse coo else dense tensor
|
| 396 |
+
"""
|
| 397 |
+
states = copy.deepcopy(states_dict)
|
| 398 |
+
for state in states.values():
|
| 399 |
+
if state["mask"] is not None:
|
| 400 |
+
if isinstance(state["mask"], list):
|
| 401 |
+
for idx in range(len(state["mask"])):
|
| 402 |
+
if sparse_coo:
|
| 403 |
+
state["mask"][idx] = state["mask"][idx].to_sparse_coo()
|
| 404 |
+
else:
|
| 405 |
+
state["mask"][idx] = state["mask"][idx].to_dense()
|
| 406 |
+
else:
|
| 407 |
+
if sparse_coo:
|
| 408 |
+
state["mask"] = state["mask"].to_sparse_coo()
|
| 409 |
+
else:
|
| 410 |
+
state["mask"] = state["mask"].to_dense()
|
| 411 |
+
return states
|
| 412 |
+
|
| 413 |
+
def state_dict(self) -> dict[str, Any]:
|
| 414 |
+
r"""Returns the state of the sparsifier as a :class:`dict`.
|
| 415 |
+
|
| 416 |
+
It contains:
|
| 417 |
+
* state - contains name -> mask mapping.
|
| 418 |
+
* data_groups - a dictionary containing all config information for each
|
| 419 |
+
layer
|
| 420 |
+
* defaults - the default config while creating the constructor
|
| 421 |
+
"""
|
| 422 |
+
data_groups = self._get_serializable_data_groups()
|
| 423 |
+
state = self._convert_mask(self.state)
|
| 424 |
+
return {"state": state, "data_groups": data_groups, "defaults": self.defaults}
|
| 425 |
+
|
| 426 |
+
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
|
| 427 |
+
r"""The load_state_dict() restores the state of the sparsifier based on the state_dict
|
| 428 |
+
|
| 429 |
+
Args:
|
| 430 |
+
* state_dict - the dictionary to which the current sparsifier needs to be restored to
|
| 431 |
+
"""
|
| 432 |
+
state = state_dict["state"]
|
| 433 |
+
data_groups, defaults = state_dict["data_groups"], state_dict["defaults"]
|
| 434 |
+
|
| 435 |
+
self.__set_state__(
|
| 436 |
+
{"state": state, "data_groups": data_groups, "defaults": defaults}
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
def __get_state__(self) -> dict[str, Any]:
|
| 440 |
+
data_groups = self._get_serializable_data_groups()
|
| 441 |
+
state = self._convert_mask(self.state)
|
| 442 |
+
return {
|
| 443 |
+
"defaults": self.defaults,
|
| 444 |
+
"state": state,
|
| 445 |
+
"data_groups": data_groups,
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
def __set_state__(self, state: dict[str, Any]) -> None:
|
| 449 |
+
state["state"] = self._convert_mask(
|
| 450 |
+
state["state"], sparse_coo=False
|
| 451 |
+
) # convert mask to dense tensor
|
| 452 |
+
self.__dict__.update(state)
|
| 453 |
+
|
| 454 |
+
# need to attach layer and hook info into the data_groups
|
| 455 |
+
for name, config in self.data_groups.items():
|
| 456 |
+
# fetch layer
|
| 457 |
+
layer = fqn_to_module(self.model, name)
|
| 458 |
+
if layer is None:
|
| 459 |
+
raise AssertionError(f"layer {name} not found in the model")
|
| 460 |
+
|
| 461 |
+
# if agg_mode is True, then layer in aggregate mode
|
| 462 |
+
if "hook_state" in config and config["hook_state"] == "aggregate":
|
| 463 |
+
hook = layer.register_forward_pre_hook(self._aggregate_hook(name))
|
| 464 |
+
|
| 465 |
+
elif "hook_state" in config and config["hook_state"] == "sparsify":
|
| 466 |
+
hook = layer.register_forward_pre_hook(self._sparsify_hook(name))
|
| 467 |
+
|
| 468 |
+
config["layer"] = layer
|
| 469 |
+
config["hook"] = hook # type: ignore[possibly-undefined]
|
| 470 |
+
|
| 471 |
+
def __repr__(self):
|
| 472 |
+
format_string = self.__class__.__name__ + " ("
|
| 473 |
+
for name, config in self.data_groups.items():
|
| 474 |
+
format_string += "\n"
|
| 475 |
+
format_string += "\tData Group\n"
|
| 476 |
+
format_string += f"\t name: {name}\n"
|
| 477 |
+
for key in sorted(config.keys()):
|
| 478 |
+
if key in ["data", "hook", "reduce_fn", "mask_fn", "aggregate_fn"]:
|
| 479 |
+
continue
|
| 480 |
+
format_string += f"\t {key}: {config[key]}\n"
|
| 481 |
+
format_string += ")"
|
| 482 |
+
return format_string
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base_data_scheduler import BaseDataScheduler
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = [
|
| 5 |
+
"BaseDataScheduler",
|
| 6 |
+
]
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (316 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-312.pyc
ADDED
|
Binary file (9.38 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import abc
|
| 3 |
+
import warnings
|
| 4 |
+
import weakref
|
| 5 |
+
from functools import wraps
|
| 6 |
+
|
| 7 |
+
from torch.ao.pruning._experimental.data_sparsifier import BaseDataSparsifier
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = ["BaseDataScheduler"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class BaseDataScheduler:
|
| 14 |
+
r"""
|
| 15 |
+
The BaseDataScheduler is the abstract scheduler class specifically for the
|
| 16 |
+
BaseDataSparsifier class. This class controls a specific hyperparameter of
|
| 17 |
+
the sparsifier class and varies it across the training process (or across time).
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
data_sparsifier (instance of BaseDataSparsifier)
|
| 21 |
+
Implemented class data sparsifier class wherein the update_mask is implemented
|
| 22 |
+
schedule_param (str)
|
| 23 |
+
A specific hyperparameter of the passed sparsifier that needs to be scheduled/varied
|
| 24 |
+
last_epoch (int, default=-1)
|
| 25 |
+
This is specifically passed when training needs to be resumed from a particular
|
| 26 |
+
point.
|
| 27 |
+
verbose (bool, default=False)
|
| 28 |
+
Verbosity of the BaseDataScheduler
|
| 29 |
+
|
| 30 |
+
The *get_hyperparam()* function needs to be implemented by the user.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self, data_sparsifier, schedule_param: str, last_epoch=-1, verbose=False
|
| 35 |
+
):
|
| 36 |
+
# Attach sparsifier
|
| 37 |
+
if not isinstance(data_sparsifier, BaseDataSparsifier):
|
| 38 |
+
raise TypeError(
|
| 39 |
+
f"{type(data_sparsifier).__name__} is not an instance of torch.ao.pruning.BaseDataSparsifier"
|
| 40 |
+
)
|
| 41 |
+
self.data_sparsifier = data_sparsifier
|
| 42 |
+
self.schedule_param = schedule_param
|
| 43 |
+
|
| 44 |
+
# Initialize epoch and base hyper-params
|
| 45 |
+
self.base_param = {
|
| 46 |
+
name: config.get(schedule_param, None)
|
| 47 |
+
for name, config in self.data_sparsifier.data_groups.items()
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
self.last_epoch = last_epoch
|
| 51 |
+
|
| 52 |
+
# Following https://github.com/pytorch/pytorch/issues/20124
|
| 53 |
+
# We would like to ensure that `scheduler.step()` is called after
|
| 54 |
+
# `sparsifier.step()`
|
| 55 |
+
def with_counter(method):
|
| 56 |
+
if getattr(method, "_with_counter", False):
|
| 57 |
+
# `sparsifier.step()` has already been replaced, return.
|
| 58 |
+
return method
|
| 59 |
+
|
| 60 |
+
# Keep a weak reference to the sparsifier instance to prevent
|
| 61 |
+
# cyclic references.
|
| 62 |
+
instance_ref = weakref.ref(method.__self__)
|
| 63 |
+
# Get the unbound method for the same purpose.
|
| 64 |
+
func = method.__func__
|
| 65 |
+
cls = instance_ref().__class__
|
| 66 |
+
del method
|
| 67 |
+
|
| 68 |
+
@wraps(func)
|
| 69 |
+
def wrapper(*args, **kwargs):
|
| 70 |
+
instance = instance_ref()
|
| 71 |
+
instance._step_count += 1 # type: ignore[union-attr]
|
| 72 |
+
wrapped = func.__get__(instance, cls)
|
| 73 |
+
return wrapped(*args, **kwargs)
|
| 74 |
+
|
| 75 |
+
# Note that the returned function here is no longer a bound method,
|
| 76 |
+
# so attributes like `__func__` and `__self__` no longer exist.
|
| 77 |
+
wrapper._with_counter = True # type: ignore[attr-defined]
|
| 78 |
+
return wrapper
|
| 79 |
+
|
| 80 |
+
self.data_sparsifier.step = with_counter(self.data_sparsifier.step) # type: ignore[assignment]
|
| 81 |
+
self.data_sparsifier._step_count = 0 # type: ignore[attr-defined]
|
| 82 |
+
self._step_count: int = 0
|
| 83 |
+
self.verbose = verbose
|
| 84 |
+
|
| 85 |
+
# Housekeeping
|
| 86 |
+
self._get_sp_called_within_step: bool = False # sp -> schedule parameter
|
| 87 |
+
self.step()
|
| 88 |
+
|
| 89 |
+
@abc.abstractmethod
|
| 90 |
+
def get_schedule_param(self):
|
| 91 |
+
r"""
|
| 92 |
+
Abstract method that needs to be implemented by the child class.
|
| 93 |
+
The expected return type should be a dictionary of name to schedule_param value
|
| 94 |
+
The returned values will be updated in sparsifier when the scheduler step() function
|
| 95 |
+
is called.
|
| 96 |
+
|
| 97 |
+
Example:
|
| 98 |
+
>>> def get_schedule_param(self):
|
| 99 |
+
... new_param = {}
|
| 100 |
+
... for name in self.sparsifier.data_groups.keys():
|
| 101 |
+
... new_param[name] = (
|
| 102 |
+
... self.sparsifier.data_groups[name][self.schedule_param] * 0.5
|
| 103 |
+
... )
|
| 104 |
+
... return new_param
|
| 105 |
+
|
| 106 |
+
When the step() function is called, the value in self.sparsifier.data_groups[name][self.schedule_param]
|
| 107 |
+
would be halved
|
| 108 |
+
"""
|
| 109 |
+
raise NotImplementedError
|
| 110 |
+
|
| 111 |
+
def __repr__(self):
|
| 112 |
+
format_string = self.__class__.__name__ + " ("
|
| 113 |
+
format_string += "\n"
|
| 114 |
+
format_string += f"Data Sparsifier {self.data_sparsifier}\n"
|
| 115 |
+
format_string += f" {self.schedule_param}: {self.base_param}\n"
|
| 116 |
+
format_string += ")"
|
| 117 |
+
return format_string
|
| 118 |
+
|
| 119 |
+
def state_dict(self):
|
| 120 |
+
"""Returns the state of the scheduler as a :class:`dict`.
|
| 121 |
+
|
| 122 |
+
It contains an entry for every variable in self.__dict__ which
|
| 123 |
+
is not the sparsifier.
|
| 124 |
+
|
| 125 |
+
Note:
|
| 126 |
+
The scheduler class does not track the state of the data_sparsifier.
|
| 127 |
+
Make sure to store the state of the sparsifier before storing the
|
| 128 |
+
state of the scheduler
|
| 129 |
+
"""
|
| 130 |
+
return {
|
| 131 |
+
key: value
|
| 132 |
+
for key, value in self.__dict__.items()
|
| 133 |
+
if key != "data_sparsifier"
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
def load_state_dict(self, state_dict):
|
| 137 |
+
"""Loads the schedulers state.
|
| 138 |
+
|
| 139 |
+
Note:
|
| 140 |
+
Remember to restore the state of the data_sparsifier before the scheduler.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
state_dict (dict): scheduler state. Should be an object returned
|
| 144 |
+
from a call to :meth:`state_dict`.
|
| 145 |
+
"""
|
| 146 |
+
self.__dict__.update(state_dict)
|
| 147 |
+
|
| 148 |
+
def get_last_param(self):
|
| 149 |
+
return self._last_param
|
| 150 |
+
|
| 151 |
+
def step(self):
|
| 152 |
+
# Raise warning if trying to call scheduler step before the sparsifier.
|
| 153 |
+
# https://github.com/pytorch/pytorch/issues/20124
|
| 154 |
+
if self._step_count == 1:
|
| 155 |
+
if not hasattr(self.data_sparsifier.step, "_with_counter"):
|
| 156 |
+
warnings.warn(
|
| 157 |
+
"Seems like `data_sparsifier.step()` has been overridden after sparsity scheduler "
|
| 158 |
+
"initialization. Please, make sure to call `data_sparsifier.step()` before "
|
| 159 |
+
"`scheduler.step()`.",
|
| 160 |
+
UserWarning,
|
| 161 |
+
stacklevel=2,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Just check if there were two first scheduler.step() calls before sparsifier.step()
|
| 165 |
+
elif self.data_sparsifier._step_count < 1: # type: ignore[attr-defined]
|
| 166 |
+
warnings.warn(
|
| 167 |
+
"Detected call of `scheduler.step()` before `data_sparsifier.step()`. "
|
| 168 |
+
"You have to make sure you run the data_sparsifier.step() BEFORE any "
|
| 169 |
+
"calls to the scheduler.step().",
|
| 170 |
+
UserWarning,
|
| 171 |
+
stacklevel=2,
|
| 172 |
+
)
|
| 173 |
+
self._step_count += 1
|
| 174 |
+
|
| 175 |
+
class _enable_get_sp_call:
|
| 176 |
+
def __init__(self, o):
|
| 177 |
+
self.o = o
|
| 178 |
+
|
| 179 |
+
def __enter__(self):
|
| 180 |
+
self.o._get_sp_called_within_step = True
|
| 181 |
+
return self
|
| 182 |
+
|
| 183 |
+
def __exit__(self, type, value, traceback):
|
| 184 |
+
self.o._get_sp_called_within_step = False
|
| 185 |
+
|
| 186 |
+
with _enable_get_sp_call(self):
|
| 187 |
+
self.last_epoch += 1
|
| 188 |
+
updated_scheduler_params = self.get_schedule_param()
|
| 189 |
+
|
| 190 |
+
for name, param in updated_scheduler_params.items():
|
| 191 |
+
self.data_sparsifier.data_groups[name][self.schedule_param] = param
|
| 192 |
+
if self.verbose:
|
| 193 |
+
print(f"Adjusting {self.schedule_param} for group {name} to {param}")
|
| 194 |
+
|
| 195 |
+
self._last_param = {
|
| 196 |
+
name: config.get(self.schedule_param, None)
|
| 197 |
+
for name, config in self.data_sparsifier.data_groups.items()
|
| 198 |
+
}
|
| 199 |
+
self.data_sparsifier.enable_mask_update = True
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base_data_sparsifier import BaseDataSparsifier
|
| 2 |
+
from .data_norm_sparsifier import DataNormSparsifier
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"BaseDataSparsifier",
|
| 7 |
+
"DataNormSparsifier",
|
| 8 |
+
]
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (393 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-312.pyc
ADDED
|
Binary file (16.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-312.pyc
ADDED
|
Binary file (8.01 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-312.pyc
ADDED
|
Binary file (6.37 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/base_data_sparsifier.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import abc
|
| 3 |
+
import copy
|
| 4 |
+
import sys
|
| 5 |
+
import warnings
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch import nn
|
| 11 |
+
from torch.ao.pruning.sparsifier import base_sparsifier, utils
|
| 12 |
+
from torch.nn.utils import parametrize
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if not sys.warnoptions:
|
| 16 |
+
# to suppress repeated warnings when being used in a training loop.
|
| 17 |
+
warnings.simplefilter("once")
|
| 18 |
+
|
| 19 |
+
__all__ = ["BaseDataSparsifier"]
|
| 20 |
+
|
| 21 |
+
EMBEDDING_TYPES = {
|
| 22 |
+
nn.Embedding,
|
| 23 |
+
nn.EmbeddingBag,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
SUPPORTED_TYPES = {
|
| 27 |
+
torch.Tensor,
|
| 28 |
+
nn.Parameter,
|
| 29 |
+
*EMBEDDING_TYPES,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class _Container(nn.Module):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class BaseDataSparsifier(base_sparsifier.BaseSparsifier):
|
| 38 |
+
r"""
|
| 39 |
+
Base Data Sparsifier class for all Data sparsifiers.
|
| 40 |
+
The abstract class accepts raw torch tensors / embedding / embedding bags (refer to SUPPORTED_TYPES above)
|
| 41 |
+
to prepare for sparsification.
|
| 42 |
+
In this case, mask (and parametrizations) is owned by the class and not by the user.
|
| 43 |
+
Specifically, the container object inside the class maintains the mask and parametrizations of the input data
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
data_list (list of tuples)
|
| 47 |
+
list of (name, data) tuples to sparsify. Lookup SUPPORTED_TYPES
|
| 48 |
+
for type of data. Internally, a container module handles the data sparsification.
|
| 49 |
+
|
| 50 |
+
defaults (dict)
|
| 51 |
+
default configurations will be attached to the
|
| 52 |
+
configuration. Only the keys that don't exist in the `config` will
|
| 53 |
+
be updated.
|
| 54 |
+
Example::
|
| 55 |
+
>>> # xdoctest: +SKIP
|
| 56 |
+
>>> data_list = [('tensor_1', torch.randn(3,3)), ('tensor_2', torch.randn(4,4))]
|
| 57 |
+
>>> defaults = {'sparsity_level': 0.7}
|
| 58 |
+
>>> sparsifier = DerivedDataSparsifier(data_list = data_list, **defaults) # Some sparsifier that inherits BaseDataSparsifier
|
| 59 |
+
>>> new_tensor_to_add = {'name': 'tensor_3', 'data': torch.randn(5,5), 'sparsity_level': 0.3}
|
| 60 |
+
>>> sparsifier.add_data(**new_tensor_to_add)
|
| 61 |
+
>>> # tensor_1 and tensor_2 will have sparsity_level of 0.7 but tensor_3 will have sparsity_level=0.3
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(self, data_list: list[tuple[str, Any]] | None = None, **defaults):
|
| 65 |
+
super().__init__(defaults=defaults)
|
| 66 |
+
|
| 67 |
+
self._container = _Container()
|
| 68 |
+
|
| 69 |
+
self.data_groups: dict[str, dict] = defaultdict(dict) # name -> {**config}
|
| 70 |
+
if data_list is not None:
|
| 71 |
+
# add data with default config here
|
| 72 |
+
[self.add_data(name, data, **self.defaults) for name, data in data_list]
|
| 73 |
+
|
| 74 |
+
def prepare(self, model, config):
|
| 75 |
+
raise NotImplementedError("this function is undefined for this class")
|
| 76 |
+
|
| 77 |
+
def _extract_weight(self, data):
|
| 78 |
+
# extract the weight parameter instead of underlying data
|
| 79 |
+
if type(data) in [torch.Tensor, nn.Parameter]:
|
| 80 |
+
return data
|
| 81 |
+
elif type(data) in EMBEDDING_TYPES:
|
| 82 |
+
return data.weight
|
| 83 |
+
|
| 84 |
+
def add_data(self, name: str, data, reuse_mask=True, **config):
|
| 85 |
+
r"""Configures and parametrizes the internal container model with name and data.
|
| 86 |
+
|
| 87 |
+
**Note**:
|
| 88 |
+
1. If the data with name already exists, it replaces the data.
|
| 89 |
+
2. While replacing, the old mask is reused when `reuse_mask=True`
|
| 90 |
+
3. If `reuse_mask=True`, then the replacing data needs to have the same shape as that of old data.
|
| 91 |
+
4. By default, the config of the replaced data is used as config for the replacing data, unless something
|
| 92 |
+
is specified in the config dictionary.
|
| 93 |
+
"""
|
| 94 |
+
if type(data) not in SUPPORTED_TYPES:
|
| 95 |
+
raise AssertionError(
|
| 96 |
+
f"specified data type:{type(data)} not supported at the moment"
|
| 97 |
+
)
|
| 98 |
+
local_args = copy.deepcopy(self.defaults)
|
| 99 |
+
local_args.update(config)
|
| 100 |
+
weight = self._extract_weight(data)
|
| 101 |
+
|
| 102 |
+
# Bookkeeping in the container class
|
| 103 |
+
mask = local_args.get("mask", torch.ones_like(weight))
|
| 104 |
+
param_class = local_args.get("parametrization", utils.FakeSparsity)
|
| 105 |
+
|
| 106 |
+
if name in self.state:
|
| 107 |
+
# If the named data already exists - replace
|
| 108 |
+
warnings.warn(
|
| 109 |
+
"Replacing existing data of the same name. - Did you mean a different name?",
|
| 110 |
+
stacklevel=2,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# reuse old config
|
| 114 |
+
old_args = self.data_groups[name]
|
| 115 |
+
local_args = copy.deepcopy(old_args)
|
| 116 |
+
local_args.update(config)
|
| 117 |
+
|
| 118 |
+
if reuse_mask:
|
| 119 |
+
current_data = self.get_data(name=name)
|
| 120 |
+
if weight.shape != current_data.shape:
|
| 121 |
+
raise AssertionError(
|
| 122 |
+
"to retain the old mask, the shape of the new data must be the same as the previous one"
|
| 123 |
+
)
|
| 124 |
+
mask = self.get_mask(
|
| 125 |
+
name=name
|
| 126 |
+
) # reuse mask instead of creating a new one
|
| 127 |
+
|
| 128 |
+
self._delete_data(name=name)
|
| 129 |
+
|
| 130 |
+
# parameter creates a deepcopy of the weight inside, so create a buffer
|
| 131 |
+
self._container.register_buffer(name=name, tensor=weight)
|
| 132 |
+
parametrize.register_parametrization(self._container, name, param_class(mask))
|
| 133 |
+
self.state[name]["mask"] = mask
|
| 134 |
+
self.data_groups[name] = local_args
|
| 135 |
+
return getattr(self._container, name)
|
| 136 |
+
|
| 137 |
+
def get_data(self, name: str, return_original: bool = True):
|
| 138 |
+
r"""Returns weight tensor (or data)
|
| 139 |
+
Args:
|
| 140 |
+
- name: name of the data to be returned
|
| 141 |
+
- return_original returns weight tensor without applying parametrization if True
|
| 142 |
+
else - returns the sparsified version (parametrized)
|
| 143 |
+
"""
|
| 144 |
+
if name not in self.data_groups:
|
| 145 |
+
raise ValueError("data with specified name does not exist")
|
| 146 |
+
|
| 147 |
+
if return_original:
|
| 148 |
+
if not parametrize.is_parametrized(self._container, name):
|
| 149 |
+
raise ValueError("mask squashed - original mask value does not exist")
|
| 150 |
+
data = getattr(self._container.parametrizations, name).original
|
| 151 |
+
return data
|
| 152 |
+
else:
|
| 153 |
+
return getattr(self._container, name)
|
| 154 |
+
|
| 155 |
+
def _convert_mask(self, states, sparse_coo=True):
|
| 156 |
+
r"""Converts the mask to sparse coo or dense tensors depending on the `sparse_coo` argument."""
|
| 157 |
+
states = copy.deepcopy(states)
|
| 158 |
+
for state in states.values():
|
| 159 |
+
if sparse_coo:
|
| 160 |
+
state["mask"] = state["mask"].to_sparse_coo()
|
| 161 |
+
else:
|
| 162 |
+
state["mask"] = state["mask"].to_dense()
|
| 163 |
+
|
| 164 |
+
return states
|
| 165 |
+
|
| 166 |
+
def state_dict(self):
|
| 167 |
+
r"""Returns the state of the optimizer as a :class:`dict`.
|
| 168 |
+
|
| 169 |
+
It contains:
|
| 170 |
+
* state - contains name -> mask mapping.
|
| 171 |
+
* data_groups - a list containing all sparsity configuration groups
|
| 172 |
+
with the key name specifying the name of the data
|
| 173 |
+
* container_state_dict - the state dictionary of the internal
|
| 174 |
+
container model used for sparsification
|
| 175 |
+
"""
|
| 176 |
+
state = self._convert_mask(self.state)
|
| 177 |
+
return {
|
| 178 |
+
"state": state,
|
| 179 |
+
"data_groups": self.data_groups,
|
| 180 |
+
"_container": self._container.state_dict(),
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
def _load_container_from_state(self, states, data_groups, container_state_dict):
|
| 184 |
+
r"""This restores the state of the container specifically based on the data present in state and data_groups
|
| 185 |
+
If the data was parametrized, then the data would be added to the container and then parametrized,
|
| 186 |
+
else it would just add the attribute to the container.
|
| 187 |
+
"""
|
| 188 |
+
for name, state in states.items():
|
| 189 |
+
config_name = data_groups.get(name, None)
|
| 190 |
+
if config_name is None:
|
| 191 |
+
raise RuntimeError(f"Error loading {name}")
|
| 192 |
+
|
| 193 |
+
# check if the data with such a name was parametrized, if so parametrize
|
| 194 |
+
# otherwise just set the attribute and continue
|
| 195 |
+
parametrized_name = f"parametrizations.{name}.original"
|
| 196 |
+
parametrized = False
|
| 197 |
+
data = container_state_dict.get(name, None)
|
| 198 |
+
if name in container_state_dict:
|
| 199 |
+
# the parametrization was probably removed for this
|
| 200 |
+
data = container_state_dict.get(name)
|
| 201 |
+
|
| 202 |
+
elif parametrized_name in container_state_dict:
|
| 203 |
+
# so the weight was parametrized
|
| 204 |
+
data = container_state_dict.get(parametrized_name)
|
| 205 |
+
parametrized = True
|
| 206 |
+
|
| 207 |
+
else:
|
| 208 |
+
raise RuntimeError(f"Error loading {name}")
|
| 209 |
+
|
| 210 |
+
self._container.register_buffer(name=name, tensor=data)
|
| 211 |
+
|
| 212 |
+
if parametrized:
|
| 213 |
+
# register parameter if parametrized
|
| 214 |
+
mask = state.get("mask", torch.ones_like(data))
|
| 215 |
+
param_class = data_groups.get(
|
| 216 |
+
"parametrization", utils.FakeSparsity
|
| 217 |
+
) # change once public_api for utils is fixed!
|
| 218 |
+
parametrize.register_parametrization(
|
| 219 |
+
self._container, name, param_class(mask)
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
def load_state_dict(self, state_dict, strict=True):
|
| 223 |
+
r"""The load_state_dict() restores the state of the sparsifier based on the state_dict
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
* state_dict - the dictionary to which the current sparsifier needs to be restored to
|
| 227 |
+
* strict - If True - the sparsifier is reset and is restored exactly to the state in state_dict.
|
| 228 |
+
If False - the current sparsifier is not reset before loading the state_dict i.e. data added
|
| 229 |
+
before loading the state_dict is not erased.
|
| 230 |
+
"""
|
| 231 |
+
states = copy.deepcopy(state_dict["state"])
|
| 232 |
+
data_groups = copy.deepcopy(state_dict["data_groups"])
|
| 233 |
+
container_state_dict = copy.deepcopy(state_dict["_container"])
|
| 234 |
+
|
| 235 |
+
states = self._convert_mask(
|
| 236 |
+
states, sparse_coo=False
|
| 237 |
+
) # convert sparse coo mask to dense
|
| 238 |
+
if strict:
|
| 239 |
+
# if strict load -> then reset container
|
| 240 |
+
self._container = _Container()
|
| 241 |
+
|
| 242 |
+
self._load_container_from_state(states, data_groups, container_state_dict)
|
| 243 |
+
|
| 244 |
+
if not strict:
|
| 245 |
+
states.update(self.state)
|
| 246 |
+
data_groups.update(self.data_groups)
|
| 247 |
+
|
| 248 |
+
self.__setstate__({"state": states, "data_groups": data_groups})
|
| 249 |
+
|
| 250 |
+
def __setstate__(self, state):
|
| 251 |
+
if "_container" in state: # If container object is in state then load model
|
| 252 |
+
container_dict = state.pop("_container")
|
| 253 |
+
self._container = _Container()
|
| 254 |
+
state["state"] = self._convert_mask(
|
| 255 |
+
state["state"], sparse_coo=False
|
| 256 |
+
) # convert sparse coo mask to dense
|
| 257 |
+
self._load_container_from_state(
|
| 258 |
+
state["state"], state["data_groups"], container_dict
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
self.__dict__.update(state)
|
| 262 |
+
|
| 263 |
+
def __getstate__(self):
|
| 264 |
+
state = self._convert_mask(self.state)
|
| 265 |
+
return {
|
| 266 |
+
"defaults": self.defaults,
|
| 267 |
+
"state": state,
|
| 268 |
+
"data_groups": self.data_groups,
|
| 269 |
+
"_container": self._container.state_dict(),
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
def __repr__(self): # type:ignore[override]
|
| 273 |
+
format_string = self.__class__.__name__ + " ("
|
| 274 |
+
for name, sparse_args in self.data_groups.items():
|
| 275 |
+
format_string += "\n"
|
| 276 |
+
format_string += "\tData Group\n"
|
| 277 |
+
format_string += f"\t name: {name}\n"
|
| 278 |
+
for key in sorted(sparse_args.keys()):
|
| 279 |
+
if key == "data":
|
| 280 |
+
continue
|
| 281 |
+
format_string += f"\t {key}: {sparse_args[key]}\n"
|
| 282 |
+
format_string += ")"
|
| 283 |
+
return format_string
|
| 284 |
+
|
| 285 |
+
def get_mask(self, name: str):
|
| 286 |
+
if name not in self.state:
|
| 287 |
+
raise ValueError("data with specified name does not exist")
|
| 288 |
+
return self.state[name]["mask"]
|
| 289 |
+
|
| 290 |
+
def squash_mask(self, *args, leave_parametrized=True, names=None, **kwargs):
|
| 291 |
+
r"""Squashes the sparse masks into the appropriate tensors. Also, accepts list of strings
|
| 292 |
+
to squash mask for. If none, squashes mask for all the keys
|
| 293 |
+
kwargs:
|
| 294 |
+
* names: list of strings to squash mask for
|
| 295 |
+
* sparsified: if true - applies the mask before squashing
|
| 296 |
+
if false - does not apply the mask before squashing
|
| 297 |
+
"""
|
| 298 |
+
if names is None:
|
| 299 |
+
names = list(self.data_groups.keys())
|
| 300 |
+
for name in names:
|
| 301 |
+
parametrize.remove_parametrizations(
|
| 302 |
+
self._container, name, leave_parametrized=leave_parametrized
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
def step(self): # type:ignore[override]
|
| 306 |
+
if not self.enable_mask_update:
|
| 307 |
+
return
|
| 308 |
+
with torch.no_grad():
|
| 309 |
+
for name, config in self.data_groups.items():
|
| 310 |
+
# get non-sparsified data
|
| 311 |
+
data = self.get_data(name)
|
| 312 |
+
# need name for the mask otherwise can directly pass mask?
|
| 313 |
+
self.update_mask(name, data, **config)
|
| 314 |
+
|
| 315 |
+
@abc.abstractmethod
|
| 316 |
+
def update_mask(self, name, data, **kwargs): # type: ignore[override]
|
| 317 |
+
pass
|
| 318 |
+
|
| 319 |
+
def _delete_data(self, name):
|
| 320 |
+
"""Detaches some data from the sparsifier.
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
name (str)
|
| 324 |
+
Name of the data to be removed from the sparsifier
|
| 325 |
+
|
| 326 |
+
Note:
|
| 327 |
+
Currently private. Kind of used as a helper function when replacing data of the same name
|
| 328 |
+
"""
|
| 329 |
+
self.squash_mask(
|
| 330 |
+
names=[name], leave_parametrized=False
|
| 331 |
+
) # do not apply the mask while deleting
|
| 332 |
+
delattr(self._container, name)
|
| 333 |
+
self.state.pop(name)
|
| 334 |
+
self.data_groups.pop(name)
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
from functools import reduce
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.nn import functional as F
|
| 8 |
+
|
| 9 |
+
from .base_data_sparsifier import BaseDataSparsifier
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = ["DataNormSparsifier"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class DataNormSparsifier(BaseDataSparsifier):
|
| 16 |
+
r"""L1-Norm Sparsifier
|
| 17 |
+
This sparsifier computes the *L1-norm* of every sparse block and "zeroes-out" the
|
| 18 |
+
ones with the lowest norm. The level of sparsity defines how many of the
|
| 19 |
+
blocks are removed.
|
| 20 |
+
This sparsifier is controlled by three variables:
|
| 21 |
+
1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out
|
| 22 |
+
2. `sparse_block_shape` defines the shape of the sparse blocks. Note that
|
| 23 |
+
the sparse blocks originate at the zero-index of the tensor.
|
| 24 |
+
3. `zeros_per_block` is the number of zeros that we are expecting in each
|
| 25 |
+
sparse block. By default we assume that all elements within a block are
|
| 26 |
+
zeroed-out. However, setting this variable sets the target number of
|
| 27 |
+
zeros per block. The zeros within each block are chosen as the *smallest
|
| 28 |
+
absolute values*.
|
| 29 |
+
Args:
|
| 30 |
+
sparsity_level: The target level of sparsity
|
| 31 |
+
sparse_block_shape: The shape of a sparse block
|
| 32 |
+
zeros_per_block: Number of zeros in a sparse block
|
| 33 |
+
Note::
|
| 34 |
+
All arguments to the DataNormSparsifier constructor are "default"
|
| 35 |
+
arguments and could be overridden by the configuration provided in the
|
| 36 |
+
`add_data` step.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
data_list: list[tuple[str, Any]] | None = None,
|
| 42 |
+
sparsity_level: float = 0.5,
|
| 43 |
+
sparse_block_shape: tuple[int, int] = (1, 4),
|
| 44 |
+
zeros_per_block: int | None = None,
|
| 45 |
+
norm: str = "L1",
|
| 46 |
+
):
|
| 47 |
+
if zeros_per_block is None:
|
| 48 |
+
zeros_per_block = reduce(operator.mul, sparse_block_shape)
|
| 49 |
+
|
| 50 |
+
if norm not in ["L1", "L2"]:
|
| 51 |
+
raise AssertionError("only L1 and L2 norm supported at the moment")
|
| 52 |
+
|
| 53 |
+
defaults = {
|
| 54 |
+
"sparsity_level": sparsity_level,
|
| 55 |
+
"sparse_block_shape": sparse_block_shape,
|
| 56 |
+
"zeros_per_block": zeros_per_block,
|
| 57 |
+
}
|
| 58 |
+
self.norm = norm
|
| 59 |
+
super().__init__(data_list=data_list, **defaults)
|
| 60 |
+
|
| 61 |
+
def __get_scatter_folded_mask(
|
| 62 |
+
self, data, dim, indices, output_size, sparse_block_shape
|
| 63 |
+
):
|
| 64 |
+
mask = torch.ones_like(data)
|
| 65 |
+
mask.scatter_(dim=dim, index=indices, value=0) # zeroing out
|
| 66 |
+
mask = F.fold(
|
| 67 |
+
mask,
|
| 68 |
+
output_size=output_size,
|
| 69 |
+
kernel_size=sparse_block_shape,
|
| 70 |
+
stride=sparse_block_shape,
|
| 71 |
+
)
|
| 72 |
+
mask = mask.to(torch.int8)
|
| 73 |
+
return mask
|
| 74 |
+
|
| 75 |
+
def __get_block_level_mask(self, data, sparse_block_shape, zeros_per_block):
|
| 76 |
+
# Assume data is a squeezed tensor
|
| 77 |
+
height, width = data.shape[-2], data.shape[-1]
|
| 78 |
+
block_height, block_width = sparse_block_shape
|
| 79 |
+
values_per_block = block_height * block_width
|
| 80 |
+
|
| 81 |
+
# just return zeros if zeroing all elements in block
|
| 82 |
+
if values_per_block == zeros_per_block:
|
| 83 |
+
return torch.zeros_like(data, dtype=torch.int8)
|
| 84 |
+
|
| 85 |
+
# creating additional height and width to support padding
|
| 86 |
+
dh = (block_height - height % block_height) % block_height
|
| 87 |
+
dw = (block_width - width % block_width) % block_width
|
| 88 |
+
|
| 89 |
+
# create a new padded tensor like data (to match the block_shape)
|
| 90 |
+
padded_data = torch.ones(
|
| 91 |
+
height + dh, width + dw, dtype=data.dtype, device=data.device
|
| 92 |
+
)
|
| 93 |
+
padded_data = (
|
| 94 |
+
padded_data * torch.nan
|
| 95 |
+
) # can also be replaced with 0 to stop the removal of edge data
|
| 96 |
+
padded_data[0:height, 0:width] = data
|
| 97 |
+
unfolded_data = F.unfold(
|
| 98 |
+
padded_data[None, None, :],
|
| 99 |
+
kernel_size=sparse_block_shape,
|
| 100 |
+
stride=sparse_block_shape,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
_, sorted_idx = torch.sort(unfolded_data, dim=1)
|
| 104 |
+
sorted_idx = sorted_idx[
|
| 105 |
+
:, :zeros_per_block, :
|
| 106 |
+
] # zero out zeros_per_block number of elements
|
| 107 |
+
|
| 108 |
+
mask = self.__get_scatter_folded_mask(
|
| 109 |
+
data=unfolded_data,
|
| 110 |
+
dim=1,
|
| 111 |
+
indices=sorted_idx,
|
| 112 |
+
output_size=padded_data.shape,
|
| 113 |
+
sparse_block_shape=sparse_block_shape,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
mask = (
|
| 117 |
+
mask.squeeze(0).squeeze(0)[:height, :width].contiguous()
|
| 118 |
+
) # remove padding and make contiguous
|
| 119 |
+
return mask
|
| 120 |
+
|
| 121 |
+
def __get_data_level_mask(self, data, sparsity_level, sparse_block_shape):
|
| 122 |
+
height, width = data.shape[-2], data.shape[-1]
|
| 123 |
+
block_height, block_width = sparse_block_shape
|
| 124 |
+
dh = (block_height - height % block_height) % block_height
|
| 125 |
+
dw = (block_width - width % block_width) % block_width
|
| 126 |
+
|
| 127 |
+
data_norm = F.avg_pool2d(
|
| 128 |
+
data[None, None, :],
|
| 129 |
+
kernel_size=sparse_block_shape,
|
| 130 |
+
stride=sparse_block_shape,
|
| 131 |
+
ceil_mode=True,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
values_per_block = reduce(operator.mul, sparse_block_shape)
|
| 135 |
+
|
| 136 |
+
data_norm = data_norm.flatten()
|
| 137 |
+
num_blocks = len(data_norm)
|
| 138 |
+
|
| 139 |
+
data_norm = data_norm.repeat(
|
| 140 |
+
1, values_per_block, 1
|
| 141 |
+
) # get similar shape after unfold
|
| 142 |
+
_, sorted_idx = torch.sort(data_norm, dim=2)
|
| 143 |
+
|
| 144 |
+
threshold_idx = round(sparsity_level * num_blocks) # number of blocks to remove
|
| 145 |
+
sorted_idx = sorted_idx[:, :, :threshold_idx]
|
| 146 |
+
|
| 147 |
+
mask = self.__get_scatter_folded_mask(
|
| 148 |
+
data=data_norm,
|
| 149 |
+
dim=2,
|
| 150 |
+
indices=sorted_idx,
|
| 151 |
+
output_size=(height + dh, width + dw),
|
| 152 |
+
sparse_block_shape=sparse_block_shape,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
mask = mask.squeeze(0).squeeze(0)[
|
| 156 |
+
:height, :width
|
| 157 |
+
] # squeeze only the first 2 dimension
|
| 158 |
+
return mask
|
| 159 |
+
|
| 160 |
+
def update_mask( # type: ignore[override]
|
| 161 |
+
self, name, data, sparsity_level, sparse_block_shape, zeros_per_block, **kwargs
|
| 162 |
+
):
|
| 163 |
+
values_per_block = reduce(operator.mul, sparse_block_shape)
|
| 164 |
+
if zeros_per_block > values_per_block:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
"Number of zeros per block cannot be more than "
|
| 167 |
+
"the total number of elements in that block."
|
| 168 |
+
)
|
| 169 |
+
if zeros_per_block < 0:
|
| 170 |
+
raise ValueError("Number of zeros per block should be positive.")
|
| 171 |
+
|
| 172 |
+
if self.norm == "L1":
|
| 173 |
+
data_norm = torch.abs(data).squeeze() # absolute value based (L1)
|
| 174 |
+
else:
|
| 175 |
+
data_norm = (data * data).squeeze() # square every element for L2
|
| 176 |
+
|
| 177 |
+
if len(data_norm.shape) > 2: # only supports 2 dimensional data at the moment
|
| 178 |
+
raise ValueError("only supports 2-D at the moment")
|
| 179 |
+
|
| 180 |
+
elif len(data_norm.shape) == 1: # in case the data is bias (or 1D)
|
| 181 |
+
data_norm = data_norm[None, :]
|
| 182 |
+
|
| 183 |
+
mask = self.get_mask(name)
|
| 184 |
+
if sparsity_level <= 0 or zeros_per_block == 0:
|
| 185 |
+
mask.data = torch.ones_like(mask)
|
| 186 |
+
elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block):
|
| 187 |
+
mask.data = torch.zeros_like(mask)
|
| 188 |
+
|
| 189 |
+
# Fetch the high level mask that zeros out entire blocks
|
| 190 |
+
data_lvl_mask = self.__get_data_level_mask(
|
| 191 |
+
data=data_norm,
|
| 192 |
+
sparsity_level=sparsity_level,
|
| 193 |
+
sparse_block_shape=sparse_block_shape,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# Fetch block level mask that zeros out 'zeros_per_block' number of elements in every block
|
| 197 |
+
block_lvl_mask = self.__get_block_level_mask(
|
| 198 |
+
data=data_norm,
|
| 199 |
+
sparse_block_shape=sparse_block_shape,
|
| 200 |
+
zeros_per_block=zeros_per_block,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# zero out the entries inside those blocks whose block is sparsified
|
| 204 |
+
mask.data = torch.where(data_lvl_mask == 1, data_lvl_mask, block_lvl_mask)
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (231 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (241 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/_data_sparstity_utils.cpython-312.pyc
ADDED
|
Binary file (2.34 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-312.pyc
ADDED
|
Binary file (8.14 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
from torch.ao.pruning._experimental.data_sparsifier.base_data_sparsifier import (
|
| 5 |
+
SUPPORTED_TYPES,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
logger: logging.Logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _attach_model_to_data_sparsifier(module, data_sparsifier, config=None):
|
| 13 |
+
"""Attaches a data sparsifier to all the layers of the module.
|
| 14 |
+
Essentially, loop over all the weight parameters in the module and
|
| 15 |
+
attach it to the data sparsifier.
|
| 16 |
+
Note::
|
| 17 |
+
The '.' in the layer names are replaced with '_' (refer to _get_valid_name() below)
|
| 18 |
+
before attaching to the sparsifier. This is because, the data
|
| 19 |
+
sparsifier uses a dummy model inside to store the weight parameters.
|
| 20 |
+
"""
|
| 21 |
+
if config is None:
|
| 22 |
+
config = {}
|
| 23 |
+
for name, parameter in module.named_parameters():
|
| 24 |
+
if type(parameter) in SUPPORTED_TYPES:
|
| 25 |
+
valid_name = _get_valid_name(name)
|
| 26 |
+
# will be defaulted to default configs
|
| 27 |
+
data_sparsifier.add_data(
|
| 28 |
+
name=valid_name, data=parameter, **config.get(valid_name, {})
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _get_valid_name(name):
|
| 33 |
+
return name.replace(".", "_") # . is not allowed as a name
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _log_sparsified_level(model, data_sparsifier) -> None:
|
| 37 |
+
# Show the level of sparsity AFTER step:
|
| 38 |
+
for name, parameter in model.named_parameters():
|
| 39 |
+
if type(parameter) not in SUPPORTED_TYPES:
|
| 40 |
+
continue
|
| 41 |
+
valid_name = _get_valid_name(name)
|
| 42 |
+
mask = data_sparsifier.get_mask(name=valid_name)
|
| 43 |
+
sparsity_level = 1.0 - mask.float().mean()
|
| 44 |
+
logger.info("Sparsity in layer %s = % .2%", name, sparsity_level)
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from typing import Any, TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
import pytorch_lightning as pl # type: ignore[import]
|
| 7 |
+
|
| 8 |
+
from ._data_sparstity_utils import (
|
| 9 |
+
_attach_model_to_data_sparsifier,
|
| 10 |
+
_get_valid_name,
|
| 11 |
+
_log_sparsified_level,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PostTrainingDataSparsity(pl.callbacks.Callback):
|
| 20 |
+
"""Lightning callback that enables post-training sparsity.
|
| 21 |
+
|
| 22 |
+
This callback aims to sparsify the model inside lightning module after training.
|
| 23 |
+
**Note that the model is copied and then sparsified, so the existing model is not modified**
|
| 24 |
+
|
| 25 |
+
The sparsified model can be used for comparison and can be accessed using
|
| 26 |
+
<callback_obj>.sparsified
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
data_sparsifier_class (some implemented class of BaseDataSparsifier)
|
| 30 |
+
The data sparsifier object of this class is created when the
|
| 31 |
+
training starts.
|
| 32 |
+
Note: Objects should not be passed in here as they are created
|
| 33 |
+
once the training completes.
|
| 34 |
+
|
| 35 |
+
data_sparsifier_args (Dict)
|
| 36 |
+
Dictionary of args to be passed to the data sparsifier.
|
| 37 |
+
Note: data_list arg should be ignored
|
| 38 |
+
|
| 39 |
+
Hooks implemented:
|
| 40 |
+
on_fit_end()
|
| 41 |
+
1. copies the model and attaches it to the sparsifier
|
| 42 |
+
2. sparsifier step() is called
|
| 43 |
+
3. squashes the mask()
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, data_sparsifier_class, data_sparsifier_args):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.data_sparsifier_class = data_sparsifier_class
|
| 49 |
+
self.data_sparsifier_args = data_sparsifier_args
|
| 50 |
+
self.data_sparsifier: Any = None
|
| 51 |
+
self.sparsified: torch.nn.Module | None = None
|
| 52 |
+
|
| 53 |
+
def on_fit_end(self, trainer, pl_module) -> None:
|
| 54 |
+
self.sparsified = deepcopy(pl_module.model).eval()
|
| 55 |
+
self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args)
|
| 56 |
+
|
| 57 |
+
_attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier)
|
| 58 |
+
|
| 59 |
+
self.data_sparsifier.step()
|
| 60 |
+
|
| 61 |
+
self.data_sparsifier.squash_mask() # currently squashes params for all mask
|
| 62 |
+
|
| 63 |
+
_log_sparsified_level(self.sparsified, self.data_sparsifier)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class TrainingAwareDataSparsity(pl.callbacks.Callback):
|
| 67 |
+
"""Lightning callback that enables in-training sparsity.
|
| 68 |
+
|
| 69 |
+
This callback aims to sparsify the model inside lightning module during training.
|
| 70 |
+
**Note that the model is copied and then sparsified, so the existing model is not modified**
|
| 71 |
+
|
| 72 |
+
The sparsified model can be used for comparison and can be accessed using
|
| 73 |
+
<callback_obj>.sparsified
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
data_sparsifier_class (some implemented class of BaseDataSparsifier)
|
| 77 |
+
The data sparsifier object of this class is created when the
|
| 78 |
+
training starts.
|
| 79 |
+
Note: Objects should not be passed in here as they are created
|
| 80 |
+
when the training starts.
|
| 81 |
+
|
| 82 |
+
data_sparsifier_args (Dict)
|
| 83 |
+
Dictionary of args to be passed to the data sparsifier.
|
| 84 |
+
Note: data_list arg should be ignored
|
| 85 |
+
|
| 86 |
+
data_scheduler_class (some implemented class of BaseDataScheduler)
|
| 87 |
+
The data scheduler of this class is created when the training starts
|
| 88 |
+
Note: Objects should not be passed in here as they are created
|
| 89 |
+
when the training starts.
|
| 90 |
+
|
| 91 |
+
data_scheduler_args(Dict)
|
| 92 |
+
Dictionary of args to be passed to the data scheduler.
|
| 93 |
+
**Note: data_sparsifier arg should be ignored as the recipe
|
| 94 |
+
creates and pass sparsifier object into the class**
|
| 95 |
+
|
| 96 |
+
Hooks implemented:
|
| 97 |
+
on_train_start()
|
| 98 |
+
Data sparsifier and scheduler objects are created.
|
| 99 |
+
Pytorch model attached to the sparsifier
|
| 100 |
+
|
| 101 |
+
on_train_epoch_start()
|
| 102 |
+
Loads the state_dict of the data sparsifier
|
| 103 |
+
|
| 104 |
+
on_train_epoch_end()
|
| 105 |
+
1. Copies the model and attaches it to the sparsifier
|
| 106 |
+
2. sparsifier step() and scheduler step()
|
| 107 |
+
3. Dump state_dict of the current sparsifier
|
| 108 |
+
|
| 109 |
+
on_train_end()
|
| 110 |
+
squash mask
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
data_sparsifier_class,
|
| 116 |
+
data_sparsifier_args,
|
| 117 |
+
data_scheduler_class,
|
| 118 |
+
data_scheduler_args,
|
| 119 |
+
):
|
| 120 |
+
super().__init__()
|
| 121 |
+
# data sparsifier objects
|
| 122 |
+
self.data_sparsifier_class = data_sparsifier_class
|
| 123 |
+
self.data_sparsifier_args = data_sparsifier_args
|
| 124 |
+
|
| 125 |
+
# scheduler objects
|
| 126 |
+
self.data_scheduler_class = data_scheduler_class
|
| 127 |
+
self.data_scheduler_args = data_scheduler_args
|
| 128 |
+
|
| 129 |
+
# fields
|
| 130 |
+
self.data_sparsifier: Any = None
|
| 131 |
+
self.data_scheduler: Any = None
|
| 132 |
+
self.sparsified: torch.nn.Module | None = None
|
| 133 |
+
|
| 134 |
+
self.data_sparsifier_state_dict: Any = None
|
| 135 |
+
|
| 136 |
+
def on_train_start(self, trainer, pl_module) -> None:
|
| 137 |
+
# create sparsifier
|
| 138 |
+
self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args)
|
| 139 |
+
self.sparsified = deepcopy(pl_module.model)
|
| 140 |
+
|
| 141 |
+
_attach_model_to_data_sparsifier(
|
| 142 |
+
self.sparsified, self.data_sparsifier
|
| 143 |
+
) # just to populate the base_sl in the scheduler
|
| 144 |
+
|
| 145 |
+
# create scheduler
|
| 146 |
+
args = deepcopy(self.data_scheduler_args)
|
| 147 |
+
args["data_sparsifier"] = self.data_sparsifier
|
| 148 |
+
self.data_scheduler = self.data_scheduler_class(**args)
|
| 149 |
+
|
| 150 |
+
def on_train_epoch_start(self, trainer, pl_module):
|
| 151 |
+
if self.data_sparsifier_state_dict is None:
|
| 152 |
+
return # probably first epoch
|
| 153 |
+
|
| 154 |
+
# load the existing config for each data
|
| 155 |
+
self.data_sparsifier.load_state_dict(self.data_sparsifier_state_dict)
|
| 156 |
+
|
| 157 |
+
def __create_config_based_on_state(self, pl_module):
|
| 158 |
+
config: dict = defaultdict()
|
| 159 |
+
if self.data_sparsifier_state_dict is None:
|
| 160 |
+
return config
|
| 161 |
+
for name, _ in pl_module.model.named_parameters():
|
| 162 |
+
valid_name = _get_valid_name(name)
|
| 163 |
+
config[valid_name] = self.data_sparsifier.data_groups[valid_name]
|
| 164 |
+
|
| 165 |
+
return config
|
| 166 |
+
|
| 167 |
+
def on_train_epoch_end(self, trainer, pl_module):
|
| 168 |
+
self.sparsified = deepcopy(pl_module.model)
|
| 169 |
+
config = self.__create_config_based_on_state(pl_module)
|
| 170 |
+
|
| 171 |
+
# attach model to the data sparsifier
|
| 172 |
+
_attach_model_to_data_sparsifier(
|
| 173 |
+
self.sparsified, self.data_sparsifier, config=config
|
| 174 |
+
)
|
| 175 |
+
self.data_sparsifier.step()
|
| 176 |
+
self.data_scheduler.step()
|
| 177 |
+
|
| 178 |
+
self.data_sparsifier_state_dict = self.data_sparsifier.state_dict()
|
| 179 |
+
|
| 180 |
+
def on_train_end(self, trainer, pl_module):
|
| 181 |
+
self.data_sparsifier.squash_mask()
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/data_sparsifier/quantization_utils.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.ao.pruning.sparsifier.utils import fqn_to_module, module_to_fqn
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
SUPPORTED_MODULES = {nn.Embedding, nn.EmbeddingBag}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _fetch_all_embeddings(model):
|
| 12 |
+
"""Fetches Embedding and EmbeddingBag modules from the model"""
|
| 13 |
+
embedding_modules = []
|
| 14 |
+
stack = [model]
|
| 15 |
+
while stack:
|
| 16 |
+
module = stack.pop()
|
| 17 |
+
for _, child in module.named_children():
|
| 18 |
+
fqn_name = module_to_fqn(model, child)
|
| 19 |
+
if type(child) in SUPPORTED_MODULES:
|
| 20 |
+
embedding_modules.append((fqn_name, child))
|
| 21 |
+
else:
|
| 22 |
+
stack.append(child)
|
| 23 |
+
return embedding_modules
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def post_training_sparse_quantize(
|
| 27 |
+
model,
|
| 28 |
+
data_sparsifier_class,
|
| 29 |
+
sparsify_first=True,
|
| 30 |
+
select_embeddings: list[nn.Module] | None = None,
|
| 31 |
+
**sparse_config,
|
| 32 |
+
):
|
| 33 |
+
"""Takes in a model and applies sparsification and quantization to only embeddings & embeddingbags.
|
| 34 |
+
The quantization step can happen before or after sparsification depending on the `sparsify_first` argument.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
- model (nn.Module)
|
| 38 |
+
model whose embeddings need to be sparsified
|
| 39 |
+
- data_sparsifier_class (type of data sparsifier)
|
| 40 |
+
Type of sparsification that needs to be applied to model
|
| 41 |
+
- sparsify_first (bool)
|
| 42 |
+
if true, sparsifies first and then quantizes
|
| 43 |
+
otherwise, quantizes first and then sparsifies.
|
| 44 |
+
- select_embeddings (List of Embedding modules)
|
| 45 |
+
List of embedding modules in the model to be sparsified & quantized.
|
| 46 |
+
If None, all embedding modules will be sparsified
|
| 47 |
+
- sparse_config (Dict)
|
| 48 |
+
config that will be passed to the constructor of data sparsifier object.
|
| 49 |
+
|
| 50 |
+
Note:
|
| 51 |
+
1. When `sparsify_first=False`, quantization occurs first followed by sparsification.
|
| 52 |
+
- before sparsifying, the embedding layers are dequantized.
|
| 53 |
+
- scales and zero-points are saved
|
| 54 |
+
- embedding layers are sparsified and `squash_mask` is applied
|
| 55 |
+
- embedding weights are requantized using the saved scales and zero-points
|
| 56 |
+
2. When `sparsify_first=True`, sparsification occurs first followed by quantization.
|
| 57 |
+
- embeddings are sparsified first
|
| 58 |
+
- quantization is applied on the sparsified embeddings
|
| 59 |
+
"""
|
| 60 |
+
data_sparsifier = data_sparsifier_class(**sparse_config)
|
| 61 |
+
|
| 62 |
+
# if select_embeddings is None, perform it on all embeddings
|
| 63 |
+
if select_embeddings is None:
|
| 64 |
+
embedding_modules = _fetch_all_embeddings(model)
|
| 65 |
+
|
| 66 |
+
else:
|
| 67 |
+
embedding_modules = []
|
| 68 |
+
if not isinstance(select_embeddings, list):
|
| 69 |
+
raise AssertionError(
|
| 70 |
+
"the embedding_modules must be a list of embedding modules"
|
| 71 |
+
)
|
| 72 |
+
for emb in select_embeddings:
|
| 73 |
+
if type(emb) not in SUPPORTED_MODULES:
|
| 74 |
+
raise AssertionError(
|
| 75 |
+
"the embedding_modules list must be an embedding or embedding bags"
|
| 76 |
+
)
|
| 77 |
+
fqn_name = module_to_fqn(model, emb)
|
| 78 |
+
if fqn_name is None:
|
| 79 |
+
raise AssertionError(
|
| 80 |
+
"the embedding modules must be part of input model"
|
| 81 |
+
)
|
| 82 |
+
embedding_modules.append((fqn_name, emb))
|
| 83 |
+
|
| 84 |
+
if sparsify_first:
|
| 85 |
+
# sparsify
|
| 86 |
+
for name, emb_module in embedding_modules:
|
| 87 |
+
valid_name = name.replace(".", "_")
|
| 88 |
+
data_sparsifier.add_data(name=valid_name, data=emb_module)
|
| 89 |
+
|
| 90 |
+
data_sparsifier.step()
|
| 91 |
+
data_sparsifier.squash_mask()
|
| 92 |
+
|
| 93 |
+
# quantize
|
| 94 |
+
for _, emb_module in embedding_modules:
|
| 95 |
+
# pyrefly: ignore [bad-argument-type]
|
| 96 |
+
emb_module.qconfig = torch.ao.quantization.float_qparams_weight_only_qconfig
|
| 97 |
+
|
| 98 |
+
torch.ao.quantization.prepare(model, inplace=True)
|
| 99 |
+
torch.ao.quantization.convert(model, inplace=True)
|
| 100 |
+
|
| 101 |
+
else:
|
| 102 |
+
# quantize
|
| 103 |
+
for _, emb_module in embedding_modules:
|
| 104 |
+
# pyrefly: ignore [bad-argument-type]
|
| 105 |
+
emb_module.qconfig = torch.ao.quantization.float_qparams_weight_only_qconfig
|
| 106 |
+
|
| 107 |
+
torch.ao.quantization.prepare(model, inplace=True)
|
| 108 |
+
torch.ao.quantization.convert(model, inplace=True)
|
| 109 |
+
|
| 110 |
+
# retrieve scale & zero_points
|
| 111 |
+
quantize_params: dict[str, dict] = {
|
| 112 |
+
"scales": {},
|
| 113 |
+
"zero_points": {},
|
| 114 |
+
"dequant_weights": {},
|
| 115 |
+
"axis": {},
|
| 116 |
+
"dtype": {},
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
for name, _ in embedding_modules:
|
| 120 |
+
quantized_emb = fqn_to_module(model, name)
|
| 121 |
+
if quantized_emb is None:
|
| 122 |
+
raise AssertionError(f"quantized embedding {name} not found in model")
|
| 123 |
+
|
| 124 |
+
quantized_weight = quantized_emb.weight() # type: ignore[operator]
|
| 125 |
+
quantize_params["scales"][name] = quantized_weight.q_per_channel_scales()
|
| 126 |
+
quantize_params["zero_points"][name] = (
|
| 127 |
+
quantized_weight.q_per_channel_zero_points()
|
| 128 |
+
)
|
| 129 |
+
quantize_params["dequant_weights"][name] = torch.dequantize(
|
| 130 |
+
quantized_weight
|
| 131 |
+
)
|
| 132 |
+
quantize_params["axis"][name] = quantized_weight.q_per_channel_axis()
|
| 133 |
+
quantize_params["dtype"][name] = quantized_weight.dtype
|
| 134 |
+
|
| 135 |
+
# attach data to sparsifier
|
| 136 |
+
data_sparsifier.add_data(
|
| 137 |
+
name=name.replace(".", "_"),
|
| 138 |
+
data=quantize_params["dequant_weights"][name],
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
data_sparsifier.step()
|
| 142 |
+
data_sparsifier.squash_mask()
|
| 143 |
+
|
| 144 |
+
for name, _ in embedding_modules:
|
| 145 |
+
quantized_emb = fqn_to_module(model, name)
|
| 146 |
+
if quantized_emb is None:
|
| 147 |
+
raise AssertionError(f"quantized embedding {name} not found in model")
|
| 148 |
+
requantized_vector = torch.quantize_per_channel(
|
| 149 |
+
quantize_params["dequant_weights"][name],
|
| 150 |
+
scales=quantize_params["scales"][name],
|
| 151 |
+
zero_points=quantize_params["zero_points"][name],
|
| 152 |
+
dtype=quantize_params["dtype"][name],
|
| 153 |
+
axis=quantize_params["axis"][name],
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
quantized_emb.set_weight(requantized_vector) # type: ignore[operator]
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from .base_structured_sparsifier import BaseStructuredSparsifier
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ["FPGMPruner"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class FPGMPruner(BaseStructuredSparsifier):
|
| 13 |
+
r"""Filter Pruning via Geometric Median (FPGM) Structured Pruner
|
| 14 |
+
This sparsifier prune filter (row) in a tensor according to distances among filters according to
|
| 15 |
+
`Filter Pruning via Geometric Median for Deep Convolutional Neural Networks Acceleration <https://arxiv.org/abs/1811.00250>`_.
|
| 16 |
+
|
| 17 |
+
This sparsifier is controlled by three variables:
|
| 18 |
+
1. `sparsity_level` defines the number of filters (rows) that are zeroed-out.
|
| 19 |
+
2. `dist` defines the distance measurement type. Default: 3 (L2 distance).
|
| 20 |
+
Available options are: [1, 2, (custom callable distance function)].
|
| 21 |
+
|
| 22 |
+
Note::
|
| 23 |
+
Inputs should be a 4D convolutional tensor of shape (N, C, H, W).
|
| 24 |
+
- N: output channels size
|
| 25 |
+
- C: input channels size
|
| 26 |
+
- H: height of kernel
|
| 27 |
+
- W: width of kernel
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, sparsity_level: float = 0.5, dist: Callable | int | None = None):
|
| 31 |
+
defaults = {
|
| 32 |
+
"sparsity_level": sparsity_level,
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
if dist is None:
|
| 36 |
+
dist = 2
|
| 37 |
+
|
| 38 |
+
if callable(dist):
|
| 39 |
+
self.dist_fn = dist
|
| 40 |
+
elif dist == 1:
|
| 41 |
+
self.dist_fn = lambda x: torch.cdist(x, x, p=1)
|
| 42 |
+
elif dist == 2:
|
| 43 |
+
self.dist_fn = lambda x: torch.cdist(x, x, p=2)
|
| 44 |
+
else:
|
| 45 |
+
raise NotImplementedError("Distance function is not yet implemented.")
|
| 46 |
+
super().__init__(defaults=defaults)
|
| 47 |
+
|
| 48 |
+
def _compute_distance(self, t):
|
| 49 |
+
r"""Compute distance across all entries in tensor `t` along all dimension
|
| 50 |
+
except for the one identified by dim.
|
| 51 |
+
Args:
|
| 52 |
+
t (torch.Tensor): tensor representing the parameter to prune
|
| 53 |
+
Returns:
|
| 54 |
+
distance (torch.Tensor): distance computed across filters
|
| 55 |
+
"""
|
| 56 |
+
dim = 0 # prune filter (row)
|
| 57 |
+
|
| 58 |
+
size = t.size(dim)
|
| 59 |
+
slc = [slice(None)] * t.dim()
|
| 60 |
+
|
| 61 |
+
# flatten the tensor along the dimension
|
| 62 |
+
t_flatten = [
|
| 63 |
+
t[tuple(slc[:dim] + [slice(i, i + 1)] + slc[dim + 1 :])].reshape(-1)
|
| 64 |
+
for i in range(size)
|
| 65 |
+
]
|
| 66 |
+
t_flatten = torch.stack(t_flatten)
|
| 67 |
+
|
| 68 |
+
# distance measurement
|
| 69 |
+
dist_matrix = self.dist_fn(t_flatten)
|
| 70 |
+
|
| 71 |
+
# more similar with other filter indicates large in the sum of row
|
| 72 |
+
distance = torch.sum(torch.abs(dist_matrix), 1)
|
| 73 |
+
|
| 74 |
+
return distance
|
| 75 |
+
|
| 76 |
+
def update_mask( # type: ignore[override]
|
| 77 |
+
self, module, tensor_name, sparsity_level, **kwargs
|
| 78 |
+
):
|
| 79 |
+
tensor_weight = getattr(module, tensor_name)
|
| 80 |
+
mask = getattr(module.parametrizations, tensor_name)[0].mask
|
| 81 |
+
|
| 82 |
+
if sparsity_level <= 0:
|
| 83 |
+
mask.data = torch.ones_like(mask).bool()
|
| 84 |
+
elif sparsity_level >= 1.0:
|
| 85 |
+
mask.data = torch.zeros_like(mask).bool()
|
| 86 |
+
else:
|
| 87 |
+
distance = self._compute_distance(tensor_weight)
|
| 88 |
+
|
| 89 |
+
tensor_size = tensor_weight.shape[0] # prune filter (row)
|
| 90 |
+
nparams_toprune = round(sparsity_level * tensor_size)
|
| 91 |
+
nparams_toprune = min(
|
| 92 |
+
max(nparams_toprune, 0), tensor_size
|
| 93 |
+
) # clamp to [0, tensor_size]
|
| 94 |
+
topk = torch.topk(distance, k=nparams_toprune, largest=False)
|
| 95 |
+
mask[topk.indices] = False
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base_structured_sparsifier import BaseStructuredSparsifier
|
| 2 |
+
from .FPGM_pruner import FPGMPruner
|
| 3 |
+
from .lstm_saliency_pruner import LSTMSaliencyPruner
|
| 4 |
+
from .parametrization import BiasHook, FakeStructuredSparsity
|
| 5 |
+
from .saliency_pruner import SaliencyPruner
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-312.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (538 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-312.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-312.pyc
ADDED
|
Binary file (2.93 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-312.pyc
ADDED
|
Binary file (2.71 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-312.pyc
ADDED
|
Binary file (3.89 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-312.pyc
ADDED
|
Binary file (22 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-312.pyc
ADDED
|
Binary file (2.13 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from itertools import chain
|
| 4 |
+
from operator import getitem
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch import nn
|
| 9 |
+
from torch.ao.pruning.sparsifier.base_sparsifier import BaseSparsifier
|
| 10 |
+
from torch.fx import symbolic_trace
|
| 11 |
+
from torch.nn.utils import parametrize
|
| 12 |
+
|
| 13 |
+
from .match_utils import apply_match, MatchAllNode
|
| 14 |
+
from .parametrization import BiasHook, FakeStructuredSparsity, module_contains_param
|
| 15 |
+
from .prune_functions import (
|
| 16 |
+
prune_conv2d,
|
| 17 |
+
prune_conv2d_activation_conv2d,
|
| 18 |
+
prune_conv2d_activation_pool_conv2d,
|
| 19 |
+
prune_conv2d_conv2d,
|
| 20 |
+
prune_conv2d_pool_activation_conv2d,
|
| 21 |
+
prune_conv2d_pool_flatten_linear,
|
| 22 |
+
prune_linear,
|
| 23 |
+
prune_linear_activation_linear,
|
| 24 |
+
prune_linear_linear,
|
| 25 |
+
prune_lstm_output_layernorm_linear,
|
| 26 |
+
prune_lstm_output_linear,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _get_supported_structured_pruning_modules():
|
| 31 |
+
SUPPORTED_STRUCTURED_PRUNING_MODULES = { # added to config if None given
|
| 32 |
+
nn.Linear,
|
| 33 |
+
nn.Conv2d,
|
| 34 |
+
nn.LSTM,
|
| 35 |
+
}
|
| 36 |
+
return SUPPORTED_STRUCTURED_PRUNING_MODULES
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _get_supported_activation_functions():
|
| 40 |
+
SUPPORTED_ACTIVATION_FUNCTIONS = {
|
| 41 |
+
F.relu,
|
| 42 |
+
F.rrelu,
|
| 43 |
+
F.hardtanh,
|
| 44 |
+
F.relu6,
|
| 45 |
+
F.sigmoid,
|
| 46 |
+
F.hardsigmoid,
|
| 47 |
+
F.tanh,
|
| 48 |
+
F.silu,
|
| 49 |
+
F.mish,
|
| 50 |
+
F.hardswish,
|
| 51 |
+
F.elu,
|
| 52 |
+
F.celu,
|
| 53 |
+
F.selu,
|
| 54 |
+
F.hardshrink,
|
| 55 |
+
F.leaky_relu,
|
| 56 |
+
F.logsigmoid,
|
| 57 |
+
F.softplus,
|
| 58 |
+
F.prelu,
|
| 59 |
+
F.softsign,
|
| 60 |
+
F.tanhshrink,
|
| 61 |
+
F.gelu,
|
| 62 |
+
}
|
| 63 |
+
return SUPPORTED_ACTIVATION_FUNCTIONS
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _get_supported_activation_modules():
|
| 67 |
+
SUPPORTED_ACTIVATION_MODULES = {
|
| 68 |
+
nn.ReLU,
|
| 69 |
+
nn.RReLU,
|
| 70 |
+
nn.Hardtanh,
|
| 71 |
+
nn.ReLU6,
|
| 72 |
+
nn.Sigmoid,
|
| 73 |
+
nn.Hardsigmoid,
|
| 74 |
+
nn.Tanh,
|
| 75 |
+
nn.SiLU,
|
| 76 |
+
nn.Mish,
|
| 77 |
+
nn.Hardswish,
|
| 78 |
+
nn.ELU,
|
| 79 |
+
nn.CELU,
|
| 80 |
+
nn.SELU,
|
| 81 |
+
nn.Hardshrink,
|
| 82 |
+
nn.LeakyReLU,
|
| 83 |
+
nn.LogSigmoid,
|
| 84 |
+
nn.Softplus,
|
| 85 |
+
nn.PReLU,
|
| 86 |
+
nn.Softsign,
|
| 87 |
+
nn.Tanhshrink,
|
| 88 |
+
nn.GELU,
|
| 89 |
+
}
|
| 90 |
+
return SUPPORTED_ACTIVATION_MODULES
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _get_default_structured_pruning_patterns() -> dict[
|
| 94 |
+
tuple[type[nn.Module] | Callable | MatchAllNode | str, ...],
|
| 95 |
+
Callable[..., None],
|
| 96 |
+
]:
|
| 97 |
+
"""
|
| 98 |
+
Returns the patterns for conv2d / linear conversion for each element in the activation functions/modules defined above.
|
| 99 |
+
"""
|
| 100 |
+
patterns: dict[
|
| 101 |
+
tuple[type[nn.Module] | Callable | MatchAllNode | str, ...],
|
| 102 |
+
Callable[..., None],
|
| 103 |
+
] = {
|
| 104 |
+
# linear -> linear
|
| 105 |
+
(nn.Linear, "output"): prune_linear,
|
| 106 |
+
(nn.Linear, nn.Linear): prune_linear_linear,
|
| 107 |
+
# conv2d -> conv2d
|
| 108 |
+
(nn.Conv2d, "output"): prune_conv2d,
|
| 109 |
+
(nn.Conv2d, nn.Conv2d): prune_conv2d_conv2d,
|
| 110 |
+
# TODO LSTM Structured pruning does not support returned state currently.
|
| 111 |
+
# Should find a way to explicitly match getitem(0) instead of getitem.
|
| 112 |
+
# This will also require changing the pruning function.
|
| 113 |
+
# lstm -> getitem(0) -> linear
|
| 114 |
+
(nn.LSTM, getitem, nn.Linear): prune_lstm_output_linear,
|
| 115 |
+
# lstm -> getitem(0) -> layernorm -> linear
|
| 116 |
+
(nn.LSTM, getitem, nn.LayerNorm, nn.Linear): prune_lstm_output_layernorm_linear,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
for activation in chain(
|
| 120 |
+
_get_supported_activation_functions(), _get_supported_activation_modules()
|
| 121 |
+
):
|
| 122 |
+
patterns.update(
|
| 123 |
+
{
|
| 124 |
+
# linear -> activation -> linear
|
| 125 |
+
(nn.Linear, activation, nn.Linear): prune_linear_activation_linear,
|
| 126 |
+
# conv2d -> activation -> conv2d
|
| 127 |
+
(nn.Conv2d, activation, nn.Conv2d): prune_conv2d_activation_conv2d,
|
| 128 |
+
# conv2d -> activation -> pool -> conv2d
|
| 129 |
+
(
|
| 130 |
+
nn.Conv2d,
|
| 131 |
+
activation,
|
| 132 |
+
nn.AvgPool2d,
|
| 133 |
+
nn.Conv2d,
|
| 134 |
+
): prune_conv2d_activation_pool_conv2d,
|
| 135 |
+
(
|
| 136 |
+
nn.Conv2d,
|
| 137 |
+
activation,
|
| 138 |
+
F.avg_pool2d,
|
| 139 |
+
nn.Conv2d,
|
| 140 |
+
): prune_conv2d_activation_pool_conv2d,
|
| 141 |
+
(
|
| 142 |
+
nn.Conv2d,
|
| 143 |
+
activation,
|
| 144 |
+
nn.MaxPool2d,
|
| 145 |
+
nn.Conv2d,
|
| 146 |
+
): prune_conv2d_activation_pool_conv2d,
|
| 147 |
+
(
|
| 148 |
+
nn.Conv2d,
|
| 149 |
+
activation,
|
| 150 |
+
F.max_pool2d,
|
| 151 |
+
nn.Conv2d,
|
| 152 |
+
): prune_conv2d_activation_pool_conv2d,
|
| 153 |
+
# conv2d -> pool -> activation -> conv2d
|
| 154 |
+
(
|
| 155 |
+
nn.Conv2d,
|
| 156 |
+
nn.AvgPool2d,
|
| 157 |
+
activation,
|
| 158 |
+
nn.Conv2d,
|
| 159 |
+
): prune_conv2d_pool_activation_conv2d,
|
| 160 |
+
(
|
| 161 |
+
nn.Conv2d,
|
| 162 |
+
F.avg_pool2d,
|
| 163 |
+
activation,
|
| 164 |
+
nn.Conv2d,
|
| 165 |
+
): prune_conv2d_pool_activation_conv2d,
|
| 166 |
+
(
|
| 167 |
+
nn.Conv2d,
|
| 168 |
+
nn.MaxPool2d,
|
| 169 |
+
activation,
|
| 170 |
+
nn.Conv2d,
|
| 171 |
+
): prune_conv2d_pool_activation_conv2d,
|
| 172 |
+
(
|
| 173 |
+
nn.Conv2d,
|
| 174 |
+
F.max_pool2d,
|
| 175 |
+
activation,
|
| 176 |
+
nn.Conv2d,
|
| 177 |
+
): prune_conv2d_pool_activation_conv2d,
|
| 178 |
+
# conv2d -> adaptive pool -> flatten -> linear
|
| 179 |
+
(
|
| 180 |
+
nn.Conv2d,
|
| 181 |
+
nn.AdaptiveAvgPool2d,
|
| 182 |
+
nn.Flatten,
|
| 183 |
+
nn.Linear,
|
| 184 |
+
): prune_conv2d_pool_flatten_linear,
|
| 185 |
+
(
|
| 186 |
+
nn.Conv2d,
|
| 187 |
+
nn.AdaptiveAvgPool2d,
|
| 188 |
+
torch.flatten,
|
| 189 |
+
nn.Linear,
|
| 190 |
+
): prune_conv2d_pool_flatten_linear,
|
| 191 |
+
(
|
| 192 |
+
nn.Conv2d,
|
| 193 |
+
nn.AdaptiveMaxPool2d,
|
| 194 |
+
nn.Flatten,
|
| 195 |
+
nn.Linear,
|
| 196 |
+
): prune_conv2d_pool_flatten_linear,
|
| 197 |
+
(
|
| 198 |
+
nn.Conv2d,
|
| 199 |
+
nn.AdaptiveMaxPool2d,
|
| 200 |
+
torch.flatten,
|
| 201 |
+
nn.Linear,
|
| 202 |
+
): prune_conv2d_pool_flatten_linear,
|
| 203 |
+
}
|
| 204 |
+
)
|
| 205 |
+
return patterns
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class BaseStructuredSparsifier(BaseSparsifier):
|
| 209 |
+
r"""Base class for structured pruning.
|
| 210 |
+
|
| 211 |
+
Abstract methods that need to be implemented:
|
| 212 |
+
- update_mask: Function to compute a new mask for all keys in the
|
| 213 |
+
`groups` attribute.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
- defaults [dict]: default configurations will be attached to the
|
| 217 |
+
configuration. Only the keys that don't exist in the `config` will
|
| 218 |
+
be updated.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
def __init__(self, defaults, patterns=None):
|
| 222 |
+
super().__init__(defaults)
|
| 223 |
+
if patterns is None:
|
| 224 |
+
patterns = _get_default_structured_pruning_patterns()
|
| 225 |
+
self.patterns = patterns
|
| 226 |
+
|
| 227 |
+
def make_config_from_model(
|
| 228 |
+
self,
|
| 229 |
+
model: nn.Module,
|
| 230 |
+
SUPPORTED_MODULES: set[type] | None = None,
|
| 231 |
+
) -> None:
|
| 232 |
+
if SUPPORTED_MODULES is None:
|
| 233 |
+
SUPPORTED_MODULES = _get_supported_structured_pruning_modules()
|
| 234 |
+
super().make_config_from_model(model, SUPPORTED_MODULES=SUPPORTED_MODULES)
|
| 235 |
+
|
| 236 |
+
def _prepare(self, *args, **kwargs) -> None:
|
| 237 |
+
r"""This function will attach the FakeStructuredSparsity parameterizations
|
| 238 |
+
and BiasHooks at the appropriate points in the model.
|
| 239 |
+
"""
|
| 240 |
+
for config in self.groups:
|
| 241 |
+
module = config["module"]
|
| 242 |
+
tensor_name = config["tensor_name"]
|
| 243 |
+
parametrization = config.get("parametrization", FakeStructuredSparsity)
|
| 244 |
+
tensor = getattr(module, tensor_name)
|
| 245 |
+
|
| 246 |
+
mask = config.get(
|
| 247 |
+
"mask",
|
| 248 |
+
torch.ones(tensor.shape[0], dtype=torch.bool, device=tensor.device),
|
| 249 |
+
)
|
| 250 |
+
self.state[config["tensor_fqn"]]["mask"] = mask
|
| 251 |
+
parametrize.register_parametrization(
|
| 252 |
+
module, tensor_name, parametrization(mask)
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# if linear / conv, we add in bias hooks
|
| 256 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 257 |
+
prune_bias = config.get("prune_bias", True)
|
| 258 |
+
if module.bias is not None:
|
| 259 |
+
module.register_parameter(
|
| 260 |
+
"_bias", nn.Parameter(module.bias.detach())
|
| 261 |
+
)
|
| 262 |
+
# pyrefly: ignore [bad-assignment]
|
| 263 |
+
module.bias = None
|
| 264 |
+
module.prune_bias = prune_bias
|
| 265 |
+
|
| 266 |
+
module.register_forward_hook(
|
| 267 |
+
BiasHook(module.parametrizations.weight[0], prune_bias) # type: ignore[union-attr, index]
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
def prune(self) -> None:
|
| 271 |
+
r"""
|
| 272 |
+
This function will FX symbolically trace the model and then find instances of the patterns
|
| 273 |
+
defined in self.patterns (by default SUPPORTED_STRUCTURED_PRUNING_PATTERNS ).
|
| 274 |
+
|
| 275 |
+
For each pattern, it will apply to corresponding conversion function, which will modify the output
|
| 276 |
+
and input size expected by the modules within the pattern
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
self.traced = symbolic_trace(self.model)
|
| 280 |
+
modules = dict(self.traced.named_modules())
|
| 281 |
+
|
| 282 |
+
# Right now we check for matches simply by iterating across all the patterns
|
| 283 |
+
# if this is slow we can store patterns in a trie-structure and modify this code for faster lookup
|
| 284 |
+
for node in self.traced.graph.nodes:
|
| 285 |
+
for pattern, convert_fn in self.patterns.items():
|
| 286 |
+
matched = apply_match(modules, pattern, node, [])
|
| 287 |
+
if matched is None:
|
| 288 |
+
continue
|
| 289 |
+
|
| 290 |
+
# pyrefly: ignore [no-matching-overload]
|
| 291 |
+
first_module = modules.get(node.target)
|
| 292 |
+
# check if first module exists and has appropriate parameterization, otherwise skip
|
| 293 |
+
if (
|
| 294 |
+
first_module is not None
|
| 295 |
+
and parametrize.is_parametrized(first_module)
|
| 296 |
+
and module_contains_param(first_module, FakeStructuredSparsity)
|
| 297 |
+
):
|
| 298 |
+
convert_block = []
|
| 299 |
+
for node in matched:
|
| 300 |
+
if node.op == "call_module":
|
| 301 |
+
convert_block.append(modules.get(node.target))
|
| 302 |
+
elif node.op == "call_function":
|
| 303 |
+
convert_block.append(node.target)
|
| 304 |
+
convert_fn(*convert_block)
|
| 305 |
+
|
| 306 |
+
for module in self.traced.modules():
|
| 307 |
+
if module_contains_param(module, FakeStructuredSparsity):
|
| 308 |
+
raise Exception( # noqa: TRY002
|
| 309 |
+
f"Error: {module} still contains FakeStructuredSparsity parametrizations!"
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
self.traced.graph.lint()
|
| 313 |
+
self.traced.recompile()
|
| 314 |
+
return self.traced # type: ignore[return-value]
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, cast
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from .base_structured_sparsifier import BaseStructuredSparsifier
|
| 7 |
+
from .parametrization import FakeStructuredSparsity
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class LSTMSaliencyPruner(BaseStructuredSparsifier):
|
| 11 |
+
"""
|
| 12 |
+
Prune packed LSTM weights based on saliency.
|
| 13 |
+
For each layer {k} inside a LSTM, we have two packed weight matrices
|
| 14 |
+
- weight_ih_l{k}
|
| 15 |
+
- weight_hh_l{k}
|
| 16 |
+
|
| 17 |
+
These tensors pack the weights for the 4 linear layers together for efficiency.
|
| 18 |
+
|
| 19 |
+
[W_ii | W_if | W_ig | W_io]
|
| 20 |
+
|
| 21 |
+
Pruning this tensor directly will lead to weights being misassigned when unpacked.
|
| 22 |
+
To ensure that each packed linear layer is pruned the same amount:
|
| 23 |
+
1. We split the packed weight into the 4 constituent linear parts
|
| 24 |
+
2. Update the mask for each individual piece using saliency individually
|
| 25 |
+
|
| 26 |
+
This applies to both weight_ih_l{k} and weight_hh_l{k}.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def update_mask(self, module: nn.Module, tensor_name: str, **kwargs: Any) -> None:
|
| 30 |
+
weights = getattr(module, tensor_name)
|
| 31 |
+
|
| 32 |
+
for p in getattr(module.parametrizations, tensor_name):
|
| 33 |
+
if isinstance(p, FakeStructuredSparsity):
|
| 34 |
+
mask = cast(torch.Tensor, p.mask)
|
| 35 |
+
|
| 36 |
+
# select weights based on magnitude
|
| 37 |
+
if weights.dim() <= 1:
|
| 38 |
+
raise Exception( # noqa: TRY002
|
| 39 |
+
"Structured pruning can only be applied to a 2+dim weight tensor!"
|
| 40 |
+
)
|
| 41 |
+
# take norm over all but first dim
|
| 42 |
+
dims = tuple(range(1, weights.dim()))
|
| 43 |
+
saliency = weights.norm(dim=dims, p=1)
|
| 44 |
+
|
| 45 |
+
# handle weights in 4 groups
|
| 46 |
+
split_size = len(mask) // 4
|
| 47 |
+
masks = torch.split(mask, split_size)
|
| 48 |
+
saliencies = torch.split(saliency, split_size)
|
| 49 |
+
|
| 50 |
+
for keep_mask, sal in zip(masks, saliencies):
|
| 51 |
+
# mask smallest k values to be removed
|
| 52 |
+
k = int(len(keep_mask) * kwargs["sparsity_level"])
|
| 53 |
+
prune = sal.topk(k, largest=False, sorted=False).indices
|
| 54 |
+
keep_mask.data[prune] = False # modifies underlying p.mask directly
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Contains utility functions to check if a pattern is in the graph and return the matching nodes
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import nn
|
| 9 |
+
from torch.ao.quantization.utils import MatchAllNode
|
| 10 |
+
from torch.fx import Node
|
| 11 |
+
from torch.nn.utils import parametrize
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _match(
|
| 15 |
+
modules: dict[str, nn.ModuleDict],
|
| 16 |
+
node: Node,
|
| 17 |
+
current: nn.Module | Any,
|
| 18 |
+
) -> bool:
|
| 19 |
+
r"""
|
| 20 |
+
checks to see if a single node of a pattern matches
|
| 21 |
+
"""
|
| 22 |
+
if isinstance(current, type) and issubclass(current, MatchAllNode):
|
| 23 |
+
return True
|
| 24 |
+
if not isinstance(node, Node):
|
| 25 |
+
return False
|
| 26 |
+
if isinstance(current, type) and issubclass(current, torch.nn.Module):
|
| 27 |
+
return (
|
| 28 |
+
node.op == "call_module"
|
| 29 |
+
and parametrize.type_before_parametrizations(modules[node.target]) # type: ignore[index]
|
| 30 |
+
== current
|
| 31 |
+
)
|
| 32 |
+
elif callable(current):
|
| 33 |
+
return node.op == "call_function" and node.target is current
|
| 34 |
+
elif isinstance(current, str):
|
| 35 |
+
return node.target == current
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def apply_match(
|
| 40 |
+
modules: dict[str, nn.ModuleDict],
|
| 41 |
+
pattern: tuple[Any] | Any,
|
| 42 |
+
node: Node,
|
| 43 |
+
matched_node_pattern: list[Node],
|
| 44 |
+
) -> list[Node] | None:
|
| 45 |
+
r"""
|
| 46 |
+
This function will return the matched nodes if the pattern matches the node given
|
| 47 |
+
If there is no match, it will return None
|
| 48 |
+
"""
|
| 49 |
+
if isinstance(pattern, tuple):
|
| 50 |
+
if len(pattern) == 1:
|
| 51 |
+
if _match(modules, node, pattern[0]):
|
| 52 |
+
return matched_node_pattern + [node]
|
| 53 |
+
|
| 54 |
+
first, *rest = pattern
|
| 55 |
+
if _match(modules, node, first):
|
| 56 |
+
if rest is None:
|
| 57 |
+
return matched_node_pattern + [node]
|
| 58 |
+
|
| 59 |
+
for user in node.users:
|
| 60 |
+
return apply_match(
|
| 61 |
+
modules, tuple(rest), user, matched_node_pattern + [node]
|
| 62 |
+
)
|
| 63 |
+
elif _match(modules, node, pattern):
|
| 64 |
+
return [node]
|
| 65 |
+
return None
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
from torch.nn.utils.parametrize import is_parametrized
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def module_contains_param(module, parametrization):
|
| 8 |
+
if is_parametrized(module):
|
| 9 |
+
# see if any of the module tensors have a parametrization attached that matches the one passed in
|
| 10 |
+
return any(
|
| 11 |
+
any(isinstance(param, parametrization) for param in param_list)
|
| 12 |
+
for param_list in module.parametrizations.values()
|
| 13 |
+
)
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# Structured Pruning Parameterizations
|
| 18 |
+
class FakeStructuredSparsity(nn.Module):
|
| 19 |
+
r"""
|
| 20 |
+
Parametrization for Structured Pruning. Like FakeSparsity, this should be attached to
|
| 21 |
+
the 'weight' or any other parameter that requires a mask.
|
| 22 |
+
|
| 23 |
+
Instead of an element-wise bool mask, this parameterization uses a row-wise bool mask.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, mask):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.register_buffer("mask", mask)
|
| 29 |
+
|
| 30 |
+
def forward(self, x):
|
| 31 |
+
if not isinstance(self.mask, torch.Tensor):
|
| 32 |
+
raise AssertionError("mask must be a torch.Tensor")
|
| 33 |
+
if self.mask.shape[0] != x.shape[0]:
|
| 34 |
+
raise AssertionError(
|
| 35 |
+
f"mask shape[0] ({self.mask.shape[0]}) must match x shape[0] ({x.shape[0]})"
|
| 36 |
+
)
|
| 37 |
+
shape = [1] * len(x.shape)
|
| 38 |
+
shape[0] = -1
|
| 39 |
+
return self.mask.reshape(shape) * x
|
| 40 |
+
|
| 41 |
+
def state_dict(self, *args, **kwargs):
|
| 42 |
+
# avoid double saving masks
|
| 43 |
+
return {}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BiasHook:
|
| 47 |
+
def __init__(self, parametrization, prune_bias):
|
| 48 |
+
self.param = parametrization
|
| 49 |
+
self.prune_bias = prune_bias
|
| 50 |
+
|
| 51 |
+
def __call__(self, module, input, output):
|
| 52 |
+
if getattr(module, "_bias", None) is not None:
|
| 53 |
+
bias = module._bias.data
|
| 54 |
+
if self.prune_bias:
|
| 55 |
+
bias[~self.param.mask] = 0
|
| 56 |
+
|
| 57 |
+
# reshape bias to broadcast over output dimensions
|
| 58 |
+
idx = [1] * len(output.shape)
|
| 59 |
+
idx[1] = -1
|
| 60 |
+
bias = bias.reshape(idx)
|
| 61 |
+
|
| 62 |
+
output += bias
|
| 63 |
+
return output
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""
|
| 3 |
+
Collection of conversion functions for linear / conv2d structured pruning
|
| 4 |
+
Also contains utilities for bias propagation
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from typing import cast
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import nn, Tensor
|
| 12 |
+
from torch.nn.utils import parametrize
|
| 13 |
+
from torch.nn.utils.parametrize import ParametrizationList
|
| 14 |
+
|
| 15 |
+
from .parametrization import BiasHook, FakeStructuredSparsity
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# BIAS PROPAGATION
|
| 19 |
+
def _remove_bias_handles(module: nn.Module) -> None:
|
| 20 |
+
if hasattr(module, "_forward_hooks"):
|
| 21 |
+
bias_hooks: list[int] = []
|
| 22 |
+
for key, hook in module._forward_hooks.items():
|
| 23 |
+
if isinstance(hook, BiasHook):
|
| 24 |
+
bias_hooks.append(key)
|
| 25 |
+
|
| 26 |
+
for key in bias_hooks:
|
| 27 |
+
del module._forward_hooks[key]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _get_adjusted_next_layer_bias(
|
| 31 |
+
next_layer: nn.Module, pruned_biases: Tensor, mask: Tensor
|
| 32 |
+
) -> nn.Parameter:
|
| 33 |
+
r"""Returns new adjusted bias for the second supported module"""
|
| 34 |
+
if parametrize.is_parametrized(next_layer):
|
| 35 |
+
# need to access original weight
|
| 36 |
+
parametrization_dict = cast(nn.ModuleDict, next_layer.parametrizations)
|
| 37 |
+
weight_parameterizations = cast(
|
| 38 |
+
ParametrizationList, parametrization_dict.weight
|
| 39 |
+
)
|
| 40 |
+
next_weight = weight_parameterizations.original
|
| 41 |
+
else:
|
| 42 |
+
next_weight = cast(Tensor, next_layer.weight)
|
| 43 |
+
|
| 44 |
+
scaling_weight = next_weight[:, ~mask]
|
| 45 |
+
if isinstance(next_layer, nn.Conv2d): # checking for Conv2d
|
| 46 |
+
# Propagating first layer pruned biases and calculating the new second layer bias
|
| 47 |
+
# involves more steps since the Conv2d scaling weight has extra dimensions,
|
| 48 |
+
# so adding bias involves broadcasting, logically:
|
| 49 |
+
# for each channel k in range(oC):
|
| 50 |
+
# scaled_biases = sum(first_bias[pruned_idx] @ next_weight[k, pruned_idx, :, :].T)
|
| 51 |
+
# new_next_bias[k] = old_next_bias[k] + scaled_biases
|
| 52 |
+
scaling_product = torch.matmul(
|
| 53 |
+
pruned_biases.reshape(1, -1), torch.transpose(scaling_weight, 1, 2)
|
| 54 |
+
)
|
| 55 |
+
sum_range = list(range(len(scaling_product.shape)))[
|
| 56 |
+
1:
|
| 57 |
+
] # all but the first dimension
|
| 58 |
+
scaled_biases = torch.sum(scaling_product, sum_range)
|
| 59 |
+
elif isinstance(next_layer, nn.Linear): # Linear
|
| 60 |
+
scaled_biases = torch.matmul(
|
| 61 |
+
pruned_biases, torch.transpose(scaling_weight, 0, 1)
|
| 62 |
+
) # recall b2_new = b1 @ w2.T + b2
|
| 63 |
+
else:
|
| 64 |
+
raise NotImplementedError(f"Type {type(next_layer)} not supported yet.")
|
| 65 |
+
|
| 66 |
+
if (
|
| 67 |
+
parametrize.is_parametrized(next_layer)
|
| 68 |
+
and getattr(next_layer, "_bias", None) is not None
|
| 69 |
+
): # next_layer is parametrized & has original bias ._bias
|
| 70 |
+
adjusted_bias = nn.Parameter(scaled_biases + next_layer._bias) # type: ignore[operator]
|
| 71 |
+
elif (
|
| 72 |
+
not parametrize.is_parametrized(next_layer) and next_layer.bias is not None
|
| 73 |
+
): # next_layer not parametrized & has .bias
|
| 74 |
+
adjusted_bias = nn.Parameter(scaled_biases + next_layer.bias) # type: ignore[operator]
|
| 75 |
+
else: # next_layer has no bias
|
| 76 |
+
adjusted_bias = nn.Parameter(scaled_biases)
|
| 77 |
+
return adjusted_bias
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _prune_module_bias(module: nn.Module, mask: Tensor) -> None:
|
| 81 |
+
r"""Applies mask to given modules bias"""
|
| 82 |
+
# prune bias along with weights, discard pruned indices of bias
|
| 83 |
+
original_bias = cast(Tensor, getattr(module, "_bias", module.bias))
|
| 84 |
+
if original_bias is not None:
|
| 85 |
+
module.bias = nn.Parameter(original_bias[mask])
|
| 86 |
+
|
| 87 |
+
# remove _bias parameter
|
| 88 |
+
if hasattr(module, "_bias"):
|
| 89 |
+
delattr(module, "_bias")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _propagate_module_bias(module: nn.Module, mask: Tensor) -> Tensor | None:
|
| 93 |
+
r"""
|
| 94 |
+
In the case that we need to propagate biases, this function will return the biases we need
|
| 95 |
+
"""
|
| 96 |
+
# set current module bias
|
| 97 |
+
if module.bias is not None:
|
| 98 |
+
module.bias = nn.Parameter(cast(Tensor, module.bias)[mask])
|
| 99 |
+
elif getattr(module, "_bias", None) is not None:
|
| 100 |
+
# pyrefly: ignore [bad-assignment]
|
| 101 |
+
module.bias = nn.Parameter(cast(Tensor, module._bias)[mask])
|
| 102 |
+
|
| 103 |
+
# get pruned biases to propagate to subsequent layer
|
| 104 |
+
if getattr(module, "_bias", None) is not None:
|
| 105 |
+
pruned_biases = cast(Tensor, module._bias)[~mask]
|
| 106 |
+
else:
|
| 107 |
+
pruned_biases = None
|
| 108 |
+
|
| 109 |
+
if hasattr(module, "_bias"):
|
| 110 |
+
delattr(module, "_bias")
|
| 111 |
+
|
| 112 |
+
return pruned_biases
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# LINEAR
|
| 116 |
+
def _prune_linear_helper(linear: nn.Linear) -> Tensor:
|
| 117 |
+
# expects linear to be a parameterized linear module
|
| 118 |
+
parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
|
| 119 |
+
weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
|
| 120 |
+
for p in weight_parameterizations:
|
| 121 |
+
if isinstance(p, FakeStructuredSparsity):
|
| 122 |
+
mask = cast(Tensor, p.mask)
|
| 123 |
+
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
parametrize.remove_parametrizations(linear, "weight", leave_parametrized=True)
|
| 126 |
+
linear.weight = nn.Parameter(linear.weight[mask]) # type: ignore[possibly-undefined]
|
| 127 |
+
linear.out_features = linear.weight.shape[0]
|
| 128 |
+
_remove_bias_handles(linear)
|
| 129 |
+
|
| 130 |
+
# pyrefly: ignore [unbound-name]
|
| 131 |
+
return mask
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def prune_linear(linear: nn.Linear) -> None:
|
| 135 |
+
mask = _prune_linear_helper(linear)
|
| 136 |
+
if getattr(linear, "prune_bias", False):
|
| 137 |
+
_prune_module_bias(linear, mask)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def prune_linear_linear(linear1: nn.Linear, linear2: nn.Linear) -> None:
|
| 141 |
+
prune_linear_activation_linear(linear1, None, linear2)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def prune_linear_activation_linear(
|
| 145 |
+
linear1: nn.Linear,
|
| 146 |
+
activation: Callable[[Tensor], Tensor] | None,
|
| 147 |
+
linear2: nn.Linear,
|
| 148 |
+
):
|
| 149 |
+
mask = _prune_linear_helper(linear1)
|
| 150 |
+
if getattr(linear1, "prune_bias", False):
|
| 151 |
+
_prune_module_bias(linear1, mask)
|
| 152 |
+
else:
|
| 153 |
+
pruned_biases = _propagate_module_bias(linear1, mask)
|
| 154 |
+
if pruned_biases is not None:
|
| 155 |
+
if activation:
|
| 156 |
+
pruned_biases = activation(pruned_biases)
|
| 157 |
+
linear2.bias = _get_adjusted_next_layer_bias(linear2, pruned_biases, mask)
|
| 158 |
+
|
| 159 |
+
with torch.no_grad():
|
| 160 |
+
if parametrize.is_parametrized(linear2):
|
| 161 |
+
parametrization_dict = cast(nn.ModuleDict, linear2.parametrizations)
|
| 162 |
+
weight_parameterizations = cast(
|
| 163 |
+
ParametrizationList, parametrization_dict.weight
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
weight_parameterizations.original = nn.Parameter(
|
| 167 |
+
weight_parameterizations.original[:, mask]
|
| 168 |
+
)
|
| 169 |
+
linear2.in_features = weight_parameterizations.original.shape[1]
|
| 170 |
+
else:
|
| 171 |
+
linear2.weight = nn.Parameter(linear2.weight[:, mask])
|
| 172 |
+
linear2.in_features = linear2.weight.shape[1]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# CONV2D
|
| 176 |
+
def _prune_conv2d_helper(conv2d: nn.Conv2d) -> Tensor:
|
| 177 |
+
parametrization_dict = cast(nn.ModuleDict, conv2d.parametrizations)
|
| 178 |
+
weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
|
| 179 |
+
for p in weight_parameterizations:
|
| 180 |
+
if isinstance(p, FakeStructuredSparsity):
|
| 181 |
+
mask = cast(Tensor, p.mask)
|
| 182 |
+
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
parametrize.remove_parametrizations(conv2d, "weight", leave_parametrized=True)
|
| 185 |
+
conv2d.weight = nn.Parameter(conv2d.weight[mask]) # type: ignore[possibly-undefined]
|
| 186 |
+
conv2d.out_channels = conv2d.weight.shape[0]
|
| 187 |
+
|
| 188 |
+
_remove_bias_handles(conv2d)
|
| 189 |
+
# pyrefly: ignore [unbound-name]
|
| 190 |
+
return mask
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def prune_conv2d_padded(conv2d_1: nn.Conv2d) -> None:
|
| 194 |
+
parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations)
|
| 195 |
+
weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
|
| 196 |
+
for p in weight_parameterizations:
|
| 197 |
+
if isinstance(p, FakeStructuredSparsity):
|
| 198 |
+
mask = cast(Tensor, p.mask)
|
| 199 |
+
|
| 200 |
+
with torch.no_grad():
|
| 201 |
+
parametrize.remove_parametrizations(conv2d_1, "weight", leave_parametrized=True)
|
| 202 |
+
|
| 203 |
+
if getattr(conv2d_1, "_bias", None) is not None:
|
| 204 |
+
if (
|
| 205 |
+
conv2d_1.bias is not None
|
| 206 |
+
): # conv2d_1 has original bias and bias propagated from previous layer
|
| 207 |
+
new_bias = torch.zeros(conv2d_1.bias.shape)
|
| 208 |
+
new_bias[mask] = conv2d_1.bias[mask] # type: ignore[possibly-undefined]
|
| 209 |
+
# adjusted bias to keep in conv2d_1
|
| 210 |
+
# pyrefly: ignore [unbound-name]
|
| 211 |
+
new_bias[~mask] = cast(Tensor, conv2d_1._bias)[~mask]
|
| 212 |
+
# pruned biases that are kept instead of propagated
|
| 213 |
+
conv2d_1.bias = nn.Parameter(new_bias)
|
| 214 |
+
else: # conv2d_1 has only original bias
|
| 215 |
+
conv2d_1.bias = nn.Parameter(cast(Tensor, conv2d_1._bias))
|
| 216 |
+
else:
|
| 217 |
+
# no original bias, only propagated bias
|
| 218 |
+
if (
|
| 219 |
+
conv2d_1.bias is not None
|
| 220 |
+
): # conv2d_1 has bias propagated from previous layer
|
| 221 |
+
conv2d_1.bias.data[~mask] = 0 # type: ignore[possibly-undefined]
|
| 222 |
+
|
| 223 |
+
if hasattr(conv2d_1, "_bias"):
|
| 224 |
+
delattr(conv2d_1, "_bias")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def prune_conv2d(conv2d: nn.Conv2d) -> None:
|
| 228 |
+
mask = _prune_conv2d_helper(conv2d)
|
| 229 |
+
if getattr(conv2d, "prune_bias", False):
|
| 230 |
+
_prune_module_bias(conv2d, mask)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def prune_conv2d_conv2d(conv2d_1: nn.Conv2d, conv2d_2: nn.Conv2d) -> None:
|
| 234 |
+
prune_conv2d_activation_conv2d(conv2d_1, None, conv2d_2)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def prune_conv2d_activation_conv2d(
|
| 238 |
+
conv2d_1: nn.Conv2d,
|
| 239 |
+
activation: Callable[[Tensor], Tensor] | None,
|
| 240 |
+
conv2d_2: nn.Conv2d,
|
| 241 |
+
):
|
| 242 |
+
r"""
|
| 243 |
+
Fusion Pattern for conv2d -> some activation module / function -> conv2d layers
|
| 244 |
+
"""
|
| 245 |
+
parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations)
|
| 246 |
+
weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
|
| 247 |
+
for p in weight_parameterizations:
|
| 248 |
+
if isinstance(p, FakeStructuredSparsity):
|
| 249 |
+
mask = cast(Tensor, p.mask)
|
| 250 |
+
|
| 251 |
+
prune_bias = getattr(conv2d_1, "prune_bias", False)
|
| 252 |
+
if (
|
| 253 |
+
hasattr(conv2d_2, "padding")
|
| 254 |
+
and cast(tuple[int], conv2d_2.padding) > (0, 0)
|
| 255 |
+
and (conv2d_1.bias is not None or getattr(conv2d_1, "_bias", None) is not None)
|
| 256 |
+
):
|
| 257 |
+
prune_conv2d_padded(conv2d_1)
|
| 258 |
+
else:
|
| 259 |
+
mask = _prune_conv2d_helper(conv2d_1)
|
| 260 |
+
if prune_bias:
|
| 261 |
+
_prune_module_bias(conv2d_1, mask)
|
| 262 |
+
else:
|
| 263 |
+
pruned_biases = _propagate_module_bias(conv2d_1, mask)
|
| 264 |
+
if pruned_biases is not None:
|
| 265 |
+
if activation:
|
| 266 |
+
pruned_biases = activation(pruned_biases)
|
| 267 |
+
conv2d_2.bias = _get_adjusted_next_layer_bias(
|
| 268 |
+
conv2d_2, pruned_biases, mask
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
if (
|
| 272 |
+
not (
|
| 273 |
+
hasattr(conv2d_2, "padding")
|
| 274 |
+
and cast(tuple[int], conv2d_2.padding) > (0, 0)
|
| 275 |
+
)
|
| 276 |
+
or conv2d_1.bias is None
|
| 277 |
+
):
|
| 278 |
+
with torch.no_grad():
|
| 279 |
+
if parametrize.is_parametrized(conv2d_2):
|
| 280 |
+
parametrization_dict = cast(
|
| 281 |
+
nn.ModuleDict, conv2d_2.parametrizations
|
| 282 |
+
)
|
| 283 |
+
weight_parameterizations = cast(
|
| 284 |
+
ParametrizationList, parametrization_dict.weight
|
| 285 |
+
)
|
| 286 |
+
weight_parameterizations.original = nn.Parameter(
|
| 287 |
+
weight_parameterizations.original[:, mask]
|
| 288 |
+
)
|
| 289 |
+
conv2d_2.in_channels = weight_parameterizations.original.shape[1]
|
| 290 |
+
else:
|
| 291 |
+
conv2d_2.weight = nn.Parameter(conv2d_2.weight[:, mask])
|
| 292 |
+
conv2d_2.in_channels = conv2d_2.weight.shape[1]
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def prune_conv2d_pool_activation_conv2d(
|
| 296 |
+
c1: nn.Conv2d,
|
| 297 |
+
pool: nn.Module,
|
| 298 |
+
activation: Callable[[Tensor], Tensor] | None,
|
| 299 |
+
c2: nn.Conv2d,
|
| 300 |
+
) -> None:
|
| 301 |
+
prune_conv2d_activation_conv2d(c1, activation, c2)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def prune_conv2d_activation_pool_conv2d(
|
| 305 |
+
c1: nn.Conv2d,
|
| 306 |
+
activation: Callable[[Tensor], Tensor] | None,
|
| 307 |
+
pool: nn.Module,
|
| 308 |
+
c2: nn.Conv2d,
|
| 309 |
+
) -> None:
|
| 310 |
+
prune_conv2d_activation_conv2d(c1, activation, c2)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def prune_conv2d_pool_flatten_linear(
|
| 314 |
+
conv2d: nn.Conv2d,
|
| 315 |
+
pool: nn.Module,
|
| 316 |
+
flatten: Callable[[Tensor], Tensor] | None,
|
| 317 |
+
linear: nn.Linear,
|
| 318 |
+
) -> None:
|
| 319 |
+
mask = _prune_conv2d_helper(conv2d)
|
| 320 |
+
|
| 321 |
+
# We map the pruned indices of the Conv2d output to the flattened indices of the Linear following the Flatten layer.
|
| 322 |
+
# we determine the flattening scale (h * w), and readjust `first_pruned_indices`
|
| 323 |
+
# (each idx maps to range idx * h * w to (idx+1) * h * w), `first_valid_indices`,
|
| 324 |
+
# and `pruned_biases` (repeat each bias by h * w).
|
| 325 |
+
if parametrize.is_parametrized(linear):
|
| 326 |
+
parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
|
| 327 |
+
weight_parameterizations = cast(
|
| 328 |
+
ParametrizationList, parametrization_dict.weight
|
| 329 |
+
)
|
| 330 |
+
linear_ic = weight_parameterizations.original.shape[1]
|
| 331 |
+
else:
|
| 332 |
+
linear_ic = linear.weight.shape[1]
|
| 333 |
+
|
| 334 |
+
conv2d_oc = len(mask)
|
| 335 |
+
if linear_ic % conv2d_oc != 0:
|
| 336 |
+
raise AssertionError(
|
| 337 |
+
f"Flattening from dimensions {conv2d_oc} to {linear_ic} not supported"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
flatten_scale = linear_ic // conv2d_oc
|
| 341 |
+
flattened_mask = torch.tensor(
|
| 342 |
+
[[val] * flatten_scale for val in mask], dtype=torch.bool, device=mask.device
|
| 343 |
+
).flatten()
|
| 344 |
+
|
| 345 |
+
if getattr(conv2d, "prune_bias", False):
|
| 346 |
+
_prune_module_bias(conv2d, mask)
|
| 347 |
+
else:
|
| 348 |
+
pruned_biases = cast(Tensor, _propagate_module_bias(conv2d, mask))
|
| 349 |
+
flattened_pruned_biases = torch.tensor(
|
| 350 |
+
[[bias] * flatten_scale for bias in pruned_biases], device=mask.device
|
| 351 |
+
).flatten()
|
| 352 |
+
linear.bias = _get_adjusted_next_layer_bias(
|
| 353 |
+
linear, flattened_pruned_biases, flattened_mask
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
with torch.no_grad():
|
| 357 |
+
if parametrize.is_parametrized(linear):
|
| 358 |
+
parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
|
| 359 |
+
weight_parameterizations = cast(
|
| 360 |
+
ParametrizationList, parametrization_dict.weight
|
| 361 |
+
)
|
| 362 |
+
weight_parameterizations.original = nn.Parameter(
|
| 363 |
+
weight_parameterizations.original[:, flattened_mask]
|
| 364 |
+
)
|
| 365 |
+
linear.in_features = weight_parameterizations.original.shape[1]
|
| 366 |
+
else:
|
| 367 |
+
linear.weight = nn.Parameter(linear.weight[:, flattened_mask])
|
| 368 |
+
linear.in_features = linear.weight.shape[1]
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def prune_lstm_output_linear(
|
| 372 |
+
lstm: nn.LSTM, getitem: Callable, linear: nn.Linear
|
| 373 |
+
) -> None:
|
| 374 |
+
prune_lstm_output_layernorm_linear(lstm, getitem, None, linear)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def prune_lstm_output_layernorm_linear(
|
| 378 |
+
lstm: nn.LSTM,
|
| 379 |
+
getitem: Callable,
|
| 380 |
+
layernorm: nn.LayerNorm | None,
|
| 381 |
+
linear: nn.Linear,
|
| 382 |
+
) -> None:
|
| 383 |
+
for i in range(lstm.num_layers):
|
| 384 |
+
if parametrize.is_parametrized(lstm, f"weight_ih_l{i}"):
|
| 385 |
+
parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations)
|
| 386 |
+
weight_parameterizations = cast(
|
| 387 |
+
ParametrizationList, parametrization_dict[f"weight_ih_l{i}"]
|
| 388 |
+
)
|
| 389 |
+
mask = weight_parameterizations[0].mask
|
| 390 |
+
|
| 391 |
+
with torch.no_grad():
|
| 392 |
+
parametrize.remove_parametrizations(
|
| 393 |
+
lstm, f"weight_ih_l{i}", leave_parametrized=True
|
| 394 |
+
)
|
| 395 |
+
setattr(
|
| 396 |
+
lstm,
|
| 397 |
+
f"weight_ih_l{i}",
|
| 398 |
+
nn.Parameter(getattr(lstm, f"weight_ih_l{i}")[mask]),
|
| 399 |
+
)
|
| 400 |
+
setattr(
|
| 401 |
+
lstm,
|
| 402 |
+
f"bias_ih_l{i}",
|
| 403 |
+
nn.Parameter(getattr(lstm, f"bias_ih_l{i}")[mask]),
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
if parametrize.is_parametrized(lstm, f"weight_hh_l{i}"):
|
| 407 |
+
parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations)
|
| 408 |
+
weight_parameterizations = cast(
|
| 409 |
+
ParametrizationList, parametrization_dict[f"weight_hh_l{i}"]
|
| 410 |
+
)
|
| 411 |
+
mask = weight_parameterizations[0].mask
|
| 412 |
+
|
| 413 |
+
with torch.no_grad():
|
| 414 |
+
parametrize.remove_parametrizations(
|
| 415 |
+
lstm, f"weight_hh_l{i}", leave_parametrized=True
|
| 416 |
+
)
|
| 417 |
+
# splitting out hidden-hidden masks
|
| 418 |
+
W_hi, W_hf, W_hg, W_ho = torch.split(
|
| 419 |
+
getattr(lstm, f"weight_hh_l{i}"), lstm.hidden_size
|
| 420 |
+
)
|
| 421 |
+
M_hi, M_hf, M_hg, M_ho = torch.split(mask, lstm.hidden_size) # type: ignore[arg-type]
|
| 422 |
+
|
| 423 |
+
# resize each individual weight separately
|
| 424 |
+
W_hi = W_hi[M_hi][:, M_hi]
|
| 425 |
+
W_hf = W_hf[M_hf][:, M_hf]
|
| 426 |
+
W_hg = W_hg[M_hg][:, M_hg]
|
| 427 |
+
W_ho = W_ho[M_ho][:, M_ho]
|
| 428 |
+
|
| 429 |
+
# concat, use this as new weight
|
| 430 |
+
new_weight = torch.cat((W_hi, W_hf, W_hg, W_ho))
|
| 431 |
+
setattr(lstm, f"weight_hh_l{i}", nn.Parameter(new_weight))
|
| 432 |
+
setattr(
|
| 433 |
+
lstm,
|
| 434 |
+
f"bias_hh_l{i}",
|
| 435 |
+
nn.Parameter(getattr(lstm, f"bias_hh_l{i}")[mask]),
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
# If this is the final layer, then we need to prune linear layer columns
|
| 439 |
+
if i + 1 == lstm.num_layers:
|
| 440 |
+
lstm.hidden_size = int(M_hi.sum())
|
| 441 |
+
with torch.no_grad():
|
| 442 |
+
if parametrize.is_parametrized(linear):
|
| 443 |
+
parametrization_dict = cast(
|
| 444 |
+
nn.ModuleDict, linear.parametrizations
|
| 445 |
+
)
|
| 446 |
+
weight_parameterizations = cast(
|
| 447 |
+
ParametrizationList, parametrization_dict.weight
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
weight_parameterizations.original = nn.Parameter(
|
| 451 |
+
weight_parameterizations.original[:, M_ho]
|
| 452 |
+
)
|
| 453 |
+
linear.in_features = weight_parameterizations.original.shape[1]
|
| 454 |
+
else:
|
| 455 |
+
linear.weight = nn.Parameter(linear.weight[:, M_ho])
|
| 456 |
+
linear.in_features = linear.weight.shape[1]
|
| 457 |
+
|
| 458 |
+
# if layernorm module, prune weight and bias
|
| 459 |
+
if layernorm is not None:
|
| 460 |
+
layernorm.normalized_shape = (linear.in_features,)
|
| 461 |
+
layernorm.weight = nn.Parameter(layernorm.weight[M_ho])
|
| 462 |
+
layernorm.bias = nn.Parameter(layernorm.bias[M_ho])
|
| 463 |
+
|
| 464 |
+
# otherwise need to prune the columns of the input of the next LSTM layer
|
| 465 |
+
else:
|
| 466 |
+
with torch.no_grad():
|
| 467 |
+
if parametrize.is_parametrized(lstm, f"weight_ih_l{i + 1}"):
|
| 468 |
+
parametrization_dict = cast(
|
| 469 |
+
nn.ModuleDict, lstm.parametrizations
|
| 470 |
+
)
|
| 471 |
+
weight_parameterizations = cast(
|
| 472 |
+
ParametrizationList,
|
| 473 |
+
getattr(parametrization_dict, f"weight_ih_l{i + 1}"),
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
weight_parameterizations.original = nn.Parameter(
|
| 477 |
+
weight_parameterizations.original[:, M_ho]
|
| 478 |
+
)
|
| 479 |
+
else:
|
| 480 |
+
next_layer_weight = getattr(lstm, f"weight_ih_l{i + 1}")
|
| 481 |
+
setattr(
|
| 482 |
+
lstm,
|
| 483 |
+
f"weight_ih_l{i + 1}",
|
| 484 |
+
nn.Parameter(next_layer_weight[:, M_ho]),
|
| 485 |
+
)
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from .base_structured_sparsifier import BaseStructuredSparsifier
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class SaliencyPruner(BaseStructuredSparsifier):
|
| 6 |
+
"""
|
| 7 |
+
Prune rows based on the saliency (L1 norm) of each row.
|
| 8 |
+
|
| 9 |
+
This pruner works on N-Dimensional weight tensors.
|
| 10 |
+
For each row, we will calculate the saliency, which is the sum of the L1 norm of all weights in that row.
|
| 11 |
+
We expect that the resulting saliency vector has the same shape as our mask.
|
| 12 |
+
We then pick elements to remove until we reach the target sparsity_level.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def update_mask(self, module, tensor_name, **kwargs):
|
| 16 |
+
# tensor_name will give you the FQN, all other entries in sparse config is present in kwargs
|
| 17 |
+
weights = getattr(module, tensor_name)
|
| 18 |
+
mask = getattr(module.parametrizations, tensor_name)[0].mask
|
| 19 |
+
|
| 20 |
+
# use negative weights so we can use topk (we prune out the smallest)
|
| 21 |
+
if weights.dim() <= 1:
|
| 22 |
+
raise Exception( # noqa: TRY002
|
| 23 |
+
"Structured pruning can only be applied to a 2+dim weight tensor!"
|
| 24 |
+
)
|
| 25 |
+
saliency = -weights.norm(dim=tuple(range(1, weights.dim())), p=1)
|
| 26 |
+
if saliency.shape != mask.shape:
|
| 27 |
+
raise AssertionError(
|
| 28 |
+
f"saliency shape ({saliency.shape}) must match mask shape ({mask.shape})"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
num_to_pick = int(len(mask) * kwargs["sparsity_level"])
|
| 32 |
+
prune = saliency.topk(num_to_pick).indices
|
| 33 |
+
|
| 34 |
+
# Set the mask to be false for the rows we want to prune
|
| 35 |
+
mask.data[prune] = False
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/_mappings.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
__all__ = [
|
| 3 |
+
"get_static_sparse_quantized_mapping",
|
| 4 |
+
"get_dynamic_sparse_quantized_mapping",
|
| 5 |
+
]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_static_sparse_quantized_mapping():
|
| 9 |
+
import torch.ao.nn.sparse
|
| 10 |
+
|
| 11 |
+
_static_sparse_quantized_mapping = {
|
| 12 |
+
torch.nn.Linear: torch.ao.nn.sparse.quantized.Linear,
|
| 13 |
+
}
|
| 14 |
+
return _static_sparse_quantized_mapping
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_dynamic_sparse_quantized_mapping():
|
| 18 |
+
import torch.ao.nn.sparse
|
| 19 |
+
|
| 20 |
+
_dynamic_sparse_quantized_mapping = {
|
| 21 |
+
torch.nn.Linear: torch.ao.nn.sparse.quantized.dynamic.Linear,
|
| 22 |
+
}
|
| 23 |
+
return _dynamic_sparse_quantized_mapping
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (201 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-312.pyc
ADDED
|
Binary file (8.07 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-312.pyc
ADDED
|
Binary file (4.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-312.pyc
ADDED
|
Binary file (3.34 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/base_scheduler.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
import weakref
|
| 5 |
+
from functools import wraps
|
| 6 |
+
|
| 7 |
+
from torch.ao.pruning.sparsifier.base_sparsifier import BaseSparsifier
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = ["BaseScheduler"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class BaseScheduler:
|
| 14 |
+
def __init__(self, sparsifier, last_epoch=-1, verbose=False):
|
| 15 |
+
# Attach sparsifier
|
| 16 |
+
if not isinstance(sparsifier, BaseSparsifier):
|
| 17 |
+
raise TypeError(
|
| 18 |
+
f"{type(sparsifier).__name__} is not an instance of torch.ao.pruning.BaseSparsifier"
|
| 19 |
+
)
|
| 20 |
+
self.sparsifier = sparsifier
|
| 21 |
+
|
| 22 |
+
# Initialize epoch and base sparsity levels
|
| 23 |
+
|
| 24 |
+
self.base_sl = [group["sparsity_level"] for group in sparsifier.groups]
|
| 25 |
+
self.last_epoch = last_epoch
|
| 26 |
+
|
| 27 |
+
# Following https://github.com/pytorch/pytorch/issues/20124
|
| 28 |
+
# We would like to ensure that `scheduler.step()` is called after
|
| 29 |
+
# `sparsifier.step()`
|
| 30 |
+
def with_counter(method):
|
| 31 |
+
if getattr(method, "_with_counter", False):
|
| 32 |
+
# `sparsifier.step()` has already been replaced, return.
|
| 33 |
+
return method
|
| 34 |
+
|
| 35 |
+
# Keep a weak reference to the sparsifier instance to prevent
|
| 36 |
+
# cyclic references.
|
| 37 |
+
instance_ref = weakref.ref(method.__self__)
|
| 38 |
+
# Get the unbound method for the same purpose.
|
| 39 |
+
func = method.__func__
|
| 40 |
+
cls = instance_ref().__class__
|
| 41 |
+
del method
|
| 42 |
+
|
| 43 |
+
@wraps(func)
|
| 44 |
+
def wrapper(*args, **kwargs):
|
| 45 |
+
instance = instance_ref()
|
| 46 |
+
instance._step_count += 1 # type: ignore[union-attr]
|
| 47 |
+
wrapped = func.__get__(instance, cls)
|
| 48 |
+
return wrapped(*args, **kwargs)
|
| 49 |
+
|
| 50 |
+
# Note that the returned function here is no longer a bound method,
|
| 51 |
+
# so attributes like `__func__` and `__self__` no longer exist.
|
| 52 |
+
wrapper._with_counter = True # type: ignore[attr-defined]
|
| 53 |
+
return wrapper
|
| 54 |
+
|
| 55 |
+
self.sparsifier.step = with_counter(self.sparsifier.step) # type: ignore[assignment]
|
| 56 |
+
self.sparsifier._step_count = 0 # type: ignore[attr-defined]
|
| 57 |
+
self._step_count: int = 0
|
| 58 |
+
self.verbose = verbose
|
| 59 |
+
|
| 60 |
+
# Housekeeping
|
| 61 |
+
self._get_sl_called_within_step: bool = False
|
| 62 |
+
|
| 63 |
+
self.step()
|
| 64 |
+
|
| 65 |
+
def state_dict(self):
|
| 66 |
+
"""Returns the state of the scheduler as a :class:`dict`.
|
| 67 |
+
|
| 68 |
+
It contains an entry for every variable in self.__dict__ which
|
| 69 |
+
is not the sparsifier.
|
| 70 |
+
"""
|
| 71 |
+
return {
|
| 72 |
+
key: value for key, value in self.__dict__.items() if key != "sparsifier"
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
def load_state_dict(self, state_dict):
|
| 76 |
+
"""Loads the schedulers state.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
state_dict (dict): scheduler state. Should be an object returned
|
| 80 |
+
from a call to :meth:`state_dict`.
|
| 81 |
+
"""
|
| 82 |
+
self.__dict__.update(state_dict)
|
| 83 |
+
|
| 84 |
+
def get_last_sl(self):
|
| 85 |
+
"""Return last computed sparsity level by current scheduler."""
|
| 86 |
+
return self._last_sl
|
| 87 |
+
|
| 88 |
+
def get_sl(self):
|
| 89 |
+
# Compute sparsity level using chainable form of the scheduler
|
| 90 |
+
# Note: This method is not intended to be called directly, and is only
|
| 91 |
+
# used by the ".step" method. Use .get_last_sl() instead.
|
| 92 |
+
if not self._get_sl_called_within_step:
|
| 93 |
+
warnings.warn(
|
| 94 |
+
"To get the last sparsity level computed by the scheduler, "
|
| 95 |
+
"please use `get_last_sl()`.",
|
| 96 |
+
stacklevel=2,
|
| 97 |
+
)
|
| 98 |
+
raise NotImplementedError
|
| 99 |
+
|
| 100 |
+
def print_sl(self, is_verbose, group, sl, epoch=None):
|
| 101 |
+
"""Display the current sparsity level."""
|
| 102 |
+
if is_verbose:
|
| 103 |
+
if epoch is None:
|
| 104 |
+
print(f"Adjusting sparsity level of group {group} to {sl:.4e}.")
|
| 105 |
+
else:
|
| 106 |
+
print(
|
| 107 |
+
f"Epoch {epoch:5d}: adjusting sparsity level of group {group} to {sl:.4e}."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
def __repr__(self):
|
| 111 |
+
format_string = self.__class__.__name__ + " ("
|
| 112 |
+
format_string += "\n"
|
| 113 |
+
format_string += f"Sparsifier {self.sparsifier}\n"
|
| 114 |
+
format_string += f" base_sl: {self.base_sl}\n"
|
| 115 |
+
format_string += ")"
|
| 116 |
+
return format_string
|
| 117 |
+
|
| 118 |
+
def step(self, epoch=None):
|
| 119 |
+
# Raise warning if trying to call scheduler step before the sparsifier.
|
| 120 |
+
# https://github.com/pytorch/pytorch/issues/20124
|
| 121 |
+
if self._step_count == 1:
|
| 122 |
+
if not hasattr(self.sparsifier.step, "_with_counter"):
|
| 123 |
+
warnings.warn(
|
| 124 |
+
"Seems like `sparsifier.step()` has been overridden after sparsity scheduler "
|
| 125 |
+
"initialization. Please, make sure to call `sparsifier.step()` before "
|
| 126 |
+
"`scheduler.step()`.",
|
| 127 |
+
UserWarning,
|
| 128 |
+
stacklevel=2,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Just check if there were two first scheduler.step() calls before sparsifier.step()
|
| 132 |
+
elif self.sparsifier._step_count < 1: # type: ignore[attr-defined]
|
| 133 |
+
warnings.warn(
|
| 134 |
+
"Detected call of `scheduler.step()` before `sparsifier.step()`. "
|
| 135 |
+
"You have to make sure you run the sparsifier.step() BEFORE any "
|
| 136 |
+
"calls to the scheduler.step().",
|
| 137 |
+
UserWarning,
|
| 138 |
+
stacklevel=2,
|
| 139 |
+
)
|
| 140 |
+
self._step_count += 1
|
| 141 |
+
|
| 142 |
+
class _enable_get_sl_call:
|
| 143 |
+
def __init__(self, o):
|
| 144 |
+
self.o = o
|
| 145 |
+
|
| 146 |
+
def __enter__(self):
|
| 147 |
+
self.o._get_sl_called_within_step = True
|
| 148 |
+
return self
|
| 149 |
+
|
| 150 |
+
def __exit__(self, type, value, traceback):
|
| 151 |
+
self.o._get_sl_called_within_step = False
|
| 152 |
+
|
| 153 |
+
with _enable_get_sl_call(self):
|
| 154 |
+
self.last_epoch += 1
|
| 155 |
+
values = self.get_sl()
|
| 156 |
+
|
| 157 |
+
for i, data in enumerate(zip(self.sparsifier.groups, values)):
|
| 158 |
+
param_group, sl = data
|
| 159 |
+
param_group["sparsity_level"] = sl
|
| 160 |
+
self.print_sl(self.verbose, i, sl, epoch)
|
| 161 |
+
|
| 162 |
+
self._last_sl = [group["sparsity_level"] for group in self.sparsifier.groups]
|
| 163 |
+
self.sparsifier.enable_mask_update = True
|
| 164 |
+
|
| 165 |
+
def _make_sure_a_list(self, var):
|
| 166 |
+
r"""Utility that extends it to the same length as the .groups, ensuring it is a list"""
|
| 167 |
+
n = len(self.sparsifier.groups)
|
| 168 |
+
if not isinstance(var, (list, tuple)):
|
| 169 |
+
return [var] * n
|
| 170 |
+
else:
|
| 171 |
+
if len(var) != n:
|
| 172 |
+
raise ValueError(f"Expected variable of length {n}, but got {len(var)}")
|
| 173 |
+
return list(var) # We want the result to be in a list, not tuple
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
from .base_scheduler import BaseScheduler
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["CubicSL"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _clamp(x, lo, hi):
|
| 11 |
+
return max(lo, min(hi, x))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class CubicSL(BaseScheduler):
|
| 15 |
+
r"""Sets the sparsity level of each parameter group to the final sl
|
| 16 |
+
plus a given exponential function.
|
| 17 |
+
|
| 18 |
+
.. math::
|
| 19 |
+
|
| 20 |
+
s_i = s_f + (s_0 - s_f) \cdot \left( 1 - \frac{t - t_0}{n\Delta t} \right)^3
|
| 21 |
+
|
| 22 |
+
where :math:`s_i` is the sparsity at epoch :math:`t`, :math;`s_f` is the final
|
| 23 |
+
sparsity level, :math:`f(i)` is the function to be applied to the current epoch
|
| 24 |
+
:math:`t`, initial epoch :math:`t_0`, and final epoch :math:`t_f`.
|
| 25 |
+
:math:`\Delta t` is used to control how often the update of the sparsity level
|
| 26 |
+
happens. By default,
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
sparsifier (BaseSparsifier): Wrapped sparsifier.
|
| 30 |
+
init_sl (int, list): Initial level of sparsity
|
| 31 |
+
init_t (int, list): Initial step, when pruning starts
|
| 32 |
+
delta_t (int, list): Pruning frequency
|
| 33 |
+
total_t (int, list): Total number of pruning steps
|
| 34 |
+
initially_zero (bool, list): If True, sets the level of sparsity to 0
|
| 35 |
+
before init_t (:math:`t_0`). Otherwise, the sparsity level before
|
| 36 |
+
init_t (:math:`t_0`) is set to init_sl(:math:`s_0`)
|
| 37 |
+
last_epoch (int): The index of last epoch. Default: -1.
|
| 38 |
+
verbose (bool): If ``True``, prints a message to stdout for
|
| 39 |
+
each update. Default: ``False``.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
sparsifier,
|
| 45 |
+
init_sl=0.0,
|
| 46 |
+
init_t=0,
|
| 47 |
+
delta_t=10,
|
| 48 |
+
total_t=100,
|
| 49 |
+
initially_zero=False,
|
| 50 |
+
last_epoch=-1,
|
| 51 |
+
verbose=False,
|
| 52 |
+
):
|
| 53 |
+
self.sparsifier = sparsifier
|
| 54 |
+
|
| 55 |
+
self.init_sl = self._make_sure_a_list(init_sl)
|
| 56 |
+
self.init_t = self._make_sure_a_list(init_t)
|
| 57 |
+
self.delta_t = self._make_sure_a_list(delta_t)
|
| 58 |
+
self.total_t = self._make_sure_a_list(total_t)
|
| 59 |
+
|
| 60 |
+
self.initially_zero = self._make_sure_a_list(initially_zero)
|
| 61 |
+
|
| 62 |
+
super().__init__(sparsifier, last_epoch, verbose)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def sparsity_compute_fn(s_0, s_f, t, t_0, dt, n, initially_zero=False):
|
| 66 |
+
r""" "Computes the current level of sparsity.
|
| 67 |
+
|
| 68 |
+
Based on https://arxiv.org/pdf/1710.01878.pdf
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
s_0: Initial level of sparsity, :math:`s_i`
|
| 72 |
+
s_f: Target level of sparsity, :math:`s_f`
|
| 73 |
+
t: Current step, :math:`t`
|
| 74 |
+
t_0: Initial step, :math:`t_0`
|
| 75 |
+
dt: Pruning frequency, :math:`\Delta T`
|
| 76 |
+
n: Pruning steps, :math:`n`
|
| 77 |
+
initially_zero: Sets the level of sparsity to 0 before t_0.
|
| 78 |
+
If False, sets to s_0
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
The sparsity level :math:`s_t` at the current step :math:`t`
|
| 82 |
+
"""
|
| 83 |
+
if initially_zero and t < t_0:
|
| 84 |
+
return 0
|
| 85 |
+
s_t = s_f + (s_0 - s_f) * (1.0 - (t - t_0) / (dt * n)) ** 3
|
| 86 |
+
s_t = _clamp(s_t, s_0, s_f)
|
| 87 |
+
return s_t
|
| 88 |
+
|
| 89 |
+
def get_sl(self):
|
| 90 |
+
if not self._get_sl_called_within_step:
|
| 91 |
+
warnings.warn(
|
| 92 |
+
"To get the last sparsity level computed by the scheduler, "
|
| 93 |
+
"please use `get_last_sl()`.",
|
| 94 |
+
stacklevel=2,
|
| 95 |
+
)
|
| 96 |
+
return [
|
| 97 |
+
self.sparsity_compute_fn(
|
| 98 |
+
s_0=initial_sparsity,
|
| 99 |
+
s_f=final_sparsity,
|
| 100 |
+
t=self.last_epoch,
|
| 101 |
+
t_0=initial_epoch,
|
| 102 |
+
dt=delta_epoch,
|
| 103 |
+
n=interval_epochs,
|
| 104 |
+
initially_zero=initially_zero,
|
| 105 |
+
)
|
| 106 |
+
for initial_sparsity, final_sparsity, initial_epoch, delta_epoch, interval_epochs, initially_zero in zip(
|
| 107 |
+
self.init_sl,
|
| 108 |
+
self.base_sl,
|
| 109 |
+
self.init_t,
|
| 110 |
+
self.delta_t,
|
| 111 |
+
self.total_t,
|
| 112 |
+
self.initially_zero,
|
| 113 |
+
)
|
| 114 |
+
]
|
.venv/lib/python3.12/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
|
| 4 |
+
from torch.ao.pruning.sparsifier.base_sparsifier import BaseSparsifier
|
| 5 |
+
|
| 6 |
+
from .base_scheduler import BaseScheduler
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ["LambdaSL"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LambdaSL(BaseScheduler):
|
| 13 |
+
"""Sets the sparsity level of each parameter group to the final sl
|
| 14 |
+
times a given function. When last_epoch=-1, sets initial sl as zero.
|
| 15 |
+
Args:
|
| 16 |
+
sparsifier (BaseSparsifier): Wrapped sparsifier.
|
| 17 |
+
sl_lambda (function or list): A function which computes a multiplicative
|
| 18 |
+
factor given an integer parameter epoch, or a list of such
|
| 19 |
+
functions, one for each group in sparsifier.param_groups.
|
| 20 |
+
last_epoch (int): The index of last epoch. Default: -1.
|
| 21 |
+
verbose (bool): If ``True``, prints a message to stdout for
|
| 22 |
+
each update. Default: ``False``.
|
| 23 |
+
Example:
|
| 24 |
+
>>> # Assuming sparsifier has two groups.
|
| 25 |
+
>>> lambda1 = lambda epoch: epoch // 30
|
| 26 |
+
>>> lambda2 = lambda epoch: 0.95**epoch
|
| 27 |
+
>>> # xdoctest: +SKIP
|
| 28 |
+
>>> scheduler = LambdaSL(sparsifier, sl_lambda=[lambda1, lambda2])
|
| 29 |
+
>>> for epoch in range(100):
|
| 30 |
+
>>> train(...)
|
| 31 |
+
>>> validate(...)
|
| 32 |
+
>>> scheduler.step()
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
sparsifier: BaseSparsifier,
|
| 38 |
+
sl_lambda: Callable[[int], float] | list[Callable[[int], float]],
|
| 39 |
+
last_epoch: int = -1,
|
| 40 |
+
verbose: bool = False,
|
| 41 |
+
) -> None:
|
| 42 |
+
self.sparsifier = sparsifier
|
| 43 |
+
|
| 44 |
+
if not isinstance(sl_lambda, list) and not isinstance(sl_lambda, tuple):
|
| 45 |
+
self.sl_lambdas = [sl_lambda] * len(sparsifier.groups)
|
| 46 |
+
else:
|
| 47 |
+
if len(sl_lambda) != len(sparsifier.groups):
|
| 48 |
+
raise ValueError(
|
| 49 |
+
f"Expected {len(sparsifier.groups)} lr_lambdas, but got {len(sl_lambda)}"
|
| 50 |
+
)
|
| 51 |
+
self.sl_lambdas = list(sl_lambda)
|
| 52 |
+
super().__init__(sparsifier, last_epoch, verbose) # type: ignore[no-untyped-call]
|
| 53 |
+
|
| 54 |
+
def get_sl(self) -> list[float]:
|
| 55 |
+
if not self._get_sl_called_within_step:
|
| 56 |
+
warnings.warn(
|
| 57 |
+
"To get the last sparsity level computed by the scheduler, "
|
| 58 |
+
"please use `get_last_sl()`.",
|
| 59 |
+
stacklevel=2,
|
| 60 |
+
)
|
| 61 |
+
return [
|
| 62 |
+
base_sl * lmbda(self.last_epoch)
|
| 63 |
+
for lmbda, base_sl in zip(self.sl_lambdas, self.base_sl)
|
| 64 |
+
]
|