GithubHelp home page GithubHelp logo

mit-han-lab / haq Goto Github PK

View Code? Open in Web Editor NEW
354.0 20.0 84.0 66 KB

[CVPR 2019, Oral] HAQ: Hardware-Aware Automated Quantization with Mixed Precision

Home Page: https://hanlab.mit.edu/projects/haq/

License: MIT License

Python 97.48% Shell 2.52%
quantization automl mixed-precision efficient-model

haq's Introduction

HAQ: Hardware-Aware Automated Quantization with Mixed Precision

Introduction

This repo contains PyTorch implementation for paper HAQ: Hardware-Aware Automated Quantization with Mixed Precision (CVPR2019, oral)

overview

@inproceedings{haq,
author = {Wang, Kuan and Liu, Zhijian and Lin, Yujun and Lin, Ji and Han, Song},
title = {HAQ: Hardware-Aware Automated Quantization With Mixed Precision},
booktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
year = {2019}
}

Other papers related to automated model design:

  • AMC: AutoML for Model Compression and Acceleration on Mobile Devices (ECCV 2018)

  • ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware (ICLR 2019)

Dependencies

We evaluate this code with Pytorch 1.1 (cuda10) and torchvision 0.3.0, you can install pytorch with conda:

# install pytorch
conda install -y pytorch torchvision cudatoolkit=10.0 -c pytorch

And you can use the following command to set up the environment:

# install packages and download the pretrained model
bash run/setup.sh

(If the server is down, you can download the pretrained model from google drive: mobilenetv2-150.pth.tar)

Current code base is tested under following environment:

  1. Python 3.7.3
  2. PyTorch 1.1
  3. torchvision 0.3.0
  4. numpy 1.14
  5. matplotlib 3.0.1
  6. scikit-learn 0.21.0
  7. easydict 1.8
  8. progress 1.4
  9. tensorboardX 1.7

Dataset

If you already have the ImageNet dataset for pytorch, you could create a link to data folder and use it:

# prepare dataset, change the path to your own
ln -s /path/to/imagenet/ data/

If you do not have the ImageNet yet, you can download the ImageNet dataset and move validation images to labeled subfolders. To do this, you can use the following script: https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh

We use a subset of ImageNet in the linear quantizaiton search phase to save the training time, to create the link of the subset, you can use the following tool:

# prepare imagenet100 dataset
python lib/utils/make_data.py

Reinforcement learning search

  • You can run the bash file as following to search the K-Means quantization strategy, which only quantizes the weights with K-Means to compress model size of specific model.
# K-Means quantization, for model size
bash run/run_kmeans_quantize_search.sh
  • You can run the bash file as following to search the linear quantization strategy, which linearly quantizes both the weights and activations to reduce latency/energy of specific model.
# Linear quantization, for latency/energy
bash run/run_linear_quantize_search.sh
  • Usage details
python rl_quantize.py --help

Finetune Policy

  • After searching, you can get the quantization strategy list, and you can replace the strategy list in finetune.py to finetune and evaluate the performance on ImageNet dataset.
  • We set the default K-Means quantization strategy searched under preserve ratio = 0.1 like:
# preserve ratio 10%
strategy = [6, 6, 5, 5, 5, 5, 4, 5, 5, 4, 5, 5, 5, 5, 5, 5, 3, 5, 4, 3, 5, 4, 3, 4, 4, 4, 2, 5, 4, 3, 3, 5, 3, 2, 5, 3, 2, 4, 3, 2, 5, 3, 2, 5, 3, 4, 2, 5, 2, 3, 4, 2, 3, 4]

You can follow the following bash file to finetune the K-Means quantized model to get a better performance:

bash run/run_kmeans_quantize_finetune.sh
  • We set the default linear quantization strategy searched under preserve ratio = 0.6 like:
