You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

weights_average.py 2.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """Weight average."""
  16. import os
  17. import argparse
  18. import numpy as np
  19. from mindspore.train.serialization import load_checkpoint
  20. parser = argparse.ArgumentParser(description='transformer')
  21. parser.add_argument("--input_files", type=str, default=None, required=False,
  22. help="Multi ckpt files path.")
  23. parser.add_argument("--input_folder", type=str, default=None, required=False,
  24. help="Ckpt files folder.")
  25. parser.add_argument("--output_file", type=str, default=None, required=True,
  26. help="Output model file path.")
  27. def average_me_models(ckpt_list):
  28. """
  29. Average multi ckpt params.
  30. Args:
  31. ckpt_list (list): Ckpt paths.
  32. Returns:
  33. dict, params dict.
  34. """
  35. avg_model = {}
  36. # load all checkpoint
  37. for ckpt in ckpt_list:
  38. if not ckpt.endswith(".ckpt"):
  39. continue
  40. if not os.path.exists(ckpt):
  41. raise FileNotFoundError(f"Checkpoint file is not existed.")
  42. print(f" | Loading ckpt from {ckpt}.")
  43. ms_ckpt = load_checkpoint(ckpt)
  44. for param_name in ms_ckpt:
  45. if param_name not in avg_model:
  46. avg_model[param_name] = []
  47. avg_model[param_name].append(ms_ckpt[param_name].data.asnumpy())
  48. for name in avg_model:
  49. avg_model[name] = sum(avg_model[name]) / float(len(ckpt_list))
  50. return avg_model
  51. def main():
  52. """Entry point."""
  53. args, _ = parser.parse_known_args()
  54. if not args.input_files and not args.input_folder:
  55. raise ValueError("`--input_files` or `--input_folder` must be provided one as least.")
  56. ckpt_list = []
  57. if args.input_files:
  58. ckpt_list.extend(args.input_files.split(","))
  59. if args.input_folder and os.path.exists(args.input_folder) and os.path.isdir(args.input_folder):
  60. for file in os.listdir(args.input_folder):
  61. ckpt_list.append(os.path.join(args.input_folder, file))
  62. avg_weights = average_me_models(ckpt_list)
  63. np.savez(args.output_file, **avg_weights)
  64. if __name__ == '__main__':
  65. main()