ultralytics / yolov5

YOLOv5 πŸš€ in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
49.72k stars 16.12k forks source link

Loading model custom trained weights using Pytorch hub #1605

Closed p9anand closed 3 years ago

p9anand commented 3 years ago

❔Question

Loading model custom trained weights using Pytorch hub

Additional context

Hi,

I'm trying to load my custom model weights using torch hub. As you can see in the image. In one case It was able to load it and second case it failed.

image

But in the other case i got following error. image

image image

Lets say, if i choose first method to load the custom weights. how can i make inference directly of a PIL image. Because when i was trying to do that i got following error. image image

github-actions[bot] commented 3 years ago

Hello @p9anand, 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.

zhiqwang commented 3 years ago

I think that

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=6)
model.load_state_dict(torch.load('...')['model'].state_dict())

model = model.fuse().autoshape()

would be a method?

p9anand commented 3 years ago

I tried that but getting following error: image image image

custom weights are loaded successfully and Autoshape was also loaded successfully.

zhiqwang commented 3 years ago

It seems that this line

https://github.com/ultralytics/yolov5/blob/ba48f867ead1fcdc59f2a69fbe40c915bd4936bd/models/yolo.py#L192

didn't work as expected, could you please upload your model so that I could debug this problem (sorry I didn't train any custom model)

zhiqwang commented 3 years ago

Hi @p9anand

I did a quick fixes as below:

import torch
from PIL import Image

def copy_attr(a, b, include=(), exclude=()):
    # Copy attributes from b to a, options to only include [...] and to exclude [...]
    for k, v in b.__dict__.items():
        if (len(include) and k not in include) or k.startswith('_') or k in exclude:
            continue
        else:
            setattr(a, k, v)

# my network so slow that I can't download your model above successfully :(
# so I just use ultralytics's pretrained model here 
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=False, classes=80)
checkpoint_ = torch.load('../yolov5-ultralytics/weights/yolov5s.pt')['model']
model.load_state_dict(checkpoint_.state_dict())

copy_attr(model, checkpoint_, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=())

model = model.fuse().autoshape()

img = Image.open('./notebooks/assets/zidane.jpg')
output = model(img)

print(f'prediction: {output.pred}')

Hope it can help you

p9anand commented 3 years ago

It worked. Thanks for the help!!

glenn-jocher commented 3 years ago

@zhiqwang would you be able to submit a PR with your updates to copy_attr()? Thanks!!

zhiqwang commented 3 years ago

Hi @glenn-jocher It's my pleasure to contribute this awesome repo.

The copy_attr() function is actually copied from

https://github.com/ultralytics/yolov5/blob/ba48f867ead1fcdc59f2a69fbe40c915bd4936bd/utils/torch_utils.py#L199-L205

This issue only occur when somebody are loading the trained model with torch.hub and setting pretrained to be False. It's normal using

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, classes=80)

And there is a tutorial of the usage with torch.hub in #36, and you comment that

Load a State Dict

To load a custom state dict, first load a PyTorch Hub model of the same kind with the same number of classes:

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=10)
model.load_state_dict(torch.load('yolov5s_10cls.pt')['model'].state_dict())

So maybe it would be better to put this directions of the usage of copy_attr() there?

glenn-jocher commented 3 years ago

@zhiqwang ah yes, I understand. We probably want to make changes in two places:

  1. tutorial with the changes you recommended
  2. yolo.py addition to automatically create a default names attribute that can be used for when people don't pass their own names in 1.
glenn-jocher commented 3 years ago

@p9anand @zhiqwang I've updated the PyTorch Hub tutorial as follows and implemented a default class names list in PR #1608.

@p9anand can you confirm that the new tutorial directions work for you? They are here. I think names is the only attribute that was missing before.

Load a State Dict

