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.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 models"""
  16. import argparse
  17. import numpy as np
  18. from mindspore import Tensor, context
  19. import mindspore.common.dtype as mstype
  20. from mindspore.train.serialization import load_checkpoint, export
  21. from src.finetune_eval_model import BertCLSModel, BertSquadModel, BertNERModel
  22. from src.finetune_eval_config import optimizer_cfg, bert_net_cfg
  23. from src.utils import convert_labels_to_index
  24. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  25. parser = argparse.ArgumentParser(description='Bert export')
  26. parser.add_argument('--use_crf', type=str, default="false", help='Use cfg, default is false.')
  27. parser.add_argument('--downstream_task', type=str, choices=["NER", "CLS", "SQUAD"], default="NER",
  28. help='at present,support NER only')
  29. parser.add_argument('--num_class', type=int, default=2, help='The number of class, default is 2.')
  30. parser.add_argument('--label_file_path', type=str, default="", help='label file path, used in clue benchmark.')
  31. parser.add_argument('--ckpt_file', type=str, required=True, help='Bert ckpt file.')
  32. parser.add_argument('--output_file', type=str, default='Bert.air', help='bert output air name.')
  33. parser.add_argument('--file_format', type=str, choices=["AIR", "ONNX", "MINDIR"], default='AIR', help='file format')
  34. args = parser.parse_args()
  35. label_list = []
  36. with open(args.label_file_path) as f:
  37. for label in f:
  38. label_list.append(label.strip())
  39. tag_to_index = convert_labels_to_index(label_list)
  40. if args.use_crf.lower() == "true":
  41. max_val = max(tag_to_index.values())
  42. tag_to_index["<START>"] = max_val + 1
  43. tag_to_index["<STOP>"] = max_val + 2
  44. number_labels = len(tag_to_index)
  45. else:
  46. number_labels = args.num_class
  47. if __name__ == '__main__':
  48. if args.downstream_task == "NER":
  49. net = BertNERModel(bert_net_cfg, False, number_labels, use_crf=(args.use_crf.lower() == "true"))
  50. elif args.downstream_task == "CLS":
  51. net = BertCLSModel(bert_net_cfg, False, num_labels=number_labels)
  52. elif args.downstream_task == "SQUAD":
  53. net = BertSquadModel(bert_net_cfg, False)
  54. else:
  55. raise ValueError("unsupported downstream task")
  56. load_checkpoint(args.ckpt_file, net=net)
  57. net.set_train(False)
  58. input_ids = Tensor(np.zeros([optimizer_cfg.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  59. input_mask = Tensor(np.zeros([optimizer_cfg.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  60. token_type_id = Tensor(np.zeros([optimizer_cfg.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  61. input_data = [input_ids, input_mask, token_type_id]
  62. export(net, *input_data, file_name=args.output_file, file_format=args.file_format)