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

How to save model <AutoShape> #12156

Closed
1 task done
sobassy opened this issue Sep 21, 2023 · 5 comments
Closed
1 task done

How to save model <AutoShape> #12156

sobassy opened this issue Sep 21, 2023 · 5 comments
Labels
question Further information is requested Stale

Comments

@sobassy
Copy link

sobassy commented Sep 21, 2023

Search before asking

Question

I want to custom model to torch.hub loadable file.

After training, I changed class name mannually,

model = torch.hub.load(".", "custom", path="all.pt", source="local")
model.names[4] = 'sample'

How to save this model object same type file ?

I tried below,

torch.save(model, "all2.pt")
torch.save(model.model, "all2.pt")
torch.save(model.half(), "all2.pt") 
model = torch.hub.load(".", "custom", path="all2.pt", source="local")

but these 3 tries caused same error,

YOLOv5  2023-3-23 Python-3.9.17 torch-2.0.1 CUDA:0 (NVIDIA GeForce RTX 3080, 10240MiB)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File \\10.213.84.20\yolov5\hubconf.py:49, in _create(name, pretrained, channels, classes, autoshape, verbose, device)
     48 try:
---> 49     model = DetectMultiBackend(path, device=device, fuse=autoshape)  # detection model
     50     if autoshape:

File \\10.213.84.20\yolov5\.\models\common.py:344, in DetectMultiBackend.__init__(self, weights, device, dnn, data, fp16, fuse)
    343 if pt:  # PyTorch
--> 344     model = attempt_load(weights if isinstance(weights, list) else w, device=device, inplace=True, fuse=fuse)
    345     stride = max(int(model.stride.max()), 32)  # model stride

File \\10.213.84.20\yolov5\.\models\experimental.py:80, in attempt_load(weights, device, inplace, fuse)
     79 ckpt = torch.load(attempt_download(w), map_location='cpu')  # load
---> 80 ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model
     82 # Model compatibility updates

File ~\.conda\envs\llm\lib\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: 'AutoShape' object has no attribute 'get'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
File \\10.213.84.20\yolov5\hubconf.py:60, in _create(name, pretrained, channels, classes, autoshape, verbose, device)
     59     except Exception:
---> 60         model = attempt_load(path, device=device, fuse=False)  # arbitrary model
     61 else:

File \\10.213.84.20\yolov5\.\models\experimental.py:80, in attempt_load(weights, device, inplace, fuse)
     79 ckpt = torch.load(attempt_download(w), map_location='cpu')  # load
---> 80 ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model
     82 # Model compatibility updates

File ~\.conda\envs\llm\lib\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: 'AutoShape' object has no attribute 'get'

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

Exception                                 Traceback (most recent call last)
Cell In[10], line 1
----> 1 model = torch.hub.load(".", "custom", path="all2.pt", source="local")

File ~\.conda\envs\llm\lib\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 ~\.conda\envs\llm\lib\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 \\10.213.84.20\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 \\10.213.84.20\yolov5\yolov5\hubconf.py:78, in _create(name, pretrained, channels, classes, autoshape, verbose, device)
     76 help_url = 'https://github.com/ultralytics/yolov5/issues/36'
     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: 'AutoShape' object has no attribute 'get'. Cache may be out of date, try `force_reload=True` or see https://github.com/ultralytics/yolov5/issues/36 for help.

Additional

No response

@sobassy sobassy added the question Further information is requested label Sep 21, 2023
@github-actions
Copy link
Contributor

👋 Hello @sobassy, 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.8.0 with all requirements.txt installed including PyTorch>=1.8. 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
Copy link
Member

@sobassy to save the YOLOv5 model, you can use the following code:

model.save("all2.pt")

This will save the model object as a file named "all2.pt".

After that, you can load the saved model using the code you provided:

model = torch.hub.load(".", "custom", path="all2.pt", source="local")

Please make sure that you have the necessary permissions to save files in the specified location.

Let me know if you have any further questions!

@sobassy
Copy link
Author

sobassy commented Sep 21, 2023

@glenn-jocher

Thank so much for your advice!
I tried your code, but got error,

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[6], line 1
----> 1 model.save("all2.pt")

File ~\.conda\envs\llm\lib\site-packages\torch\nn\modules\module.py:1614, in Module.__getattr__(self, name)
   1612     if name in modules:
   1613         return modules[name]
-> 1614 raise AttributeError("'{}' object has no attribute '{}'".format(
   1615     type(self).__name__, name))

AttributeError: 'AutoShape' object has no attribute 'save'

It's wrong object, I checked object type,

print(type(model))
print(type(model.model))
print(type(model.model.model))
print(type(model.model.model.model))

returns,

<class 'models.common.AutoShape'>
<class 'models.common.DetectMultiBackend'>
<class 'models.yolo.DetectionModel'>
<class 'torch.nn.modules.container.Sequential'>

Can you give me some advice?

@github-actions
Copy link
Contributor

👋 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 ⭐

@github-actions github-actions bot added the Stale label Oct 22, 2023
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Nov 2, 2023
@glenn-jocher
Copy link
Member

@sobassy I apologize for the confusion. It seems that the AutoShape object itself does not have a save method. Instead, you should save the underlying model attribute directly. Here's the corrected code:

torch.save(model.model, "all2.pt")

This will save the inner model as a file named "all2.pt", which you can then load using the code you provided in your original question.

Let me know if you encounter any more issues!

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

2 participants