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