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 4.2 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 models"""
  16. import argparse
  17. import numpy as np
  18. import mindspore.common.dtype as mstype
  19. from mindspore import Tensor, context, load_checkpoint, export
  20. from src.finetune_eval_model import BertCLSModel, BertSquadModel, BertNERModel
  21. from src.finetune_eval_config import bert_net_cfg
  22. from src.bert_for_finetune import BertNER
  23. from src.utils import convert_labels_to_index
  24. parser = argparse.ArgumentParser(description="Bert export")
  25. parser.add_argument("--device_id", type=int, default=0, help="Device id")
  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=41, help="The number of class, default is 41.")
  30. parser.add_argument("--batch_size", type=int, default=16, help="batch size")
  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("--file_name", type=str, default="Bert", help="bert output air name.")
  34. parser.add_argument("--file_format", type=str, choices=["AIR", "ONNX", "MINDIR"], default="AIR", help="file format")
  35. parser.add_argument("--device_target", type=str, default="Ascend",
  36. choices=["Ascend", "GPU", "CPU"], help="device target (default: Ascend)")
  37. args = parser.parse_args()
  38. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  39. if args.device_target == "Ascend":
  40. context.set_context(device_id=args.device_id)
  41. label_list = []
  42. with open(args.label_file_path) as f:
  43. for label in f:
  44. label_list.append(label.strip())
  45. tag_to_index = convert_labels_to_index(label_list)
  46. if args.use_crf.lower() == "true":
  47. max_val = max(tag_to_index.values())
  48. tag_to_index["<START>"] = max_val + 1
  49. tag_to_index["<STOP>"] = max_val + 2
  50. number_labels = len(tag_to_index)
  51. else:
  52. number_labels = args.num_class
  53. if __name__ == "__main__":
  54. if args.downstream_task == "NER":
  55. if args.use_crf.lower() == "true":
  56. net = BertNER(bert_net_cfg, args.batch_size, False, num_labels=number_labels,
  57. use_crf=True, tag_to_index=tag_to_index)
  58. else:
  59. net = BertNERModel(bert_net_cfg, False, number_labels, use_crf=(args.use_crf.lower() == "true"))
  60. elif args.downstream_task == "CLS":
  61. net = BertCLSModel(bert_net_cfg, False, num_labels=number_labels)
  62. elif args.downstream_task == "SQUAD":
  63. net = BertSquadModel(bert_net_cfg, False)
  64. else:
  65. raise ValueError("unsupported downstream task")
  66. load_checkpoint(args.ckpt_file, net=net)
  67. net.set_train(False)
  68. input_ids = Tensor(np.zeros([args.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  69. input_mask = Tensor(np.zeros([args.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  70. token_type_id = Tensor(np.zeros([args.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  71. label_ids = Tensor(np.zeros([args.batch_size, bert_net_cfg.seq_length]), mstype.int32)
  72. if args.downstream_task == "NER" and args.use_crf.lower() == "true":
  73. input_data = [input_ids, input_mask, token_type_id, label_ids]
  74. else:
  75. input_data = [input_ids, input_mask, token_type_id]
  76. export(net, *input_data, file_name=args.file_name, file_format=args.file_format)