checkpoint.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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, exchange=True):
  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. if exchange:
  64. # Exchange model and ema_model to load
  65. logger.info('Exchange model and ema_model to load:')
  66. ema_state_dict = paddle.load(pdparam_path)
  67. logger.info('Loading ema_model weights from {}'.format(path +
  68. '.pdparams'))
  69. param_state_dict = paddle.load(path + '.pdema')
  70. logger.info('Loading model weights from {}'.format(path + '.pdema'))
  71. else:
  72. ema_state_dict = paddle.load(path + '.pdema')
  73. logger.info('Loading ema_model weights from {}'.format(path +
  74. '.pdema'))
  75. param_state_dict = paddle.load(pdparam_path)
  76. logger.info('Loading model weights from {}'.format(path +
  77. '.pdparams'))
  78. else:
  79. ema_state_dict = None
  80. param_state_dict = paddle.load(pdparam_path)
  81. model_dict = model.state_dict()
  82. model_weight = {}
  83. incorrect_keys = 0
  84. for key, value in model_dict.items():
  85. if key in param_state_dict.keys():
  86. if isinstance(param_state_dict[key], np.ndarray):
  87. param_state_dict[key] = paddle.to_tensor(param_state_dict[key])
  88. if value.dtype == param_state_dict[key].dtype:
  89. model_weight[key] = param_state_dict[key]
  90. else:
  91. model_weight[key] = param_state_dict[key].astype(value.dtype)
  92. else:
  93. logger.info('Unmatched key: {}'.format(key))
  94. incorrect_keys += 1
  95. assert incorrect_keys == 0, "Load weight {} incorrectly, \
  96. {} keys unmatched, please check again.".format(weight,
  97. incorrect_keys)
  98. logger.info('Finish resuming model weights: {}'.format(pdparam_path))
  99. model.set_dict(model_weight)
  100. last_epoch = 0
  101. if optimizer is not None and os.path.exists(path + '.pdopt'):
  102. optim_state_dict = paddle.load(path + '.pdopt')
  103. # to solve resume bug, will it be fixed in paddle 2.0
  104. for key in optimizer.state_dict().keys():
  105. if not key in optim_state_dict.keys():
  106. optim_state_dict[key] = optimizer.state_dict()[key]
  107. if 'last_epoch' in optim_state_dict:
  108. last_epoch = optim_state_dict.pop('last_epoch')
  109. optimizer.set_state_dict(optim_state_dict)
  110. if ema_state_dict is not None:
  111. ema.resume(ema_state_dict,
  112. optim_state_dict['LR_Scheduler']['last_epoch'])
  113. elif ema_state_dict is not None:
  114. ema.resume(ema_state_dict)
  115. return last_epoch
  116. def match_state_dict(model_state_dict, weight_state_dict):
  117. """
  118. Match between the model state dict and pretrained weight state dict.
  119. Return the matched state dict.
  120. The method supposes that all the names in pretrained weight state dict are
  121. subclass of the names in models`, if the prefix 'backbone.' in pretrained weight
  122. keys is stripped. And we could get the candidates for each model key. Then we
  123. select the name with the longest matched size as the final match result. For
  124. example, the model state dict has the name of
  125. 'backbone.res2.res2a.branch2a.conv.weight' and the pretrained weight as
  126. name of 'res2.res2a.branch2a.conv.weight' and 'branch2a.conv.weight'. We
  127. match the 'res2.res2a.branch2a.conv.weight' to the model key.
  128. """
  129. model_keys = sorted(model_state_dict.keys())
  130. weight_keys = sorted(weight_state_dict.keys())
  131. def match(a, b):
  132. if b.startswith('backbone.res5'):
  133. # In Faster RCNN, res5 pretrained weights have prefix of backbone,
  134. # however, the corresponding model weights have difficult prefix,
  135. # bbox_head.
  136. b = b[9:]
  137. return a == b or a.endswith("." + b)
  138. match_matrix = np.zeros([len(model_keys), len(weight_keys)])
  139. for i, m_k in enumerate(model_keys):
  140. for j, w_k in enumerate(weight_keys):
  141. if match(m_k, w_k):
  142. match_matrix[i, j] = len(w_k)
  143. max_id = match_matrix.argmax(1)
  144. max_len = match_matrix.max(1)
  145. max_id[max_len == 0] = -1
  146. load_id = set(max_id)
  147. load_id.discard(-1)
  148. not_load_weight_name = []
  149. for idx in range(len(weight_keys)):
  150. if idx not in load_id:
  151. not_load_weight_name.append(weight_keys[idx])
  152. if len(not_load_weight_name) > 0:
  153. logger.info('{} in pretrained weight is not used in the model, '
  154. 'and its will not be loaded'.format(not_load_weight_name))
  155. matched_keys = {}
  156. result_state_dict = {}
  157. for model_id, weight_id in enumerate(max_id):
  158. if weight_id == -1:
  159. continue
  160. model_key = model_keys[model_id]
  161. weight_key = weight_keys[weight_id]
  162. weight_value = weight_state_dict[weight_key]
  163. model_value_shape = list(model_state_dict[model_key].shape)
  164. if list(weight_value.shape) != model_value_shape:
  165. logger.info(
  166. 'The shape {} in pretrained weight {} is unmatched with '
  167. 'the shape {} in model {}. And the weight {} will not be '
  168. 'loaded'.format(weight_value.shape, weight_key,
  169. model_value_shape, model_key, weight_key))
  170. continue
  171. assert model_key not in result_state_dict
  172. result_state_dict[model_key] = weight_value
  173. if weight_key in matched_keys:
  174. raise ValueError('Ambiguity weight {} loaded, it matches at least '
  175. '{} and {} in the model'.format(
  176. weight_key, model_key, matched_keys[
  177. weight_key]))
  178. matched_keys[weight_key] = model_key
  179. return result_state_dict
  180. def load_pretrain_weight(model, pretrain_weight):
  181. if is_url(pretrain_weight):
  182. pretrain_weight = get_weights_path(pretrain_weight)
  183. path = _strip_postfix(pretrain_weight)
  184. if not (os.path.isdir(path) or os.path.isfile(path) or
  185. os.path.exists(path + '.pdparams')):
  186. raise ValueError("Model pretrain path `{}` does not exists. "
  187. "If you don't want to load pretrain model, "
  188. "please delete `pretrain_weights` field in "
  189. "config file.".format(path))
  190. model_dict = model.state_dict()
  191. weights_path = path + '.pdparams'
  192. param_state_dict = paddle.load(weights_path)
  193. param_state_dict = match_state_dict(model_dict, param_state_dict)
  194. for k, v in param_state_dict.items():
  195. if isinstance(v, np.ndarray):
  196. v = paddle.to_tensor(v)
  197. if model_dict[k].dtype != v.dtype:
  198. param_state_dict[k] = v.astype(model_dict[k].dtype)
  199. model.set_dict(param_state_dict)
  200. logger.info('Finish loading model weights: {}'.format(weights_path))
  201. def save_model(model,
  202. optimizer,
  203. save_dir,
  204. save_name,
  205. last_epoch,
  206. ema_model=None):
  207. """
  208. save model into disk.
  209. Args:
  210. model (dict): the model state_dict to save parameters.
  211. optimizer (paddle.optimizer.Optimizer): the Optimizer instance to
  212. save optimizer states.
  213. save_dir (str): the directory to be saved.
  214. save_name (str): the path to be saved.
  215. last_epoch (int): the epoch index.
  216. ema_model (dict|None): the ema_model state_dict to save parameters.
  217. """
  218. if paddle.distributed.get_rank() != 0:
  219. return
  220. assert isinstance(model, dict), ("model is not a instance of dict, "
  221. "please call model.state_dict() to get.")
  222. if not os.path.exists(save_dir):
  223. os.makedirs(save_dir)
  224. save_path = os.path.join(save_dir, save_name)
  225. # save model
  226. if ema_model is None:
  227. paddle.save(model, save_path + ".pdparams")
  228. else:
  229. assert isinstance(ema_model,
  230. dict), ("ema_model is not a instance of dict, "
  231. "please call model.state_dict() to get.")
  232. # Exchange model and ema_model to save
  233. paddle.save(ema_model, save_path + ".pdparams")
  234. paddle.save(model, save_path + ".pdema")
  235. # save optimizer
  236. state_dict = optimizer.state_dict()
  237. state_dict['last_epoch'] = last_epoch
  238. paddle.save(state_dict, save_path + ".pdopt")
  239. logger.info("Save checkpoint: {}".format(save_dir))