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 can I move and run the classification model out of YOLOV5 codebase? #8790

Closed
1 task done
AI-Passionner opened this issue Jul 30, 2022 · 19 comments · Fixed by #9027
Closed
1 task done

How can I move and run the classification model out of YOLOV5 codebase? #8790

AI-Passionner opened this issue Jul 30, 2022 · 19 comments · Fixed by #9027
Labels
question Further information is requested

Comments

@AI-Passionner
Copy link

Search before asking

Question

It seems that loading the classification model can't leave out of the YOLOV5-Classifier code base. When loading the model,
model = torch.load('path/to/best.pt', map_location=torch.device('cpu'))['model'].float(), it throws error like this
"""
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'models'
"""
Once the folders of models and utils are copied to a new project directory, the loading works.

I am asking if there is a way I can load the classification model and use it as a stand-alone and for example, converting to TensorFlow like the object detection codebase.
As I know, the YOLOV5 object detection doesn't have this problem.

Thanks.

Additional

No response

@AI-Passionner AI-Passionner added the question Further information is requested label Jul 30, 2022
@glenn-jocher
Copy link
Member

@AI-Passionner this is a good question. In general for any pytorch model you'll need to have the modules available in the workspace prior to loading. PyTorch Hub accomplishes this in the background by downloading and caching the repo in a separate directory.

To point PyTorch Hub to a specific branch in a repo, i.e. the classifier branch in the YOLOv5 repo you can try this, though the classifier should be merged into master as part of the upcoming v6.2 release in the next few weeks.

model = torch.hub.load('ultralytics/yolov5:classifier', 'custom', path='path/to/model.pt')  # local model

@AI-Passionner
Copy link
Author

@glenn-jocher Thank you. Let me try. I bet this is what I am looking for. Really appreciate your help.
Tiger

@AI-Passionner
Copy link
Author

AI-Passionner commented Aug 1, 2022

The classification model was trained as yolov5s. I copied the model file to the new project and. But it didn't work when loading the new model as your suggested scripts.
model = torch.hub.load('ultralytics/yolov5:classifier', 'custom', path='weights/yolov5s_exp30/weights/best.pt')

I threw the error message like this. Adding force_reload=True didn't work. Deleting the Cache didn't work. Any suggestion?
Do I need to specify the custom in the script?

""""
Fusing layers...
YOLOv5s summary: 117 layers, 4169250 parameters, 0 gradients, 10.4 GFLOPs
Adding AutoShape...
Traceback (most recent call last):
File "C:\Users\tiger.cao/.cache\torch\hub\ultralytics_yolov5_classifier\hubconf.py", line 62, in _create
return model.to(device)
File "C:\Users\tiger.cao\anaconda3\envs\Yolov5\lib\site-packages\torch\nn\modules\module.py", line 927, in to
return self._apply(convert)
File "C:\Users\tiger.cao/.cache\torch\hub\ultralytics_yolov5_classifier\models\common.py", line 571, in _apply
m.stride = fn(m.stride)
File "C:\Users\tiger.cao\anaconda3\envs\Yolov5\lib\site-packages\torch\nn\modules\module.py", line 1207, in getattr
raise AttributeError("'{}' object has no attribute '{}'".format(
AttributeError: 'Classify' object has no attribute 'stride'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\tiger.cao\anaconda3\envs\Yolov5\lib\site-packages\IPython\core\interactiveshell.py", line 3398, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 1, in <cell line: 1>
model = torch.hub.load('ultralytics/yolov5:classifier', 'custom', force_reload=True, path='weights/yolov5s_exp30/weights/best.pt') # local model
File "C:\Users\tiger.cao\anaconda3\envs\Yolov5\lib\site-packages\torch\hub.py", line 540, in load
model = _load_local(repo_or_dir, model, *args, **kwargs)
File "C:\Users\tiger.cao\anaconda3\envs\Yolov5\lib\site-packages\torch\hub.py", line 569, in _load_local
model = entry(*args, **kwargs)
File "C:\Users\tiger.cao/.cache\torch\hub\ultralytics_yolov5_classifier\hubconf.py", line 72, in custom
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
File "C:\Users\tiger.cao/.cache\torch\hub\ultralytics_yolov5_classifier\hubconf.py", line 67, in _create
raise Exception(s) from e
Exception: 'Classify' object has no attribute 'stride'. Cache may be out of date, try force_reload=True or see https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading for help.
""""

@glenn-jocher
Copy link
Member

@AI-Passionner got it. It looks like we need to add some classifier-specific code to hubconf.py to handle these models differently, which makes sense. I'll add a TODO for this.

@AI-Passionner
Copy link
Author

