ultralytics / yolov5

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

AttributeError: 'Detect' object has no attribute 'grid' #11542

Closed Wu-Jian-Ting closed 1 year ago

Wu-Jian-Ting commented 1 year ago

Search before asking

YOLOv5 Component

PyTorch Hub

Bug

Hi all, I run the code

import cv2 import torch from torchvision import transforms from PIL import Image model = torch.hub.load('.', 'custom',path='weights/best.pt',source='local',force_reload=True)

and it occurs error

AttributeError Traceback (most recent call last) File ~/yolov5/hubconf.py:73, in _create(name, pretrained, channels, classes, autoshape, verbose, device) 72 LOGGER.setLevel(logging.INFO) # reset to default ---> 73 return model.to(device) 75 except Exception as e:

File ~/anaconda3/envs/yolo/lib/python3.8/site-packages/torch/nn/modules/module.py:1145, in Module.to(self, *args, **kwargs) 1143 return t.to(device, dtype if t.is_floating_point() or t.is_complex() else None, non_blocking) -> 1145 return self._apply(convert)

File ~/.cache/torch/hub/ultralytics_yolov5_master/models/common.py:651, in AutoShape._apply(self, fn) 650 m.stride = fn(m.stride) --> 651 m.grid = list(map(fn, m.grid)) 652 if isinstance(m.anchor_grid, list):

File ~/anaconda3/envs/yolo/lib/python3.8/site-packages/torch/nn/modules/module.py:1614, in Module.getattr(self, name) 1613 return modules[name] -> 1614 raise AttributeError("'{}' object has no attribute '{}'".format( 1615 type(self).name, name))

AttributeError: 'Detect' object has no attribute 'grid' The above exception was the direct cause of the following exception:

Exception Traceback (most recent call last) Cell In[17], line 7 4 from PIL import Image ----> 7 model = torch.hub.load('.', 'custom',path='weights/best.pt',source='local',force_reload=True) 10 cap = cv2.VideoCapture(0)

File ~/anaconda3/envs/yolo/lib/python3.8/site-packages/torch/hub.py:558, in load(repo_or_dir, model, source, trust_repo, force_reload, verbose, skip_validation, *args, *kwargs) 554 if source == 'github': 555 repo_or_dir = _get_cache_or_reload(repo_or_dir, force_reload, trust_repo, "load", 556 verbose=verbose, skip_validation=skip_validation) --> 558 model = _load_local(repo_or_dir, model, args, **kwargs) 559 return model

File ~/anaconda3/envs/yolo/lib/python3.8/site-packages/torch/hub.py:587, in _load_local(hubconf_dir, model, *args, *kwargs) 584 hub_module = _import_module(MODULE_HUBCONF, hubconf_path) 586 entry = _load_entry_from_hubconf(hub_module, model) --> 587 model = entry(args, **kwargs) 589 return model

File ~/yolov5/hubconf.py:83, in custom(path, autoshape, _verbose, device) 81 def custom(path='path/to/model.pt', autoshape=True, _verbose=True, device=None): 82 # YOLOv5 custom or local model ---> 83 return _create(path, autoshape=autoshape, verbose=_verbose, device=device)

File ~/yolov5/hubconf.py:78, in _create(name, pretrained, channels, classes, autoshape, verbose, device) 76 help_url = 'https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading' 77 s = f'{e}. Cache may be out of date, try force_reload=True or see {help_url} for help.' ---> 78 raise Exception(s) from e

Exception: 'Detect' object has no attribute 'grid'. Cache may be out of date, try force_reload=True or see >https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading for help.

How can i do?

Environment

-YOLOv5 -Python=3.8.0 -Ubuntu=20.04

Minimal Reproducible Example


import torch
from torchvision import transforms
from PIL import Image
model = torch.hub.load('.', 'custom',path='weights/best.pt',source='local',force_reload=True)

### Additional

_No response_

### Are you willing to submit a PR?

- [X] Yes I'd like to help by submitting a PR!
github-actions[bot] commented 1 year ago

πŸ‘‹ Hello @Wu-Jian-Ting, 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 a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

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

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

YOLOv5 CI

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training, validation, inference, export and benchmarks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

Introducing YOLOv8 πŸš€

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 πŸš€!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics
glenn-jocher commented 1 year ago

Hi @Wu-Jian-Ting,

It seems like you are encountering some issues in loading the custom YOLOv5 model with torch.hub.load().

The error message suggests that the model object does not have an attribute grid which might be caused due to an outdated cache. You can try adding force_reload=True in torch.hub.load() command, which will ensure that the cache is refreshed.

