checkpoint_utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import contextlib
  6. import fnmatch
  7. import logging
  8. from typing import (
  9. Any,
  10. Callable,
  11. Dict,
  12. List,
  13. Mapping,
  14. Optional,
  15. Sequence,
  16. Set,
  17. Tuple,
  18. Union,
  19. )
  20. import numpy as np
  21. import torch
  22. import torch.nn as nn
  23. from iopath.common.file_io import g_pathmgr
  24. from torch.jit._script import RecursiveScriptModule
  25. def unix_pattern_to_parameter_names(
  26. constraints: List[str], all_parameter_names: Sequence[str]
  27. ) -> Union[None, Set[str]]:
  28. """
  29. Go through the list of parameter names and select those that match
  30. any of the provided constraints
  31. """
  32. parameter_names = []
  33. for param_name in constraints:
  34. matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
  35. assert (
  36. len(matching_parameters) > 0
  37. ), f"param_names {param_name} don't match any param in the given names."
  38. parameter_names.append(matching_parameters)
  39. return set.union(*parameter_names)
  40. def filter_params_matching_unix_pattern(
  41. patterns: List[str], state_dict: Dict[str, torch.Tensor]
  42. ) -> Dict[str, torch.Tensor]:
  43. """
  44. Remove from the state dictionary the parameters matching the provided unix patterns
  45. Args:
  46. patterns: the list of unix patterns to exclude
  47. state_dict: the dictionary to filter
  48. Returns:
  49. A new state dictionary
  50. """
  51. if len(patterns) == 0:
  52. return {}
  53. all_keys = list(state_dict.keys())
  54. included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
  55. return {k: state_dict[k] for k in included_keys}
  56. def exclude_params_matching_unix_pattern(
  57. patterns: List[str], state_dict: Dict[str, torch.Tensor]
  58. ) -> Dict[str, torch.Tensor]:
  59. """
  60. Remove from the state dictionary the parameters matching the provided unix patterns
  61. Args:
  62. patterns: the list of unix patterns to exclude
  63. state_dict: the dictionary to filter
  64. Returns:
  65. A new state dictionary
  66. """
  67. if len(patterns) == 0:
  68. return state_dict
  69. all_keys = list(state_dict.keys())
  70. excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
  71. return {k: v for k, v in state_dict.items() if k not in excluded_keys}
  72. def _get_state_dict_summary(state_dict: Dict[str, torch.Tensor]):
  73. keys = []
  74. trace = []
  75. for k, v in state_dict.items():
  76. keys.append(k)
  77. trace.append(v.sum().item())
  78. trace = np.array(trace)[np.argsort(keys)]
  79. return trace
  80. def assert_skipped_parameters_are_frozen(model: nn.Module, patterns: List[str]):
  81. """
  82. Verifies that all the parameters matching the provided patterns
  83. are frozen - this acts as a safeguard when ignoring parameter
  84. when saving checkpoints - if the parameters are in fact trainable
  85. """
  86. if not patterns:
  87. return
  88. frozen_state_dict = filter_params_matching_unix_pattern(
  89. patterns=patterns, state_dict=model.state_dict()
  90. )
  91. non_frozen_keys = {
  92. n
  93. for n, p in model.named_parameters()
  94. if n in frozen_state_dict and p.requires_grad
  95. }
  96. if non_frozen_keys:
  97. raise ValueError(
  98. f"Parameters excluded with `skip_saving_parameters` should be frozen: {non_frozen_keys}"
  99. )
  100. @contextlib.contextmanager
  101. def with_check_parameter_frozen(
  102. model: nn.Module, patterns: List[str], disabled: bool = True
  103. ):
  104. """
  105. Context manager that inspects a model surrounding a piece of code
  106. and verifies if the model has been updated by this piece of code
  107. The function will raise an exception if the model has been updated
  108. on at least one of the parameter that matches one of the pattern
  109. Args:
  110. model: the model that might have been updated
  111. patterns: for the parameters we want to observe
  112. allowed:
  113. """
  114. if not patterns or disabled:
  115. yield
  116. return
  117. frozen_state_dict = filter_params_matching_unix_pattern(
  118. patterns=patterns, state_dict=model.state_dict()
  119. )
  120. summary_before = _get_state_dict_summary(frozen_state_dict)
  121. yield
  122. frozen_state_dict = filter_params_matching_unix_pattern(
  123. patterns=patterns, state_dict=model.state_dict()
  124. )
  125. summary_after = _get_state_dict_summary(frozen_state_dict)
  126. if not np.allclose(summary_before, summary_after, atol=1e-6):
  127. raise ValueError(
  128. f"""
  129. The `model_weight_initializer` has initialized parameters frozen with `skip_saving_parameters`.
  130. You can resolve this error by either initializing those parameters from within the model definition
  131. or using the flag `trainer.checkpoint.initialize_after_preemption` to True.
  132. """
  133. )
  134. class CkptExcludeKernel:
  135. """
  136. Removes the keys from the given model state_dict that match the key_pattern.
  137. Args:
  138. key_pattern: Patterns used to select the keys in the state_dict
  139. that are eligible for this kernel.
  140. """
  141. def __init__(self, key_pattern: List[str]):
  142. self.key_pattern = key_pattern
  143. def __call__(self, state_dict: Dict):
  144. """
  145. Args:
  146. state_dict: A dictionary representing the given checkpoint's state dict.
  147. """
  148. if len(self.key_pattern) == 0:
  149. return state_dict
  150. exclude_keys = unix_pattern_to_parameter_names(
  151. self.key_pattern, state_dict.keys()
  152. )
  153. return {k: v for k, v in state_dict.items() if k not in exclude_keys}
  154. def load_checkpoint(
  155. path_list: List[str],
  156. pick_recursive_keys: Optional[List[str]] = None,
  157. map_location: str = "cpu",
  158. ) -> Any:
  159. """
  160. Loads a checkpoint from the specified path.
  161. Args:
  162. path_list: A list of paths which contain the checkpoint. Each element
  163. is tried (in order) until a file that exists is found. That file is then
  164. used to read the checkpoint.
  165. pick_recursive_keys: Picks sub dicts from the loaded checkpoint if not None.
  166. For pick_recursive_keys = ["a", "b"], will return checkpoint_dict["a"]["b"]
  167. map_location (str): a function, torch.device, string or a dict specifying how to
  168. remap storage locations
  169. Returns: Model with the matchin pre-trained weights loaded.
  170. """
  171. path_exists = False
  172. for path in path_list:
  173. if g_pathmgr.exists(path):
  174. path_exists = True
  175. break
  176. if not path_exists:
  177. raise ValueError(f"No path exists in {path_list}")
  178. with g_pathmgr.open(path, "rb") as f:
  179. checkpoint = torch.load(f, map_location=map_location)
  180. logging.info(f"Loaded checkpoint from {path}")
  181. if pick_recursive_keys is not None:
  182. for key in pick_recursive_keys:
  183. checkpoint = checkpoint[key]
  184. return checkpoint
  185. def get_state_dict(checkpoint, ckpt_state_dict_keys):
  186. if isinstance(checkpoint, RecursiveScriptModule):
  187. # This is a torchscript JIT model
  188. return checkpoint.state_dict()
  189. pre_train_dict = checkpoint
  190. for i, key in enumerate(ckpt_state_dict_keys):
  191. if (isinstance(pre_train_dict, Mapping) and key not in pre_train_dict) or (
  192. isinstance(pre_train_dict, Sequence) and key >= len(pre_train_dict)
  193. ):
  194. key_str = (
  195. '["' + '"]["'.join(list(map(ckpt_state_dict_keys[:i], str))) + '"]'
  196. )
  197. raise KeyError(
  198. f"'{key}' not found in checkpoint{key_str} "
  199. f"with keys: {pre_train_dict.keys()}"
  200. )
  201. pre_train_dict = pre_train_dict[key]
  202. return pre_train_dict
  203. def load_checkpoint_and_apply_kernels(
  204. checkpoint_path: str,
  205. checkpoint_kernels: List[Callable] = None,
  206. ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
  207. map_location: str = "cpu",
  208. ) -> nn.Module:
  209. """
  210. Performs checkpoint loading with a variety of pre-processing kernel applied in
  211. sequence.
  212. Args:
  213. checkpoint_path (str): Path to the checkpoint.
  214. checkpoint_kernels List(Callable): A list of checkpoint processing kernels
  215. to apply in the specified order. Supported kernels include `CkptIncludeKernel`,
  216. `CkptExcludeKernel`, etc. These kernels are applied in the
  217. given order.
  218. ckpt_state_dict_keys (str): Keys containing the model state dict.
  219. map_location (str): a function, torch.device, string or a dict specifying how to
  220. remap storage locations
  221. Returns: Model with the matchin pre-trained weights loaded.
  222. """
  223. assert g_pathmgr.exists(checkpoint_path), "Checkpoint '{}' not found".format(
  224. checkpoint_path
  225. )
  226. # Load the checkpoint on CPU to avoid GPU mem spike.
  227. with g_pathmgr.open(checkpoint_path, "rb") as f:
  228. checkpoint = torch.load(f, map_location=map_location)
  229. pre_train_dict = get_state_dict(checkpoint, ckpt_state_dict_keys)
  230. # Not logging into info etc since it's a huge log
  231. logging.debug(
  232. "Loaded Checkpoint State Dict pre-kernel application: %s"
  233. % str(", ".join(list(pre_train_dict.keys())))
  234. )
  235. # Apply kernels
  236. if checkpoint_kernels is not None:
  237. for f in checkpoint_kernels:
  238. pre_train_dict = f(state_dict=pre_train_dict)
  239. logging.debug(
  240. "Loaded Checkpoint State Dict Post-kernel application %s"
  241. % str(", ".join(list(pre_train_dict.keys())))
  242. )
  243. return pre_train_dict
  244. def check_load_state_dict_errors(
  245. missing_keys,
  246. unexpected_keys,
  247. strict: bool,
  248. ignore_missing_keys: List[str] = None,
  249. ignore_unexpected_keys: List[str] = None,
  250. ):
  251. if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
  252. ignored_keys = unix_pattern_to_parameter_names(
  253. ignore_missing_keys, missing_keys
  254. )
  255. missing_keys = [key for key in missing_keys if key not in ignored_keys]
  256. if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
  257. ignored_unexpected_keys = unix_pattern_to_parameter_names(
  258. ignore_unexpected_keys, unexpected_keys
  259. )
  260. unexpected_keys = [
  261. key for key in unexpected_keys if key not in ignored_unexpected_keys
  262. ]
  263. err = "State key mismatch."
  264. if unexpected_keys:
  265. err += f" Unexpected keys: {unexpected_keys}."
  266. if missing_keys:
  267. err += f" Missing keys: {missing_keys}."
  268. if unexpected_keys or missing_keys:
  269. logging.warning(err)
  270. if unexpected_keys or strict:
  271. raise KeyError(err)
  272. def load_state_dict_into_model(
  273. state_dict: Dict,
  274. model: nn.Module,
  275. strict: bool = True,
  276. ignore_missing_keys: List[str] = None,
  277. ignore_unexpected_keys: List[str] = None,
  278. checkpoint_kernels: List[Callable] = None,
  279. ):
  280. """
  281. Loads a state dict into the given model.
  282. Args:
  283. state_dict: A dictionary containing the model's
  284. state dict, or a subset if strict is False
  285. model: Model to load the checkpoint weights into
  286. strict: raise if the state_dict has missing state keys
  287. ignore_missing_keys: unix pattern of keys to ignore
  288. """
  289. # Apply kernels
  290. if checkpoint_kernels is not None:
  291. for f in checkpoint_kernels:
  292. state_dict = f(state_dict=state_dict)
  293. missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
  294. check_load_state_dict_errors(
  295. missing_keys,
  296. unexpected_keys,
  297. strict=strict,
  298. ignore_missing_keys=ignore_missing_keys,
  299. ignore_unexpected_keys=ignore_unexpected_keys,
  300. )
  301. return model