A unified framework for Pruning in Pytorch
Project description
UniP
A unified framework for Multi-Modality Pruning
Requirements
torchtorchvisionnumpytqdmthop- (optional)
pynvmlpyRAPLjtoptorch2onnxdeform_conv2d_onnx_exporter
Install from source
pip install -U unip
Minimal Example
import torch
import torchvision.models as models
from unip.core.pruner import BasePruner
from unip.utils.evaluation import cal_flops
# load model and example input
model = models.resnet18()
example_input = torch.rand(1, 3, 224, 224, requires_grad=True)
# record the flops and params
cal_flops(model, example_input, device)
# define pruner
BP = BasePruner(
model,
example_input,
"UniformRatio",
algo_args={"score_fn": "weight_sum_l1_out"},
)
pruner.prune(0.3)
# record the flops and params
cal_flops(model, example_input, device)
Advanced Example
import sys
sys.path.append("./tests")
import torch
from model.radarnet import RCNet
from model.backbone.conv_utils.dcn import DeformableConv2d
from unip.core.pruner import BasePruner
from unip.utils.evaluation import cal_flops
# RCNet need more customized node for deformable conv
from unip.core.node import dcnNode
# load model and example input
model = RCNet(in_channels=3)
example_input = torch.randn(1, 3, 320, 320, requires_grad=True)
# record the flops and params
cal_flops(model, example_input)
# define a dict indicate the module with node
igtype2nodetype = {DeformableConv2d: dcnNode}
# define pruner
BP = BasePruner(
model,
example_input,
"UniformRatio",
algo_args={"score_fn": "weight_sum_l1_out"},
igtype2nodetype=igtype2nodetype,
)
BP.prune(0.3)
# record the flops and params
cal_flops(model, example_input, device)
More examples
Please refer to the ./tutorials folder for more examples.
Troubleshooting
Report a bug
Before report bugs by opening an issue in the GitHub Issue Tracker, you may follow the instructions of test_Unip README.md. Basically, you need to provide the following information:
- the model you want to prune
- an example inference Once you new a issue, we will fix it as soon as possible.
Contributions
You are welcome to contribute to this project. Please follow the Contribution Guide.
Support List
- Nodes for operations:
BaseNode: Base class for all other nodesInOutNode: Node for conv, linear, and bundle parametersOutOutNode: Node for bn, ln, gn, and dwconvInInNode: Node for add, sub, mul, and divRemapNode: Node for concat, split, and sliceChangeNode: Node for reshape, permute, expand, transpose, matmul, and upsampleDummyNode: Node for dummy input and outputActivationNode: Node for activationPoolNode: Node for adaptive pooling, max pooling, and average poolingCustomNode: Node for custom module
- Algorithm:
BaseAlgo: Base class for all other algorithmsRandomAlgo: Random ratio and indexUniformAlgo: Uniform ratio and random index
- Tested models:
- classification:
- GoogleNet
- VGG
- ResNet, WideResNet,
- MobileNetV2, MobileNetV3
- EfficientNet, EfficientNetV2
- SqueezeNet
- mobilevit
- achelous
- Edge_end_Multi_model_Visual_Grounding_Framework
- classification:
- Tested modules:
- conv: basic conv, depth-wise conv, deformable conv (with Custom Node
dcnNode) - linear: basic linear, linear with input more than 2 dimensions
- calculation operators: concat, split, slice, reshape, permute, expand, transpose, matmul, upsample, add, sub, div, mul, squeeze, unsqueeze
- fired design: residual, ghost module, attention, shuffle attention
- conv: basic conv, depth-wise conv, deformable conv (with Custom Node
- support backwards type
- ConvolutionBackward0
- AddmmBackward0, MmBackward0, BmmBackward0
- AddBackward0, SubBackward0, MulBackward0, DivBackward0
- NativeBatchNormBackward0, NativeLayerNormBackward0, NativeGroupNormBackward0
- CatBackward0, SplitBackward0, SliceBackward0
- ReshapeAliasBackward0, UnsafeViewBackward0, ViewBackward0, PermuteBackward0, ExpandBackward0, TransposeBackward0, SqueezeBackward1, UnsqueezeBackward0,
- MeanBackward1, MaxPool2DWithIndicesBackward0, AvgPool2DBackward0, UpsampleBilinear2DBackward0, UpsampleNearest2DBackward0, UpsampleBicubic2DBackward0
- ReluBackward0, SiluBackward0, GeluBackward0, HardswishBackward0, SigmoidBackward0, TanhBackward0, SoftmaxBackward0, LogSoftmaxBackward0
- AccumulateGrad, TBackward0, CloneBackward0
- RepeatBackward0
- EmbeddingBackward0
- AsStridedBackward0
- CopySlices
- UnsafeSplitBackward0
- UnbindBackward0
- IndexBackward0
- SqueezeBackward0
- MaxBackward0
- UnsafeSplitBackward0
- StackBackward0
- TransposeBackward1
Bugs
- when
in_channelsgreater thangroups - when operation
convandfcdoes not usePyTorchmodule implementation - fix the bug of useless
split, when the prev_node's group isnon-prunable -
TransposeConverror - for some nodes starting from a non-
Input, the dim_offset is wrong -
ConcatNodeis the next ofReshapeNode -
nn.MultiheadAttentionmodule not working: fixed by addingCustomNode - RCNet may failed cuz the residual with input
- fix the bug for
DCNmodule: usedcnNode - fix the bug for such module like GhostModule, use Non-
InOutNodebeforeOutputNode - does not prune the
LastLienarNodeforto_qkvlike module - need to fix the
round_tolike attribute forto_qkvlike module -
dim_offsetfor reshape node is not always correct
Energy Calculation Part
Requirements
pynvml: 11.5.0pyRAPL: 0.2.3.1
Note: require to give read permission to the specific file:
sudo chmod -R a+r /sys/class/powercap/intel-rapl
Example: calculation of whole model
import torch
import torchvision.models as models
from unip.utils.energy import Calculator
# define a device dict
device_dict = {
"NvidiaDev": {'device_id': 0},
"IntelDev": {},
}
calculator = Calculator(device_dict)
model = models.resnet18()
model.eval().cuda()
example_input = torch.randn(1, 3, 224, 224).cuda()
@calculator.measure(times=1000)
def inference(model, example_input):
model(example_input)
inference(model, example_input)
Example: calculation of single module
import torch
import torchvision.models as models
from unip.utils.energy import Calculator
calculator = Calculator(cpu=False, device_id=4)
model = models.resnet18()
model.eval().cuda()
def forward_hook_record_input(module, input, output):
setattr(module, "input", input[0])
hook = model.layer1.register_forward_hook(forward_hook_record_input)
example_input = torch.randn(1, 3, 224, 224).cuda()
model(example_input)
hook.remove()
@calculator.measure(times=100)
def inference(model, example_input):
model(example_input)
inference(module, torch.randn_like(module.input))
Change Log
v1.0.5: 2023-09-01 Fix bugs for v1.0.4, add features, and optimize the project (on-going)
- new features:
- add better inheritance for
Multi-Modality Pruning - add
github wikipage for better documentation - add
tutorial/examples/*for better usage
- add better inheritance for
- changes:
- add examples in
./tutorial/examples - optimize
energy.pyfor jetson - optimize
evaluation.pyfor fps
- add examples in
- bug fixing:
- fix the bug of useless
split, when the prev_node's group isnon-prunable
- fix the bug of useless
v1.0.4: 2023-08-25 Fix bugs for v1.0.3, add features, and optimize the project
- new features:
- add support for
torch 1.xx.xx - add
prune_transposeconvtoprune_ops.py - add
utils/validate.pyfor some handy functions to test new model - add
RePeatBackward0andRepeatNode - add
deploy.py
- add support for
- changes:
- change the
fclayer detection forAddBackward0incore/pruner.py - add
nn.Dropoutlayer detection, and pass the grad_fn - optimize the
prune()function forInoutNode - optimize the
in_shapeandout_shapeofConcatNode - optimize and add
splitattribute toReshapeNodeforchannel shuffle - optimize the
RatioAlgo, and fixed the bug.
- change the
- bug fixing:
- fix the bug for
ConcatNodeis the next ofReshapeNode nn.MultiheadAttentionmodule not working, addCustomNodefor it- for some nodes starting from a non-
Input, the dim_offset is wrong: we ignore the nodes TransposeConverror
- fix the bug for
v1.0.3: 2023-08-21 Fix bugs for v1.0.2 and optimize the project
-
new features:
- add
energycalculation forNVIDIAGPU andIntelCPU: Note: require to give read permission to the specific file:sudo chmod -R a+r /sys/class/powercap/intel-rapl
This may has some problem, as it could not record the simutaneous energy consumption. Besides, it need to be changed to multi-thread version. - add example code for
energycalculation inREADME.MD - add model saving and loading methods
- add
weight_sum_l1_outscore function - add
name2node,name2score, andname2algo
- add
-
changes:
- organize the
BaseAlgofor better inheritance- add
RatioAlgoandGlobalAlgoas the lower level ofBaseAlgo - change
UniformAlgoandRandomAlgoas the lower level ofRatioAlgo - add
paramattributeNodefor Algorithm score function - rename the Third-level class of
BaseAlgotoUnifomRatioandRandomRatio
- add
- optimize the node for better saving and loading strategy
- organize the
./ttlfolder for better example- change
./ttlto./tutorials - some key actions are added to the
./tutorials/utilsfolder - the
./tutorials/examplesfolder will be used for the example usage of UniP
- change
- organize the
./testfolder for better test
- organize the
-
bug fixing:
- fix the bug of RCNet: may failed cuz the residual with input
v1.0.2: 2023-08-14 Fix bugs for v1.0.1 and add features
- new features:
- add
ignore_listfor some unwanted and unsupported modules - add
CustomNodefor custom module - add support for
SliceBackward0 - add support for
SqueezeBackward1andUnsqueezeBackward0 - add support for
UpsampleBilinear2DBackward0,UpsampleNearest2DBackward0,UpsampleBicubic2DBackward0 - add support for
GhostModuleas theSlicenode is supported
- add
- changes:
- remove the
hasdummy, and search the prev_node ofDummyNodeinBaseGroupinstead - change
update_dim_offsetmethod
- remove the
- bug fixing:
- fix the bug for
DCNmodule: usedcnNode - fix the bug for such module like GhostModule, use Non-
InOutNodebeforeOutputNode
- fix the bug for
v1.0.1: 2023-08-13 Fix bugs for v1.0.0 and add features
- new features:
- new dim change calculation method as patches for
ReshapeNode
- new dim change calculation method as patches for
- changes:
- move
MatmulNodetoChangeNodefromInInNodeas its previous node could not be in the same group
- move
- bug fixing:
- does not prune the
LastLienarNodeforto_qkvlike module - need to fix the
round_tolike attribute forto_qkvlike module dim_offsetfor reshape node is not always correct
- does not prune the
v1.0.0: 2023-08-10 Finish the basic framework of UniP
- Add nodes definition:
BaseNode,InOutNode,OutOutNode,InInNode,RemapNode,ChangeNode,DummyNode,ActivationNode,PoolNodeandCustomNode - Add groups definition:
BaseGroup,CurrentGroup, andNextGroup - Add algorithm definition:
BaseAlgo,RandomAlgo, andUniformAlgo - Add pruner
- Add three example models to test the framework
- Add module pruning functions: conv, linear, bn, and bundle parameters
Acknowledge
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file Unified-Pruning-1.0.5.tar.gz.
File metadata
- Download URL: Unified-Pruning-1.0.5.tar.gz
- Upload date:
- Size: 24.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.9.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
aacc363e68904a6e8547432648a3f0f8bfb29c300478d1e7e749c5c305d929fe
|
|
| MD5 |
bd48b50495da19ace98fcbf4139372a6
|
|
| BLAKE2b-256 |
5996a4be5867959297852e43c5c6243f4d30bb15bab820e8f0ca7362548d4d76
|
File details
Details for the file Unified_Pruning-1.0.5-py3-none-any.whl.
File metadata
- Download URL: Unified_Pruning-1.0.5-py3-none-any.whl
- Upload date:
- Size: 25.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.9.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
70207df4fcd103a4885be6eda58643e1b8227e01cc25272a15a703587fd73522
|
|
| MD5 |
d16199310888948a00da93bedfa3e30e
|
|
| BLAKE2b-256 |
f6b4e103ae9fb8ed0ff95b13b41a8946f24f24301d96205b9e8d566561dac81f
|