@glenn-jocher Thank you.
Currently, I copied the folders models/ and utils/ with a little bit of cleaning to the new project. It works.

@glenn-jocher
Copy link
Member

glenn-jocher commented Aug 4, 2022

@AI-Passionner I think this should work now for newly trained models of type models.yolo.ClassificationModel, (but not for older models of type models.yolo.Model).

I'll run some tests to verify today.

@AI-Passionner
Copy link
Author

@glenn-jocher Thank you. I will run the train again and have a try.
Tiger

@glenn-jocher
Copy link
Member

glenn-jocher commented Aug 4, 2022

@AI-Passionner I've confirmed PyTorch Hub loading works in a test just now on Google Colab. I uploaded a recent ImageNet trained YOLOv5m-cls model (about 75 top-1 accuracy after 90 epochs) and then requested it like this. This does not need a local git clone of YOLOv5.
https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5m-cls.pt

import torch

model = torch.hub.load('ultralytics/yolov5:classifier', 'custom', 'yolov5m-cls.pt')  # or use local cls model
print(type(model))

Screen Shot 2022-08-04 at 9 11 47 PM

EDIT: Once we release 6.2 with built-in classification support then you no longer need to point torch.hub.load() to the classifier branch, i.e. you can use torch.hub.load('ultralytics/yolov5', ...)

glenn-jocher added a commit that referenced this issue Aug 4, 2022
* Fix TensorRT --dynamic excess outputs bug

Potential fix for #8790

* Cleanup

* Update common.py

* Update common.py

* New fix
@AI-Passionner
Copy link
Author

Great. Really appreciate your effort. YOLOV5 is the best for our object detection project so far, no matter its accuracy and speed.

@UygarUsta
Copy link

UygarUsta commented Aug 18, 2022

I am getting the same issue trying to inference using hub with classification models. Exception: 'Classify' object has no attribute 'stride'. Cache may be out of date, try force_reload=True or see https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading for help. classify/predict.py works fine though.

@glenn-jocher
Copy link
Member

@UygarUsta can you please submit a minimum reproducible example?

@glenn-jocher
Copy link
Member

@UygarUsta works for me.

Screenshot 2022-08-18 at 20 57 13

@UygarUsta
Copy link

@UygarUsta can you please submit a minimum reproducible example?

image

@UygarUsta
Copy link

I also tried it with ultralytics cache.No luck.

image

glenn-jocher added a commit that referenced this issue Aug 18, 2022
Add PyTorch Hub loading of official and custom trained classification models to CI checks. 

May help resolve #8790 (comment)

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>
@glenn-jocher
Copy link
Member

@UygarUsta added a CI check for this use case and can now reproduce in https://github.com/ultralytics/yolov5/runs/7905622621?check_suite_focus=true, I'll investigate.

glenn-jocher added a commit that referenced this issue Aug 18, 2022
* Add PyTorch Hub classification CI checks

Add PyTorch Hub loading of official and custom trained classification models to CI checks. 

May help resolve #8790 (comment)

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>

* Update hubconf.py

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>
@glenn-jocher
Copy link
Member

@UygarUsta good news 😃! Your original issue may now be fixed ✅ in PR #9027. 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 🚀!

@glenn-jocher glenn-jocher removed the TODO label Aug 18, 2022
@UygarUsta
Copy link

@UygarUsta good news 😃! Your original issue may now be fixed ✅ in PR #9027. 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 🚀!

Unfortunately another error arises.

image

I also tried my luck with ultralytics cache.As always thank you for your hard work .
image

ctjanuhowski pushed a commit to ctjanuhowski/yolov5 that referenced this issue Sep 8, 2022
* Fix TensorRT --dynamic excess outputs bug

Potential fix for ultralytics#8790

* Cleanup

* Update common.py

* Update common.py

* New fix
ctjanuhowski pushed a commit to ctjanuhowski/yolov5 that referenced this issue Sep 8, 2022
* Add PyTorch Hub classification CI checks

Add PyTorch Hub loading of official and custom trained classification models to CI checks. 

May help resolve ultralytics#8790 (comment)

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>

* Update hubconf.py

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>

Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com>
@aiakash
Copy link

aiakash commented Jun 22, 2023

its not working

import torch

model = torch.hub.load('ultralytics/yolov5:classifier', 'custom', 'yolov5m-cls.pt')  # or use local cls model
print(type(model))

ValueError: Cannot find classifier in https://github.com/ultralytics/yolov5. If it's a commit from a forked repo, please call hub.load() with forked repo directly.

@glenn-jocher
Copy link
Member

Understood, @aiakash. The error may be due to the ultralytics/yolov5:classifier hub identifier not yet being available. This is now under investigation. Thank you for your patience.

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

Successfully merging a pull request may close this issue.

4 participants