If the above-mentioned solution doesn't work, we suggest updating the repository files and re-installing the YOLOv5 package. Additionally, please check if you have installed all the dependencies by running pip install -r requirements.txt from the cloned directory.

We hope this solution helps. Kindly let us know if it doesn't resolve your issue.

Best,
Glenn

github-actions[bot] commented 1 year ago

πŸ‘‹ Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

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 YOLO πŸš€ and Vision AI ⭐

MrKhan96 commented 1 year ago

I am currently facing the same issue, ive tried removing and resintalling the library, this is happening for me on the yolov5nu model, i think your repo on torch hub does not have the updates for the "u" models

glenn-jocher commented 1 year ago

@MrKhan96 thank you for your feedback. We apologize for the inconvenience you are experiencing with the yolov5nu model on Torch Hub.

Our team is aware of the issue and is actively working on updating the repository to include the latest models, including the "u" models. We appreciate your patience as we work to resolve this.

In the meantime, you can try using the yolov5x model as an alternative. This model provides similar performance and capabilities to the yolov5nu model.

Please let us know if you have any further questions or concerns.

unraxesy commented 3 months ago

I tried to run a very simple code: `import sys sys.path.append('/home/myname/venvir/lib/python3.11/site-packages')

import torch

model = torch.hub.load('ultralytics/yolov5', 'custom', path='weights/best.pt', force_reload=True)`

But, I encounter an error: Traceback (most recent call last): File "/home/myname/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", in line 78, in_create return model.to(device) File "/home/myname/venvir/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1173, in to return self._apply(convert) File "/home/myname/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 814, in_apply m.grid = list(map(fn, m.grid)) File "/home/myname/venvir/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1709, ingetattr raise AttributeError(f"'{type(self).name}' object has no attribute '{name}'" AttributeError: 'Detect' object has no attribute 'grid'

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

Traceback (most recent call last): File "/home/myname/yolov5/test.py", line 7, in model = torch.hub.load('ultralytics/yolov5', 'custom', path='weights/best.pt') File "/home/myname/venvir/lib/python3.11/site-packages/torch/hub.py", line 568, in load model = _load_local(repo_or_dir, model, *args, *kwargs) File "/home/myname/venvir/lib/python3.11/site-packages/torch/hub.py", line 597, in _load_local model = entry(args, **kwargs) File "/home/myname/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 88, in custom return _create(path, autoshape=autoshape, verbose=_verbose, device=device) File "/home/myname/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 83, in _create raise Exception(s) from e Exception: 'Detect' object has no attribute 'grid'. Cache may be out of date, try 'force_reload=True' or see https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading for help.

For additional info Python version: 3.11 Device: Raspberry Pi 4 Model B Custom Model Name: "best.pt" (YOLOv5s)

I have done:

It is so hard for me to troubleshoot this since there is so little references regarding this issue. Please help me. Thank you.

unraxesy commented 3 months ago

Oh, and I wonder can I modify detect.py file to use my custom model ("best.pt")? I'm sorry I'm a newbie at this.

glenn-jocher commented 3 months ago

Hi @unraxesy,

Thank you for providing detailed information about the issue you're facing. Let's work through this together.

Firstly, it looks like you've done a great job troubleshooting so far. The error you're encountering, AttributeError: 'Detect' object has no attribute 'grid', often indicates a mismatch between the model architecture and the codebase version.

Steps to Resolve

  1. Ensure Latest Versions:

    • Verify that you are using the latest versions of both torch and the YOLOv5 repository. You can update them using:
      pip install --upgrade torch
      git pull
      pip install -r requirements.txt
  2. Force Reload:

    • Since you've already tried force_reload=True, let's ensure the cache is completely cleared. You can manually delete the cache directory:
      rm -rf ~/.cache/torch/hub/ultralytics_yolov5_master
  3. Minimal Reproducible Example:

    • Please provide a minimal reproducible code example if the issue persists. This helps us reproduce the bug on our end and investigate a solution. You can refer to this guide for more details on creating one.

Custom Model Integration

Regarding your question about modifying detect.py to use your custom model (best.pt), it's generally not necessary to modify the core YOLOv5 files. Instead, you can load your custom model directly using the provided API. Here's a simple example:

import torch

# Load custom model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='weights/best.pt', force_reload=True)

# Perform inference
img = 'path/to/your/image.jpg'
results = model(img)

# Print results
print(results.pandas().xyxy[0])

Additional Tips

