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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 re
  17. import argparse
  18. import numpy as np
  19. from mindspore import Tensor, context
  20. from mindspore.train.serialization import load_checkpoint, load_param_into_net, export
  21. from src.td_config import td_student_net_cfg
  22. from src.tinybert_model import BertModelCLS, BertModelNER
  23. parser = argparse.ArgumentParser(description='tinybert task distill')
  24. parser.add_argument("--device_id", type=int, default=0, help="Device id")
  25. parser.add_argument("--ckpt_file", type=str, required=True, help="tinybert ckpt file.")
  26. parser.add_argument("--file_name", type=str, default="tinybert", help="output file name.")
  27. parser.add_argument("--file_format", type=str, choices=["AIR", "ONNX", "MINDIR"], default="AIR", help="file format")
  28. parser.add_argument("--device_target", type=str, default="Ascend",
  29. choices=["Ascend", "GPU", "CPU"], help="device target (default: Ascend)")
  30. parser.add_argument("--task_type", type=str, default="classification", choices=["classification", "ner"],
  31. help="The type of the task to train.")
  32. parser.add_argument("--task_name", type=str, default="", choices=["SST-2", "QNLI", "MNLI", "TNEWS", "CLUENER"],
  33. help="The name of the task to train.")
  34. args = parser.parse_args()
  35. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  36. if args.device_target == "Ascend":
  37. context.set_context(device_id=args.device_id)
  38. DEFAULT_NUM_LABELS = 2
  39. DEFAULT_SEQ_LENGTH = 128
  40. DEFAULT_BS = 32
  41. task_params = {"SST-2": {"num_labels": 2, "seq_length": 64},
  42. "QNLI": {"num_labels": 2, "seq_length": 128},
  43. "MNLI": {"num_labels": 3, "seq_length": 128},
  44. "TNEWS": {"num_labels": 15, "seq_length": 128},
  45. "CLUENER": {"num_labels": 43, "seq_length": 128}}
  46. class Task:
  47. """
  48. Encapsulation class of get the task parameter.
  49. """
  50. def __init__(self, task_name):
  51. self.task_name = task_name
  52. @property
  53. def num_labels(self):
  54. if self.task_name in task_params and "num_labels" in task_params[self.task_name]:
  55. return task_params[self.task_name]["num_labels"]
  56. return DEFAULT_NUM_LABELS
  57. @property
  58. def seq_length(self):
  59. if self.task_name in task_params and "seq_length" in task_params[self.task_name]:
  60. return task_params[self.task_name]["seq_length"]
  61. return DEFAULT_SEQ_LENGTH
  62. if __name__ == '__main__':
  63. task = Task(args.task_name)
  64. td_student_net_cfg.seq_length = task.seq_length
  65. td_student_net_cfg.batch_size = DEFAULT_BS
  66. if args.task_type == "classification":
  67. eval_model = BertModelCLS(td_student_net_cfg, False, task.num_labels, 0.0, phase_type="student")
  68. elif args.task_type == "ner":
  69. eval_model = BertModelNER(td_student_net_cfg, False, task.num_labels, 0.0, phase_type="student")
  70. else:
  71. raise ValueError(f"Not support task type: {args.task_type}")
  72. param_dict = load_checkpoint(args.ckpt_file)
  73. new_param_dict = {}
  74. for key, value in param_dict.items():
  75. new_key = re.sub('tinybert_', 'bert_', key)
  76. new_key = re.sub('^bert.', '', new_key)
  77. new_param_dict[new_key] = value
  78. load_param_into_net(eval_model, new_param_dict)
  79. eval_model.set_train(False)
  80. input_ids = Tensor(np.zeros((td_student_net_cfg.batch_size, task.seq_length), np.int32))
  81. token_type_id = Tensor(np.zeros((td_student_net_cfg.batch_size, task.seq_length), np.int32))
  82. input_mask = Tensor(np.zeros((td_student_net_cfg.batch_size, task.seq_length), np.int32))
  83. input_data = [input_ids, token_type_id, input_mask]
  84. export(eval_model, *input_data, file_name=args.file_name, file_format=args.file_format)