ultralytics / yolov5

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

AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' #6948

Closed JakobStadlhuber closed 2 years ago

JakobStadlhuber commented 2 years ago

Search before asking

YOLOv5 Component

Other

Bug

I just have run pip install -r yolov5/requirements.txt again and now I get this error when running my main class.

Fusing layers... Model Summary: 232 layers, 7278882 parameters, 0 gradients Adding AutoShape... Traceback (most recent call last): File "/mnt/space/work/thesis/main.py", line 177, in <module> results = model(resized_img, size=img_size) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/usr/local/lib/python3.8/dist-packages/torch/autograd/grad_mode.py", line 27, in decorate_context return func(*args, **kwargs) File "/root/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 540, in forward y = self.model(x, augment, profile) # forward File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/root/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 399, in forward y = self.model(im) if self.jit else self.model(im, augment=augment, visualize=visualize) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/root/.cache/torch/hub/ultralytics_yolov5_master/models/yolo.py", line 126, in forward return self._forward_once(x, profile, visualize) # single-scale inference, train File "/root/.cache/torch/hub/ultralytics_yolov5_master/models/yolo.py", line 149, in _forward_once x = m(x) # run File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1110, in _call_impl return forward_call(*input, **kwargs) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/upsampling.py", line 154, in forward recompute_scale_factor=self.recompute_scale_factor) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1185, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'".format( AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor'

Environment

YOLOv5 πŸš€ 2022-1-31 torch 1.11.0+cu102 CPU

Minimal Reproducible Example

Clone current master (11.03.2022) pip install -r yolov5/requirements.txt

Additional

No response

Are you willing to submit a PR?

github-actions[bot] commented 2 years ago

πŸ‘‹ Hello @JakobStadlhuber, 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 support@ultralytics.com.

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

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.

glenn-jocher commented 2 years ago

@JakobStadlhuber good news πŸ˜ƒ! This is fixed βœ… in yesterday's PyTorch 1.11.0 compatibility PR https://github.com/ultralytics/yolov5/pull/6932

To receive this update:

glenn-jocher commented 2 years ago

@JakobStadlhuber BTW you can see in your post that your environment is not current master, it was last updated at the end of January:

YOLOv5 πŸš€ 2022-1-31 torch 1.11.0+cu102 CPU

yourdaddaddadd commented 2 years ago

Yes, I also encountered the same problem, but do not know what the reason is, my cuda is version 11.5, I followed the link on the official website to download the cuda 11.5 version recommended pytorch, but reported the error, and then I downloaded the cuda 11.3 version recommended, but the same error

glenn-jocher commented 2 years ago

@yourdaddaddadd I've already posted the solution in https://github.com/ultralytics/yolov5/issues/6948#issuecomment-1065213047

stephenfujiwara commented 2 years ago

I've encountered the same issue, but on a trained model that I trained several months ago. What's the best way to deal with this?

glenn-jocher commented 2 years ago

@stephenfujiwara I would retrain using latest PyTorch and YOLOv5.

stephenfujiwara commented 2 years ago

I was going to do that. Actually force_reload=True did the trick. Is there any way I can make this more explicit for other people having a similar issue? I'm not too good with Github.

EdwardAndersonMcDermott commented 2 years ago

When will the pip release be updated with this fix please?

Arsalan66 commented 2 years ago

detect: weights=['runs/train/exp11/weights/last.pt'], source=data/images/, data=data\coco128.yaml, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs\detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False YOLOv5 2022-1-10 torch 1.11.0+cu113 CUDA:0 (NVIDIA GeForce RTX 2060, 6144MiB)

Fusing layers... Model Summary: 444 layers, 86200330 parameters, 0 gradients Traceback (most recent call last): File "detect.py", line 257, in main(opt) File "detect.py", line 252, in main run(vars(opt)) File "E:\condaaa\lib\site-packages\torch\autograd\grad_mode.py", line 27, in decorate_context return func(*args, kwargs) File "detect.py", line 113, in run model.warmup(imgsz=(1, 3, imgsz), half=half) # warmup File "E:\fiverr\mask yolo gen\yolov5-master\models\common.py", line 460, in warmup self.forward(im) # warmup File "E:\fiverr\mask yolo gen\yolov5-master\models\common.py", line 397, in forward y = self.model(im) if self.jit else self.model(im, augment=augment, visualize=visualize) File "E:\condaaa\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl return forward_call(input, kwargs) File "E:\fiverr\mask yolo gen\yolov5-master\models\yolo.py", line 126, in forward return self._forward_once(x, profile, visualize) # single-scale inference, train File "E:\fiverr\mask yolo gen\yolov5-master\models\yolo.py", line 149, in _forward_once x = m(x) # run File "E:\condaaa\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl return forward_call(*input, kwargs) File "E:\condaaa\lib\site-packages\torch\nn\modules\upsampling.py", line 154, in forward recompute_scale_factor=self.recompute_scale_factor) File "E:\condaaa\lib\site-packages\torch\nn\modules\module.py", line 1185, in getattr raise AttributeError("'{}' object has no attribute '{}'".format( AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor

