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.

export.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. """export checkpoint file into air models"""
  16. import argparse
  17. import numpy as np
  18. from mindspore import Tensor, context
  19. from mindspore.common import dtype as mstype
  20. from mindspore.train.serialization import export
  21. from src.utils import Dictionary
  22. from src.utils.load_weights import load_infer_weights
  23. from src.transformer.transformer_for_infer import TransformerInferModel
  24. from config import TransformerConfig
  25. parser = argparse.ArgumentParser(description="mass export")
  26. parser.add_argument("--device_id", type=int, default=0, help="Device id")
  27. parser.add_argument("--file_name", type=str, default="mass", help="output file name.")
  28. parser.add_argument("--file_format", type=str, choices=["AIR", "ONNX", "MINDIR"], default="AIR", help="file format")
  29. parser.add_argument("--device_target", type=str, default="Ascend",
  30. choices=["Ascend", "GPU", "CPU"], help="device target (default: Ascend)")
  31. parser.add_argument('--gigaword_infer_config', type=str, required=True, help='gigaword config file')
  32. parser.add_argument('--vocab_file', type=str, required=True, help='vocabulary file')
  33. args = parser.parse_args()
  34. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  35. if args.device_target == "Ascend":
  36. context.set_context(device_id=args.device_id)
  37. def get_config(config_file):
  38. tfm_config = TransformerConfig.from_json_file(config_file)
  39. tfm_config.compute_type = mstype.float16
  40. tfm_config.dtype = mstype.float32
  41. return tfm_config
  42. if __name__ == '__main__':
  43. vocab = Dictionary.load_from_persisted_dict(args.vocab_file)
  44. config = get_config(args.gigaword_infer_config)
  45. dec_len = config.max_decode_length
  46. tfm_model = TransformerInferModel(config=config, use_one_hot_embeddings=False)
  47. tfm_model.init_parameters_data()
  48. params = tfm_model.trainable_params()
  49. weights = load_infer_weights(config)
  50. for param in params:
  51. value = param.data
  52. name = param.name
  53. if name not in weights:
  54. raise ValueError(f'{name} is not found in weights.')
  55. with open('weight_after_deal.txt', 'a+') as f:
  56. weights_name = name
  57. f.write(weights_name + '\n')
  58. if isinstance(value, Tensor):
  59. if weights_name in weights:
  60. assert weights_name in weights
  61. param.set_data(Tensor(weights[weights_name], mstype.float32))
  62. else:
  63. raise ValueError(f'{weights_name} is not found in checkpoint')
  64. else:
  65. raise TypeError(f'Type of {weights_name} is not Tensor')
  66. print(' | Load weights successfully.')
  67. tfm_model.set_train(False)
  68. source_ids = Tensor(np.ones((1, config.seq_length)).astype(np.int32))
  69. source_mask = Tensor(np.ones((1, config.seq_length)).astype(np.int32))
  70. export(tfm_model, source_ids, source_mask, file_name=args.file_name, file_format=args.file_format)