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

Problems with quantized model #12609

Closed
1 task done
joaopdss opened this issue Jan 10, 2024 · 10 comments
Closed
1 task done

Problems with quantized model #12609

joaopdss opened this issue Jan 10, 2024 · 10 comments
Labels
question Further information is requested

Comments

@joaopdss
Copy link

Search before asking

Question

Hey, I've been having some problems with the YoloV5 model after quantization:

  • I am getting "dots" boxes in certain parts of my output
  • It don't work as expected if compared to the non quantized model.

Not exactly sure if it's something related to my input, but I don't think so

I'll provide a part of my code below

Code for quantized (uint8) model:

interpreter = tf.lite.Interpreter("model_non_quantized.tflite")
interpreter.allocate_tensors()

image = cv2.imread(r"C:\Users\Admin\Documents\Projetos\vehicle-detector\dataset\valid\images\000193_jpeg.rf.4eb3678b99257c194bad925261b3fcc2.jpg")
image = cv2.resize(original_image, (224, 224))
image = image.astype(np.float32)
image = cv2.cvtColor(image.astype(np.float32), cv2.COLOR_BGR2RGB)
image /= 255
img = np.expand_dims(image, axis=0)

output_zero = interpreter.get_output_details()[0]['quantization'][1]
output_scale = interpreter.get_output_details()[0]['quantization'][0]
img = (img / output_scale + output_zero).astype(np.uint8)

interpreter.set_tensor(input_details[0]['index'], img)
interpreter.invoke()

output = interpreter.get_tensor(interpreter.get_output_details()[0]['index'])
output = (output.astype(np.float32) - output_zero) * output_scale

w, h = input_details[0]["shape"][1:3]
output[0][..., :4] *= [w, h, w, h]
print(output[0][..., :4])

output:

[[  0.          7.4162035   6.489178    9.270255 ]
 [  0.          7.4162035  12.978356   14.832407 ]
 [  0.          7.4162035   7.4162035  13.905382 ]
 ...
 [221.55908   200.23749     0.          0.       ]
 [200.23749   200.23749     0.          0.       ]
 [200.23749   200.23749     0.          0.       ]]

after applying NMS, we have the following results
image

Code for non quantized (float32) model:

interpreter = tf.lite.Interpreter("model_quantized.tflite")
interpreter.allocate_tensors()

image = cv2.imread(r"C:\Users\Admin\Documents\Projetos\vehicle-detector\dataset\valid\images\000193_jpeg.rf.4eb3678b99257c194bad925261b3fcc2.jpg")
image = cv2.resize(original_image, (224, 224))
image = image.astype(np.float32)
image = cv2.cvtColor(image.astype(np.float32), cv2.COLOR_BGR2RGB)
image /= 255
img = np.expand_dims(image, axis=0)

interpreter.set_tensor(input_details[0]['index'], img)
interpreter.invoke()

output = interpreter.get_tensor(interpreter.get_output_details()[0]['index'])

w, h = input_details[0]["shape"][1:3]
output[0][..., :4] *= [w, h, w, h]
print(output[0][..., :4])

output:

[[  2.7024584   4.1183963   8.367914   10.148943 ]
 [  3.111283    4.3573003   8.727393   10.300795 ]
 [  3.2405856   4.46125     9.25566    11.281149 ]
 ...
 [212.82776   200.03745    21.792944   36.60185  ]
 [209.99141   194.01413    30.422749   41.619286 ]
 [199.55162   199.17126    55.95596    42.3295   ]]

after applying NMS, we have the following results
image

Any ideas about the reason I am getting these huge differences between the results? Am I doing something wrong with the input for the quantized model?
And why the output of the quantized model is like this?

[221.55908   200.23749     0.          0.       ]
 [200.23749   200.23749     0.          0.       ]
 [200.23749   200.23749     0.          0.       ]]

Additional

No response

@joaopdss joaopdss added the question Further information is requested label Jan 10, 2024
Copy link
Contributor

github-actions bot commented Jan 10, 2024

👋 Hello @joaopdss, 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 a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.8.0 with all requirements.txt installed including PyTorch>=1.8. To get started:

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

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

