ultralytics / yolov5

YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
49.74k stars 16.12k forks source link

Quantizing Yolov5 - torch.save() and additional error #12501

Closed TCGoingW closed 6 months ago

TCGoingW commented 9 months ago

Search before asking

Question

Greeting! Thank you for your teams hard work and for providing such an incredible YOLOv5 model.

As the title said, I'm trying to quantization the YOLOv5 with https://github.com/Xilinx/brevitas. I encountered the problem with the torch.save(). Here comes the related issue on the Brevitas Github which mention in https://github.com/Xilinx/brevitas/issues/627. The issue mentioned that the Brevitas quantization method couldn't save with pickle method. Followed the issue solution, I replaced torch.save(ckpt, /* target*/ ) with torch.save(model.state_dict(), /* target*/ ). Only stored the weight instead of the whole ckpt. So I didn't have the others informations, as ema, model, etc. The actual code as below:

In yolov5/train.py

if (not nosave) or (final_epoch and not evolve):  # if save
    ckpt = {
        'epoch': epoch,
        'best_fitness': best_fitness,
        'model': deepcopy(de_parallel(model)).half(),
        'ema': deepcopy(ema.ema).half(),
        'updates': ema.updates,
        'optimizer': optimizer.state_dict(),
        'opt': vars(opt),
        'git': GIT_INFO,  # {remote, branch, commit} if a git repo
        'date': datetime.now().isoformat()}

    # Save last, best and delete
    # torch.save(ckpt, last) 
    torch.save(model.state_dict(), last)
    if best_fitness == fi:
        # torch.save(ckpt, best)
        torch.save(model.state_dict(), best)
    if opt.save_period > 0 and epoch % opt.save_period == 0:
        # torch.save(ckpt, w / f'epoch{epoch}.pt')
        torch.save(model.state_dict(), w / f'epoch{epoch}.pt')
    del ckpt
    callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)

The solution work! But I got another error needed to be solve. When the training phase have done, the error involves the attempt_load(f, device).half() functionality. Because of only store the weight instead of the whole ckpt, I got the lack of the informations, as ema, model, etc. So the error occured in yolov5/models/experimental.py's attempt_load() function at the ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float(). The error message as below:

Starting training for 1 epochs...
 # the output of the epoch message in training phase
1 epochs completed in 0.000 hours.

Validating runs/train/exp12/weights/best.pt...
Traceback (most recent call last):
  File "train.py", line 662, in <module>
    main(opt)
  File "train.py", line 551, in main
    train(opt.hyp, opt, device, callbacks)
  File "train.py", line 436, in train
    model=attempt_load(f, device).half(),
  File "/**/yolov5/models/experimental.py", line 96, in attempt_load
    ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model
KeyError: 'model'

How do I solve the error? Or maybe give me some suggestions to revise the problem to make YOLOv5 train successfully, it can be the alternative way to save the ckpt whole informations not only the weight(w/o pickle method) or replace the code in the attempt_load() function.

Best regards, thank you very much for your time and your interest in my request. @glenn-jocher

Additional

No response

github-actions[bot] commented 9 months ago

👋 Hello @TCGoingW, 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 commented 9 months ago

@TCGoingW hi there! 🌟 Thanks for your kind words and for using YOLOv5!

Regarding the torch.save() issue, you can save *.pt files with the entire model state dictionary (including EMA, optimizer states etc) as suggested here. Then, to load the model using attempt_load(f, device).half(), just replace the ckpt.get('ema') or ckpt['model'] line with ckpt['model'].to(device).float() in your yolov5/models/experimental.py file to resolve the error.

Let me know if you encounter any further issues! Keep up the great work! 🚀

TCGoingW commented 9 months ago

@TCGoingW hi there! 🌟 Thanks for your kind words and for using YOLOv5!

Regarding the torch.save() issue, you can save *.pt files with the entire model state dictionary (including EMA, optimizer states etc) as suggested here. Then, to load the model using attempt_load(f, device).half(), just replace the ckpt.get('ema') or ckpt['model'] line with ckpt['model'].to(device).float() in your yolov5/models/experimental.py file to resolve the error.

Let me know if you encounter any further issues! Keep up the great work! 🚀

Sorry @glenn-jocher, the link, which is the alternative way to save *.pt files with the entire model state dictionary, is missing! Maybe the wrong link or something. Thanks for the kindly reply!!!

glenn-jocher commented 9 months ago

@TCGoingW Apologies for the confusion! You can find information about saving *.pt files with the entire model state dictionary, including EMA and optimizer states, at https://docs.ultralytics.com/yolov5/training#optimize-hardware. Hope this helps! If you have any more questions, feel free to ask. Good luck with your project! 🌟

github-actions[bot] commented 8 months 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 ⭐

github-actions[bot] commented 7 months 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 ⭐