MMRazor: a model compression toolkit for model slimming and AutoML

Related tags

Deep Learningmmrazor
Overview

PyPI - Python Version PyPI docs badge codecov license issue resolution open issues

Documentation: https://mmrazor.readthedocs.io/

English | 简体中文

Introduction

MMRazor is a model compression toolkit for model slimming and AutoML, which includes 3 mainstream technologies:

  • Neural Architecture Search (NAS)
  • Pruning
  • Knowledge Distillation (KD)
  • Quantization (in the next release)

It is a part of the OpenMMLab project.

Major features:

  • Compatibility

    MMRazor can be easily applied to various projects in OpenMMLab, due to similar architecture design of OpenMMLab as well as the decoupling of slimming algorithms and vision tasks.

  • Flexibility

    Different algorithms, e.g., NAS, pruning and KD, can be incorporated in a plug-n-play manner to build a more powerful system.

  • Convenience

    With better modular design, developers can implement new model compression algorithms with only a few codes, or even by simply modifying config files.

Below is an overview of MMRazor's design and implementation, please refer to tutorials for more details.


License

This project is released under the Apache 2.0 license.

Changelog

v0.1.0 was released in 12/23/2021.

Benchmark and model zoo

Results and models are available in the model zoo.

Installation

Please refer to get_started.md for installation.

Getting Started

Please refer to train.md and test.md for the basic usage of MMRazor. There are also tutorials:

Citation

If you find this project useful in your research, please consider cite:

