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

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. target_label1 = ['0', '1', '2', '3']
  38. elif args.data_name == 'dbpedia':
  39. from src.config import config_db as config
  40. target_label1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
  41. elif args.data_name == 'yelp_p':
  42. from src.config import config_yelpp as config
  43. target_label1 = ['0', '1']
  44. context.set_context(
  45. mode=context.GRAPH_MODE,
  46. save_graphs=False,
  47. device_target="Ascend")
  48. class FastTextInferExportCell(nn.Cell):
  49. """
  50. Encapsulation class of FastText network infer.
  51. Args:
  52. network (nn.Cell): FastText model.
  53. Returns:
  54. Tuple[Tensor, Tensor], predicted_ids
  55. """
  56. def __init__(self, network):
  57. super(FastTextInferExportCell, self).__init__(auto_prefix=False)
  58. self.network = network
  59. self.argmax = P.ArgMaxWithValue(axis=1, keep_dims=True)
  60. self.log_softmax = nn.LogSoftmax(axis=1)
  61. def construct(self, src_tokens, src_tokens_lengths):
  62. """construct fasttext infer cell"""
  63. prediction = self.network(src_tokens, src_tokens_lengths)
  64. predicted_idx = self.log_softmax(prediction)
  65. predicted_idx, _ = self.argmax(predicted_idx)
  66. return predicted_idx
  67. def run_fasttext_export():
  68. """export function"""
  69. fasttext_model = FastText(config.vocab_size, config.embedding_dims, config.num_class)
  70. parameter_dict = load_checkpoint(args.ckpt_file)
  71. load_param_into_net(fasttext_model, parameter_dict)
  72. ft_infer = FastTextInferExportCell(fasttext_model)
  73. if args.data_name == "ag":
  74. src_tokens_shape = [config.batch_size, 467]
  75. src_tokens_length_shape = [config.batch_size, 1]
  76. elif args.data_name == 'dbpedia':
  77. src_tokens_shape = [config.batch_size, 1120]
  78. src_tokens_length_shape = [config.batch_size, 1]
  79. elif args.data_name == 'yelp_p':
  80. src_tokens_shape = [config.batch_size, 2955]
  81. src_tokens_length_shape = [config.batch_size, 1]
  82. file_name = args.file_name + '_' + args.data_name
  83. src_tokens = Tensor(np.ones((src_tokens_shape)).astype(np.int32))
  84. src_tokens_length = Tensor(np.ones((src_tokens_length_shape)).astype(np.int32))
  85. export(ft_infer, src_tokens, src_tokens_length, file_name=file_name, file_format=args.file_format)
  86. if __name__ == '__main__':
  87. run_fasttext_export()