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

Error in loading yolov5 in local windows 11 #13500

Closed
1 of 2 tasks
pratyooshraj opened this issue Jan 27, 2025 · 5 comments
Closed
1 of 2 tasks

Error in loading yolov5 in local windows 11 #13500

pratyooshraj opened this issue Jan 27, 2025 · 5 comments
Labels
bug Something isn't working detect Object Detection issues, PR's

Comments

@pratyooshraj
Copy link

Search before asking

  • I have searched the YOLOv5 issues and found no similar bug report.

YOLOv5 Component

Detection

Bug

Currently running windows 11 and python 3.11. I trained my custom model using yolov5 using my custom data set in google colab. The model is used to detect sign language vowels.
!python train.py --img 416 --batch 16 --epochs 10 --data '/content/YOLO_vowels/data.yaml' --cfg ./models/custom_yolov5s.yaml --weights 'yolov5s.pt' --name yolov5s_vowels_results --cache disk --workers 4
The resulting best.pt in yolov5s_vowels_results i have downloaded and renamed. But an error occurs when i run the model in my device. I also tried running the pretrained yolov5s.pt model in my local device, which runs properly. Could you help me with the error.

Code

import torch
import os

print("Number of GPU: ", torch.cuda.device_count())
print("GPU Name: ", torch.cuda.get_device_name())


device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', force_reload=True)
model = torch.hub.load("ultralytics/yolov5", "custom", path="D:/Programming/cuda_test/yolov5/vowels_only_5epochs.pt" ,force_reload=True)  

Error

PS D:\Programming\cuda_test> python test1.py
Number of GPU:  1
GPU Name:  NVIDIA GeForce GTX 1650
Using device: cuda
Downloading: "https://github.com/ultralytics/yolov5/zipball/master" to C:\Users\ACER/.cache\torch\hub\master.zip
YOLOv5  2025-1-27 Python-3.11.4 torch-2.5.1+cu124 CUDA:0 (NVIDIA GeForce GTX 1650, 4096MiB)

---success in pretrained model

Fusing layers... 
YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients, 16.4 GFLOPs
Adding AutoShape... 
Downloading: "https://github.com/ultralytics/yolov5/zipball/master" to C:\Users\ACER/.cache\torch\hub\master.zip
YOLOv5  2025-1-27 Python-3.11.4 torch-2.5.1+cu124 CUDA:0 (NVIDIA GeForce GTX 1650, 4096MiB)

---Error in running custom model

