load_pretrained_model.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. def filter_state_dict(
  10. dst_state: Dict[str, Union[float, torch.Tensor]],
  11. src_state: Dict[str, Union[float, torch.Tensor]],
  12. ):
  13. """Filter name, size mismatch instances between dicts.
  14. Args:
  15. dst_state: reference state dict for filtering
  16. src_state: target state dict for filtering
  17. """
  18. match_state = {}
  19. for key, value in src_state.items():
  20. if key in dst_state and (dst_state[key].size() == src_state[key].size()):
  21. match_state[key] = value
  22. else:
  23. if key not in dst_state:
  24. logging.warning(
  25. f"Filter out {key} from pretrained dict"
  26. + " because of name not found in target dict"
  27. )
  28. else:
  29. logging.warning(
  30. f"Filter out {key} from pretrained dict"
  31. + " because of size mismatch"
  32. + f"({dst_state[key].size()}-{src_state[key].size()})"
  33. )
  34. return match_state
  35. def load_pretrained_model(
  36. path: str,
  37. model: torch.nn.Module,
  38. ignore_init_mismatch: bool=True,
  39. map_location: str = "cpu",
  40. oss_bucket=None,
  41. scope_map=[],
  42. excludes=None,
  43. ignore_mismatch=False,
  44. **kwargs,
  45. ):
  46. """Load a model state and set it to the model.
  47. Args:
  48. init_param: <file_path>:<src_key>:<dst_key>:<exclude_Keys>
  49. Examples:
  50. """
  51. obj = model
  52. dst_state = obj.state_dict()
  53. print(f"ckpt: {path}")
  54. if oss_bucket is None:
  55. src_state = torch.load(path, map_location=map_location)
  56. else:
  57. buffer = BytesIO(oss_bucket.get_object(path).read())
  58. src_state = torch.load(buffer, map_location=map_location)
  59. if "state_dict" in src_state:
  60. src_state = src_state["state_dict"]
  61. src_state = src_state["model"] if "model" in src_state else src_state
  62. if isinstance(scope_map, str):
  63. scope_map = scope_map.split(",")
  64. scope_map += ["module.", "None"]
  65. for k in dst_state.keys():
  66. k_src = k
  67. if scope_map is not None:
  68. src_prefix = ""
  69. dst_prefix = ""
  70. for i in range(0, len(scope_map), 2):
  71. src_prefix = scope_map[i] if scope_map[i].lower() != "none" else ""
  72. dst_prefix = scope_map[i+1] if scope_map[i+1].lower() != "none" else ""
  73. if dst_prefix == "" and (src_prefix + k) in src_state.keys():
  74. k_src = src_prefix + k
  75. print(f"init param, map: {k} from {k_src} in ckpt")
  76. elif k.startswith(dst_prefix) and k.replace(dst_prefix, src_prefix, 1) in src_state.keys():
  77. k_src = k.replace(dst_prefix, src_prefix, 1)
  78. print(f"init param, map: {k} from {k_src} in ckpt")
  79. if k_src in src_state.keys():
  80. if ignore_init_mismatch and dst_state[k].shape != src_state[k_src].shape:
  81. print(f"ignore_mismatch:{ignore_mismatch}, dst: {k, dst_state[k].shape}, src: {k_src, src_state[k_src].shape}")
  82. else:
  83. dst_state[k] = src_state[k_src]
  84. else:
  85. print(f"Warning, miss key in ckpt: {k}, mapped: {k_src}")
  86. flag = obj.load_state_dict(dst_state, strict=True)
  87. # print(flag)