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

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