Got the same error any help will be appreocated

glenn-jocher commented 2 years ago

@Arsalan66 πŸ‘‹ hi, thanks for letting us know about this possible problem with YOLOv5 πŸš€. It looks like you are using the latest version of torch, so the error might be due to an out of date model.

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! πŸ˜ƒ

EdwardAndersonMcDermott commented 2 years ago

@Arsalan66 As a work around you can edit your upsampling.py file:

"E:\condaaa\lib\site-packages\torch\nn\modules\upsampling.py"

If you comment out the "recompute_scale_factor=self.recompute_scale_factor" parameter everything seems to work fine.

Arsalan66 commented 2 years ago

thank you so much let me retry and get back to you.

Arsalan66 commented 2 years ago
def forward(self, input: Tensor) -> Tensor:
    return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners,
                         #recompute_scale_factor=self.recompute_scale_factor
                         )

For anyone looking for the solution , modify your upsampling.py in E:\condaaa\Lib\site-packages\torch\nn\modules (conda files) , according to the function above.

alanrizky commented 2 years ago

Thanks it works

DaniDotExe commented 2 years ago

i fixed with https://github.com/ultralytics/yolov5/issues/6948#issuecomment-1075528897, thanks.

alexHxun commented 2 years ago

i fixed with https://github.com/ultralytics/yolov5/issues/6948#issuecomment-1075528897, thanks.

MaxwellHogan commented 2 years ago

I used an earlier version of PyTorch and torchvision - probably the worst solution, but for those who need a quick and dirty solution without having to upgrade the repo:

!pip install torch==1.10.1+cu111 torchvision==0.11.2+cu111 torchaudio==0.10.1 -f https://download.pytorch.org/whl/torch_stable.html

dsabarinathan commented 2 years ago

I used the below pytorch and torchvision version and it is working well. This one is not working for me https://github.com/ultralytics/yolov5/issues/6948#issuecomment-1109739265.

!pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html

lakshaydulani commented 2 years ago

how can i fix this in colab?

MaxwellHogan commented 2 years ago

how can i fix this in colab?

try the solution I or @dsabarinathan have posted

johnson7788 commented 2 years ago

Greet works!

C0NGTRI123 commented 2 years ago
def forward(self, input: Tensor) -> Tensor:
    return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners,
                         #recompute_scale_factor=self.recompute_scale_factor
                         )

For anyone looking for the solution , modify your upsampling.py in E:\condaaa\Lib\site-packages\torch\nn\modules (conda files) , according to the function above.

it's work. Thank's you very much

donghyeops commented 1 year ago

I solved this problem without modifying upsample.py.

import torch.nn as nn

for m in model.modules():
    if isinstance(m, nn.Upsample):
        m.recompute_scale_factor = None

I hope this will help someone.

nikolaydyankov commented 1 year ago

I solved this problem without modifying upsample.py. I hope this will help someone.

It did, thank you!!!

Crear12 commented 1 year ago

Hi, can anyone explain why this happens? I mean, PyTorch provides that line on purpose, right?

NaragintiChanduPriya commented 1 year ago

I solved this problem without modifying upsample.py.

import torch.nn as nn

for m in model.modules():
    if isinstance(m, nn.Upsample):
        m.recompute_scale_factor = None

I hope this will help someone.

can you please tell me where should we add that?

NaragintiChanduPriya commented 1 year ago
def forward(self, input: Tensor) -> Tensor:
    return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners,
                         #recompute_scale_factor=self.recompute_scale_factor
                         )

