sefaburakokcu / quantized-yolov5

Low Precision(quantized) Yolov5
GNU General Public License v3.0
31 stars 7 forks source link

Quantised YOLOv5 #36

Closed g12bftd closed 7 months ago

g12bftd commented 1 year ago

Hey, thank you for the repo. Can you add a quantised yolov5 model, where the user has individual control of the weight bit-widths for each layer and activation separately?

I have already seen the other issue mentioning yolov5. The quantised yolov1 is very good, but there is a difference with yolov5 that is non-trivial.

Thank you.

Additional context

github-actions[bot] commented 1 year ago

๐Ÿ‘‹ Hello @g12bftd, thank you for your interest in YOLOv5 ๐Ÿš€! Please visit our โญ๏ธ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a ๐Ÿ› Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training โ“ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

Python>=3.6.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

$ git clone https://github.com/ultralytics/yolov5
$ cd yolov5
$ pip install -r requirements.txt

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

sefaburakokcu commented 1 year ago

Hi Glenn,

I appreciate your interest. I can provide an implementation of quantized Yolov5. Nevertheless, it can not be exported for FINN synthesis due to unimplemented/incompatible layers. However, I can add a quantized config if you want to utilize the quantized Yolov5 in Brevitas for testing different weight bit-widths.

g12bftd commented 1 year ago

Hey,

Thank you so much. It would be great to have a quantized yolov5m model. I just need to be able to control individual bit-widths for each layer and activation function. No need for deployment with FINN.

Thanks ๐Ÿ˜Š

sefaburakokcu commented 1 year ago

I have added a config for quantized Yolov5(https://github.com/sefaburakokcu/quantized-yolov5/blob/quantized_yolo/models/yolov5m-quant.yaml). It was a bit tricky.

g12bftd commented 1 year ago

Hey @sefaburakokcu,

Thank you so much for this! Amazing effort. A few questions just to clarify:

1) With the current setup, we are able to modify the bit-widths of individual conv layers and their activation functions? 2) I want quantise the model starting from the version pre-trained on COCO. Do I have to change anything in the current setup?

Thanks again for your help.

mdhosen commented 1 year ago

Hi, Thank you for your great effort. I was trying to run yolov5m-quant.yaml on my coustome dataset ( person detection). However, I got the following error: ......../train.py", line 252, in train model_definition['anchors'] = (model.module.model[-1].anchorsmodel.module.model[-1].stride).cpu().reshape(model.module.model[-1].anchors.shape[0], -1).tolist() if hasattr(model, 'module') else (model.model[-1].anchorsmodel.model[-1].stride).cpu().reshape(model.model[-1].anchors.shape[0], -1).tolist() RuntimeError: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 2

Walid-AMARA commented 9 months ago

Hi! I'm trying to build the quantized Yolov5 model following your implementation, yet I'm getting this error:

/content/quantized-yolov5/models/common.py in 25 26 # Quant layer imports ---> 27 from brevitas.nn import QuantConv2d, QuantLinear, QuantReLU, QuantAvgPool2d, QuantSigmoid, QuantHardTanh, QuantIdentity 28 from brevitas.quant import IntBias, Int8ActPerTensorFloatMinMaxInit 29

I fixed it by removing those unnecessery imports from the common.py, they both cause an error and are not used.

TCGoingW commented 9 months ago

Hi! I'm trying to build the quantized Yolov5 model as well, which following your implementation but I'm having some question:

In /content/quantized-yolov5/models/common.py of QuantBottleneck structure, which is the sub-structure of the QuantC3, will make the yolov5 cannot be start a next epoch when completed a epoch. It will pop out the error as below.

Traceback (most recent call last):
  File "train.py", line 660, in <module>
     main(opt)
  File "train.py", line 549, in main
    train(opt.hyp, opt, device, callbacks)
  File "train.py", line 335, in train
    ema.update(model)
  File "/home/user/yolov5QuantBrevitas/yolov5/utils/torch_utils.py", line 432, in update
    v*=d
RuntimeError: Inplace update to inference tensor outside InferenceMode is not allowed.You can make a clone to get a normal tensor before doing inplace update.See https://github.com/pytorch/rfcs/pull/17 for more details.

By traced the code, I found out the problem is the self.quant_identity = QuantIdentity(bit_width=weight_bit_width) cause the error. But it maybe due to lack of understanding of the brevitas library, just don't know how to use QuantIdentity function to fix the error. So I corrected the QuantBottlneck as below:

class QuantBottleneck(nn.Module):`
    # Standard quantized bottleneck
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5,
                 weight_bit_width=4, act_bit_width=2):  # ch_in, ch_out, shortcut, groups, expansion, weight bit, act bit
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = QuantConv(c1, c_, 1, 1, weight_bit_width=weight_bit_width, act_bit_width=act_bit_width)
        self.cv2 = QuantConv(c_, c2, 3, 1, g=g, weight_bit_width=weight_bit_width, act_bit_width=act_bit_width)
        self.add = shortcut and c1 == c2
        # self.quant_identity = QuantIdentity(bit_width=weight_bit_width)
        self.bd = weight_bit_width
    def forward(self, x):
        qx = QuantTensor(x, bit_width=self.bd)
        return qx + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))

It's work! But I don't know the replacement will change the initial intention of the QuantBottleneck. Maybe @sefaburakokcu can comfirm this change will works and not affect initial intention of the function.

Thank you.

sefaburakokcu commented 9 months ago

Hi @mdhosen,

Thank you for your interest. I fixed the problem. You can pull the latest commits for the fix.

sefaburakokcu commented 9 months ago

Hi @Walid-AMARA!

I appreciate your interest. I think that your problem is coming form a new version of Brevitas since QuantAvgPool2d was replaced with TruncAvgPool2d. I fixed it too. You can also pull the latest repo.

sefaburakokcu commented 9 months ago

Hi @TCGoingW!

Thank you for your interest and a detailed question. Nevertheless, I am currently not sure whether replacing QuantIdentity with QuantTensor will effect the performance, but I don't think so. You can test it and share your findings here.

mdhosen commented 9 months ago

Dear @sefaburakokcu, thank you for your kind response. When I am running the code, it is showing following error while validating and loading.

Validating runs\train\exp5\weights\best.pt... Traceback (most recent call last): File "...\quantized-yolov5-quantized_yolo\models\experimental.py", line 97, in attempt_load ema = ckpt['ema' if ckpt.get('ema') else 'model'].float() KeyError: 'model'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "train.py", line 650, in main(opt) File "train.py", line 542, in main train(opt.hyp, opt, device, callbacks) File "train.py", line 439, in train model=attempt_load(f, device).half(), File "..\quantized-yolov5-quantized_yolo\models\experimental.py", line 100, in attempt_load cfg = w.replace("weights/best.pt", "model.yaml") TypeError: replace() takes 2 positional arguments but 3 were given

sefaburakokcu commented 8 months ago

Dear @mdhosen,

Can you share your training arguments in order to reproduce your error? Which model config are you using?

mdhosen commented 8 months ago

Dear @sefaburakokcu , Thank you again for your kind response. I am using "yolov5m-quant" config and "coco128_person_only" dataset. My training arguments are: " python train.py --data coco128_person_only.yaml --cfg models/yolov5m-quant.yaml --weights '' --batch-size 8 ". The model is saving but it is not validating. Problem occurring while model loading may be.

sefaburakokcu commented 8 months ago

Dear @mdhosen,

I ran "train.py" with the arguments you provided. Unfortunately, I couldn't reproduce the error you mentioned; my run was successful. Are you using the latest repository?

mdhosen commented 8 months ago

Dear @sefaburakokcu , Thanks a lot for your prompt responses. I have downloaded the recent model from "https://github.com/sefaburakokcu/quantized-yolov5.git", and run it. I have also tried in google Colab (because I thought it may be my environment problem), still I am getting the error. After completing the last epoch, when it is trying to validate then error occurs. Also, one more question, does the model using validation after each epoch? Thank you.

ramyen1 commented 8 months ago

Hi๏ผfirst of all, thank you very much for your selfless sharing and updates, which have been very helpful for my learning. You mentioned earlier that quantized YOLOv5 cannot be exported for use with FINN. What are the main layers that are difficult to implement in this context? Do you have any good ideas for replacing these layers?

sefaburakokcu commented 8 months ago

Dear @sefaburakokcu , Thanks a lot for your prompt responses. I have downloaded the recent model from "https://github.com/sefaburakokcu/quantized-yolov5.git", and run it. I have also tried in google Colab (because I thought it may be my environment problem), still I am getting the error. After completing the last epoch, when it is trying to validate then error occurs. Also, one more question, does the model using validation after each epoch? Thank you.

Dear @mdhosen,

The problem occurred due to attempting to load the model from a weight folder after the last epoch. The path to weights was not a string. Therefore, I converted the weights path to a string. However, I encountered a different error, which could be due to the different versions of PyTorch and Brevitas that I am currently using. Thus, I also replaced the model that is loaded from the folder with the final model in training. I have pushed the changes to the repo. You can try them.

mdhosen commented 7 months ago

Dear @sefaburakokcu, Thank you very much for your kind help. I have implemented on coco128 person only dataset (only 128 samples) and found no error. Now I am trying to implement on large dataset. Thank you again.