# preserve ratio 60%
strategy = [[8, -1], [7, 7], [5, 6], [4, 6], [5, 6], [5, 7], [5, 6], [7, 4], [4, 6], [4, 6], [7, 7], [5, 6], [4, 6], [7, 3], [5, 7], [4, 7], [7, 3], [5, 7], [4, 7], [7, 7], [4, 7], [4, 7], [6, 4], [6, 7], [4, 7], [7, 4], [6, 7], [5, 7], [7, 4], [6, 7], [5, 7], [7, 4], [6, 7], [6, 7], [6, 4], [5, 7], [6, 7], [6, 4], [5, 7], [6, 7], [7, 7], [4, 7], [7, 7], [7, 7], [4, 7], [7, 7], [7, 7], [4, 7], [7, 7], [7, 7], [4, 7], [7, 7], [8, 8]]

You can follow the following bash file to finetune the linear quantized model to get a better performance:

bash run/run_linear_quantize_finetune.sh
  • Usage details
python finetune.py --help

Evaluate

You can download the pretrained quantized model like this:

# download checkpoint
mkdir -p checkpoints/resnet50/
mkdir -p checkpoints/mobilenetv2/
cd checkpoints/resnet50/
wget https://hanlab.mit.edu/files/haq/resnet50_0.1_75.48.pth.tar
cd ../mobilenetv2/
wget https://hanlab.mit.edu/files/haq/qmobilenetv2_0.6_71.23.pth.tar
cd ../..

(If the server is down, you can download the pretrained model from google drive: qmobilenetv2_0.6_71.23.pth.tar)

You can evaluate the K-Means quantized model like this:

# evaluate K-Means quantization
bash run/run_kmeans_quantize_eval.sh
Models preserve ratio Top1 Acc (%) Top5 Acc (%)
resnet50 (original) 1.0 76.15 92.87
resnet50 (10x compress) 0.1 75.48 92.42

You can evaluate the linear quantized model like this:

# evaluate linear quantization
bash run/run_linear_quantize_eval.sh
Models preserve ratio Top1 Acc (%) Top5 Acc (%)
mobilenetv2 (original) 1.0 72.05 90.49
mobilenetv2 (0.6x latency) 0.6 71.23 90.00

haq's People

Contributors

kuan-wang avatar tonylins avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

haq's Issues

Quantizing activation

It seems that only weight quantization is supported in this repo, isn't it?
Do you have plan to release the implementation including activation quantization in the future?

activation quantization

can you tell me which part is using for quantize activation?

I just find quantization codes for weights and bias, but not activation.

Performance for mixed precision Resnets?

Thanks for sharing a great work!

image

I was interested in the results of deep compression vs HAQ in the paper: in case of resnets, mixed precision quantization did not bring much benefits.
I was wondering if mixed precision quantization is effective in resnet architecture or not.
Did you compare the results of HAQ vs PACT with resnets? It would be great if you can share!

RuntimeError: CUDA error: out of memory

(.haq) [root@b6706b6a30d7 HAQ-master]# python rl_quantize.py --gpu_id 2
support models: ['alexnet', 'densenet121', 'densenet161', 'densenet169', 'densenet201', 'googlenet', 'inception_v3', 'mobilenet_v2', 'resnet101', 'resnet152', 'resnet18', 'resnet34', 'resnet50', 'resnext101_32x8d', 'resnext50_32x4d', 'shufflenet_v2_x0_5', 'shufflenet_v2_x1_0', 'shufflenet_v2_x1_5', 'shufflenet_v2_x2_0', 'squeezenet1_0', 'squeezenet1_1', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 'vgg19', 'vgg19_bn', 'mobilenet_v3']
==> Output path: ../../save/mobilenet_v2_imagenet...
Traceback (most recent call last):
File "rl_quantize.py", line 210, in
model = torch.nn.DataParallel(model).cuda()
File "/aiml/.haq/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 265, in cuda
return self._apply(lambda t: t.cuda(device))
File "/aiml/.haq/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 193, in _apply
module._apply(fn)
File "/aiml/.haq/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 193, in _apply
module._apply(fn)
File "/aiml/.haq/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 193, in _apply
module._apply(fn)
[Previous line repeated 1 more time]
File "/aiml/.haq/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 199, in _apply
param.data = fn(param.data)
File "/aiml/.haq/lib64/python3.6/site-packages/torch/nn/modules/module.py", line 265, in
return self._apply(lambda t: t.cuda(device))
RuntimeError: CUDA error: out of memory

