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

How to find mAP (mean absolute precision) of tflite of object detection? #5481

Closed
1 task done
MhmudAlpurd opened this issue Nov 3, 2021 · 17 comments · Fixed by #5549
Closed
1 task done

How to find mAP (mean absolute precision) of tflite of object detection? #5481

MhmudAlpurd opened this issue Nov 3, 2021 · 17 comments · Fixed by #5549
Labels
question Further information is requested Stale Stale and schedule for closing soon

Comments

@MhmudAlpurd
Copy link

Search before asking

Question

Hi everyone, I converted the PyTorch file of yolov5 to tflite (object detection model). and I’m going to get the mAP(mean absolute precision) or other performance metrics of this file. but I can’t find code or a way to do that. do you have this experience or solution?

thank you

Additional

No response

@MhmudAlpurd MhmudAlpurd added the question Further information is requested label Nov 3, 2021
@github-actions
Copy link
Contributor

github-actions bot commented Nov 3, 2021

👋 Hello @MhmudAlpurd, 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 [email protected].

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.

@glenn-jocher
Copy link
Member

@MhmudAlpurd there are no existing methods for obtaining mAP on exported models. You can run inference using detect.py on many model formats including TFLite for anecdotal comparisons however.

@MhmudAlpurd
Copy link
Author

@glenn-jocher thanks a lot for your helping.

@glenn-jocher
Copy link
Member

@MhmudAlpurd a number of users have asked about this, so we'll likely do a PR in the future to add this capability, but be aware TFLite inference is typically very slow on CPU, so running val.py on COCO for example with a TFLite model will take a very long time.

@glenn-jocher glenn-jocher linked a pull request Nov 9, 2021 that will close this issue
9 tasks
@glenn-jocher
Copy link
Member

glenn-jocher commented Nov 9, 2021

@MhmudAlpurd good news 😃! Your original issue may now be fixed ✅ in PR #5549. This PR consolidates all backends into a single YOLOv5 DetectMultiBackend() class. Supports following model formats:

  • PyTorch *.pt
  • TorchScript *.torchscript.pt
  • CoreML *.mlmodel
  • TensorFlow saved_model
  • TensorFlow *.pb
  • TensorFlow Lite *.tflite
  • TensorFlow.js web_model
  • ONNX Runtime *.onnx
  • OpenCV DNN *.onnx

Usage

# Export
python export.py --weights yolov5s.pt --include tflite

# Inference
python detect.py --weights yolov5s.tflite
python val.py --weights yolov5s.tflite

To receive this update:

  • Gitgit pull from within your yolov5/ directory or git clone https://github.com/ultralytics/yolov5 again
  • PyTorch Hub – Force-reload model = torch.hub.load('ultralytics/yolov5', 'yolov5s', force_reload=True)
  • Notebooks – View updated notebooks Open In Colab Open In Kaggle
  • Dockersudo docker pull ultralytics/yolov5:latest to update your image Docker Pulls

Thank you for spotting this issue and informing us of the problem. Please let us know if this update resolves the issue for you, and feel free to inform us of any other issues you discover or feature requests that come to mind. Happy trainings with YOLOv5 🚀!

@MhmudAlpurd
Copy link
Author

@glenn-jocher you are amazing. thanks a lot.

@Hyungjun-K1m
Copy link

Hyungjun-K1m commented Dec 6, 2021

@glenn-jocher It's amazing that the library already supports tflite inference!

