yolov5 导出LibTorch模型(CPU和GPU)

举报
AI浩 发表于 2021/12/22 23:53:14 2021/12/22
【摘要】  官方给出的是CPU: """Exports a YOLOv5 *.pt model to ONNX and TorchScript formatsUsage: $ export PYTHONPATH="$PWD" && python models/export.py --weights ./weigh...

 官方给出的是CPU:


  
  1. """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
  2. Usage:
  3. $ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1
  4. """
  5. import argparse
  6. import torch
  7. import torch.nn as nn
  8. import models
  9. from models.experimental import attempt_load
  10. from utils.activations import Hardswish
  11. from utils.general import set_logging
  12. if __name__ == '__main__':
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument('--weights', type=str, default='../runs/exp7/weights/best.pt', help='weights path') # from yolov5/models/
  15. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
  16. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  17. opt = parser.parse_args()
  18. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  19. print(opt)
  20. set_logging()
  21. # Input
  22. img = torch.zeros((opt.batch_size, 3, *opt.img_size)) # image size(1,3,320,192) iDetection
  23. # Load PyTorch model
  24. model = attempt_load(opt.weights, map_location=torch.device('cpu')) # load FP32 model
  25. # Update model
  26. for k, m in model.named_modules():
  27. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatability
  28. if isinstance(m, models.common.Conv) and isinstance(m.act, nn.Hardswish):
  29. m.act = Hardswish() # assign activation
  30. # if isinstance(m, models.yolo.Detect):
  31. # m.forward = m.forward_export # assign forward (optional)
  32. model.model[-1].export = True # set Detect() layer export=True
  33. y = model(img) # dry run
  34. # TorchScript export
  35. try:
  36. print('\nStarting TorchScript export with torch %s...' % torch.__version__)
  37. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  38. ts = torch.jit.trace(model, img)
  39. ts.save(f)
  40. print('TorchScript export success, saved as %s' % f)
  41. except Exception as e:
  42. print('TorchScript export failure: %s' % e)

 GPU


  
  1. import argparse
  2. import torch
  3. import torch.nn as nn
  4. import models
  5. from models.experimental import attempt_load
  6. from utils.activations import Hardswish
  7. from utils.general import set_logging
  8. if __name__ == '__main__':
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument('--weights', type=str, default='../runs/exp7/weights/best.pt', help='weights path') # from yolov5/models/
  11. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
  12. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  13. opt = parser.parse_args()
  14. opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
  15. print(opt)
  16. set_logging()
  17. # Input
  18. img = torch.zeros((opt.batch_size, 3, *opt.img_size)).to(device='cuda') # image size(1,3,320,192) iDetection
  19. # Load PyTorch model
  20. model = attempt_load(opt.weights, map_location=torch.device('cuda')) # load FP32 model
  21. # Update model
  22. for k, m in model.named_modules():
  23. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatability
  24. if isinstance(m, models.common.Conv) and isinstance(m.act, nn.Hardswish):
  25. m.act = Hardswish() # assign activation
  26. # if isinstance(m, models.yolo.Detect):
  27. # m.forward = m.forward_export # assign forward (optional)
  28. model.model[-1].export = True # set Detect() layer export=True
  29. y = model(img) # dry run
  30. # TorchScript export
  31. try:
  32. print('\nStarting TorchScript export with torch %s...' % torch.__version__)
  33. f = opt.weights.replace('.pt', '.torchscript.pt') # filename
  34. ts = torch.jit.trace(model, img)
  35. ts.save(f)
  36. print('TorchScript export success, saved as %s' % f)
  37. except Exception as e:
  38. print('TorchScript export failure: %s' % e)

 

文章来源: wanghao.blog.csdn.net,作者:AI浩,版权归原作者所有,如需转载,请联系作者。

原文链接:wanghao.blog.csdn.net/article/details/116117544

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。