For anyone looking for the solution , modify your upsampling.py in E:\condaaa\Lib\site-packages\torch\nn\modules (conda files) , according to the function above. ....................................................................................................................................................................................................... I tried this but it still showing same errors File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\detect.py", line 238, in main(opt) File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\detect.py", line 233, in main Traceback (most recent call last): File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\detect.py", line 238, in run(vars(opt)) File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\autograd\grad_mode.py", line 27, in decorate_context main(opt) File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\detect.py", line 233, in main run(vars(opt)) return func(*args, kwargs) File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\detect.py", line 98, in run model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\autograd\grad_mode.py", line 27, in decorate_context return func(*args, *kwargs) File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\detect.py", line 98, in run return forward_call(input, kwargs) File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\models\yolo.py", line 122, in forward model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl return self.forward_once(x, profile, visualize) # single-scale inference, train File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\models\yolo.py", line 153, in forward_once return forward_call(*input, *kwargs) x = m(x) # run File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\models\yolo.py", line 122, in forward return forward_call(input, **kwargs) File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\upsampling.py", line 154, in forward return self.forward_once(x, profile, visualize) # single-scale inference, train File "C:\Users\chandu\OneDrive\Desktop\yolo v5\flask\models\yolo.py", line 153, in forward_once recompute_scale_factor=self.recompute_scale_factor)x = m(x) # run

File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py", line 1185, in getattr File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl raise AttributeError("'{}' object has no attribute '{}'".format( return forward_call(*input, **kwargs) File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\upsampling.py", line 154, in forward AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' recompute_scale_factor=self.recompute_scale_factor) File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py", line 1185, in getattr

