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

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