To load a custom state dict, first load a PyTorch Hub model of the same kind with the same number of classes:

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=10)  # create model
ckpt = torch.load('yolov5s_10cls.pt')['model']  # load checkpoint
model.load_state_dict(ckpt.state_dict())
model.names = ckpt.names  # transfer class names (recommended)
glenn-jocher commented 3 years ago

@zhiqwang ah also, the .autoshape() method contains a .fuse() call inside it, so you can simply do model.autoshape().

zhiqwang commented 3 years ago

Hi @glenn-jocher , Got it, it's more clean now.

p9anand commented 3 years ago

@glenn-jocher : It worked. Thanks for the help!!

Sagor-Saha commented 3 years ago

It didnt work in my case image here is the code I am using for custom model image

glenn-jocher commented 3 years ago

@Sagor-Saha see pytorch hub tutorial for correct loading of custom models.

Sagor-Saha commented 3 years ago

I am trying to integrate the custom trained model into a django project. The command for custom model in [https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading] does not work when I run the model from django. But it definitely works without django. image.

glenn-jocher commented 3 years ago

@Sagor-Saha those error messages are simply due to your environment not meeting the requirements in requirements.txt.

It appears you may have environment problems. Please ensure you meet all dependency requirements if you are attempting to run YOLOv5 locally. If in doubt, create a new virtual Python 3.8 environment, clone the latest repo (code changes daily), and pip install -r requirements.txt again. We also highly recommend using one of our verified environments below.

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 passing. These tests evaluate proper operation of basic YOLOv5 functionality, including training (train.py), testing (test.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu.

DineshKumar9412 commented 3 years ago

i Run that same program i face this error

AttributeError: 'AutoShape' object has no attribute 'fuse'

glenn-jocher commented 3 years ago

@DineshKumar9412 πŸ‘‹ hi, thanks for letting us know about this problem with YOLOv5 πŸš€. We've created a few short guidelines below to help users provide what we need in order to get started investigating a possible problem.

How to create a Minimal, Reproducible Example

When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:

In addition to the above requirements, for Ultralytics to provide assistance your code should be:

If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the πŸ› Bug Report template and providing a minimum reproducible example to help us better understand and diagnose your problem.

Thank you! πŸ˜ƒ

shawonis08 commented 3 years ago

model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt') # default model = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local') # local repo

abhigoku10 commented 3 years ago

@zhiqwang @glenn-jocher thanks for the detailed explanation but wanted to know that model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt') # default yolov5 architecture trained on COCO data and model = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local') # local repo with architecture changes ie adding mulittaksking / removed few layers / instead gave path to yolov5m , does still torch.hub will be alble to load the custom model.???

DineshKumar9412 commented 3 years ago

Thank you so much

On Tue, Aug 10, 2021, 11:02 PM abhigoku10 @.***> wrote:

@zhiqwang https://github.com/zhiqwang @glenn-jocher https://github.com/glenn-jocher thanks for the detailed explanation but wanted to know that model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/ best.pt') # default yolov5 architecture trained on COCO data and model = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local') # local repo with architecture changes ie adding mulittaksking / removed few layers / instead gave path to yolov5m , does still torch.hub will be alble to load the custom model.???

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/ultralytics/yolov5/issues/1605#issuecomment-896178580, or unsubscribe https://github.com/notifications/unsubscribe-auth/ATZ55VEW2BYGM7MF7PHKH23T4FPDZANCNFSM4UOKYJLA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&utm_campaign=notification-email .

littlerain2310 commented 3 years ago

Do we need to redefine the number of classes when we load a custom weight by pytorch ? Because my new weights have only 1 class

glenn-jocher commented 3 years ago

@littlerain2310 no

littlerain2310 commented 3 years ago

Thanks @glenn-jocher. One more question:

glenn-jocher commented 3 years ago

@littlerain2310 πŸ‘‹ hi, thanks for letting us know about this problem with YOLOv5 πŸš€. We've created a few short guidelines below to help users provide what we need in order to get started investigating a possible problem.

How to create a Minimal, Reproducible Example