Traceback (most recent call last):
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\hubconf.py", line 70, in _create
    model = DetectMultiBackend(path, device=device, fuse=autoshape)  # detection model
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\models\common.py", line 489, in __init__
    model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\models\experimental.py", line 98, in attempt_load
    ckpt = torch.load(attempt_download(w), map_location="cpu")  # load
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\ultralytics\utils\patches.py", line 86, in torch_load
    return _torch_load(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\torch\serialization.py", line 1360, in load
    return _load(
           ^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\torch\serialization.py", line 1848, in _load
    result = unpickler.load()
             ^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\pathlib.py", line 873, in __new__
    raise NotImplementedError("cannot instantiate %r on your system"
NotImplementedError: cannot instantiate 'PosixPath' on your system

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\hubconf.py", line 85, in _create
    model = attempt_load(path, device=device, fuse=False)  # arbitrary model
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\models\experimental.py", line 98, in attempt_load
    ckpt = torch.load(attempt_download(w), map_location="cpu")  # load
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\ultralytics\utils\patches.py", line 86, in torch_load
    return _torch_load(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\torch\serialization.py", line 1360, in load
    return _load(
           ^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\torch\serialization.py", line 1848, in _load
    result = unpickler.load()
             ^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\pathlib.py", line 873, in __new__
    raise NotImplementedError("cannot instantiate %r on your system"
NotImplementedError: cannot instantiate 'PosixPath' on your system

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\Programming\cuda_test\test1.py", line 14, in <module>
    model = torch.hub.load("ultralytics/yolov5", "custom", path="D:/Programming/cuda_test/yolov5/vowels_only_5epochs.pt" ,force_reload=True)  # local model
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\torch\hub.py", line 647, in load
    model = _load_local(repo_or_dir, model, *args, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Programming\cuda_test\.venv\Lib\site-packages\torch\hub.py", line 676, in _load_local
    model = entry(*args, **kwargs)
            ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\hubconf.py", line 135, in custom
    return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ACER/.cache\torch\hub\ultralytics_yolov5_master\hubconf.py", line 103, in _create
    raise Exception(s) from e
Exception: cannot instantiate 'PosixPath' on your system. Cache may be out of date, try `force_reload=True` or see https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading for help.

I tried to run my custom trained model for computer vision, trained in google colab and downloaded in windows 11. Instead of running an error occurs. However in google colab, correct detection and testing images were shown.

Environment

-YOLO -v5 ultralytics==8.3.68, torch==2.5.1+cu124
-OS: windows 11

Minimal Reproducible Example

import torch
import os

print("Number of GPU: ", torch.cuda.device_count())
print("GPU Name: ", torch.cuda.get_device_name())


device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', force_reload=True)
model = torch.hub.load("ultralytics/yolov5", "custom", path="D:/Programming/cuda_test/yolov5/vowels_only_5epochs.pt" ,force_reload=True)  

Additional

is it due to the ultralytics version. How can i downgrade to yolov5

Are you willing to submit a PR?

  • Yes I'd like to help by submitting a PR!
@pratyooshraj pratyooshraj added the bug Something isn't working label Jan 27, 2025
@UltralyticsAssistant UltralyticsAssistant added the detect Object Detection issues, PR's label Jan 27, 2025
@UltralyticsAssistant
Copy link
Member

👋 Hello @pratyooshraj, thank you for your interest in YOLOv5 🚀!

Your error seems related to loading your custom-trained model on your local setup. For a detailed diagnosis and resolution, we'll need some additional information. In the meantime, here are a few steps to help troubleshoot and debug:


Debug Checklist 🐛

  1. Ensure Compatibility:

    • Verify that your model file (vowels_only_5epochs.pt) is not corrupted and was downloaded properly.
    • Confirm you are using compatible versions of Python, PyTorch, and YOLOv5. Based on your description, your local setup uses torch 2.5.1, which might not be fully compatible. YOLOv5 supports PyTorch>=1.8 for stable operation.
  2. Force Reload:

    • Clear your .cache directory where the repo is stored by deleting C:\Users\ACER\.cache\torch\hub\ and running the script again with force_reload=True as you've already specified.
  3. Pathlib Error:

    • The error cannot instantiate 'PosixPath' on your system usually arises because Python's pathlib behaves differently across platforms (Windows vs Unix). This might indicate compatibility or serialization issues in the vowels_only_5epochs.pt. Re-save the model with the current YOLOv5 version in Colab and retry.

Instructions ✅

For additional assistance, please:

  • Provide the exact YOLOv5 version you used in Google Colab to train your model.
  • Share a Minimum Reproducible Example (MRE) that includes the Colab training pipeline and your local system pipeline with as much detail as possible.
  • Verify you've followed the official PyTorch Hub Model Loading guide and ensure there are no discrepancies when loading pretrained/custom models.

Requirements 💡

Ensure all requirements are met by running the following setup commands for YOLOv5 locally:

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

For safe compatibility, consider running YOLOv5 in one of our verified environments. These include:


Next Steps 🔍

If you're unable to resolve this, an Ultralytics engineer will assist you further soon. In the meantime:

  • Double-check your model path, environment setup, and dependencies.
  • Share additional logs or information that might help reproduce the issue on our end.

Thank you for bringing this to our attention! 😊

@pratyooshraj
Copy link
Author

used this command to get the YOLOversion. Trained the model on 25th jan 2025
!git clone https://github.com/ultralytics/yolov5.git

Training command
!python train.py --img 416 --batch 16 --epochs 10 --data '/content/YOLO_vowels/data.yaml' --cfg ./models/custom_yolov5s.yaml --weights 'yolov5s.pt' --name yolov5s_vowels_results --cache disk --workers 4

MRE

import torch

model = torch.hub.load("ultralytics/yolov5", "custom", path="D:\Programming\cuda_test\yolov5\vowels_only_5epochs.pt", force_reload=True) 

@pderrenger
Copy link
Member

The error likely stems from incompatibilities between the YOLOv5 version you trained your model with and the version you're using to load it. Since you cloned the YOLOv5 repo on January 25, 2025, it may include changes that differ from the version installed via PyTorch Hub. Ensure the versions match by using the same codebase for training and inference.

Instead of PyTorch Hub, try running your script directly from the cloned YOLOv5 directory:

from models.common import DetectMultiBackend

model = DetectMultiBackend("D:/Programming/cuda_test/yolov5/vowels_only_5epochs.pt", device='cuda')

Alternatively, ensure the latest YOLOv5 repo is cloned and retry. More details on custom model loading are available here.

@pratyooshraj
Copy link
Author

I just added:

import pathlib
temp = pathlib.PosixPath
pathlib.PosixPath = pathlib.WindowsPath

in the python file. It worked

@pderrenger
Copy link
Member

@pratyooshraj thank you for sharing your workaround! While this approach can resolve the issue, it’s a modification of Python's standard library behavior and may have unintended side effects. A better solution is to ensure compatibility by using the same YOLOv5 version for both training and inference. If the issue persists, you can also try running the script directly from the cloned YOLOv5 directory after installing its dependencies. For reference, check the PyTorch Hub guide.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working detect Object Detection issues, PR's
Projects
None yet
Development

No branches or pull requests

3 participants