또르르's 개발 Story

[18-3] fairseq 사용하기 본문

부스트캠프 AI 테크 U stage/실습

[18-3] fairseq 사용하기

또르르21 2021. 2. 18. 03:00

대표적인 pytorch library 중 하나인 fairseq는 번역 모델을 편리하게 학습이 가능합니다.

자연어 처리 관련 여러 라이브러리가 있지만 번역 task에서 가장 자주 활용되고 있는 fairseq는 pytorch를 개발하고 있는 facebook에서 작업 중인 오픈소스 프로젝트입니다. library의 이름처럼 sequence를 다루는 데에 필요한 여러 모델과 전처리, 평가 관련 코드를 포함해 인기가 많은 library 중 하나입니다.

 

1️⃣ 설정

 

필요한 fairseq 패키지를 설치합니다.

!pip install fastBPE sacremoses subword_nmt hydra-core omegaconf fairseq

git을 clone하고 iwsit14 데이터를 준비합니다.

# clone fairseq git

!git clone https://github.com/pytorch/fairseq.git

# iwslt14 데이터 준비 (https://github.com/pytorch/fairseq/blob/master/examples/translation/prepare-iwslt14.sh)

!bash fairseq/examples/translation/prepare-iwslt14.sh

 

2️⃣ Library reference

 

1. [tasks](https://fairseq.readthedocs.io/en/latest/tasks.html)

 

translation task와 language modeling task가 있고 나머지 sequence를 다루는 task는 register_task() function decorator를 이용해 등록할 수 있습니다.

 

2. [models](https://fairseq.readthedocs.io/en/latest/models.html)

 

- 모델은 CNN, LSTM, Transformer 기반 모델들이 분류가 되어 있습니다. 새로운 모델을 등록하기 위해서는 register_model() function decorator를 이용할 수 있습니다.

 

3. [criterions](https://fairseq.readthedocs.io/en/latest/criterions.html)

 

- 모델 학습을 위한 다양한 loss들이 구현되어 있습니다.

 

4. [optimizers](https://fairseq.readthedocs.io/en/latest/optim.html)

 

- 모델 학습을 위한 다양한 optimizer들이 구현되어 있습니다.

 

5. [learning rate schedulers](https://fairseq.readthedocs.io/en/latest/lr_scheduler.html)

 

- 모델의 더 나은 학습을 위한 다양한 learning rate scheduler들이 구현되어 있습니다.

 

6. [data loading and utilities](https://fairseq.readthedocs.io/en/latest/data.html)

 

- 전처리 및 데이터 관련 다양한 class들이 구현되어 있습니다.

 

7. [modules](https://fairseq.readthedocs.io/en/latest/modules.html)

 

- 앞의 6군데 외 다양한 모듈들이 구현되어 있습니다.

 

3️⃣ Command-line Tools

 

fairseq은 학습과 평가를 쉽게 할 수 있는 command-line tool을 제공하고 있습니다.

 

  1. fairseq-preprocess
    • 데이터 학습을 위한 vocab을 만들고 data를 구성합니다.
  2. fairseq-train
    • 여러 gpu 또는 단일 gpu에서 모델을 학습시킵니다.
  3. fairseq-generate
    • 학습된 모델을 이용해 전처리된 데이터를 번역합니다.
  4. fairseq-interactive
    • 학습된 모델을 이용해 raw 데이터를 번역합니다.
  5. fairseq-score
    • 학습된 모델이 생성한 문장과 정답 문장을 비교해 bleu score를 산출합니다.
  6. fairseq-eval-lm
    • language model을 평가할 수 있는 command입니다.

 

4️⃣ Command-line Tools을 사용한 BELU 구하기

 

1) Preprocess

  • --source-lang: source language
  • --target-lang: target language
  • --trainpref: train file prefix
  • --validpref: valid file prefix
  • --testpref: test file prefix
  • --destdir: destination dir
!fairseq-preprocess --source-lang de --target-lang en --trainpref ./iwslt14.tokenized.de-en/train --validpref ./iwslt14.tokenized.de-en/valid --testpref ./iwslt14.tokenized.de-en/test --destdir ./iwslt14.tokenized.de-en/

 

2) Train

  • --arch: architecture
  • --optimizer: optimizer {adadelta, adam, adafactor, adagrad, lamb, composite, nag, adamax, sgd}
  • --clip-norm: clip threshold of gradients
  • --lr: learning rate
  • --lr-scheduler: learning rate scheduler {pass_through, cosine, reduce_lr_on_plateau, fixed, triangular, polynomial_decay, tri_stage, manual, inverse_sqrt}
  • --criterion loss function {sentence_prediction, ctc, adaptive_loss, label_smoothed_cross_entropy, composite_loss, nat_loss, masked_lm, sentence_ranking, legacy_masked_lm_loss, cross_entropy, model, wav2vec, label_smoothed_cross_entropy_with_alignment, vocab_parallel_cross_entropy}
  • --max-tokens: maximum number of tokens in a batch
  • --max-epoch: maximum number of training epoch
!fairseq-train ./iwslt14.tokenized.de-en/ --arch transformer_iwslt_de_en --optimizer adam --clip-norm 0.0 --lr 5e-4 --lr-scheduler inverse_sqrt --criterion label_smoothed_cross_entropy --max-tokens 4096 --max-epoch 3

 

3) 예측 문장 생성 및 평가

 

checkpoints 폴더에 epoch마다 모델이 저장되고 best checkpoint는 checkpoint_best.pt라는 이름으로 저장됩니다

!fairseq-generate ./iwslt14.tokenized.de-en --path ./checkpoints/checkpoint_best.pt --beam 5 --remove-bpe
# Generate test with beam=5: BLEU4 = 20.03, 59.6/30.3/16.9/9.6 (BP=0.861, ratio=0.870, syslen=114104, reflen=131161)

 

5️⃣ fairseq-score 사용

fairseq-score은 학습된 모델이 생성한 문장과 정답 문장을 비교해 BELU score를 산출합니다.

Reference file과 System file의 BELU를 쉽게 비교할 수 있습니다.

# Reference.txt

# hello Sam ! my name is John.
# System.txt

# hello John ! my name is Sam.
# s : system file, -r : reference file, -o : order (default:4)

!fairseq-score -s "System.txt" -r "Reference.txt" -o 4
# Namespace(ignore_case=False, order=4, ref='Reference.txt', sacrebleu=False, sentence_bleu=False, sys='System.txt')
# BLEU4 = 43.47, 71.4/50.0/40.0/25.0 (BP=1.000, ratio=1.000, syslen=7, reflen=7)

이번에는 다른 문구입니다.

# Reference.txt

# William Shakespeare's name is synonymous with many of the famous lines he wrote in his plays and prose. 
# Yet his poems are not nearly as recognizable to many as the characters and famous monologues from his many plays.
# System.txt

# William Shakespeare's name synonymous with is many of the famous lines he in his plays and prose. 
# Yet as recognizable his poems are not nearly his to many as the wrote characters and famous monologues from many plays.
!fairseq-score -s "System.txt" -r "Reference.txt" -o 4
# Namespace(ignore_case=False, order=4, ref='Reference.txt', sacrebleu=False, sentence_bleu=False, sys='System.txt')
# BLEU4 = 56.15, 97.4/69.4/47.1/31.2 (BP=1.000, ratio=1.000, syslen=38, reflen=38)
Comments