quantization environment

In quantize_env.py line 130, 131

    self.cur_ind += 1  # the index of next layer
    self.layer_embedding[self.cur_ind][-1] = action

Why cur_ind is increased by one before layer_embedding is updated?

Quantization of custom models

Can this project be used for the Hardware Aware quantization of self made custom models that are trained on datasets other than ImageNet so as to reduce the latency on a particular GPU?

Question about linear quantization

I figure out the procedure of linear quantization and reproduce the experiments,

  1. Search the quantization strategy on the imagenet100 dataset.
  2. Finetune the model on the whole imagenet dataset with the strategy obtained from step 1.

It seems like the final accuracy of the quantized model is more dependent on the fine-tuning.
Another question is why the bit reduction process starts from the last layer as the _final_action_wall function shows.

Why use the 8-bit floating numbers to compute the original cost?

Hi,
The work is amazing.
When I looked through the code, I foud that you employed the 8-bit floating numbers to compute the original cost and store
it as a lookup table. I wondered why not use the 32-bit floating(not use the flag "--half" in the pretraining process) or use the 16-bit floating (use the flag "--half" in the pretraining process)? Could you please clarify that?
Thanks a lot!

Training with simulated quantization

I have noticed that the quantization mechanism is quantize(w, ak, c) = round(clamp(w, c)/s) × s. It seems like you have use the "Training with simulated quantization" in paper "Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference". Is it true?

If yes, Training with simulated quantization is just used for training. I wonder does the model also use the Integer-arithmetic-only inference process like round(clamp(w, c)/s) during the inference process?

Typo or feature?

In HAQ/lib/utils/data_utils.py in lane 93 valset = datasets.ImageFolder(traindir, test_transform) should be valset = datasets.ImageFolder(valdir, test_transform) ?

fused mobilenet v1

If we applied haq on fused mobilenet v1, i.e., fuse convolutional and batch norm layer together, it seems very difficult to quantize such model in 1~8bits.
Do you have any comment on such case?

torch version problem

I configured the Python virtual environment according to the instructions, but there is a problem with the cuda version. The cuda version I used is 11.8.

image

Pretrained Mobilenet model

Hi, Dear author,
The figures in the paper show the parameters' bitwidth in MobileNet. Is it possible for you to release the pretrained quantized MobileNet model?
Thanks!

How to measure model size?

Thanks for sharing the amazing work! I'm wondering how did you measure the model size. I downloaded your pretrained model 'resnet50_0.1_75.48.pth.tar', and found the size of the model is 102.7MB which is big.

Linear quantization

Can you please point to the part where the linear quantization is used? Thanks. I can't find it in linear quantize environment.
self.quantizable_layer_types = [QConv2d, QLinear] might be [nn.Conv2d, nn.Linear]?

Question about model size constraint

Dear authors,

I notice in the first two lines of Table 6 that your searched model has a model size even smaller than 2-bits quantization but a much higher accuracy. Can you illustrate your quantization policy under this constraint? It's a little strange to me because it seems your minimum bitwidth choice is 2 in the paper.

Thank you

Regarding paper and codes

By diving deep into the codes and the paper, I have two questions.

  1. I've read from the paper that "If the current policy exceeds our resource budget (on latency, energy or model size), we will sequentially decrease the bitwidth of each layer until the
    constraint is finally satisfied." Where in the codes correspond to this statement "decrease the bitwidth of the layer when the current policy exceeds budget?"

  2. Why don't you use the k-means quantization for latency/energy constraint experiments? Will you release codes for linear quantization?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.