If you continue to face issues, please share the minimal reproducible example, and we'll be happy to assist further. The YOLO community and the Ultralytics team are here to help you succeed!

unraxesy commented 3 months ago

Thank you so much for your quick response @glenn-jocher, I have done step 1-2 you provided above but the error still remains.

I did yolo checks and here's the result:

Dependencies Ultralytics YOLOv8.2.30 οš€ Python-3.11.2 torch-2.3.1 CPU (Cortex-A72) Setup complete βœ… (4 CPUs, 3.7 GB RAM, 15.3/28.7 GB disk)

OS Linux-6.6.31+rpt-rpi-v8-aarch64-with-glibc2.36 Environment Linux Python 3.11.2 Install pip RAM 3.70 GB CPU Cortex-A72 CUDA None

matplotlib βœ… 3.9.0>=3.3.0 opencv-python βœ… 4.8.1.78>=4.6.0 pillow βœ… 10.3.0>=7.1.2 pyyaml βœ… 6.0.1>=5.3.1 requests βœ… 2.32.3>=2.23.0 scipy βœ… 1.13.1>=1.4.1 torch βœ… 2.3.1>=1.8.0 torchvision βœ… 0.18.1>=0.9.0 tqdm βœ… 4.66.4>=4.64.0 psutil βœ… 5.9.8 py-cpuinfo βœ… 9.0.0 pandas βœ… 2.2.2>=1.1.4 seaborn βœ… 0.13.2>=0.11.0 ultralytics-thop βœ… 0.2.8>=0.2.5

So I think we can assume that I have all libraries updated and upgraded.

But there is one thing I forgot to tell you. So I'm running this code in Raspberry Pi 4 Model B and always use virtual environment (venvir) to be able to install all of the libraries from the command prompt. However, when I run the simple program I provide earlier (I run the program with Thonny code editor), there's some warning like this:

Error Message requirements: Ultralytics requirements ['pillow>=10.3.0', 'requests>=2.32.0'] not found, attempting AutoUpdate... error: externally-managed-environment

Γ— This environment is externally managed ╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install.

If you wish to install a non-Debian-packaged Python package, create a virtual environment using python3 -m venv path/to/venv. Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make sure you have python3-full installed. For more information visit http://rptl.io/venv

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages. hint: See PEP 668 for the detailed specification. Retry 1/2 failed: Command 'pip install --no-cache-dir "pillow>=10.3.0" "requests>=2.32.0" ' returned non-zero exit status 1. error: externally-managed-environment

Γ— This environment is externally managed ╰─> {...}

hint: See PEP 668 for the detailed specification. Retry 2/2 failed: Command 'pip install --no-cache-dir "pillow>=10.3.0" "requests>=2.32.0" ' returned non-zero exit status 1. requirements: ❌ Command 'pip install --no-cache-dir "pillow>=10.3.0" "requests>=2.32.0" ' returned non-zero exit status 1.

I ignore this issue because I already have pillow 10.3.0 and requests 2.32.3. But I wonder maybe this can cause the issue?

Additional Info After I install requirements.txt, I uninstall torch torchvision torchaudio and install it again using official command: pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu I did this to make sure I'm using PyTorch that specifically for CPU since I run it on my Raspberry Pi. I don't know is this matter or not. I wonder maybe because I use the default PyTorch when I train the model "best.pt" on Google Colab, and using different PyTorch (the CPU ver) can cause this issue?

glenn-jocher commented 3 months ago

Hi @unraxesy,

Thank you for providing detailed information and for your patience. Let's address the issues step-by-step to help you resolve this.

Minimum Reproducible Example

Firstly, it's crucial to ensure that we can reproduce the issue on our end. If you haven't already, please provide a minimal reproducible example. This helps us understand the exact scenario and investigate the problem effectively. You can refer to our guide on creating a minimum reproducible example.

Dependency Check

From your yolo checks output, it looks like your dependencies are up-to-date. However, the warning about the "externally managed environment" suggests that there might be some issues with your virtual environment setup. Let's address this:

  1. Virtual Environment Setup: Ensure you are activating your virtual environment correctly before running your script. Here’s a quick reminder:

    python3 -m venv path/to/venv
    source path/to/venv/bin/activate
  2. Install Dependencies: After activating the virtual environment, install the required dependencies:

    pip install -r requirements.txt

Custom Model Loading

Given that you are using a Raspberry Pi 4 Model B, it's essential to ensure compatibility between the model trained on Google Colab (which likely uses a GPU) and the CPU-only environment on your Raspberry Pi.