YOLOv5 CI

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

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics

@glenn-jocher
Copy link
Member

@joaopdss hello! Thanks for reaching out with your quantization issue. Quantization can indeed introduce some discrepancies due to the reduced precision of the model weights and activations. Here are a few things to consider:

  1. Quantization Parameters: Ensure that the quantization parameters (scale and zero-point) are correctly applied. It's crucial that these are accurate for both the input and output tensors.

  2. Model Accuracy: Post-quantization, some drop in accuracy is expected. It's important to evaluate the quantized model's performance on a representative dataset to understand the impact.

  3. Quantization Aware Training (QAT): If you haven't already, consider using QAT, which can help the model to adapt to the lower precision and potentially improve the quantized model's performance.

  4. Debugging: Check for any potential bugs in the preprocessing and postprocessing steps. The "dots" you're seeing could be due to incorrect bounding box scaling or non-maximum suppression (NMS) issues.

  5. Model Compatibility: Ensure that the model architecture is compatible with quantization. Some operations may not quantize well, leading to significant degradation.

  6. Version Mismatch: Verify that you're using the same version of TensorFlow for both training and inference, as differences can lead to unexpected behavior.

If you continue to face issues, consider providing more details on the quantization process you followed, and check out our documentation for any additional guidance. Keep in mind that quantization is a trade-off between model size, speed, and accuracy. 🤖🔍

@joaopdss
Copy link
Author

@joaopdss hello! Thanks for reaching out with your quantization issue. Quantization can indeed introduce some discrepancies due to the reduced precision of the model weights and activations. Here are a few things to consider:

  1. Quantization Parameters: Ensure that the quantization parameters (scale and zero-point) are correctly applied. It's crucial that these are accurate for both the input and output tensors.
  2. Model Accuracy: Post-quantization, some drop in accuracy is expected. It's important to evaluate the quantized model's performance on a representative dataset to understand the impact.
  3. Quantization Aware Training (QAT): If you haven't already, consider using QAT, which can help the model to adapt to the lower precision and potentially improve the quantized model's performance.
  4. Debugging: Check for any potential bugs in the preprocessing and postprocessing steps. The "dots" you're seeing could be due to incorrect bounding box scaling or non-maximum suppression (NMS) issues.
  5. Model Compatibility: Ensure that the model architecture is compatible with quantization. Some operations may not quantize well, leading to significant degradation.
  6. Version Mismatch: Verify that you're using the same version of TensorFlow for both training and inference, as differences can lead to unexpected behavior.

If you continue to face issues, consider providing more details on the quantization process you followed, and check out our documentation for any additional guidance. Keep in mind that quantization is a trade-off between model size, speed, and accuracy. 🤖🔍

The thing that does not make sense for me is that I am exporting with the YoloV5 Ultranalytics way and executing with the same scripts the non quantized and quantized models, and the results have a huge difference.

export line:

!python yolov5/export.py --weights /content/drive/MyDrive/IA_Checkpoint_YoloV5/exp/weights/best.pt --img 224 --data yolov5/dataset/data.yaml --include tflite --int8

execution line:

!python yolov5/detect.py --weights /content/drive/MyDrive/IA_Checkpoint_YoloV5/exp/weights/best-int8.tflite --img 224 --data /content/yolov5/dataset/data.yaml --conf 0.2 --source /content/yolov5/dataset/valid/images

some results with the non quantized model:
image

same results with the quantized model:
image

Maybe is there something missing in the export.py line? I know the results can be different from both models but the difference is just too much, does not make sense for me

@glenn-jocher
Copy link
Member

