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

Convert to Tensorflow.js model #2127

Closed
pravastacaraka opened this issue Feb 4, 2021 · 28 comments
Closed

Convert to Tensorflow.js model #2127

pravastacaraka opened this issue Feb 4, 2021 · 28 comments
Labels
question Further information is requested Stale

Comments

@pravastacaraka
Copy link

❔Question

Hello,, is it possible to convert the YOLOv5 PyTorch model to the Tensorflow.js model?

@pravastacaraka pravastacaraka added the question Further information is requested label Feb 4, 2021
@github-actions
Copy link
Contributor

github-actions bot commented Feb 4, 2021

👋 Hello @pravastacaraka, 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://www.ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

Python 3.8 or later with all requirements.txt dependencies installed, including torch>=1.7. To install run:

$ 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), testing (test.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

@pravastacaraka yes, you can convert to TF js by exporting to TF first and then onward to js. See #1127 for TF export.

@pravastacaraka
Copy link
Author

@glenn-jocher I have an issue with the Colab, when I try to export use
!PYTHONPATH=. python models/tf.py --weights weights/tooth.pt --cfg models/yolov5s.yaml --img 416 --tf-nms

There is an error

TensorFlow saved_model export failure: 'Conv2d' object has no attribute 'conv'
Traceback (most recent call last):
File "models/tf.py", line 391, in
tf_model = tf_Model(opt.cfg, model=model, nc=nc)
File "models/tf.py", line 306, in init
self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model) # model, savelist, ch_out
File "models/tf.py", line 278, in parse_model
else tf_m(*args, w=model.model[i]) # module
File "models/tf.py", line 147, in init
self.cv2 = tf_Conv(c1, c_, 1, 1, w=w.cv2)
File "models/tf.py", line 62, in init
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()))
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 779, in getattr
type(self).name, name))
torch.nn.modules.module.ModuleAttributeError: 'Conv2d' object has no attribute 'conv'

Starting TensorFlow GraphDef export with TensorFlow 2.4.1...
TensorFlow GraphDef export failure: name 'keras_model' is not defined
Traceback (most recent call last):
File "models/tf.py", line 416, in
tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
NameError: name 'keras_model' is not defined

Is there something wrong?

@glenn-jocher
Copy link
Member

@pravastacaraka Keras and TF export should be working, but I remember seeing a similar error message on the PR. Is this error reproducible with the default models?

Also I'm not sure if export is verified with TF 2.4.1, only TF 2.4.0 as far as I've seen.

@pravastacaraka
Copy link
Author

@pravastacaraka Keras and TF export should be working, but I remember seeing a similar error message on the PR. Is this error reproducible with the default models?

@glenn-jocher I haven't tried to convert the default model from YOLOv5.

Also I'm not sure if export is verified with TF 2.4.1, only TF 2.4.0 as far as I've seen.

I tried this on Colab, should I change the Tensorflow version to 2.4.0 first? Because I have tried it on my laptop with installed TF 2.4.0 and PyTorch 1.7.1 the results are the same as the error I showed before.

Then I tried to change to TF 2.3.0, and PyTorch 1.6.0 resulted in a different error. Here it is the error:

Namespace(batch_size=1, cfg='models/yolov5s.yaml', dynamic_batch_size=False, img_size=[416, 416], iou_thres=0.5, ncalib=100, no_tfl_detect=False, score_thres=0.4, source='../data/coco128.yaml', tf_nms=True, tfl_int8=False, topk_all=100, topk_per_class=100, weights='weights/tooth.pt')
Traceback (most recent call last):
File "tf.py", line 383, in
model = torch.load(opt.weights, map_location=torch.device('cpu'))['model'].float() # .fuse()
File "D:\proyek-akhir\yolov5-tf-export.env\lib\site-packages\torch\serialization.py", line 584, in load
return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args)
File "D:\proyek-akhir\yolov5-tf-export.env\lib\site-packages\torch\serialization.py", line 842, in _load
result = unpickler.load()
AttributeError: Can't get attribute 'SiLU' on <module 'torch.nn.modules.activation' from 'D:\proyek-akhir\yolov5-tf-export.env\lib\site-packages\torch\nn\modules\activation.py'>

@glenn-jocher
Copy link
Member

@pravastacaraka yes your new error is expected. torch requirements are >=1.7.0.

In your results then it seems that 2.4.1 and 2.4.0 behave identically for our intents and purposes. You may want to verify export with a default model before trying a custom model to remove your model as a source of error.

@pravastacaraka
Copy link
Author

@glenn-jocher Ahh... I have tried it for the YOLOv5s default model, and it works. What's wrong with my training custom model?

@glenn-jocher
Copy link
Member

@pravastacaraka it's likely just out of date. I would git clone a new copy fo the repo and retrain your model, then it will export correctly.

@pravastacaraka
Copy link
Author

Can I use the previous model as my checkpoint?