Code Example

Here’s a refined version of your code to ensure proper loading and inference:

import torch

# Ensure you are using the correct path to your custom model
model_path = 'weights/best.pt'

# Load the custom model
model = torch.hub.load('ultralytics/yolov5', 'custom', path=model_path, force_reload=True)

# Perform inference on a sample image
img = 'path/to/your/image.jpg'
results = model(img)

# Print results
print(results.pandas().xyxy[0])

Potential Issues

  1. Externally Managed Environment: The warning about the "externally managed environment" indicates that your system might be restricting package installations. Ensure you are running your script within the virtual environment and not system-wide.

  2. PyTorch Version: Since you mentioned reinstalling PyTorch for CPU, ensure that the versions are compatible. The model trained on GPU should still work on CPU, but ensure you are using the same PyTorch version series (e.g., 2.x).

Additional Steps

  1. Clear Cache: Manually clear the Torch Hub cache to ensure no outdated files are causing issues:

    rm -rf ~/.cache/torch/hub/ultralytics_yolov5_master
  2. Check Model Compatibility: Ensure that the best.pt model is compatible with the YOLOv5 version you are using. If the model was trained with an older version, it might not be fully compatible with the latest codebase.

Conclusion

If the issue persists, please provide the minimal reproducible example, and we will investigate further. The YOLO community and the Ultralytics team are here to support you. Thank you for your patience and cooperation!

unraxesy commented 3 months ago

Hi @glenn-jocher ! After about a week failed to do YOLOv5s custom model inference on my Raspberry Pi 4 Model B using torch.hub.load, I finally did it! It turns out that I missed some details about implementing YOLOv5s custom model inference on Raspberry. I also use different approach since I always failed to do inference with torch.hub.load Here's what I did:

  1. Set up Ultralytics on Raspberry Pi At first I didn't know that setting up Ultralytics on Raspberry Pi is different. Based on https://docs.ultralytics.com/guides/raspberry-pi/#set-up-ultralytics, there are two ways of setting up Ultralytics on Raspberry Pi. I did the second option, Start without Docker. It took me about 4 hours to finish the installations.
  2. Converting best.pt model to NCNN I run this command yolo export model=best.pt format=ncnn on command prompt to convert best.pt to ncnn format. This step is based on https://docs.ultralytics.com/integrations/ncnn/#deployment-options-with-ncnn. It said that NCNN is the best option to run inference on embedded system and IoT device like Raspberry Pi. After converting, the model is saved in form of a folder named best_ncnn_model.
  3. Run Inference After the model successfully converted, the next step is to do inference. Here's the code I use to run YOLOv5s custom model inference on Raspberry Pi. Screenshot 2024-06-14 121819 And here's the result! Screenshot 2024-06-14 121607 As you can see, it successfully detect object (cigarette)! I'm so happy to share this with you after stressing out for a week straight lmao. My fault for missing out some details 😩.

Notes Don't forget to to do this step first: Screenshot 2024-06-14 122838 before doing the earlier step. And copy best.pt model from your laptop/PC to Raspberry Pi (to yolov5 folder). I did it with WinSCP since it's very easy!

glenn-jocher commented 3 months ago

Hi @unraxesy,

Thank you for sharing your detailed solution and experience with running YOLOv5s custom model inference on your Raspberry Pi 4 Model B! πŸŽ‰ It's fantastic to hear that you were able to resolve the issue and successfully detect objects with your custom model.

Your approach of setting up Ultralytics on the Raspberry Pi and converting the model to NCNN format is indeed a great solution for embedded systems. The steps you provided will undoubtedly be helpful to others facing similar challenges.

For anyone else encountering similar issues, here are the key steps @unraxesy followed:

  1. Set Up Ultralytics on Raspberry Pi:

  2. Convert Model to NCNN Format:

    • Use the command yolo export model=best.pt format=ncnn to convert your custom model to NCNN format. This is based on the NCNN Integration Guide.
  3. Run Inference:

    • After converting the model, run the inference using the NCNN format. Ensure you follow any additional setup steps, such as copying the best.pt model to your Raspberry Pi.

It's also important to note the initial setup steps and the use of tools like WinSCP for transferring files, which can simplify the process.

If anyone else is facing issues, please ensure you provide a minimum reproducible code example as outlined in our guide. This helps us reproduce the bug and investigate a solution effectively.

Thank you again for sharing your journey and solution, @unraxesy! Your contribution is invaluable to the YOLO community and the Ultralytics team. If you have any further questions or need additional assistance, feel free to reach out.