Attention is all you need pytorchソースコード解析04-モデルのテストと翻訳を実現


今日は最後の節でAttention is all you need pytorchの実現に対する解析です.この節はとても簡単で、私は持っています.前回はここに接続しました:Attention is all you need pytorch実現ソースコード解析01-データ前処理、ワードテーブルの構築-https://blog.csdn.net/weixin_42744102/article/details/87006081
Attention is all you need pytorch実現ソースコード解析02-モデルのトレーニング(1)-モデルのトレーニングコード-https://blog.csdn.net/weixin_42744102/article/details/87076089
Attention is all you need pytorch実装ソースコード解析03-モデルの訓練(2)-transformerモデルのコード実装および構造-https://blog.csdn.net/weixin_42744102/article/details/87088748
githubソースを先に入力:https://github.com/Eathoublu/attention-is-all-you-need-pytorch
今日の説明はtranslateです.py





''' Translate input text with trained model. '''

import torch
import torch.utils.data
import argparse
from tqdm import tqdm

from dataset import collate_fn, TranslationDataset
from transformer.Translator import Translator
from preprocess import read_instances_from_file, convert_instance_to_idx_seq

# 1 - main , , ,-model -src -vocab , : ,data vocab( ) 。
def main():
    '''Main Function'''

    parser = argparse.ArgumentParser(description='translate.py')

    parser.add_argument('-model', required=True,
                        help='Path to model .pt file')
    parser.add_argument('-src', required=True,
                        help='Source sequence to decode (one line per sequence)')
    parser.add_argument('-vocab', required=True,
                        help='Source sequence to decode (one line per sequence)')
    parser.add_argument('-output', default='pred.txt',
                        help="""Path to output the predictions (each line will
                        be the decoded sequence""")
    parser.add_argument('-beam_size', type=int, default=5,
                        help='Beam size')
    parser.add_argument('-batch_size', type=int, default=30,
                        help='Batch size')
    parser.add_argument('-n_best', type=int, default=1,
                        help="""If verbose is set, will output the n_best
                        decoded sentences""")
    parser.add_argument('-no_cuda', action='store_true')

    opt = parser.parse_args()
    opt.cuda = not opt.no_cuda

    # Prepare DataLoader
    preprocess_data = torch.load(opt.vocab)
    preprocess_settings = preprocess_data['settings']
    test_src_word_insts = read_instances_from_file(
        opt.src,
        preprocess_settings.max_word_seq_len,
        preprocess_settings.keep_case)
    test_src_insts = convert_instance_to_idx_seq(
        test_src_word_insts, preprocess_data['dict']['src'])

    test_loader = torch.utils.data.DataLoader(
        TranslationDataset(
            src_word2idx=preprocess_data['dict']['src'],
            tgt_word2idx=preprocess_data['dict']['tgt'],
            src_insts=test_src_insts),
        num_workers=2,
        batch_size=opt.batch_size,
        collate_fn=collate_fn)

    # 2 -  , translator 

    translator = Translator(opt)

    # 3 -  , translate

    with open(opt.output, 'w') as f:
        for batch in tqdm(test_loader, mininterval=2, desc='  - (Test)', leave=False):

            # 4 -  data batch translate , , 。

            all_hyp, all_scores = translator.translate_batch(*batch)
            for idx_seqs in all_hyp:
                for idx_seq in idx_seqs:
                    pred_line = ' '.join([test_loader.dataset.tgt_idx2word[idx] for idx in idx_seq])
                    f.write(pred_line + '
'
) print('[Info] Finished.') if __name__ == "__main__": main()