When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a minimum reproducible example. Your code that reproduces the problem should be:

In addition to the above requirements, for Ultralytics to provide assistance your code should be:

If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the πŸ› Bug Report template and providing a minimum reproducible example to help us better understand and diagnose your problem.

Thank you! πŸ˜ƒ

littlerain2310 commented 3 years ago

@glenn-jocher thanks for your reply!

HasibGit commented 2 years ago

For my custom model, after a lot of trial and error i tried this way and it worked!

model = torch.hub.load( "ultralytics/yolov5", "custom", path = './tests/last.pt', force_reload=True, autoshape=True ) # force_reload = recache latest code

glenn-jocher commented 2 years ago

@HasibGit yes

# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')  # or yolov5m, ... yolov5x6 etc. official models
model = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt')  # custom model
Barry04 commented 2 years ago

can some one help me ? image

glenn-jocher commented 2 years ago

@Barry04 your pytorch is likely out of date. See https://pytorch.org/get-started/locally/

gd1925 commented 2 years ago

Hii, I have been struggling a lot to load a custom model as here - https://github.com/ultralytics/yolov5/releases/download/v6.0/yolov5m_Objects365.pt to my main.py file using torch.hub.load but its been failing for the last two days now. I have tried multiple ways, but I cant seem to get it working. Could someone please help me with it? image

glenn-jocher commented 2 years ago

@gd1925 πŸ‘‹ Hello! Thanks for asking about handling inference results. YOLOv5 πŸš€ PyTorch Hub models allow for simple model loading and inference in a pure python environment without using detect.py.

Simple Inference Example

This example loads a pretrained YOLOv5s model from PyTorch Hub as model and passes an image for inference. 'yolov5s' is the YOLOv5 'small' model. For details on all available models please see the README. Custom models can also be loaded, including custom trained PyTorch models and their exported variants, i.e. ONNX, TensorRT, TensorFlow, OpenVINO YOLOv5 models.

import torch

# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')  # yolov5n - yolov5x6 official model
#                                            'custom', 'path/to/best.pt')  # custom model

# Images
im = 'https://ultralytics.com/images/zidane.jpg'  # or file, Path, URL, PIL, OpenCV, numpy, list

# Inference
results = model(im)

# Results
results.print()  # or .show(), .save(), .crop(), .pandas(), etc.
results.xyxy[0]  # im predictions (tensor)

results.pandas().xyxy[0]  # im predictions (pandas)
#      xmin    ymin    xmax   ymax  confidence  class    name
# 0  749.50   43.50  1148.0  704.5    0.874023      0  person
# 2  114.75  195.75  1095.0  708.0    0.624512      0  person
# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie

results.pandas().xyxy[0].value_counts('name')  # class counts (pandas)
# person    2
# tie       1

See YOLOv5 PyTorch Hub Tutorial for details.

Good luck πŸ€ and let us know if you have any other questions!

gd1925 commented 2 years ago

Hi @glenn-jocher, Thank you so much for your reply and the explanation. Its working on my side now!!

gd1925 commented 2 years ago

Hi @glenn-jocher, my question is in reference to the integrating the above yolov5 with CVAT toolkit. I have added the following lines of code to my main.py but I am not sure if it is correct. Could you please take a look and let me know if its the correct way to load the model? MicrosoftTeams-image (9)

I am not getting any error, but on running deploy_gpu.sh, it stops at building image ... image

Could you please help me? Thank you in advance..

glenn-jocher commented 2 years ago

YOLOv5 PyTorch Hub models automatically load on GPU if available, so your logic is redundant.

Also I think you might need cuda:0 rather than cuda if you're going to manually attempt device logic.

gd1925 commented 2 years ago

Hi @glenn-jocher, Thank you so much for your reply. I will try it out.

glenn-jocher commented 10 months ago

@gd1925 you're welcome! 😊 Don't hesitate to reach out if you have any more questions or run into any issues. Good luck with your implementation!