raise AttributeError("'{}' object has no attribute '{}'".format(

AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' 127.0.0.1 - - [01/Apr/2023 15:10:13] "POST /detect HTTP/1.1" 200 - 127.0.0.1 - - [01/Apr/2023 15:10:13] "POST /detect HTTP/1.1" 200 -

NaragintiChanduPriya commented 1 year ago

I solved this problem without modifying upsample.py.

import torch.nn as nn

for m in model.modules():
    if isinstance(m, nn.Upsample):
        m.recompute_scale_factor = None

I hope this will help someone.

where we need to keep this?

yuezhilanyi commented 1 year ago

I solved this problem without modifying upsample.py.

import torch.nn as nn

for m in model.modules():
    if isinstance(m, nn.Upsample):
        m.recompute_scale_factor = None

I hope this will help someone.

where we need to keep this?

maybe models/yolo.py, it works.

    def _forward_once(self, x, profile=False, visualize=False):
        y, dt = [], []  # outputs
        for m in self.model:
            if m.f != -1:  # if not from previous layer
                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers
            if profile:
                self._profile_one_layer(m, x, dt)
            if isinstance(m, nn.Upsample):
                m.recompute_scale_factor = None
            x = m(x)  # run
            y.append(x if m.i in self.save else None)  # save output
            if visualize:
                feature_visualization(x, m.type, m.i, save_dir=visualize)
        return x
NaragintiChanduPriya commented 1 year ago

model Summary: 224 layers, 7266973 parameters, 0 gradients, 0.7 GFLOPs image 1/1 C:\Users\chandu\OneDrive\Desktop\yolo\yolov5\instance\uploads\WIN_20220507_16_52_04_Pro.jpg: Traceback (most recent call last): File "C:\Users\chandu\OneDrive\Desktop\yolo\yolov5\detect.py", line 238, in main(opt) File "C:\Users\chandu\OneDrive\Desktop\yolo\yolov5\detect.py", line 233, in main run(*vars(opt)) File "C:\Users\chandu\AppData\Roaming\Python\Python310\site-packages\torch\autograd\grad_mode.py", line 27, in decorate_context return func(args, *kwargs) File "C:\Users\chandu\OneDrive\Desktop\yolo\yolov5\detect.py", line 146, in run s += f"{n} {names[int(c)]}{'s' (n > 1)}, " # add to string IndexError: list index out of range 127.0.0.1 - - [23/Apr/2023 17:19:42] "POST /detect HTTP/1.1" 200 -

I solved this problem without modifying upsample.py.

import torch.nn as nn

for m in model.modules():
    if isinstance(m, nn.Upsample):
        m.recompute_scale_factor = None

I hope this will help someone.

where we need to keep this?

maybe models/yolo.py, it works.

    def _forward_once(self, x, profile=False, visualize=False):
        y, dt = [], []  # outputs
        for m in self.model:
            if m.f != -1:  # if not from previous layer
                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers
            if profile:
                self._profile_one_layer(m, x, dt)
            if isinstance(m, nn.Upsample):
                m.recompute_scale_factor = None
            x = m(x)  # run
            y.append(x if m.i in self.save else None)  # save output
            if visualize:
                feature_visualization(x, m.type, m.i, save_dir=visualize)
        return x

after modifying models/yolo.py again I getting error like this??

donghyeops commented 1 year ago

@NaragintiChanduPriya Hi, above code should be used after instantiating yolo model.

maybe like this example

# load yolo model
model = torch.hub.load("ultralytics/yolov5", "yolov5s")
# model = Model(opt.cfg).to(device)

# error fix code
for m in model.modules():
    if isinstance(m, nn.Upsample):
        m.recompute_scale_factor = None

# model inference
results = model(img)

or you can put fix code in __init__ method of DetectionModel or ClassificationModel

But your last error doesn't seem to be related to the upsample issue. I think the number of classes predicted by your model and the number of predefined class names do not matched.

glenn-jocher commented 1 year ago

@NaragintiChanduPriya the error message IndexError: list index out of range usually means that you are trying to access an element in a list using an invalid index. In your case, it seems like you are trying to access an element in the names list using an index that is out of the valid range for that list.

One possible reason for this could be that the number of classes predicted by your model is different from the number of classes for which you have defined names. Make sure that the length of your names list matches the number of classes predicted by your model. You can check the number of classes predicted by your model using the stride attribute of the last convolutional layer in your model, like this:

import torch

model = torch.hub.load("ultralytics/yolov5", "yolov5s")
stride = model.model[-1].stride
num_classes = int(stride ** 2 * model.model[-1].out_channels)
print(num_classes)

This will print the number of classes predicted by your model based on the configuration of the last layer.

Once you know how many classes your model is predicting, make sure that your names list has the same number of elements. For example, if your model is predicting 80 classes, your names list should have 80 elements.

I hope this helps! Let me know if you have any other questions.

alps-sun commented 1 year ago

thx, it work

glenn-jocher commented 1 year ago

@Alps-Sun hi and glad to hear that the suggested solution worked for you! If you have any other issues or questions in the future, please don't hesitate to ask. Have a great day!

JAYANTH-MOHAN commented 1 year ago

modify like this to models/yolo.py

 def _forward_once(self, x, profile=False, visualize=False):
        y, dt = [], []  # outputs
        for m in self.model:
            if m.f != -1:  # if not from previous layer
                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers
            if profile:
                self._profile_one_layer(m, x, dt)
#this is where u have to update
            if isinstance(m, nn.Upsample):
                m.recompute_scale_factor = None
####
            x = m(x)  # run
            y.append(x if m.i in self.save else None)  # save output
            if visualize:
                feature_visualization(x, m.type, m.i, save_dir=visualize)
        return x
glenn-jocher commented 11 months ago

@JAYANTH-MOHAN Thanks for sharing the modification. It looks like you've added the suggested code snippet in the right place within the _forward_once method of the yolo.py file. This should help resolve the recompute_scale_factor AttributeError issue related to the nn.Upsample module.

If you have any more questions or need further assistance, feel free to ask. Good luck with your YOLOv5 project!

Fengzhennan commented 11 months ago

@Arsalan66 As a work around you can edit your upsampling.py file:

"E:\condaaa\lib\site-packages\torch\nn\modules\upsampling.py"

If you comment out the "recompute_scale_factor=self.recompute_scale_factor" parameter everything seems to work fine.

best method

glenn-jocher commented 8 months ago

@For0 While directly modifying the upsampling.py file in the PyTorch library can provide a quick fix, it's generally not recommended as it can lead to unexpected behavior when updating PyTorch or when sharing your code with others who haven't made the same modification.

Instead, it's better to handle the issue within your own codebase. If you encounter the recompute_scale_factor AttributeError, you can set the recompute_scale_factor attribute to None for each nn.Upsample module in your model after it's been instantiated, as shown in previous messages.

Remember, if you're modifying the library files, you should keep track of these changes and be aware that they might be overwritten when you update PyTorch. It's always best to keep your environment as standard as possible to avoid compatibility issues.

If you need further assistance, feel free to ask. Happy coding!

zohaibmohammad commented 6 months ago
def forward(self, input: Tensor) -> Tensor:
    return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners,
                         #recompute_scale_factor=self.recompute_scale_factor
                         )

For anyone looking for the solution , modify your upsampling.py in E:\condaaa\Lib\site-packages\torch\nn\modules (conda files) , according to the function above.

Thank you. This solution works for me.

glenn-jocher commented 6 months ago

@zohaibmohammad i'm glad to hear the solution worked for you! Just a friendly reminder, while modifying library files directly can be a quick fix, it's generally safer to adjust your code to avoid compatibility issues in the future or consider alternative solutions within your project scope. Happy coding! πŸ˜ŠπŸ‘