Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Quantised YOLOv5 #36

Closed
g12bftd opened this issue Jun 6, 2023 · 19 comments
Closed

Quantised YOLOv5 #36

g12bftd opened this issue Jun 6, 2023 · 19 comments
Labels
question Further information is requested

Comments

@g12bftd
Copy link

g12bftd commented Jun 6, 2023

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

@g12bftd g12bftd added the question Further information is requested label Jun 6, 2023
@github-actions
Copy link

github-actions bot commented Jun 6, 2023

👋 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
Copy link
Owner

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
Copy link
Author

g12bftd commented Jun 8, 2023

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
Copy link
Owner

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
Copy link
Author

g12bftd commented Jun 11, 2023

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
Copy link

mdhosen commented Aug 14, 2023

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
Copy link

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
Copy link

TCGoingW commented Dec 12, 2023

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
Copy link
Owner

Hi @mdhosen,

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

@sefaburakokcu
Copy link
Owner

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
Copy link
Owner

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
Copy link

mdhosen commented Dec 26, 2023

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
Copy link
Owner

Dear @mdhosen,

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

@mdhosen
Copy link

mdhosen commented Jan 11, 2024

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
Copy link
Owner

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
Copy link

mdhosen commented Jan 16, 2024

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
Copy link

ramyen1 commented Jan 22, 2024

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
Copy link
Owner

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
Copy link

mdhosen commented Feb 2, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

6 participants