However, it seems like the tflite model (https://github.com/ultralytics/yolov5/releases/download/v6.0/yolov5s.tflite) shows much lower mAP than the baseline model.

I'd like to know if there was any mistake.

I used the Raspberry Pi 4 B device with 64-bit linux OS and run
python val.py --data coco.yaml --weights './yolov5s.tflite' --imgsz 640

The results were

[email protected] [email protected]:.95
local mAP 0.512 0.301
pycocotools mAP 0.519 0.315

While the baseline mAP (pycocotools) results are 0.564 for [email protected] and 0.372 for [email protected]:.95, the tflite results are qutie low.
It might be due to the INT8 quantization of tflite conversion, but it's much severe than I expected.

Do you think this result is correct result?

Thanks!

@glenn-jocher
Copy link
Member

glenn-jocher commented Dec 6, 2021

@Hyungjun-K1m TFLite and CoreML exported models are at --img 320 image size suitable for mobile deployments. The PyTorch models are trained at --img 640.

If you export a tflite model yourself you will get the same mAP:

python export.py --weights yolov5s.pt --include tflite

python val.py --weights yolov5s.pt
python val.py --weights yolov5s-fp16.tflite

@glenn-jocher
Copy link
Member

Screenshot 2021-12-06 at 16 19 19

@Hyungjun-K1m
Copy link

yolov5s_head

@glenn-jocher
What I see from the downloaded tflite file is that it requires 640x640 inputs.
Thus I got ValueError about Dimension mismatch (Got 320 but expected 640 for dimension 1 of input 430) when I run the command with --imgsz 320 argument.
What do you mean by 'the tflite models are at --img 320' ?

By the way, I'll try to convert the pt model to tflite model by myself and check the performance.

Thanks for the help!

@Hyungjun-K1m
Copy link

Unfortunately, the newly exported tflite model showed similar mAP (0.520 for [email protected] and 0.314 for [email protected]:.95) as before.
Below command was used to export tflite file.
python export.py --weights ./yolov5s.pt --img 640 --include tflite --int8

Considering that the tflite model generated without --int8 flag shows acceptable mAP (0.561 for [email protected] and 0.371 for [email protected]:.95), I guess the degradation is from int8 ptq process.

Please let me know if you have different opinion! Thanks!

@glenn-jocher
Copy link
Member

@Hyungjun-K1m yes, for TFLite int8 models I also see about 5% lower mAP than with fp16 models. This is an interesting discovery! The quantization is the only difference so it must be the cause.

@glenn-jocher
Copy link
Member

@Hyungjun-K1m see https://www.tensorflow.org/lite/performance/post_training_quantization#model_accuracy

It looks like there are also a variety of quantization options, maybe you could experiment with the exact implementation here and let us know if anything works better than the current default:
https://www.tensorflow.org/lite/performance/post_training_quantization

yolov5/export.py

Lines 210 to 224 in 554f782

converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
converter.target_spec.supported_types = [tf.float16]
converter.optimizations = [tf.lite.Optimize.DEFAULT]
if int8:
dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.target_spec.supported_types = []
converter.inference_input_type = tf.uint8 # or tf.int8
converter.inference_output_type = tf.uint8 # or tf.int8
converter.experimental_new_quantizer = False
f = str(file).replace('.pt', '-int8.tflite')
tflite_model = converter.convert()

@glenn-jocher
Copy link
Member

glenn-jocher commented Dec 7, 2021

@zldrobit interesting discovery today. The YOLOv5s TFLite INT8 models are about 6% lower mAP than the FP16 TFLite/PyTorch models. As of PR #5845 3 days ago we can now validate all exported model formats.

python export.py --weights yolov5s.pt --include tflite
python export.py --weights yolov5s.pt --include tflite --int8

python val.py --data coco128.yaml --weights yolov5s.pt  # 41.3 mAP
python val.py --data coco128.yaml --weights yolov5s-fp16.tflite  # 40.9 mAP
python val.py --data coco128.yaml --weights yolov5s-int8.tflite  # 34.7 mAP

EDIT: do you think this is this within normal expectations for accuracy loss? I'm not sure myself, but I can try to export CoreML and obtain mAPs to see how well Apple is handling the int8 quantization.

@zldrobit
Copy link
Contributor

zldrobit commented Dec 8, 2021

@glenn-jocher In TFLite, full int8 quantization uses fixed-point integers, and calculates the scale and zero-point of a tensor for quantizing/dequantizing for activations (https://www.tensorflow.org/lite/performance/post_training_quantization#model_accuracy). There are only one scale and one zero-point for a tensor. This requires each value (random variable) in the tensor should have the same distribution, which is not the case. Unlike image classification, object detection needs outputs of object corrdinates. The last output tensor for the TFLite model is of shape [1, 25200, 5 + #classes], and the last dimension consists of xywh, objectiveness, and probabilities of classes. Though xywh is normalized to [0, 1] according to the range of probabilities, the distributions of xywh and the rest probabilities are different. And this introduces accuracy drops more or less.

On the other hand, some experiments on TensorFlow/TFLite (table 3 at the bottom of page 11) show that mobilenet v1 after post-training quantization (PTQ) has an accuracy drop about 10%. Changing from PTQ to quantization aware training (QAT) fixes this problem (table 4 at the bottom of page 21). I excerpt table 4:
image

Generally, if the accuracy after PTQ is acceptable, one could keep using the quantized model. Otherwise, one could (re)train and quantize the model with QAT (fine-tune).

EDIT: another example for QAT advantageous over PTQ https://developer.nvidia.com/blog/improving-int8-accuracy-using-quantization-aware-training-and-tao-toolkit/

@glenn-jocher
Copy link
Member

@zldrobit super interesting, thanks for the detailed analysis. In TFLite int8 export seems to be applied to the entire model at once, and like you said different layers have different distributions. CoreML actually quantizes each layer individually, applying a range or a lookup table (lookup table based on kmeans), so I think it might handle INT8 better because of this, but it also takes much longer. The CoreML INT8 quantization for a YOLOv5s model takes 5 minutes, and for a YOLOv5x model maybe almost an hour since it runs 256-point kmeans on each layer.

I still haven't had a chance to compare CoreML yet, but I'll try to do it this week. Naturally after #5845 the next logical step is to get mAP for each export format into a table. This is really exciting because we've never been able to validate exported models before, so we are only uncovering some of this now.

@github-actions
Copy link
Contributor

github-actions bot commented Jan 8, 2022

👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 🚀 resources:

Access additional Ultralytics ⚡ resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!

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

Successfully merging a pull request may close this issue.

4 participants