load_pretrained_model.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. from typing import Any
  2. from typing import Dict
  3. from typing import Union
  4. from io import BytesIO
  5. import logging
  6. import torch
  7. import torch.nn
  8. import torch.optim
  9. import pdb
  10. def filter_state_dict(
  11. dst_state: Dict[str, Union[float, torch.Tensor]],
  12. src_state: Dict[str, Union[float, torch.Tensor]],
  13. ):
  14. """Filter name, size mismatch instances between dicts.
  15. Args:
  16. dst_state: reference state dict for filtering
  17. src_state: target state dict for filtering
  18. """
  19. match_state = {}
  20. for key, value in src_state.items():
  21. if key in dst_state and (dst_state[key].size() == src_state[key].size()):
  22. match_state[key] = value
  23. else:
  24. if key not in dst_state:
  25. logging.warning(
  26. f"Filter out {key} from pretrained dict"
  27. + " because of name not found in target dict"
  28. )
  29. else:
  30. logging.warning(
  31. f"Filter out {key} from pretrained dict"
  32. + " because of size mismatch"
  33. + f"({dst_state[key].size()}-{src_state[key].size()})"
  34. )
  35. return match_state
  36. def assigment_scope_map(dst_state: dict, src_state: dict, scope_map: str=None):
  37. """Compute the union of the current variables and checkpoint variables."""
  38. import collections
  39. import re
  40. # current model variables
  41. name_to_variable = collections.OrderedDict()
  42. for name, var in dst_state.items():
  43. name_to_variable[name] = var
  44. scope_map_num = 0
  45. if scope_map is not None:
  46. scope_map = scope_map.split(",")
  47. scope_map_num = len(scope_map) // 2
  48. for scope_map_idx in range(scope_map_num):
  49. scope_map_id = scope_map_idx * 2
  50. logging.info('assignment_map from scope {} to {}'.format(scope_map[scope_map_id], scope_map[scope_map_id+1]))
  51. assignment_map = {}
  52. for name, var in src_state.items():
  53. if scope_map:
  54. for scope_map_idx in range(scope_map_num):
  55. scope_map_id = scope_map_idx * 2
  56. try:
  57. idx = name.index(scope_map[scope_map_id])
  58. new_name = scope_map[scope_map_id+1] + name[idx + len(scope_map[scope_map_id]):]
  59. if new_name in name_to_variable:
  60. assignment_map[name] = var
  61. except:
  62. continue
  63. else:
  64. if name in name_to_variable:
  65. assignment_map[name] = var
  66. return assignment_map
  67. def load_pretrained_model(
  68. path: str,
  69. model: torch.nn.Module,
  70. ignore_init_mismatch: bool,
  71. map_location: str = "cpu",
  72. oss_bucket=None,
  73. scope_map=None,
  74. excludes=None,
  75. ):
  76. """Load a model state and set it to the model.
  77. Args:
  78. init_param: <file_path>:<src_key>:<dst_key>:<exclude_Keys>
  79. Examples:
  80. """
  81. obj = model
  82. dst_state = obj.state_dict()
  83. print(f"ckpt: {path}")
  84. if oss_bucket is None:
  85. src_state = torch.load(path, map_location=map_location)
  86. else:
  87. buffer = BytesIO(oss_bucket.get_object(path).read())
  88. src_state = torch.load(buffer, map_location=map_location)
  89. if "state_dict" in src_state:
  90. src_state = src_state["state_dict"]
  91. for k in dst_state.keys():
  92. if not k.startswith("module.") and "module." + k in src_state.keys():
  93. k_ddp = "module." + k
  94. else:
  95. k_ddp = k
  96. if k_ddp in src_state:
  97. dst_state[k] = src_state[k_ddp]
  98. else:
  99. print(f"Miss key in ckpt: model: {k}, ckpt: {k_ddp}")
  100. flag = obj.load_state_dict(dst_state, strict=True)
  101. # print(flag)
  102. # def load_pretrained_model(
  103. # path: str,
  104. # model: torch.nn.Module,
  105. # ignore_init_mismatch: bool,
  106. # map_location: str = "cpu",
  107. # oss_bucket=None,
  108. # scope_map=None,
  109. # excludes=None,
  110. # ):
  111. # """Load a model state and set it to the model.
  112. #
  113. # Args:
  114. # init_param: <file_path>:<src_key>:<dst_key>:<exclude_Keys>
  115. #
  116. # Examples:
  117. #
  118. # """
  119. #
  120. # obj = model
  121. #
  122. # if oss_bucket is None:
  123. # src_state = torch.load(path, map_location=map_location)
  124. # else:
  125. # buffer = BytesIO(oss_bucket.get_object(path).read())
  126. # src_state = torch.load(buffer, map_location=map_location)
  127. # src_state = src_state["model"] if "model" in src_state else src_state
  128. #
  129. # if excludes is not None:
  130. # for e in excludes.split(","):
  131. # src_state = {k: v for k, v in src_state.items() if not k.startswith(e)}
  132. #
  133. # dst_state = obj.state_dict()
  134. # src_state = assigment_scope_map(dst_state, src_state, scope_map)
  135. #
  136. # if ignore_init_mismatch:
  137. # src_state = filter_state_dict(dst_state, src_state)
  138. #
  139. # logging.debug("Loaded src_state keys: {}".format(src_state.keys()))
  140. # logging.debug("Loaded dst_state keys: {}".format(dst_state.keys()))
  141. # dst_state.update(src_state)
  142. # obj.load_state_dict(dst_state, strict=True)