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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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
  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_name', type=str, default='SST-2', choices=['SST-2', 'QNLI', 'MNLI'], help='task name')
  31. args = parser.parse_args()
  32. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  33. if args.device_target == "Ascend":
  34. context.set_context(device_id=args.device_id)
  35. DEFAULT_NUM_LABELS = 2
  36. DEFAULT_SEQ_LENGTH = 128
  37. DEFAULT_BS = 32
  38. task_params = {"SST-2": {"num_labels": 2, "seq_length": 64},
  39. "QNLI": {"num_labels": 2, "seq_length": 128},
  40. "MNLI": {"num_labels": 3, "seq_length": 128}}
  41. class Task:
  42. """
  43. Encapsulation class of get the task parameter.
  44. """
  45. def __init__(self, task_name):
  46. self.task_name = task_name
  47. @property
  48. def num_labels(self):
  49. if self.task_name in task_params and "num_labels" in task_params[self.task_name]:
  50. return task_params[self.task_name]["num_labels"]
  51. return DEFAULT_NUM_LABELS
  52. @property
  53. def seq_length(self):
  54. if self.task_name in task_params and "seq_length" in task_params[self.task_name]:
  55. return task_params[self.task_name]["seq_length"]
  56. return DEFAULT_SEQ_LENGTH
  57. if __name__ == '__main__':
  58. task = Task(args.task_name)
  59. td_student_net_cfg.seq_length = task.seq_length
  60. td_student_net_cfg.batch_size = DEFAULT_BS
  61. eval_model = BertModelCLS(td_student_net_cfg, False, task.num_labels, 0.0, phase_type="student")
  62. param_dict = load_checkpoint(args.ckpt_file)
  63. new_param_dict = {}
  64. for key, value in param_dict.items():
  65. new_key = re.sub('tinybert_', 'bert_', key)
  66. new_key = re.sub('^bert.', '', new_key)
  67. new_param_dict[new_key] = value
  68. load_param_into_net(eval_model, new_param_dict)
  69. eval_model.set_train(False)
  70. input_ids = Tensor(np.zeros((td_student_net_cfg.batch_size, task.seq_length), np.int32))
  71. token_type_id = Tensor(np.zeros((td_student_net_cfg.batch_size, task.seq_length), np.int32))
  72. input_mask = Tensor(np.zeros((td_student_net_cfg.batch_size, task.seq_length), np.int32))
  73. input_data = [input_ids, token_type_id, input_mask]
  74. export(eval_model, *input_data, file_name=args.file_name, file_format=args.file_format)