@joaopdss, it's clear that the quantization is having a significant impact on your model's performance. The discrepancy you're observing is indeed larger than one might typically expect. Here are a few additional steps to consider:

  1. Model Calibration: During the quantization process, ensure that the model is calibrated with a representative dataset. This helps in determining more accurate quantization parameters.

  2. Export Verification: Double-check the export command and ensure that all necessary flags and parameters are set correctly. The --int8 flag should trigger quantization, but it's worth verifying that this process is completing as expected.

  3. Inference Script: When running the detect.py script with a quantized model, make sure that the script is compatible with the TFLite model and that it's handling quantized inputs and outputs correctly.

  4. Model Inspection: Inspect the quantized TFLite model to ensure that the quantization process has been applied uniformly across all layers and that no layers have been inadvertently missed or incorrectly quantized.

  5. Evaluation: Evaluate the quantized model on a larger set of data to get a more comprehensive understanding of its performance. Sometimes, a few images might not be representative of the overall accuracy.

  6. Compare Intermediate Outputs: Compare the intermediate outputs of both the quantized and non-quantized models to pinpoint where the divergence begins. This can help identify if the issue is in the early or later stages of the model.

  7. Consult Documentation: Review the Ultralytics documentation for any updates or notes on quantization that might be relevant to your issue.

If these steps don't resolve the issue, it might be helpful to open a detailed issue on the YOLOv5 repository with all the information you've gathered, including the exact commands used, sample outputs, and any other relevant details. This can help the community to provide more targeted assistance. Remember, quantization is complex, and sometimes it requires a bit of trial and error to get right. 🛠️🧐

@joaopdss
Copy link
Author

@joaopdss, it's clear that the quantization is having a significant impact on your model's performance. The discrepancy you're observing is indeed larger than one might typically expect. Here are a few additional steps to consider:

  1. Model Calibration: During the quantization process, ensure that the model is calibrated with a representative dataset. This helps in determining more accurate quantization parameters.
  2. Export Verification: Double-check the export command and ensure that all necessary flags and parameters are set correctly. The --int8 flag should trigger quantization, but it's worth verifying that this process is completing as expected.
  3. Inference Script: When running the detect.py script with a quantized model, make sure that the script is compatible with the TFLite model and that it's handling quantized inputs and outputs correctly.
  4. Model Inspection: Inspect the quantized TFLite model to ensure that the quantization process has been applied uniformly across all layers and that no layers have been inadvertently missed or incorrectly quantized.
  5. Evaluation: Evaluate the quantized model on a larger set of data to get a more comprehensive understanding of its performance. Sometimes, a few images might not be representative of the overall accuracy.
  6. Compare Intermediate Outputs: Compare the intermediate outputs of both the quantized and non-quantized models to pinpoint where the divergence begins. This can help identify if the issue is in the early or later stages of the model.
  7. Consult Documentation: Review the Ultralytics documentation for any updates or notes on quantization that might be relevant to your issue.

If these steps don't resolve the issue, it might be helpful to open a detailed issue on the YOLOv5 repository with all the information you've gathered, including the exact commands used, sample outputs, and any other relevant details. This can help the community to provide more targeted assistance. Remember, quantization is complex, and sometimes it requires a bit of trial and error to get right. 🛠️🧐

I solved the issue, looks like there is some problem with the recent versions of TensorFlow when applying Post-training quantization. I ran the quantization script (export.py) again but with Tensorflow 2.12.0 and it worked.

@glenn-jocher
Copy link
Member

@joaopdss, that's great news! I'm glad to hear you were able to resolve the issue by using TensorFlow 2.12.0 for the quantization process. It's not uncommon for different versions of TensorFlow to behave differently, especially with operations as sensitive as quantization. Your findings could be valuable for others in the community facing similar issues, so thank you for sharing your solution.

If you encounter any more challenges or have further questions as you continue working with YOLOv5, feel free to reach out. Happy detecting! 😊👍

@YejinHwang909
Copy link

Thank you!! i solved same problem with Tensorflow 2.12.0 !! 😊

@glenn-jocher
Copy link
Member

You're welcome! I'm glad it worked out with TensorFlow 2.12.0. If you have any more questions, feel free to ask.

@AllanKamimura
Copy link

Thanks for this thread,
the Tensorflow 2.12.0 worked like a charm. 🙃👍

@pderrenger
Copy link
Member

Glad TensorFlow 2.12.0 worked for you! 🚀 For others facing similar issues, ensure you follow our TFLite export guide and verify TF compatibility. If problems persist, share your exact environment details for community help.

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

5 participants