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

5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 models"""
  16. import argparse
  17. import numpy as np
  18. import mindspore.nn as nn
  19. from mindspore.common.tensor import Tensor
  20. import mindspore.ops.operations as P
  21. from mindspore import context
  22. from mindspore.train.serialization import load_checkpoint, export, load_param_into_net
  23. from src.fasttext_model import FastText
  24. parser = argparse.ArgumentParser(description='fasttexts')
  25. parser.add_argument('--device_target', type=str, choices=["Ascend", "GPU", "CPU"],
  26. default='Ascend', help='Device target')
  27. parser.add_argument('--device_id', type=int, default=0, help='Device id')
  28. parser.add_argument('--ckpt_file', type=str, required=True, help='Checkpoint file path')
  29. parser.add_argument('--file_name', type=str, default='fasttexts', help='Output file name')
  30. parser.add_argument('--file_format', type=str, choices=["AIR", "ONNX", "MINDIR"], default='AIR',
  31. help='Output file format')
  32. parser.add_argument('--data_name', type=str, required=True, default='ag',
  33. help='Dataset name. eg. ag, dbpedia, yelp_p')
  34. args = parser.parse_args()
  35. if args.data_name == "ag":
  36. from src.config import config_ag as config
  37. from src.config import config_ag_gpu as config_gpu
  38. target_label1 = ['0', '1', '2', '3']
  39. elif args.data_name == 'dbpedia':
  40. from src.config import config_db as config
  41. from src.config import config_db_gpu as config_gpu
  42. target_label1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
  43. elif args.data_name == 'yelp_p':
  44. from src.config import config_yelpp as config
  45. from src.config import config_yelpp_gpu as config_gpu
  46. target_label1 = ['0', '1']
  47. context.set_context(
  48. mode=context.GRAPH_MODE,
  49. save_graphs=False,
  50. device_target=args.device_target)
  51. config = config_ascend if args.device_target == 'Ascend' else config_gpu
  52. class FastTextInferExportCell(nn.Cell):
  53. """
  54. Encapsulation class of FastText network infer.
  55. Args:
  56. network (nn.Cell): FastText model.
  57. Returns:
  58. Tuple[Tensor, Tensor], predicted_ids
  59. """
  60. def __init__(self, network):
  61. super(FastTextInferExportCell, self).__init__(auto_prefix=False)
  62. self.network = network
  63. self.argmax = P.ArgMaxWithValue(axis=1, keep_dims=True)
  64. self.log_softmax = nn.LogSoftmax(axis=1)
  65. def construct(self, src_tokens, src_tokens_lengths):
  66. """construct fasttext infer cell"""
  67. prediction = self.network(src_tokens, src_tokens_lengths)
  68. predicted_idx = self.log_softmax(prediction)
  69. predicted_idx, _ = self.argmax(predicted_idx)
  70. return predicted_idx
  71. def run_fasttext_export():
  72. """export function"""
  73. fasttext_model = FastText(config.vocab_size, config.embedding_dims, config.num_class)
  74. parameter_dict = load_checkpoint(args.ckpt_file)
  75. load_param_into_net(fasttext_model, parameter_dict)
  76. ft_infer = FastTextInferExportCell(fasttext_model)
  77. batch_size = config.batch_size
  78. if args.device_target == 'GPU':
  79. batch_size = config.distribute_batch_size
  80. if args.data_name == "ag":
  81. src_tokens_shape = [batch_size, 467]
  82. src_tokens_length_shape = [batch_size, 1]
  83. elif args.data_name == 'dbpedia':
  84. src_tokens_shape = [batch_size, 1120]
  85. src_tokens_length_shape = [batch_size, 1]
  86. elif args.data_name == 'yelp_p':
  87. src_tokens_shape = [batch_size, 2955]
  88. src_tokens_length_shape = [batch_size, 1]
  89. file_name = args.file_name + '_' + args.data_name
  90. src_tokens = Tensor(np.ones((src_tokens_shape)).astype(np.int32))
  91. src_tokens_length = Tensor(np.ones((src_tokens_length_shape)).astype(np.int32))
  92. export(ft_infer, src_tokens, src_tokens_length, file_name=file_name, file_format=args.file_format)
  93. if __name__ == '__main__':
  94. run_fasttext_export()