build.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import torch
  4. import torch.nn as nn
  5. from .loss import build_criterion
  6. from .artdet import ARTDet
  7. # build object detector
  8. def build_artdet(args, cfg, device, num_classes=80, trainable=False, deploy=False):
  9. print('==============================')
  10. print('Build {} ...'.format(args.model.upper()))
  11. # -------------- Build ARTDet --------------
  12. model = ARTDet(
  13. cfg=cfg,
  14. device=device,
  15. num_classes=num_classes,
  16. trainable=trainable,
  17. conf_thresh=args.conf_thresh,
  18. nms_thresh=args.nms_thresh,
  19. topk=args.topk,
  20. deploy=deploy
  21. )
  22. # -------------- Initialize ARTDet --------------
  23. for m in model.modules():
  24. if isinstance(m, nn.BatchNorm2d):
  25. m.eps = 1e-3
  26. m.momentum = 0.03
  27. # Init head
  28. init_prob = 0.01
  29. bias_value = -torch.log(torch.tensor((1. - init_prob) / init_prob))
  30. for det_head in model.det_heads:
  31. # cls pred
  32. b = det_head.cls_pred.bias.view(1, -1)
  33. b.data.fill_(bias_value.item())
  34. det_head.cls_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  35. # reg pred
  36. b = det_head.reg_pred.bias.view(-1, )
  37. b.data.fill_(1.0)
  38. det_head.reg_pred.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  39. w = det_head.reg_pred.weight
  40. w.data.fill_(0.)
  41. det_head.reg_pred.weight = torch.nn.Parameter(w, requires_grad=True)
  42. # -------------- Build criterion --------------
  43. criterion = None
  44. if trainable:
  45. # build criterion for training
  46. criterion = build_criterion(cfg, device, num_classes)
  47. return model, criterion