__init__.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import torch
  4. from .yolov1.build import build_yolov1
  5. from .yolov2.build import build_yolov2
  6. from .yolov3.build import build_yolov3
  7. from .yolov5.build import build_yolov5
  8. from .yolox.build import build_yolox
  9. from .yolov8.build import build_yolov8
  10. from .rtdetr.build import build_rtdetr
  11. # build object detector
  12. def build_model(args, cfg, is_val=False):
  13. # ------------ build object detector ------------
  14. ## Modified YOLOv1
  15. if 'yolov1' in args.model:
  16. model, criterion = build_yolov1(cfg, is_val)
  17. ## Modified YOLOv2
  18. elif 'yolov2' in args.model:
  19. model, criterion = build_yolov2(cfg, is_val)
  20. ## Modified YOLOv3
  21. elif 'yolov3' in args.model:
  22. model, criterion = build_yolov3(cfg, is_val)
  23. ## Modified YOLOv5
  24. elif 'yolov5' in args.model:
  25. model, criterion = build_yolov5(cfg, is_val)
  26. ## YOLOX
  27. elif 'yolox' in args.model:
  28. model, criterion = build_yolox(cfg, is_val)
  29. ## YOLOv8
  30. elif 'yolov8' in args.model:
  31. model, criterion = build_yolov8(cfg, is_val)
  32. ## RT-DETR
  33. elif 'rtdetr' in args.model:
  34. model, criterion = build_rtdetr(cfg, is_val)
  35. if is_val:
  36. # ------------ Load pretrained weight ------------
  37. if args.pretrained is not None:
  38. print('Loading COCO pretrained weight ...')
  39. checkpoint = torch.load(args.pretrained, map_location='cpu')
  40. # checkpoint state dict
  41. checkpoint_state_dict = checkpoint.pop("model")
  42. # model state dict
  43. model_state_dict = model.state_dict()
  44. # check
  45. for k in list(checkpoint_state_dict.keys()):
  46. if k in model_state_dict:
  47. shape_model = tuple(model_state_dict[k].shape)
  48. shape_checkpoint = tuple(checkpoint_state_dict[k].shape)
  49. if shape_model != shape_checkpoint:
  50. checkpoint_state_dict.pop(k)
  51. print(k)
  52. else:
  53. checkpoint_state_dict.pop(k)
  54. print(k)
  55. model.load_state_dict(checkpoint_state_dict, strict=False)
  56. # ------------ Keep training from the given checkpoint ------------
  57. if args.resume and args.resume != "None":
  58. checkpoint = torch.load(args.resume, map_location='cpu')
  59. # checkpoint state dict
  60. try:
  61. checkpoint_state_dict = checkpoint.pop("model")
  62. print('Load model from the checkpoint: ', args.resume)
  63. model.load_state_dict(checkpoint_state_dict)
  64. del checkpoint, checkpoint_state_dict
  65. except:
  66. print("No model in the given checkpoint.")
  67. return model, criterion
  68. else:
  69. return model