@misc{2021mmrazor,
    title={OpenMMLab Model Compression Toolbox and Benchmark},
    author={MMRazor Contributors},
    howpublished = {\url{https://github.com/open-mmlab/mmrazor}},
    year={2021}
}

Contributing

We appreciate all contributions to improve MMRazor. Please refer to CONTRUBUTING.md for the contributing guideline.

Acknowledgement

MMRazor is an open source project that is contributed by researchers and engineers from various colleges and companies. We appreciate all the contributors who implement their methods or add new features, as well as users who give valuable feedbacks. We wish that the toolbox and benchmark could serve the growing research community by providing a flexible toolkit to reimplement existing methods and develop their own new model compression methods.

Projects in OpenMMLab

  • MMCV: OpenMMLab foundational library for computer vision.
  • MIM: MIM Installs OpenMMLab Packages.
  • MMClassification: OpenMMLab image classification toolbox and benchmark.
  • MMDetection: OpenMMLab detection toolbox and benchmark.
  • MMDetection3D: OpenMMLab next-generation platform for general 3D object detection.
  • MMSegmentation: OpenMMLab semantic segmentation toolbox and benchmark.
  • MMAction2: OpenMMLab next-generation action understanding toolbox and benchmark.
  • MMTracking: OpenMMLab video perception toolbox and benchmark.
  • MMPose: OpenMMLab pose estimation toolbox and benchmark.
  • MMEditing: OpenMMLab image and video editing toolbox.
  • MMOCR: OpenMMLab toolbox for text detection, recognition and understanding.
  • MMGeneration: OpenMMlab toolkit for generative models.
  • MMFlow OpenMMLab optical flow toolbox and benchmark.
  • MMFewShot: OpenMMLab FewShot Learning Toolbox and Benchmark.
  • MMHuman3D: OpenMMLab 3D Human Parametric Model Toolbox and Benchmark.
  • MMSelfSup: OpenMMLab self-supervised learning Toolbox and Benchmark.
  • MMRazor: OpenMMLab Model Compression Toolbox and Benchmark.
Comments
  • How to make pruner to support FPN like structure?

    How to make pruner to support FPN like structure?

    I am trying to prune from mmdet (https://github.com/open-mmlab/mmdetection/blob/master/configs/atss/atss_r50_fpn_1x_coco.py)

    But it throw the exception when forwarding with FPN.

    image

    Any idea?

    By the way, I think it's better to let users to configure the whole block as a group (like neck and bbox_head) which sharing the mask, since these blocks are always complicated, and the parsers are hard to modify to deal with these cases.

    bug 
    opened by twmht 23
  • use autoslim for yolox

    use autoslim for yolox

    I make a config for yolox to use autoslim, but get an error:

    error:

    Traceback (most recent call last): File "tools/mmdet/train_mmdet.py", line 199, in main() File "tools/mmdet/train_mmdet.py", line 175, in main datasets = [build_dataset(cfg.data.train)] File "/home/yangmin/share/openmmlab/mmdetection/mmdet/datasets/builder.py", line 77, in build_dataset dataset = MultiImageMixDataset(**cp_cfg) TypeError: init() got an unexpected keyword argument 'ann_file'

    config

    ########################################### base = [ '../../base/datasets/mmdet/coco_detection.py', '../../base/schedules/mmdet/schedule_1x.py', '../../base/mmdet_runtime.py' ]

    img_scale = (640, 640)

    model = dict( type='mmdet.YOLOX', input_size=img_scale, random_size_range=(15, 25), random_size_interval=10, backbone=dict(type='CSPDarknet', deepen_factor=0.33, widen_factor=0.5), neck=dict( type='YOLOXPAFPN', in_channels=[128, 256, 512], out_channels=128, num_csp_blocks=1), bbox_head=dict( type='YOLOXHead', num_classes=80, in_channels=128, feat_channels=128), train_cfg=dict(assigner=dict(type='SimOTAAssigner', center_radius=2.5)), # In order to align the source code, the threshold of the val phase is # 0.01, and the threshold of the test phase is 0.001. test_cfg=dict(score_thr=0.01, nms=dict(type='nms', iou_threshold=0.65)))

    data_root = 'data/coco/' dataset_type = 'CocoDataset'

    train_pipeline = [ dict(type='Mosaic', img_scale=img_scale, pad_val=114.0), dict( type='RandomAffine', scaling_ratio_range=(0.1, 2), border=(-img_scale[0] // 2, -img_scale[1] // 2)), dict( type='MixUp', img_scale=img_scale, ratio_range=(0.8, 1.6), pad_val=114.0), dict(type='YOLOXHSVRandomAug'), dict(type='RandomFlip', flip_ratio=0.5), # According to the official implementation, multi-scale # training is not considered here but in the # 'mmdet/models/detectors/yolox.py'. dict(type='Resize', img_scale=img_scale, keep_ratio=True), dict( type='Pad', pad_to_square=True, # If the image is three-channel, the pad value needs # to be set separately for each channel. pad_val=dict(img=(114.0, 114.0, 114.0))), dict(type='FilterAnnotations', min_gt_bbox_wh=(1, 1), keep_empty=False), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']) ]

    train_dataset = dict( type='MultiImageMixDataset', dataset=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_train2017.json', img_prefix=data_root + 'train2017/', pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True) ], filter_empty_gt=False, ), pipeline=train_pipeline)

    test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=img_scale, flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Pad', pad_to_square=True, pad_val=dict(img=(114.0, 114.0, 114.0))), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img']) ]) ]

    data = dict( samples_per_gpu=8, workers_per_gpu=4, persistent_workers=True, train=train_dataset, val=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/instances_val2017.json', img_prefix=data_root + 'val2017/', pipeline=test_pipeline))

    optimizer = dict( type='SGD', lr=0.01, momentum=0.9, weight_decay=5e-4, nesterov=True, paramwise_cfg=dict(norm_decay_mult=0., bias_decay_mult=0.)) optimizer_config = dict(grad_clip=None)

    max_epochs = 300 num_last_epochs = 15 resume_from = None interval = 10

    lr_config = dict( delete=True, policy='YOLOX', warmup='exp', by_epoch=False, warmup_by_epoch=True, warmup_ratio=1, warmup_iters=5, # 5 epoch num_last_epochs=num_last_epochs, min_lr_ratio=0.05)

    runner = dict(type='EpochBasedRunner', max_epochs=max_epochs)

    custom_hooks = [ dict( type='YOLOXModeSwitchHook', num_last_epochs=num_last_epochs, priority=48), dict( type='SyncNormHook', num_last_epochs=num_last_epochs, interval=interval, priority=48), dict( type='ExpMomentumEMAHook', resume_from=resume_from, momentum=0.0001, priority=49) ] checkpoint_config = dict(interval=interval) evaluation = dict( save_best='auto', # The evaluation interval is 'interval' when running epoch is # less than ‘max_epochs - num_last_epochs’. # The evaluation interval is 1 when running epoch is greater than # or equal to ‘max_epochs - num_last_epochs’. interval=interval, dynamic_intervals=[(max_epochs - num_last_epochs, 1)], metric='bbox') log_config = dict(interval=50)

    algorithm = dict( type='AutoSlim', architecture=dict(type='MMDetArchitecture', model=model), #distiller=dict( # type='SelfDistiller', # components=[ # dict( # student_module='bbox_head.cls_score', # teacher_module='bbox_head.cls_score', # losses=[ # dict( # type='KLDivergence', # name='loss_kd', # tau=1, # loss_weight=1, # ) # ]), # ]), pruner=dict( type='RatioPruner', ratios=(2 / 12, 3 / 12, 4 / 12, 5 / 12, 6 / 12, 7 / 12, 8 / 12, 9 / 12, 10 / 12, 11 / 12, 1.0)), retraining=False, bn_training_mode=True, input_shape=None)

    runner = dict(type='EpochBasedRunner', max_epochs=50)

    use_ddp_wrapper = True ###############################

    opened by NickYangMin 22
  • [Bug] 'AutoSlim' object has no attribute 'channel_cfg'

    [Bug] 'AutoSlim' object has no attribute 'channel_cfg'

    Describe the bug

    Refer to Pruning-Split Checkpoint(Optional) for the following command:

    $ python ./tools/model_converters/split_checkpoint.py \
    >   configs/pruning/autoslim/autoslim_mbv2_supernet_8xb256_ci10.py \
    >   output/epoch_49.pth \
    >   --channel-cfgs output/subnet_497881198.yaml,output/subnet_297081551.yaml,output/subnet_197465826.yaml
    load checkpoint from local path: output/epoch_49.pth
    Traceback (most recent call last):
      File "./tools/model_converters/split_checkpoint.py", line 69, in <module>
        main()
      File "./tools/model_converters/split_checkpoint.py", line 60, in main
        algorithm.channel_cfg[i])
      File "/home/tanghuayang/venv_torch/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 948, in __getattr__
        type(self).__name__, name))
    AttributeError: 'AutoSlim' object has no attribute 'channel_cfg'
    
    bug usage 
    opened by tanghy2016 16
  • [Bug] backward after optimzer.step()?

    [Bug] backward after optimzer.step()?

    I am trying to train autoslim on cifar10 with mobilenetV2.

    But I found there are some errors when training

    image

    And I found some of root cause. For example,

    You have already called optimized.step() here (https://github.com/open-mmlab/mmrazor/blob/master/mmrazor/models/algorithms/autoslim.py#L226)

    but in mmcv here is already have one (https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/optimizer.py#L56).

    Do i need to configure something?

    thank you

    bug 
    opened by twmht 14
  • [Bug] AttributeError: AutoSlim: 'SliceBackward' object has no attribute 'variable'

    [Bug] AttributeError: AutoSlim: 'SliceBackward' object has no attribute 'variable'

    Describe the bug

    A clear and concise description of what the bug is.

    when i running cls-AutoSlim code by step 1, training a cls supernet on my own dataset, it appeared a AttributeError.

    To Reproduce

    The command you executed.

    Traceback (most recent call last):
      File "tools/mmcls/train_mmcls.py", line 170, in <module>
        main()
      File "tools/mmcls/train_mmcls.py", line 140, in main
        algorithm = build_algorithm(cfg.algorithm)
      File "/home/ubuntu/project/hzw/mmrazor-master/mmrazor/models/builder.py", line 20, in build_algorithm
        return ALGORITHMS.build(cfg)
      File "/home/ubuntu/miniconda/envs/mmseg/lib/python3.8/site-packages/mmcv/utils/registry.py", line 212, in build
        return self.build_func(*args, **kwargs, registry=self)
      File "/home/ubuntu/miniconda/envs/mmseg/lib/python3.8/site-packages/mmcv/cnn/builder.py", line 27, in build_model_from_cfg
        return build_from_cfg(cfg, registry, default_args)
      File "/home/ubuntu/miniconda/envs/mmseg/lib/python3.8/site-packages/mmcv/utils/registry.py", line 55, in build_from_cfg
        raise type(e)(f'{obj_cls.__name__}: {e}')
    AttributeError: AutoSlim: 'SliceBackward' object has no attribute 'variable'
    
    bug 
    opened by Zhiweihhh 13
  • how to use mmrazor1.x

    how to use mmrazor1.x

    Based on my own dataset, I trained a model using mmseg1.x. Now I want to realize knowledge distillation, resnet101+deeplab--->resnet18+deeplab. I configured the mmrazor environment, but in the distill config file https://github.com/open-mmlab/mmrazor/blob/bbb58f1a5c2fe2878484856767dba540092bc7bf/configs/distill /mmseg/cwd/cwd_logits_pspnet_r101-d8_pspnet_r18-d8_4xb2-80k_cityscapes-512x1024.py#L2 I don't know where I can modify the default settings of mmseg, such as the number of categories to be segmented, data set selection, etc.? Can you give me some help?

    v-1.x 
    opened by wwjwy 11
  • Inference demo

    Inference demo

    Hi,

    Is there a inference demo in the code base? Try to init model follow test/test_apis/test_inference.py.

    result = inference_detector(model, img_path) show_result_pyplot(model, img_path, result, wait_time=1, score_thr=0.7, palette=(72, 101, 241))

    The terminal shows model and checkpoints loaded state dict do not match exactly.
    The bbox painted on image is not correct, and every time is different. However, I'm sure the mAP tested by test.py is correct.

    usage 
    opened by dzyjjpy 11
  • TypeError: 'DataContainer' object is not subscriptable

    TypeError: 'DataContainer' object is not subscriptable

    When I follow train.md for distilling model with config.py, such errors happened. It seems that my input 'imgs' data type is error in mmdet.detectors.base.lineL78 (should be tensor but Datacontainers). So, does my envs configuration version not match? Following is my envs configuration: TorchVision: 0.9.0 OpenCV: 4.5.4 MMCV: 1.4.0 MMCV Compiler: GCC 7.3 MMCV CUDA Compiler: 11.1 MMDetection: 2.20.0

    bug 
    opened by aiboys 11
  • miou=0 when running the code on voc2012 dataset

    miou=0 when running the code on voc2012 dataset

    I downloaded the voc2012 dataset, and downloaded the weights(pspnet_r101-d8_512x512_20k_voc12aug_20200617_102003-4aef3c9a.pth ) in mmsegmentation, and ran the following code.

    python tools/mmseg/train_mmseg.py configs/distill/cwd/cwd_cls_head_pspnet_r101_d8_pspnet_r18_d8_512x1024_voc2012_80k.py --cfg-options algorithm.distiller.teacher.init_cfg.type=Pretrained algorithm.distiller.teacher.init_cfg.checkpoint=pretrained/pspnet_r101-d8_512x512_20k_voc12aug_20200617_102003-4aef3c9a.pth

    the validation results are as follows: +-------------+-------+-------+ | Class | IoU | Acc | +-------------+-------+-------+ | background | 73.31 | 99.89 | | aeroplane | 0.0 | 0.0 | | bicycle | 0.0 | 0.0 | | bird | 0.0 | 0.0 | | boat | 0.0 | 0.0 | | bottle | 0.0 | 0.0 | | bus | 0.0 | 0.0 | | car | 0.0 | 0.0 | | cat | 0.0 | 0.0 | | chair | 0.0 | 0.0 | | cow | 0.0 | 0.0 | | diningtable | 0.0 | 0.0 | | dog | 0.0 | 0.0 | | horse | 0.0 | 0.0 | | motorbike | 0.0 | 0.0 | | person | 0.32 | 0.33 | | pottedplant | 0.0 | 0.0 | | sheep | 0.0 | 0.0 | | sofa | 0.0 | 0.0 | | train | 0.0 | 0.0 | | tvmonitor | 0.0 | 0.0 | +-------------+-------+-------+ 2021-12-24 11:09:10,633 - mmseg - INFO - Summary: 2021-12-24 11:09:10,633 - mmseg - INFO - +-------+------+------+ | aAcc | mIoU | mAcc | +-------+------+------+ | 73.25 | 3.51 | 4.77 | +-------+------+------+

    can you help me sove this? Thanks

    opened by wwjwy 11
  • custom tracer

    custom tracer

    model = torch.hub.load('facebookresearch/detr:main', 'detr_resnet50', pretrained=True) graph = custom_symbolic_trace(model)

    /usr/bin/python3 /Users/unicorn/MyCodes/net_op/fx/mmrazor_tracer.py Using cache found in /Users/unicorn/.cache/torch/hub/facebookresearch_detr_main /Users/unicorn/Library/Python/3.9/lib/python/site-packages/torchvision/models/_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead. warnings.warn( /Users/unicorn/Library/Python/3.9/lib/python/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or None for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing weights=ResNet50_Weights.IMAGENET1K_V1. You can also use weights=ResNet50_Weights.DEFAULT to get the most up-to-date weights. warnings.warn(msg) Downloading: "https://dl.fbaipublicfiles.com/detr/detr-r50-e632da11.pth" to /Users/unicorn/.cache/torch/hub/checkpoints/detr-r50-e632da11.pth 100%|██████████| 159M/159M [00:15<00:00, 10.5MB/s] Traceback (most recent call last): File "/Users/unicorn/MyCodes/net_op/fx/mmrazor_tracer.py", line 284, in graph = custom_symbolic_trace(model) File "/Users/unicorn/MyCodes/net_op/fx/mmrazor_tracer.py", line 75, in custom_symbolic_trace graph = tracer.trace(root, concrete_args) File "/Users/unicorn/MyCodes/net_op/fx/mmrazor_tracer.py", line 264, in trace 'output', (self.create_arg(fn(*args)), ), {}, File "/Users/unicorn/.cache/torch/hub/facebookresearch_detr_main/models/detr.py", line 61, in forward features, pos = self.backbone(samples) File "/Users/unicorn/MyCodes/net_op/fx/mmrazor_tracer.py", line 225, in module_getattr_wrapper return self._module_getattr(attr, attr_val, parameter_proxy_cache) AttributeError: 'CustomTracer' object has no attribute '_module_getattr'

    bug v-1.x 
    opened by wm901115nwpu 10
  • [Bug]在torch1.8 ,cuda试运行知识蒸馏模型时出现问题

    [Bug]在torch1.8 ,cuda试运行知识蒸馏模型时出现问题

    Describe the bug

    A clear and concise description of what the bug is.

    在选择配置文件为:cwd_logits_pspnet_r101-d8_pspnet_r18-d8_4xb2-80k_cityscapes-512x1024.py进行模型蒸馏时(其他位置未作改变),在代码运行至 runner = Runner.from_cfg(cfg)处,后经debug至from_cfg函数内发现代码会在run = cls(...)位置卡顿,等待半小时后才开始运行后面的代码。 image

    [here]

    To Reproduce

    The command you executed.

    [here]
    

    Post related information

    1. The output of pip list | grep "mmcv\|mmrazor\|^torch" [here]
    2. Your config file if you modified it or created a new one.
    [here]
    
    1. Your train log file if you meet the problem during training. [here]
    2. Other code you modified in the mmrazor folder. [here]

    Additional context

    Add any other context about the problem here.

    [here]

    Bug:P3 usage v-1.x 
    opened by worker-ljw 9
  • [Fix] Fix metafile

    [Fix] Fix metafile

    Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers.

    Motivation

    Please describe the motivation of this PR and the goal you want to achieve through this PR.

    Modification

    Please briefly describe what modification is made in this PR.

    BC-breaking (Optional)

    Does the modification introduce changes that break the backward compatibility of the downstream repositories? If so, please describe how it breaks the compatibility and how the downstream projects should modify their code to keep compatibility with this PR.

    Use cases (Optional)

    If this PR introduces a new feature, it is better to list some use cases here and update the documentation.

    Checklist

    Before PR:

    • [ ] Pre-commit or other linting tools are used to fix the potential lint issues.
    • [ ] Bug fixes are fully covered by unit tests, the case that causes the bug should be added in the unit tests.
    • [ ] The modification is covered by complete unit tests. If not, please add more unit tests to ensure the correctness.
    • [ ] The documentation has been modified accordingly, like docstring or example tutorials.

    After PR:

    • [ ] If the modification has potential influence on downstream or other related projects, this PR should be tested with those projects, like MMDet or MMSeg.
    • [ ] CLA has been signed and all committers have signed the CLA in this PR.
    opened by HIT-cwh 0
  • call after_val_epoch hooks only once to save best ckpt correctly

    call after_val_epoch hooks only once to save best ckpt correctly

    Motivation

    SingleTeacherDistillValLoop calls after_val_epoch hooks twice during the evaluation. However, the metric in the second call do not contain the key named student.accuracy/top1. As a result, if we set save_best='auto' in CheckpointHook, the program will fail.

    Please refer to this issue for more details.

    Modification

    Now we only call after_val_epoch hooks once in SingleTeacherDistillValLoop.

    opened by Weiyun1025 0
  • [Refactor & Doc] Refactor graph_utils and add docstring and pytest

    [Refactor & Doc] Refactor graph_utils and add docstring and pytest

    Modification

    1. Refactor graph_utils: We support deleting fakequant before / after op / method / function / module in graph_utils.
    2. Add 8 properties to BaseQuantizer. Each is a tuple. For example, the module_del_prev_fakequant property in OpenVINOQuantizer is (torch.nn.ReLU6, torch.nn.Identity). These properties are determined by the backend, so maybe they need to be regarded as properties.
    3. Add the corresponding pytest and docstring.
    opened by HIT-cwh 0
  • Update readme master

    Update readme master

    Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers.

    Motivation

    update readme in master branch

    opened by LKJacky 1
  • [Bug] Imcompatible with TimmClassifier

    [Bug] Imcompatible with TimmClassifier

    Describe the bug

    if the architecture or teacher of SingleTeacherDistill is a instance of TimmClassifier, the ckpt can not be load correctly.

    To Reproduce

    from mmengine.config import Config
    from mmrazor.registry import MODELS
    from mmengine.runner import load_checkpoint, save_checkpoint
    
    model = MODELS.build(Config.fromfile('./debug_config.py')['model'])
    
    save_checkpoint(model.state_dict(), './temp.pth')
    load_checkpoint(model, './temp.pth', strict=True)
    
    

    Config

    student = dict(
        _scope_='mmcls',
        type='TimmClassifier',
        model_name='deit_tiny_patch16_224',
    )
    
    teacher = dict(
        _scope_='mmcls',
        type='TimmClassifier',
        model_name='cait_s24_224',
    )
    
    model = dict(
        _scope_='mmrazor',
        type='SingleTeacherDistill',
        architecture=student,
        teacher=teacher,
        distiller=dict(
            type='ConfigurableDistiller',
        ),
    )
    
    bug v-1.x KD mmcls 
    opened by Weiyun1025 1
  • How use the SearchableShuffleNetV2 in KD for calssification

    How use the SearchableShuffleNetV2 in KD for calssification

    student = dict( type='mmcls.ImageClassifier', backbone=dict( type='SearchableShuffleNetV2', norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), ),

    neck=dict(type='GlobalAveragePooling'),
    head=dict(
        type='LinearClsHead',
        num_classes=9,
        in_channels=64,
        loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
        topk=(1, 5)))
    

    how to define the in_channels

    usage KD NAS 
    opened by MARUIHAN123 1
Releases(v1.0.0rc1)
  • v1.0.0rc1(Nov 1, 2022)

    Changelog of v1.0.0rc1

    v1.0.0rc1 (27/10/2022)

    We are excited to announce the release of MMRazor 1.0.0rc1.

    Highlights

    • New Pruning Framework:We have systematically refactored the Pruning module. The new Pruning module can more automatically resolve the dependencies between channels and cover more corner cases.

    New Features

    Pruning

    • A new pruning framework is released in this release. (#311, #313) It consists of five core modules, including Algorithm, ChannelMutator, MutableChannelUnit, MutableChannel and DynamicOp.

    • MutableChannelUnit is introduced for the first time. Each MutableChannelUnit manages all channels with channel dependency.

      from mmrazor.registry import MODELS
      
      ARCHITECTURE_CFG = dict(
          _scope_='mmcls',
          type='ImageClassifier',
          backbone=dict(type='MobileNetV2', widen_factor=1.5),
          neck=dict(type='GlobalAveragePooling'),
          head=dict(type='mmcls.LinearClsHead', num_classes=1000, in_channels=1920))
      model = MODELS.build(ARCHITECTURE_CFG)
      from mmrazor.models.mutators import ChannelMutator
      
      channel_mutator = ChannelMutator()
      channel_mutator.prepare_from_supernet(model)
      units = channel_mutator.mutable_units
      print(units[0])
      # SequentialMutableChannelUnit(
      #   name=backbone.conv1.conv_(0, 48)_48
      #   (output_related): ModuleList(
      #     (0): Channel(backbone.conv1.conv, index=(0, 48), is_output_channel=true, expand_ratio=1)
      #     (1): Channel(backbone.conv1.bn, index=(0, 48), is_output_channel=true, expand_ratio=1)
      #     (2): Channel(backbone.layer1.0.conv.0.conv, index=(0, 48), is_output_channel=true, expand_ratio=1)
      #     (3): Channel(backbone.layer1.0.conv.0.bn, index=(0, 48), is_output_channel=true, expand_ratio=1)
      #   )
      #   (input_related): ModuleList(
      #     (0): Channel(backbone.conv1.bn, index=(0, 48), is_output_channel=false, expand_ratio=1)
      #     (1): Channel(backbone.layer1.0.conv.0.conv, index=(0, 48), is_output_channel=false, expand_ratio=1)
      #     (2): Channel(backbone.layer1.0.conv.0.bn, index=(0, 48), is_output_channel=false, expand_ratio=1)
      #     (3): Channel(backbone.layer1.0.conv.1.conv, index=(0, 48), is_output_channel=false, expand_ratio=1)
      #   )
      #   (mutable_channel): SquentialMutableChannel(num_channels=48, activated_channels=48)
      # )
      

    Our new pruning algorithm can help you develop pruning algorithm more fluently. Pelease refer to our documents PruningUserGuide for model detail.

    Distillation

    • Support CRD, a distillation algorithm based on contrastive representation learning. (#281)

    • Support PKD, a distillation algorithm that can be used in MMDetection and MMDetection3D. #304

    • Support DEIT, a classic Transformer distillation algorithm.(#332)

    • Add a more powerful baseline setting for KD. (#305)

    • Add MethodInputsRecorder and FuncInputsRecorder to record the input of a class method or a function.(#320)

    NAS

    • Support DSNAS, a nas algorithm that does not require retraining. (#226 )

    Tools

    • Support configurable immediate feature map visualization. (#293 ) A useful tool is supported in this release to visualize the immediate features of a neural network. Please refer to our documents VisualizationUserGuide for more details.

    Bug Fixes

    • Fix the bug that FunctionXXRecorder and FunctionXXDelivery can not be pickled. (#320)

    Ongoing changes

    • Quantization: We are developing the basic interface of PTQ and QAT. RFC(Request for Comments) will be released soon.
    • AutoSlim: AutoSlim is not yet available and is being refactored.
    • Fx Pruning Tracer: Currently, the model topology can only be resolved through the backward tracer. In the future, both backward tracer and fx tracer will be supported.
    • More Algorithms: BigNAS、AutoFormer、GreedyNAS and Resrep will be released in the next few versions.
    • Documentation: we will add more design docs, tutorials, and migration guidance so that the community can deep dive into our new design, participate the future development, and smoothly migrate downstream libraries to MMRazor 1.x.

    Contributors

    A total of 12 developers contributed to this release. Thanks @FreakieHuang @gaoyang07 @HIT-cwh @humu789 @LKJacky @pppppM @pprp @spynccat @sunnyxiaohu @wilxy @kitecats @SheffieldCao

    New Contributors

    • @kitecats made their first contribution in #334
    • @SheffieldCao made their first contribution in #299
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0rc0(Sep 1, 2022)

    Changelog of v1.x

    v1.0.0rc0 (31/8/2022)

    We are excited to announce the release of MMRazor 1.0.0rc0. MMRazor 1.0.0rc0 is the first version of MMRazor 1.x, a part of the OpenMMLab 2.0 projects. Built upon the new training engine, MMRazor 1.x simplified the interaction with other OpenMMLab repos, and upgraded the basic APIs of KD / Pruning / NAS. It also provides a series of knowledge distillation algorithms.

    Highlights

    • New engines. MMRazor 1.x is based on MMEngine, which provides a general and powerful runner that allows more flexible customizations and significantly simplifies the entrypoints of high-level interfaces.

    • Unified interfaces. As a part of the OpenMMLab 2.0 projects, MMRazor 1.x unifies and refactors the interfaces and internal logic of train, testing, datasets, models, evaluation, and visualization. All the OpenMMLab 2.0 projects share the same design in those interfaces and logic to allow the emergence of multi-task/modality algorithms.

    • More configurable KD. MMRazor 1.x add Recorder to get the data needed for KD more automatically,Delivery to automatically pass the teacher's intermediate results to the student, and connector to handle feature dimension mismatches between teacher and student.

    • More kinds of KD algorithms. Benefitting from the powerful APIs of KD, we have added several categories of KD algorithms, data-free distillation, self-distillation, and zero-shot distillation.

    • Unify the basic interface of NAS and Pruning. We refactored Mutable, adding mutable value and mutable channel. Both NAS and Pruning can be developed based on mutables.

    • More documentation and tutorials. We add a bunch of documentation and tutorials to help users get started more smoothly. Read it here.

    Breaking Changes

    Training and testing

    • MMRazor 1.x runs on PyTorch>=1.6. We have deprecated the support of PyTorch 1.5 to embrace the mixed precision training and other new features since PyTorch 1.6. Some models can still run on PyTorch 1.5, but the full functionality of MMRazor 1.x is not guaranteed.
    • MMRazor 1.x uses Runner in MMEngine rather than that in MMCV. The new Runner implements and unifies the building logic of dataset, model, evaluation, and visualizer. Therefore, MMRazor 1.x no longer maintains the building logics of those modules in mmdet.train.apis and tools/train.py. Those code have been migrated into MMEngine.
    • The Runner in MMEngine also supports testing and validation. The testing scripts are also simplified, which has similar logic as that in training scripts to build the runner.

    Configs

    Components

    • Algorithms
    • Distillers
    • Mutators
    • Mutables
    • Hooks

    Improvements

    • Support mixed precision training of all the models. However, some models may got Nan results due to some numerical issues. We will update the documentation and list their results (accuracy of failure) of mixed precision training.

    Bug Fixes

    • AutoSlim: Models of different sizes will no longer have the same size checkpoint

    New Features

    Ongoing changes

    • Quantization: We are developing the basic interface of PTQ and QAT. RFC(Request for Comments) will be released soon.
    • AutoSlim: AutoSlim is not yet available and is being refactored.
    • Fx Pruning Tracer: Currently, the model topology can only be resolved through the backward tracer. In the future, both backward tracer and fx tracer will be supported.
    • More Algorithms: BigNAS、AutoFormer、GreedyNAS and Resrep will be released in the next few versions.
    • Documentation: we will add more design docs, tutorials, and migration guidance so that the community can deep dive into our new design, participate the future development, and smoothly migrate downstream libraries to MMRazor 1.x.

    Contributors

    A total of 13 developers contributed to this release. Thanks @FreakieHuang @gaoyang07 @HIT-cwh @humu789 @LKJacky @pppppM @pprp @spynccat @sunnyxiaohu @wilxy @wutongshenqiu @NickYangMin @Hiwyl Special thanks to @Davidgzx for his contribution to the data-free distillation algorithms

    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(May 4, 2022)

    Features

    • Support different dataloader in using different settings (#141)

    Bug Fixes

    • Fixed the inconsistent results of broadcast_object_list on multiple machines (#153 )
    • Fixed the bug that the NAS model cannot be searched in non-distributed mode (#153)
    • Fixed the bug that tools/mmseg/train_mmseg.py cannot train properly (#152)
    • Fixed the bug that models containing GroupNorm or InstanceNorm cannot be pruned (#144)

    Improvements

    • Add default mutable_cfg, channel_cfg and teacher_checkpoint in configs to reduce the use of cfg-options (#149)

    Documents

    • Fixed broken links in readthedocs (#142)
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Apr 2, 2022)

    Features

    • Support MMDeploy(#102)
    • Support Relational Knowledge Distillation(CVPR 2019)(#127)
    • Support different seeds on different ranks when distributed training(#113)
    • StructurePruner supports trace models which contain Dilated Conv2d, such as YOLOF(#113)
    • StructurePruner supports trace models which contain share modules, such as RetinaNet(#113)

    Bug Fixes

    • Fix the bug that the pruner can't trace shared modules rightly(#113)
    • Fix the bug that the pruner can't trace modules whose requires_grad is False (#113 )
    • Fix the bug that the pruner will affect the statistic of BatachNorm(#81 )

    Improvements

    • Update distributed train tools to support training with multi nodes(#114 )
    • Sync mmdet and mmcls latest version of apis(#115)

    Documents

    • Add brief installation steps in README(#121 )
    • Add real examples in GET_STARTED related docs(#133 )
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Mar 7, 2022)

    Highlights

    • Support MobileNet series search space(#82)

    Features

    • Support CPU training(#62)
    • Support resuming from the latest checkpoint automatically(#61)

    Bug Fixes

    • Fix the bug of show_result during the test(#52 )
    • Fix bug in non-distributed training/testing for all tasks(#63)
    • Fix the incorrect value of KLDivergence(#35)
    • Fix the config error of WSLD(#26)
    • Fix the config error of DetNAS(#103)
    • Fix the bug of slurm_train_mmcls.sh(#90)

    Improvements

    • Add distributed train/test tools(#105)

    Documents

    • Fix some typos(#6, #16, #18, #73)
    • Fix some mistakes in docstring(#24, #29)
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Dec 23, 2021)

    Highlights

    MMRazor v0.1.0 is released.

    Major Features

    • Compatibility

      MMRazor can be easily applied to various projects in OpenMMLab, due to similar architecture design of OpenMMLab as well as the decoupling of slimming algorithms and vision tasks.

    • Flexibility

      Different algorithms, e.g., NAS, pruning and KD, can be incorporated in a plug-n-play manner to build a more powerful system.

    • Convenience

      With better modular design, developers can implement new model compression algorithms with only a few codes, or even by simply modifying config files.

    Source code(tar.gz)
    Source code(zip)
Owner
OpenMMLab
OpenMMLab
😮The official implementation of "CoNeRF: Controllable Neural Radiance Fields" 😮

CoNeRF: Controllable Neural Radiance Fields This is the official implementation for "CoNeRF: Controllable Neural Radiance Fields" Project Page Paper V

Kacper Kania 61 Dec 24, 2022
ROS Basics and TurtleSim

Waypoint Follower Anna Garverick This package draws given waypoints, then waits for a service call with a start position to send the turtle to each wa

Anna Garverick 1 Dec 13, 2021
Image Captioning using CNN ,LSTM and Attention

Image Captioning using CNN ,LSTM and Attention This is a deeplearning model which tries to summarize an image into a text . Installation Install this

ASUTOSH GHANTO 1 Dec 16, 2021
prior-based-losses-for-medical-image-segmentation

Repository for papers: Benchmark: Effect of Prior-based Losses on Segmentation Performance: A Benchmark Midl: A Surprisingly Effective Perimeter-based

Rosana EL JURDI 9 Sep 07, 2022
Awesome Monocular 3D detection

Awesome Monocular 3D detection Paper list of 3D detetction, keep updating! Contents Paper List 2022 2021 2020 2019 2018 2017 2016 KITTI Results Paper

Zhikang Zou 184 Jan 04, 2023
Polyp-PVT: Polyp Segmentation with Pyramid Vision Transformers (arXiv2021)

Polyp-PVT by Bo Dong, Wenhai Wang, Deng-Ping Fan, Jinpeng Li, Huazhu Fu, & Ling Shao. This repo is the official implementation of "Polyp-PVT: Polyp Se

Deng-Ping Fan 102 Jan 05, 2023
Hummingbird compiles trained ML models into tensor computation for faster inference.

Hummingbird Introduction Hummingbird is a library for compiling trained traditional ML models into tensor computations. Hummingbird allows users to se

Microsoft 3.1k Dec 30, 2022
HINet: Half Instance Normalization Network for Image Restoration

HINet: Half Instance Normalization Network for Image Restoration Liangyu Chen, Xin Lu, Jie Zhang, Xiaojie Chu, Chengpeng Chen Paper: https://arxiv.org

303 Dec 31, 2022
Neural style in TensorFlow! 🎨

neural-style An implementation of neural style in TensorFlow. This implementation is a lot simpler than a lot of the other ones out there, thanks to T

Anish Athalye 5.5k Dec 29, 2022
Second-Order Neural ODE Optimizer, NeurIPS 2021 spotlight

Second-order Neural ODE Optimizer (NeurIPS 2021 Spotlight) [arXiv] ✔️ faster convergence in wall-clock time | ✔️ O(1) memory cost | ✔️ better test-tim

Guan-Horng Liu 39 Oct 22, 2022
Fast and Easy Infinite Neural Networks in Python

Neural Tangents ICLR 2020 Video | Paper | Quickstart | Install guide | Reference docs | Release notes Overview Neural Tangents is a high-level neural

Google 1.9k Jan 09, 2023
PyTorch implementation for our paper "Deep Facial Synthesis: A New Challenge"

FSGAN Here is the official PyTorch implementation for our paper "Deep Facial Synthesis: A New Challenge". This project achieve the translation between

Deng-Ping Fan 32 Oct 10, 2022
Ensemble Learning Priors Driven Deep Unfolding for Scalable Snapshot Compressive Imaging [PyTorch]

Ensemble Learning Priors Driven Deep Unfolding for Scalable Snapshot Compressive Imaging [PyTorch] Abstract Snapshot compressive imaging (SCI) can rec

integirty 6 Nov 01, 2022
Low-code/No-code approach for deep learning inference on devices

EzEdgeAI A concept project that uses a low-code/no-code approach to implement deep learning inference on devices. It provides a componentized framewor

On-Device AI Co., Ltd. 7 Apr 05, 2022
Space Ship Simulator using python

FlyOver Basic space-ship simulator using python How to run? Just double click run.py What modules do i need? All modules that i currently using is bui

0 Oct 09, 2022
《Towards High Fidelity Face Relighting with Realistic Shadows》(CVPR 2021)

Towards High Fidelity Face-Relighting with Realistic Shadows Andrew Hou, Ze Zhang, Michel Sarkis, Ning Bi, Yiying Tong, Xiaoming Liu. In CVPR, 2021. T

114 Dec 10, 2022
Code for Transformer Hawkes Process, ICML 2020.

Transformer Hawkes Process Source code for Transformer Hawkes Process (ICML 2020). Run the code Dependencies Python 3.7. Anaconda contains all the req

Simiao Zuo 111 Dec 26, 2022
git《USD-Seg:Learning Universal Shape Dictionary for Realtime Instance Segmentation》(2020) GitHub: [fig2]

USD-Seg This project is an implement of paper USD-Seg:Learning Universal Shape Dictionary for Realtime Instance Segmentation, based on FCOS detector f

Ruolin Ye 80 Nov 28, 2022
The repo contains the code of the ACL2020 paper `Dice Loss for Data-imbalanced NLP Tasks`

Dice Loss for NLP Tasks This repository contains code for Dice Loss for Data-imbalanced NLP Tasks at ACL2020. Setup Install Package Dependencies The c

223 Dec 17, 2022
Convert human motion from video to .bvh

video_to_bvh Convert human motion from video to .bvh with Google Colab Usage 1. Open video_to_bvh.ipynb in Google Colab Go to https://colab.research.g

Dene 306 Dec 10, 2022