predict_sighan.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  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. import argparse
  15. import sys
  16. from functools import partial
  17. import paddle
  18. from paddlenlp.data import Stack, Tuple, Pad, Vocab
  19. from paddlenlp.datasets import load_dataset
  20. from paddlenlp.transformers import ErnieModel, ErnieTokenizer
  21. from paddlenlp.utils.log import logger
  22. sys.path.append('../..')
  23. from pycorrector.ernie_csc.model import ErnieForCSC
  24. from pycorrector.ernie_csc.utils import read_test_ds, convert_example, create_dataloader, parse_decode
  25. # yapf: disable
  26. parser = argparse.ArgumentParser()
  27. parser.add_argument("--model_name_or_path", type=str, default="ernie-1.0", choices=["ernie-1.0"],
  28. help="Pretraining model name or path")
  29. parser.add_argument("--ckpt_path", default=None, type=str, help="The model checkpoint path.", )
  30. parser.add_argument("--max_seq_length", default=128, type=int,
  31. help="The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded.", )
  32. parser.add_argument("--batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.", )
  33. parser.add_argument("--device", default="gpu", type=str, choices=["cpu", "gpu"],
  34. help="The device to select to train the model, is must be cpu/gpu/xpu.")
  35. parser.add_argument("--pinyin_vocab_file_path", type=str, default="pinyin_vocab.txt", help="pinyin vocab file path")
  36. parser.add_argument("--test_file", type=str, default="test.txt", help="test set file")
  37. parser.add_argument("--predict_file", type=str, default="predict.txt", help="predict result file")
  38. # yapf: enable
  39. args = parser.parse_args()
  40. def write_sighan_result_to_file(args, corr_preds, det_preds, lengths,
  41. tokenizer):
  42. with open(args.test_file, 'r', encoding='utf-8') as fin:
  43. with open(args.predict_file, 'w', encoding='utf-8') as fout:
  44. for i, line in enumerate(fin.readlines()):
  45. ids, words = line.strip('\n').split('\t')[0:2]
  46. ids = ids.split('=')[1][:-1]
  47. pred_result = parse_decode(words, corr_preds[i], det_preds[i],
  48. lengths[i], tokenizer,
  49. args.max_seq_length)
  50. words = list(words)
  51. pred_result = list(pred_result)
  52. result = ids
  53. if pred_result == words:
  54. result += ', 0'
  55. else:
  56. assert len(pred_result) == len(
  57. words), "pred_result: {}, words: {}".format(pred_result,
  58. words)
  59. for i, word in enumerate(pred_result):
  60. if word != words[i]:
  61. result += ', {}, {}'.format(i + 1, word)
  62. fout.write("{}\n".format(result))
  63. @paddle.no_grad()
  64. def do_predict(args):
  65. paddle.set_device(args.device)
  66. pinyin_vocab = Vocab.load_vocabulary(
  67. args.pinyin_vocab_file_path, unk_token='[UNK]', pad_token='[PAD]')
  68. tokenizer = ErnieTokenizer.from_pretrained(args.model_name_or_path)
  69. ernie = ErnieModel.from_pretrained(args.model_name_or_path)
  70. model = ErnieForCSC(
  71. ernie,
  72. pinyin_vocab_size=len(pinyin_vocab),
  73. pad_pinyin_id=pinyin_vocab[pinyin_vocab.pad_token])
  74. eval_ds = load_dataset(read_test_ds, data_path=args.test_file, lazy=False)
  75. trans_func = partial(
  76. convert_example,
  77. tokenizer=tokenizer,
  78. pinyin_vocab=pinyin_vocab,
  79. max_seq_length=args.max_seq_length,
  80. is_test=True)
  81. batchify_fn = lambda samples, fn=Tuple(
  82. Pad(axis=0, pad_val=tokenizer.pad_token_id, dtype='int64'), # input
  83. Pad(axis=0, pad_val=tokenizer.pad_token_type_id, dtype='int64'), # segment
  84. Pad(axis=0, pad_val=pinyin_vocab.token_to_idx[pinyin_vocab.pad_token], dtype='int64'), # pinyin
  85. Stack(axis=0, dtype='int64'), # length
  86. ): [data for data in fn(samples)]
  87. test_data_loader = create_dataloader(
  88. eval_ds,
  89. mode='test',
  90. batch_size=args.batch_size,
  91. batchify_fn=batchify_fn,
  92. trans_fn=trans_func)
  93. if args.ckpt_path:
  94. model_dict = paddle.load(args.ckpt_path)
  95. model.set_dict(model_dict)
  96. logger.info("Load model from checkpoints: {}".format(args.ckpt_path))
  97. model.eval()
  98. corr_preds = []
  99. det_preds = []
  100. lengths = []
  101. for step, batch in enumerate(test_data_loader):
  102. input_ids, token_type_ids, pinyin_ids, length = batch
  103. det_error_probs, corr_logits = model(input_ids, pinyin_ids,
  104. token_type_ids)
  105. # corr_logits shape: [B, T, V]
  106. det_pred = det_error_probs.argmax(axis=-1)
  107. det_pred = det_pred.numpy()
  108. char_preds = corr_logits.argmax(axis=-1)
  109. char_preds = char_preds.numpy()
  110. length = length.numpy()
  111. corr_preds += [pred for pred in char_preds]
  112. det_preds += [prob for prob in det_pred]
  113. lengths += [l for l in length]
  114. write_sighan_result_to_file(args, corr_preds, det_preds, lengths, tokenizer)
  115. if __name__ == "__main__":
  116. do_predict(args)