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

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