utils.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # --------------------------------------------------------
  2. # Swin Transformer
  3. # Copyright (c) 2021 Microsoft
  4. # Licensed under The MIT License [see LICENSE for details]
  5. # Written by Ze Liu
  6. # --------------------------------------------------------
  7. import os
  8. import torch
  9. import torch.distributed as dist
  10. try:
  11. from torch._six import inf
  12. except:
  13. from torch import inf
  14. def load_checkpoint(config, model, optimizer, lr_scheduler, loss_scaler, logger):
  15. logger.info(f"==============> Resuming form {config.MODEL.RESUME}....................")
  16. if config.MODEL.RESUME.startswith('https'):
  17. checkpoint = torch.hub.load_state_dict_from_url(
  18. config.MODEL.RESUME, map_location='cpu', check_hash=True)
  19. else:
  20. checkpoint = torch.load(config.MODEL.RESUME, map_location='cpu')
  21. msg = model.load_state_dict(checkpoint['model'], strict=False)
  22. logger.info(msg)
  23. max_accuracy = 0.0
  24. if not config.EVAL_MODE and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'epoch' in checkpoint:
  25. optimizer.load_state_dict(checkpoint['optimizer'])
  26. lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])
  27. config.defrost()
  28. config.TRAIN.START_EPOCH = checkpoint['epoch'] + 1
  29. config.freeze()
  30. if 'scaler' in checkpoint:
  31. loss_scaler.load_state_dict(checkpoint['scaler'])
  32. logger.info(f"=> loaded successfully '{config.MODEL.RESUME}' (epoch {checkpoint['epoch']})")
  33. if 'max_accuracy' in checkpoint:
  34. max_accuracy = checkpoint['max_accuracy']
  35. del checkpoint
  36. torch.cuda.empty_cache()
  37. return max_accuracy
  38. def load_pretrained(config, model, logger):
  39. logger.info(f"==============> Loading weight {config.MODEL.PRETRAINED} for fine-tuning......")
  40. checkpoint = torch.load(config.MODEL.PRETRAINED, map_location='cpu')
  41. state_dict = checkpoint['model']
  42. # delete relative_position_index since we always re-init it
  43. relative_position_index_keys = [k for k in state_dict.keys() if "relative_position_index" in k]
  44. for k in relative_position_index_keys:
  45. del state_dict[k]
  46. # delete relative_coords_table since we always re-init it
  47. relative_position_index_keys = [k for k in state_dict.keys() if "relative_coords_table" in k]
  48. for k in relative_position_index_keys:
  49. del state_dict[k]
  50. # delete attn_mask since we always re-init it
  51. attn_mask_keys = [k for k in state_dict.keys() if "attn_mask" in k]
  52. for k in attn_mask_keys:
  53. del state_dict[k]
  54. # bicubic interpolate relative_position_bias_table if not match
  55. relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k]
  56. for k in relative_position_bias_table_keys:
  57. relative_position_bias_table_pretrained = state_dict[k]
  58. relative_position_bias_table_current = model.state_dict()[k]
  59. L1, nH1 = relative_position_bias_table_pretrained.size()
  60. L2, nH2 = relative_position_bias_table_current.size()
  61. if nH1 != nH2:
  62. logger.warning(f"Error in loading {k}, passing......")
  63. else:
  64. if L1 != L2:
  65. # bicubic interpolate relative_position_bias_table if not match
  66. S1 = int(L1 ** 0.5)
  67. S2 = int(L2 ** 0.5)
  68. relative_position_bias_table_pretrained_resized = torch.nn.functional.interpolate(
  69. relative_position_bias_table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2),
  70. mode='bicubic')
  71. state_dict[k] = relative_position_bias_table_pretrained_resized.view(nH2, L2).permute(1, 0)
  72. # bicubic interpolate absolute_pos_embed if not match
  73. absolute_pos_embed_keys = [k for k in state_dict.keys() if "absolute_pos_embed" in k]
  74. for k in absolute_pos_embed_keys:
  75. # dpe
  76. absolute_pos_embed_pretrained = state_dict[k]
  77. absolute_pos_embed_current = model.state_dict()[k]
  78. _, L1, C1 = absolute_pos_embed_pretrained.size()
  79. _, L2, C2 = absolute_pos_embed_current.size()
  80. if C1 != C1:
  81. logger.warning(f"Error in loading {k}, passing......")
  82. else:
  83. if L1 != L2:
  84. S1 = int(L1 ** 0.5)
  85. S2 = int(L2 ** 0.5)
  86. absolute_pos_embed_pretrained = absolute_pos_embed_pretrained.reshape(-1, S1, S1, C1)
  87. absolute_pos_embed_pretrained = absolute_pos_embed_pretrained.permute(0, 3, 1, 2)
  88. absolute_pos_embed_pretrained_resized = torch.nn.functional.interpolate(
  89. absolute_pos_embed_pretrained, size=(S2, S2), mode='bicubic')
  90. absolute_pos_embed_pretrained_resized = absolute_pos_embed_pretrained_resized.permute(0, 2, 3, 1)
  91. absolute_pos_embed_pretrained_resized = absolute_pos_embed_pretrained_resized.flatten(1, 2)
  92. state_dict[k] = absolute_pos_embed_pretrained_resized
  93. # check classifier, if not match, then re-init classifier to zero
  94. head_bias_pretrained = state_dict['head.bias']
  95. Nc1 = head_bias_pretrained.shape[0]
  96. Nc2 = model.head.bias.shape[0]
  97. if (Nc1 != Nc2):
  98. if Nc1 == 21841 and Nc2 == 1000:
  99. logger.info("loading ImageNet-22K weight to ImageNet-1K ......")
  100. map22kto1k_path = f'data/map22kto1k.txt'
  101. with open(map22kto1k_path) as f:
  102. map22kto1k = f.readlines()
  103. map22kto1k = [int(id22k.strip()) for id22k in map22kto1k]
  104. state_dict['head.weight'] = state_dict['head.weight'][map22kto1k, :]
  105. state_dict['head.bias'] = state_dict['head.bias'][map22kto1k]
  106. else:
  107. torch.nn.init.constant_(model.head.bias, 0.)
  108. torch.nn.init.constant_(model.head.weight, 0.)
  109. del state_dict['head.weight']
  110. del state_dict['head.bias']
  111. logger.warning(f"Error in loading classifier head, re-init classifier head to 0")
  112. msg = model.load_state_dict(state_dict, strict=False)
  113. logger.warning(msg)
  114. logger.info(f"=> loaded successfully '{config.MODEL.PRETRAINED}'")
  115. del checkpoint
  116. torch.cuda.empty_cache()
  117. def save_checkpoint(config, epoch, model, max_accuracy, optimizer, lr_scheduler, loss_scaler, logger):
  118. save_state = {'model': model.state_dict(),
  119. 'optimizer': optimizer.state_dict(),
  120. 'lr_scheduler': lr_scheduler.state_dict(),
  121. 'max_accuracy': max_accuracy,
  122. 'scaler': loss_scaler.state_dict(),
  123. 'epoch': epoch,
  124. 'config': config}
  125. save_path = os.path.join(config.OUTPUT, f'ckpt_epoch_{epoch}.pth')
  126. logger.info(f"{save_path} saving......")
  127. torch.save(save_state, save_path)
  128. logger.info(f"{save_path} saved !!!")
  129. def get_grad_norm(parameters, norm_type=2):
  130. if isinstance(parameters, torch.Tensor):
  131. parameters = [parameters]
  132. parameters = list(filter(lambda p: p.grad is not None, parameters))
  133. norm_type = float(norm_type)
  134. total_norm = 0
  135. for p in parameters:
  136. param_norm = p.grad.data.norm(norm_type)
  137. total_norm += param_norm.item() ** norm_type
  138. total_norm = total_norm ** (1. / norm_type)
  139. return total_norm
  140. def auto_resume_helper(output_dir):
  141. checkpoints = os.listdir(output_dir)
  142. checkpoints = [ckpt for ckpt in checkpoints if ckpt.endswith('pth')]
  143. print(f"All checkpoints founded in {output_dir}: {checkpoints}")
  144. if len(checkpoints) > 0:
  145. latest_checkpoint = max([os.path.join(output_dir, d) for d in checkpoints], key=os.path.getmtime)
  146. print(f"The latest checkpoint founded: {latest_checkpoint}")
  147. resume_file = latest_checkpoint
  148. else:
  149. resume_file = None
  150. return resume_file
  151. def reduce_tensor(tensor):
  152. rt = tensor.clone()
  153. dist.all_reduce(rt, op=dist.ReduceOp.SUM)
  154. rt /= dist.get_world_size()
  155. return rt
  156. def ampscaler_get_grad_norm(parameters, norm_type: float = 2.0) -> torch.Tensor:
  157. if isinstance(parameters, torch.Tensor):
  158. parameters = [parameters]
  159. parameters = [p for p in parameters if p.grad is not None]
  160. norm_type = float(norm_type)
  161. if len(parameters) == 0:
  162. return torch.tensor(0.)
  163. device = parameters[0].grad.device
  164. if norm_type == inf:
  165. total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters)
  166. else:
  167. total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(),
  168. norm_type).to(device) for p in parameters]), norm_type)
  169. return total_norm
  170. class NativeScalerWithGradNormCount:
  171. state_dict_key = "amp_scaler"
  172. def __init__(self):
  173. self._scaler = torch.cuda.amp.GradScaler()
  174. def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True):
  175. self._scaler.scale(loss).backward(create_graph=create_graph)
  176. if update_grad:
  177. if clip_grad is not None:
  178. assert parameters is not None
  179. self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place
  180. norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad)
  181. else:
  182. self._scaler.unscale_(optimizer)
  183. norm = ampscaler_get_grad_norm(parameters)
  184. self._scaler.step(optimizer)
  185. self._scaler.update()
  186. else:
  187. norm = None
  188. return norm
  189. def state_dict(self):
  190. return self._scaler.state_dict()
  191. def load_state_dict(self, state_dict):
  192. self._scaler.load_state_dict(state_dict)