@batrlatom
Copy link
Contributor

@glenn-jocher Ahh... I have tried it for the YOLOv5s default model, and it works. What's wrong with my training custom model?

Do you have a nms code written in tfjs to share? I was able to convert model to tfjs correctly, but I am struggling to parse boxes and scores after the prediction. Thanks!

@glenn-jocher
Copy link
Member

@batrlatom can you use the TF JS NMS function here?
https://js.tensorflow.org/api/latest/#image.nonMaxSuppression

@pravastacaraka
Copy link
Author

@batrlatom can you use the TF JS NMS function here?
https://js.tensorflow.org/api/latest/#image.nonMaxSuppression

@glenn-jocher where can I put the code?

@glenn-jocher
Copy link
Member

@pravastacaraka I think if you are building a TF JS version of YOLOv5 you should pipeline a nonMaxSuppression() layer immediately after the Detect() layer, but I'm a little light on details as I actually have not gone down this path myself.

@anas-899
Copy link

anas-899 commented Apr 15, 2021

@pravastacaraka @batrlatom
I have converted it to js easily using:
tensorflowjs_converter --input_format=tf_saved_model --output_format=tfjs_graph_model

was anybody able to implement the non-max-suppression and can share the javascript code?
because it's not just calling tf.NMS, there are many operations need to be done as well.

I followed the implementation from https://github.com/ModelDepot/tfjs-yolo-tiny , but I am getting wrong output.

@pravastacaraka
Copy link
Author

@anas-899 yes, i still haven't found a way to implement the nms either

@LundinMachine
Copy link

@anas-899 that repo uses yolo v3, built on darknet not torch.

@dewball345
Copy link

@glenn-jocher Ahh... I have tried it for the YOLOv5s default model, and it works. What's wrong with my training custom model?

Do you have a nms code written in tfjs to share? I was able to convert model to tfjs correctly, but I am struggling to parse boxes and scores after the prediction. Thanks!

How were you able to get the prediction!!!!!!! i'm getting Cannot read property 'name' of undefined

@pravastacaraka
Copy link
Author

pravastacaraka commented Jun 6, 2021

@batrlatom Have you found the solution?

@dewball345 As I explained here tensorflow/tfjs#4637 (comment)

@zldrobit
Copy link
Contributor

@batrlatom @anas-899 @LundinMachine @dewball345 I have updated tf-only-export branch in #1127, and it now supports tjfs model export.
To do this, I embed tf.image.non_max_suppresssion in the GraphDef and tfjs models.
So, there is no NMS code written in javascript.
Plz try the updated tf-only-export branch.

@dewball345
Copy link

@zldrobit I also created a repo with nms, but in addition it contains some preprocessing/postprocessing utilities as well as other stuff like drawing to canvas. https://github.com/dewball345/ear.js

@zldrobit
Copy link
Contributor

@dewball345 That's cool. I looked into the repo and found that you used tf.image.nonMaxSuppressionAsync in tfjs, which I didn't found before. I noticed that you reported the inference speed is 12 fps and your model resolution is 640x640. What device do you use for inference?

@dewball345
Copy link

dewball345 commented Jun 23, 2021

@zldrobit Oh my, i didn't realize that. I'm using a relatively high-end pc, so the 12 fps is definitely not that accurate. Thanks for bringing this up, I've changed my readme so as to not mislead others

@dewball345
Copy link

@dewball345 That's cool. I looked into the repo and found that you used tf.image.nonMaxSuppressionAsync in tfjs, which I didn't found before. I noticed that you reported the inference speed is 12 fps and your model resolution is 640x640. What device do you use for inference?

Originally i used tf.image.nonMaxSuppression, but i got a warning in my console.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 24, 2021

👋 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 ⭐!

@thaingoc2604
Copy link

how to convert model .pt to tflite

@glenn-jocher
Copy link
Member

glenn-jocher commented Dec 8, 2021

@thaingoc2604 see TFLite, ONNX, CoreML, TensorRT Export 🚀 tutorial for TFLite export instructions:

YOLOv5 Tutorials

@SkalskiP
Copy link
Contributor

Hi, @glenn-jocher 👋! I just wanted to let you know, that I created a yolov5js npm package that allows for almost effortless deployment of YOLOv5 models converted to tensorflow.js format on websites.

I actually used the newly created package, to add YOLOv5 support in makesense.ai. Here is a pre-release instance and a short video showcasing new feature.

2022-09-30-08-54-57-small.mp4

@glenn-jocher
Copy link
Member

Hi @SkalskiP, that's fantastic to hear! It's great to see the YOLOv5 community thriving and building innovative tools. Congratulations on creating the yolov5js NPM package and integrating YOLOv5 support into makesense.ai. Your contribution is invaluable to the community. Keep up the excellent work, and feel free to reach out if you need any assistance or have any questions.

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
Projects
None yet
Development

No branches or pull requests

9 participants