checkpoint.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from __future__ import unicode_literals
  18. import errno
  19. import os
  20. import time
  21. import numpy as np
  22. import paddle
  23. import paddle.nn as nn
  24. from .download import get_weights_path
  25. from .logger import setup_logger
  26. logger = setup_logger(__name__)
  27. def is_url(path):
  28. """
  29. Whether path is URL.
  30. Args:
  31. path (string): URL string or not.
  32. """
  33. return path.startswith('http://') \
  34. or path.startswith('https://') \
  35. or path.startswith('ppdet://')
  36. def _get_unique_endpoints(trainer_endpoints):
  37. # Sorting is to avoid different environmental variables for each card
  38. trainer_endpoints.sort()
  39. ips = set()
  40. unique_endpoints = set()
  41. for endpoint in trainer_endpoints:
  42. ip = endpoint.split(":")[0]
  43. if ip in ips:
  44. continue
  45. ips.add(ip)
  46. unique_endpoints.add(endpoint)
  47. logger.info("unique_endpoints {}".format(unique_endpoints))
  48. return unique_endpoints
  49. def _strip_postfix(path):
  50. path, ext = os.path.splitext(path)
  51. assert ext in ['', '.pdparams', '.pdopt', '.pdmodel'], \
  52. "Unknown postfix {} from weights".format(ext)
  53. return path
  54. def load_weight(model, weight, optimizer=None, ema=None):
  55. if is_url(weight):
  56. weight = get_weights_path(weight)
  57. path = _strip_postfix(weight)
  58. pdparam_path = path + '.pdparams'
  59. if not os.path.exists(pdparam_path):
  60. raise ValueError("Model pretrain path {} does not "
  61. "exists.".format(pdparam_path))
  62. if ema is not None and os.path.exists(path + '.pdema'):
  63. # Exchange model and ema_model to load
  64. ema_state_dict = paddle.load(pdparam_path)
  65. param_state_dict = paddle.load(path + '.pdema')
  66. else:
  67. ema_state_dict = None
  68. param_state_dict = paddle.load(pdparam_path)
  69. model_dict = model.state_dict()
  70. model_weight = {}
  71. incorrect_keys = 0
  72. for key in model_dict.keys():
  73. if key in param_state_dict.keys():
  74. model_weight[key] = param_state_dict[key]
  75. else:
  76. logger.info('Unmatched key: {}'.format(key))
  77. incorrect_keys += 1
  78. assert incorrect_keys == 0, "Load weight {} incorrectly, \
  79. {} keys unmatched, please check again.".format(weight,
  80. incorrect_keys)
  81. logger.info('Finish resuming model weights: {}'.format(pdparam_path))
  82. model.set_dict(model_weight)
  83. last_epoch = 0
  84. if optimizer is not None and os.path.exists(path + '.pdopt'):
  85. optim_state_dict = paddle.load(path + '.pdopt')
  86. # to solve resume bug, will it be fixed in paddle 2.0
  87. for key in optimizer.state_dict().keys():
  88. if not key in optim_state_dict.keys():
  89. optim_state_dict[key] = optimizer.state_dict()[key]
  90. if 'last_epoch' in optim_state_dict:
  91. last_epoch = optim_state_dict.pop('last_epoch')
  92. optimizer.set_state_dict(optim_state_dict)
  93. if ema_state_dict is not None:
  94. ema.resume(ema_state_dict,
  95. optim_state_dict['LR_Scheduler']['last_epoch'])
  96. elif ema_state_dict is not None:
  97. ema.resume(ema_state_dict)
  98. return last_epoch
  99. def match_state_dict(model_state_dict, weight_state_dict):
  100. """
  101. Match between the model state dict and pretrained weight state dict.
  102. Return the matched state dict.
  103. The method supposes that all the names in pretrained weight state dict are
  104. subclass of the names in models`, if the prefix 'backbone.' in pretrained weight
  105. keys is stripped. And we could get the candidates for each model key. Then we
  106. select the name with the longest matched size as the final match result. For
  107. example, the model state dict has the name of
  108. 'backbone.res2.res2a.branch2a.conv.weight' and the pretrained weight as
  109. name of 'res2.res2a.branch2a.conv.weight' and 'branch2a.conv.weight'. We
  110. match the 'res2.res2a.branch2a.conv.weight' to the model key.
  111. """
  112. model_keys = sorted(model_state_dict.keys())
  113. weight_keys = sorted(weight_state_dict.keys())
  114. def match(a, b):
  115. if b.startswith('backbone.res5'):
  116. # In Faster RCNN, res5 pretrained weights have prefix of backbone,
  117. # however, the corresponding model weights have difficult prefix,
  118. # bbox_head.
  119. b = b[9:]
  120. return a == b or a.endswith("." + b)
  121. match_matrix = np.zeros([len(model_keys), len(weight_keys)])
  122. for i, m_k in enumerate(model_keys):
  123. for j, w_k in enumerate(weight_keys):
  124. if match(m_k, w_k):
  125. match_matrix[i, j] = len(w_k)
  126. max_id = match_matrix.argmax(1)
  127. max_len = match_matrix.max(1)
  128. max_id[max_len == 0] = -1
  129. load_id = set(max_id)
  130. load_id.discard(-1)
  131. not_load_weight_name = []
  132. for idx in range(len(weight_keys)):
  133. if idx not in load_id:
  134. not_load_weight_name.append(weight_keys[idx])
  135. if len(not_load_weight_name) > 0:
  136. logger.info('{} in pretrained weight is not used in the model, '
  137. 'and its will not be loaded'.format(not_load_weight_name))
  138. matched_keys = {}
  139. result_state_dict = {}
  140. for model_id, weight_id in enumerate(max_id):
  141. if weight_id == -1:
  142. continue
  143. model_key = model_keys[model_id]
  144. weight_key = weight_keys[weight_id]
  145. weight_value = weight_state_dict[weight_key]
  146. model_value_shape = list(model_state_dict[model_key].shape)
  147. if list(weight_value.shape) != model_value_shape:
  148. logger.info(
  149. 'The shape {} in pretrained weight {} is unmatched with '
  150. 'the shape {} in model {}. And the weight {} will not be '
  151. 'loaded'.format(weight_value.shape, weight_key,
  152. model_value_shape, model_key, weight_key))
  153. continue
  154. assert model_key not in result_state_dict
  155. result_state_dict[model_key] = weight_value
  156. if weight_key in matched_keys:
  157. raise ValueError('Ambiguity weight {} loaded, it matches at least '
  158. '{} and {} in the model'.format(
  159. weight_key, model_key, matched_keys[
  160. weight_key]))
  161. matched_keys[weight_key] = model_key
  162. return result_state_dict
  163. def load_pretrain_weight(model, pretrain_weight):
  164. if is_url(pretrain_weight):
  165. pretrain_weight = get_weights_path(pretrain_weight)
  166. path = _strip_postfix(pretrain_weight)
  167. if not (os.path.isdir(path) or os.path.isfile(path) or
  168. os.path.exists(path + '.pdparams')):
  169. raise ValueError("Model pretrain path `{}` does not exists. "
  170. "If you don't want to load pretrain model, "
  171. "please delete `pretrain_weights` field in "
  172. "config file.".format(path))
  173. model_dict = model.state_dict()
  174. weights_path = path + '.pdparams'
  175. param_state_dict = paddle.load(weights_path)
  176. param_state_dict = match_state_dict(model_dict, param_state_dict)
  177. model.set_dict(param_state_dict)
  178. logger.info('Finish loading model weights: {}'.format(weights_path))
  179. def save_model(model,
  180. optimizer,
  181. save_dir,
  182. save_name,
  183. last_epoch,
  184. ema_model=None):
  185. """
  186. save model into disk.
  187. Args:
  188. model (dict): the model state_dict to save parameters.
  189. optimizer (paddle.optimizer.Optimizer): the Optimizer instance to
  190. save optimizer states.
  191. save_dir (str): the directory to be saved.
  192. save_name (str): the path to be saved.
  193. last_epoch (int): the epoch index.
  194. ema_model (dict|None): the ema_model state_dict to save parameters.
  195. """
  196. if paddle.distributed.get_rank() != 0:
  197. return
  198. assert isinstance(model, dict), ("model is not a instance of dict, "
  199. "please call model.state_dict() to get.")
  200. if not os.path.exists(save_dir):
  201. os.makedirs(save_dir)
  202. save_path = os.path.join(save_dir, save_name)
  203. # save model
  204. if ema_model is None:
  205. paddle.save(model, save_path + ".pdparams")
  206. else:
  207. assert isinstance(ema_model,
  208. dict), ("ema_model is not a instance of dict, "
  209. "please call model.state_dict() to get.")
  210. # Exchange model and ema_model to save
  211. paddle.save(ema_model, save_path + ".pdparams")
  212. paddle.save(model, save_path + ".pdema")
  213. # save optimizer
  214. state_dict = optimizer.state_dict()
  215. state_dict['last_epoch'] = last_epoch
  216. paddle.save(state_dict, save_path + ".pdopt")
  217. logger.info("Save checkpoint: {}".format(save_dir))