ultralytics / yolov5

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

AttributeError: Can't get attribute 'SPPF' #5175

Closed 2035956306 closed 2 years ago

2035956306 commented 3 years ago

❔Question

Traceback (most recent call last): File "G:/yolov5-5.0/detect.py", line 178, in detect() File "G:/yolov5-5.0/detect.py", line 34, in detect model = attempt_load(weights, map_location=device) # load FP32 model File "G:\yolov5-5.0\models\experimental.py", line 118, in attempt_load ckpt = torch.load(w, map_location=map_location) # load File "C:\Users\hp\anaconda3\envs\YOLOv5\lib\site-packages\torch\serialization.py", line 607, in load return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args) File "C:\Users\hp\anaconda3\envs\YOLOv5\lib\site-packages\torch\serialization.py", line 882, in _load result = unpickler.load() File "C:\Users\hp\anaconda3\envs\YOLOv5\lib\site-packages\torch\serialization.py", line 875, in find_class return super().find_class(mod_name, name) AttributeError: Can't get attribute 'SPPF' on <module 'models.common' from 'G:\yolov5-5.0\models\common.py'>

Additional context

github-actions[bot] commented 3 years ago

πŸ‘‹ Hello @2035956306, 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://ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

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

$ git clone https://github.com/ultralytics/yolov5
$ cd yolov5
$ 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), validation (val.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

gychen-n commented 3 years ago

I have the same problem. Have you solved it?

glenn-jocher commented 3 years ago

@gychen-n @2035956306 your code is out of date, and is autodownloading new models that it can't support. Your options are to update your code (recommended), or to manually download the older models you need from previous release assets: https://github.com/ultralytics/yolov5/releases/tag/v5.0

EDIT: A 3rd option is to update utils/datasets.py L59 below to point to an earlier release, i.e. to autodownload from v5.0 release assets: https://github.com/ultralytics/yolov5/blob/1172ac15fbf88591246b886e80fe353eb1276e53/utils/downloads.py#L56-L59

response = requests.et(f'https://api.github.com/repos/{repo}/releases/tag/v5.0').json()  # github api
junzz827 commented 3 years ago

I had the same problem this week when I ran Detect.py locally using a .pt model trained with a newly cloned yolov5. This error does not occur with .pt models trained with the cloned version around October 1st.

Usefff commented 3 years ago

Stuck with same problem. It's happened because Ultralytics release v6.0 of yolov5 12.10.2021 and it inconsistence with old code for v5.0. If you wanna work with your old code, you need to change request in str 55 of yolov5/utils/google_utils.py

from :

response = requests.et(f'https://api.github.com/repos/{repo}/releases/lastest').json()  # github api

to:

response = requests.et(f'https://api.github.com/repos/{repo}/releases/tag/v5.0').json()  # github api
yangj1e commented 3 years ago

It should be response = requests.get(f'https://api.github.com/repos/{repo}/releases/tags/v5.0').json()

EddySilence commented 3 years ago

I changed the above statement, but it didn’t solve it. Has anyone solved it?

moksh-401-511 commented 3 years ago

facing same issue

glenn-jocher commented 3 years ago

@Eddy20210324 @moksh019 3 solutions shown in https://github.com/ultralytics/yolov5/issues/5175#issuecomment-942897751

moksh-401-511 commented 3 years ago

@Eddy20210324 @moksh019 3 solutions shown in #5175 (comment)

Thanks @glenn-jocher , I deleted the new downloaded weight file and replaced it with old weight file. Now its working.

mzidni100701 commented 3 years ago

@Eddy20210324 @moksh019 3 solutions shown in #5175 (comment)

Thanks @glenn-jocher , I deleted the new downloaded weight file and replaced it with old weight file. Now its working.

Thanks Brother solved

Ranger-D commented 3 years ago

For this problem, you have use the wrong corresponding-version weights. You can go to the release guide and download the weights corresponding the model version.

animeshkalita82 commented 2 years ago

Hi I have trained a car and numberplate detection model using yolov5 using the command.

!python train.py --img 640 --batch 64 --epochs 500 --data '../data.yaml' --cfg ./models/yolov5s.yaml --weights '' --name yolov5s_results --cache

Now I am trying to use zero-shot-object-tracking to track the cars by cloning the below repository, !git clone https://github.com/roboflow-ai/zero-shot-object-tracking.

I ran the command !python clip_object_tracker.py --source ./data/video/cars.mp4 --detection-engine yolov5 --weights '/content/gdrive/MyDrive/Number_Plate_Detection/best.pt'

and encountered an error AttributeError: Can't get attribute 'SPPF' on <module 'models.common' from '/content/zero-shot-object-tracking/models/common.py'>

I have changed the line in download.py file of yolov5/utils folder while training the model. response = requests.get(f'https://api.github.com/repos/{repo}/releases/tags/v5.0').json()

But still the issue is not fixed. Can someone please help me here.

glenn-jocher commented 2 years ago

@animeshkalita82 your code is out of date, and is autodownloading new models that it can't support. Your options are to update your code (recommended), or to manually download the older models you need from previous release assets: https://github.com/ultralytics/yolov5/releases/tag/v5.0

EDIT: A 3rd option is to update utils/datasets.py L59 below to point to an earlier release, i.e. to autodownload from v5.0 release assets: https://github.com/ultralytics/yolov5/blob/1172ac15fbf88591246b886e80fe353eb1276e53/utils/downloads.py#L56-L59

response = requests.et(f'https://api.github.com/repos/{repo}/releases/tag/v5.0').json()  # github api
animeshkalita82 commented 2 years ago

@animeshkalita82 your code is out of date, and is autodownloading new models that it can't support. Your options are to update your code (recommended), or to manually download the older models you need from previous release assets: https://github.com/ultralytics/yolov5/releases/tag/v5.0

EDIT: A 3rd option is to update utils/datasets.py L59 below to point to an earlier release, i.e. to autodownload from v5.0 release assets:

https://github.com/ultralytics/yolov5/blob/1172ac15fbf88591246b886e80fe353eb1276e53/utils/downloads.py#L56-L59

response = requests.et(f'https://api.github.com/repos/{repo}/releases/tag/v5.0').json()  # github api

@glenn-jocher Thanks for your reply. I have just checkout the latest yolov5 repo from git by using !git clone https://github.com/ultralytics/yolov5 and also have the latest !git clone https://github.com/roboflow-ai/zero-shot-object-tracking.

Also I have changed the code in download.py file as you have mentioned above. response = requests.et(f'https://api.github.com/repos/{repo}/releases/tag/v5.0').json()

As you have mentioned I have downloaded the previous version weight but can you please tell me the use of it. Because I am not using the yolov5s.pt file to train my dataset. I have used --weight '' in training.

Still the issue is not resolved. Am i missing something here.

antran89 commented 2 years ago

UPDATE: my code works fine now, somehow, my repo does not pull properly.

Hi, I git pull the latest code, but instead, it has a similar problem

hyperparameters: lr0=0.01, lrf=0.1, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1.0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0
tensorboard: Start with 'tensorboard --logdir runs/train', view at http://localhost:6006/
2021-11-23 16:17:06.781918: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'libcudart.so.10.1'; dlerror: libcudart.so.10.1: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/local/nvidia/lib:/usr/local/nvidia/lib64:/usr/local/cuda/lib64
2021-11-23 16:17:06.782041: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "train.py", line 660, in <module>
    main(opt)
  File "train.py", line 560, in main
    train(opt.hyp, opt, device)
  File "train.py", line 102, in train
    run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None
  File "/opt/conda/lib/python3.6/site-packages/torch/serialization.py", line 592, in load
    return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args)
  File "/opt/conda/lib/python3.6/site-packages/torch/serialization.py", line 851, in _load
    result = unpickler.load()
