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

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