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

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

Closed
2035956306 opened this issue Oct 14, 2021 · 27 comments
Closed

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

2035956306 opened this issue Oct 14, 2021 · 27 comments
Labels
question Further information is requested Stale

Comments

@2035956306
Copy link

❔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

@2035956306 2035956306 added the question Further information is requested label Oct 14, 2021
@github-actions
Copy link
Contributor

github-actions bot commented Oct 14, 2021

👋 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
Copy link

I have the same problem. Have you solved it?

@glenn-jocher
Copy link
Member

glenn-jocher commented Oct 14, 2021

@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:

# GitHub assets
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
try:
response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api

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

@junzz827
Copy link

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
Copy link

Usefff commented Oct 14, 2021

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
Copy link

yangj1e commented Oct 16, 2021

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

@EddySilence
Copy link

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

@moksh-401-511
Copy link

facing same issue

@glenn-jocher
Copy link
Member

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

@moksh-401-511
Copy link

@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
Copy link

@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
Copy link

Ranger-D commented Nov 3, 2021

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
Copy link

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
Copy link
Member

@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:

# GitHub assets
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
try:
response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api

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

@animeshkalita82
Copy link

animeshkalita82 commented Nov 23, 2021

@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:

# GitHub assets
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
try:
response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api

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
Copy link

antran89 commented Nov 23, 2021

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
Copy link

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
Copy link
Contributor

github-actions bot commented Jan 3, 2022

👋 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
Copy link

Ndron commented Jan 13, 2022

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
Copy link

hsnawn commented Jan 14, 2022

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
Copy link

update your code (recommended)

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

@glenn-jocher
Copy link
Member

@TOTTO27149 to 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

@MZeinab
Copy link

MZeinab commented Jul 14, 2022

@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
Copy link
Member

glenn-jocher commented Jul 15, 2022

@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:

  • Minimal – Use as little code as possible to produce the problem
  • Complete – Provide all parts someone else needs to reproduce the problem
  • Reproducible – Test the code you're about to provide to make sure it reproduces the problem

For Ultralytics to provide assistance your code should also be:

  • Current – Verify that your code is up-to-date with GitHub master, and if necessary git pull or git clone a new copy to ensure your problem has not already been solved in master.
  • Unmodified – Your problem must be reproducible using official YOLOv5 code without changes. Ultralytics does not provide support for custom code ⚠️.

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

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
Copy link

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
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested Stale
Projects
None yet
Development

No branches or pull requests