AttributeError: Can't get attribute 'SPPF' on <module 'models.common' from '/data/ot-workspace/yolov5/models/common.py'>

Someone has figured out the issue.

DingZhouPeng commented 2 years ago

Because your .pth file is v6.0,while your project is v5.0,something wrong with it.You need change code in /utils/google_utils.py in line25.

github-actions[bot] commented 2 years ago

πŸ‘‹ 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 ⭐!

Ndron commented 2 years ago

copy and paste code below to common.py

import warnings

class SPPF(nn.Module):
    # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))
        super().__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * 4, c2, 1, 1)
        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)

    def forward(self, x):
        x = self.cv1(x)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning
            y1 = self.m(x)
            y2 = self.m(y1)
            return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
hsnawn commented 2 years ago

copy and paste code below to common.py

import warnings

class SPPF(nn.Module):
    # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))
        super().__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * 4, c2, 1, 1)
        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)

    def forward(self, x):
        x = self.cv1(x)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning
            y1 = self.m(x)
            y2 = self.m(y1)
            return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))

@Ndron I got the following error:

poetry run coreml-export --model-input-path '/home/hassaan/v56toml/yolov5/masked.pt' --model-output-directory '/home/hassaan/yolov5' --model-output-name 'yolov5-iOS'
Starting TorchScript export with torch 1.7.0
/home/hassaan/.cache/pypoetry/virtualenvs/coreml-tools-oTw5Ba7c-py3.8/lib/python3.8/site-packages/torch/jit/_trace.py:934: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  module._c._create_method_from_trace(
/home/hassaan/.cache/pypoetry/virtualenvs/coreml-tools-oTw5Ba7c-py3.8/lib/python3.8/site-packages/torch/jit/_trace.py:934: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  module._c._create_method_from_trace(
/home/hassaan/.cache/pypoetry/virtualenvs/coreml-tools-oTw5Ba7c-py3.8/lib/python3.8/site-packages/torch/jit/_trace.py:934: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  module._c._create_method_from_trace(
TorchScript export success, saved as /home/hassaan/yolov5/yolov5-iOS.torchscript.pt
Starting CoreML conversion with coremltools 4.1
WARNING:root:Tuple detected at graph output. This will be flattened in the converted model.
Converting Frontend ==> MIL Ops:   2%|β–Š                                    | 14/644 [00:00<00:00, 1278.89 ops/s]
CoreML conversion failure: PyTorch convert function for op 'silu_' not implemented.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/hassaan/v56toml/yolov5-coreml-tools/src/coreml_export/main.py", line 324, in main
    addOutputMetaData(modelSpec)
  File "/home/hassaan/v56toml/yolov5-coreml-tools/src/coreml_export/main.py", line 93, in addOutputMetaData
    nnSpec.description.output[i].type.multiArrayType.shape.append(1)
AttributeError: 'NoneType' object has no attribute 'description'
TOTTO27149 commented 2 years ago

update your code (recommended)

Sorry, but what do you mean by saying "update your code (recommended)"?

glenn-jocher commented 2 years ago

@TOTTO27149 to update:

MZeinab commented 2 years ago

@glenn-jocher @animeshkalita82 I did the 3rd option you explained , but still zero-shot-object tracking give SPPF error on common.py , It didn't have any problem 5 days ago ... I use the last version of both notebooks and 3rd option could you please explain it exactly (send your code)...

glenn-jocher commented 2 years ago

@MZeinab πŸ‘‹ hi, thanks for letting us know about this possible problem with YOLOv5 πŸš€. We've created a few short guidelines below to help users provide what we need in order to start 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:

For Ultralytics to provide assistance your code should also be:

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

Thank you! πŸ˜ƒ

karunakarchinnabathini1729 commented 2 years ago

copy and paste code below to common.py

import warnings

class SPPF(nn.Module):
    # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))
        super().__init__()
        c_ = c1 // 2  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_ * 4, c2, 1, 1)
        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)

    def forward(self, x):
        x = self.cv1(x)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning
            y1 = self.m(x)
            y2 = self.m(y1)
            return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))

@Ndron I got the following error:

poetry run coreml-export --model-input-path '/home/hassaan/v56toml/yolov5/masked.pt' --model-output-directory '/home/hassaan/yolov5' --model-output-name 'yolov5-iOS'
Starting TorchScript export with torch 1.7.0
/home/hassaan/.cache/pypoetry/virtualenvs/coreml-tools-oTw5Ba7c-py3.8/lib/python3.8/site-packages/torch/jit/_trace.py:934: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  module._c._create_method_from_trace(
/home/hassaan/.cache/pypoetry/virtualenvs/coreml-tools-oTw5Ba7c-py3.8/lib/python3.8/site-packages/torch/jit/_trace.py:934: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  module._c._create_method_from_trace(
/home/hassaan/.cache/pypoetry/virtualenvs/coreml-tools-oTw5Ba7c-py3.8/lib/python3.8/site-packages/torch/jit/_trace.py:934: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  module._c._create_method_from_trace(
TorchScript export success, saved as /home/hassaan/yolov5/yolov5-iOS.torchscript.pt
Starting CoreML conversion with coremltools 4.1
WARNING:root:Tuple detected at graph output. This will be flattened in the converted model.
Converting Frontend ==> MIL Ops:   2%|β–Š                                    | 14/644 [00:00<00:00, 1278.89 ops/s]
CoreML conversion failure: PyTorch convert function for op 'silu_' not implemented.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/hassaan/v56toml/yolov5-coreml-tools/src/coreml_export/main.py", line 324, in main
    addOutputMetaData(modelSpec)
  File "/home/hassaan/v56toml/yolov5-coreml-tools/src/coreml_export/main.py", line 93, in addOutputMetaData
    nnSpec.description.output[i].type.multiArrayType.shape.append(1)
AttributeError: 'NoneType' object has no attribute 'description'

If this issue is still persistent, then adding to @hsnawn changes, we should change the SPP to SPPF in yolo.py. That should work.

markuszeller commented 2 years ago

Use models of version 5.0 and it works instantly. No need to alter any scripts. https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5x6.pt

glenn-jocher commented 12 months ago

Thanks for sharing that, @markuszeller! If the issue persists with the latest version, let us know and we'll be happy to help.