Ch2. Using Transformers

1. Introduction

  • How to use tokenizers and models to replicate the pipeline API's behavior

  • How to load and save models and tokenizers

  • Different tokenization approaches, such as word-based, character-based, and subword-based

  • How to handle multiple sentences of varying lengths

Transformer library를 통해 쉽고, 유동적인 사용을 할 수 있도록 하고자 하였다.

이번 챕터를 통해 model과 tokenizer의 사용에 대해 시작부터 끝까지 배워보는 시간을 가진다.

2. Behind the pipeline

  • 학습과정은 위와 같이 주어진 Raw Text를 Tokenizer로 가공하고 Model 학습을 진행하고 예측결과를 출력하는 단계로 이루어져 있다. 이 과정에 대해 살펴보도록 하자.

2.1. Preprocessing with a Tokenizer

학습 모델은 주어진 문장을 가지고 바로 학습을 진행할 수 있다. 그렇기에 우선 raw text를 token화 하는 작업을 진행하게 되는데 이를 Tokenization 이라고 한다.

  • Splitting the input into words, subwords, or symbols (like punctuation) that are called tokens

  • Mapping each token to an integer

  • Adding additional inputs that may be useful to the model

Pre-Trained Model과 동일한 Preprocessing 과정을 거쳐야하므로 Model Hub에서 해당 정보를 다운로드 받아야한다. 아래 예시 코드를 참고하자.

  • AutoTokenizer 클래스의 from_pretrained 함수를 사용하여 해당 pipeline의 토큰화 방법을 가져온다.

  • 만들어진 tokenizer를 통해 raw text를 손쉽게 토큰화 할 수 있다.

2.2. Going through the model

Tokenizer와 마찬가지로 pre-trained model을 가져올 수 있다.

2.3. A high-dimensional vector?

  • Batch Size the number of sequence processed at a time

  • Sequence length The length of the numerical representation of the sequence

  • Hidden size The Vector dimension of each model input

  • 보통 마지막 hidden size 값으로 인해 매우 큰 차원의 값이 생성된다.

2.4. Model heads: Masking sense out of numbers

[잘 이해 하지 못함]

2.5. Postprocessing the output

output data에 softmax를 취해 각 토큰의 확률값을 구하게 된다.

즉, 첫문장의 'NEGATIVE': 0.041, 'POSITIVE': 0.9598 의 확률로 labels의 값을 나타내게 됨을 확인할 수 있다.

3. Models

모델의 생성과 사용법에 대해 좀 더 자세히 알아보자. AutoModel 클래스를 사용하여

3.1. Creating a Transformer

  • Configuration 객체를 호출하여 BERT 모델을 초기화한다.

  • config에는 위와 같이 parameter에 대한 정보가 담겨져 있다.

3.2. Different loading methods

3.1. 과 같이 모델을 호출하게되면 임의로 초기화 된 모델이 생성이 된다. 하지만 우리는 Pre-Trained Model을 사용하여 학습 성능향상과 시간 단축을 할 수 있다.

  • "bert-base-cased"의 weights로 초기화 된다.

3.3. Saving methods

  • config.json attributes necessary to build the model architecture contains metadata such as where the checkpoint originated

  • pytorch_model.bin state dictionary cotains all your model's weights

3.4. Using a Transformer model for inference

  1. Tokenizer Encoding

  2. Make it to Tensor

  3. Get output by call the model with the inputs

4. Tokenizers

토큰화하는 방식도 Boostcamp를 통해 배운 바 있다. 간략하게 사용법에 대해 익히도록 한다.

  • Word-based

    • 각 단어별로 나누는 방식

    • "Jim Henson was a puppeteer" => [Jim, Henson, was, a, puppeteer]

    • Unknown Token([UNK])이 많아지게 된다.

  • Charater-based

    • 알바벳 단위로 나누는 방식

    • Jim Henson was a puppeteer => [J, i, m, ..., t, e, e, r]

    • 단어로서의 의미가 사라지게 되는 문제가 있다. (중국어는 한 자마다 의미가 있어 좋은 성능을 낼 수 있다.)

  • Subword-Tokenization

    • 단어를 의미단위로 나누는 방식

    • Let's do tokenization! => [Let's, do, token, ization, !]

    • 이 방법으로 [UNK]를 줄일 수도 있고, 단어로써의 의미도 보존할 수 있다.

그 외에도 Byte-level BPE(GPT-2), WordPiece(BERT), SentencePiece or Unigram 등 기법이 존재한다.

4.1. Loading and Saving

4.2. Encoding

  • STEP1) split the text into tokens

  • STEP2) adds special tokens the model expects

4.3. Tokenization

4.4. From tokens to input IDs

Convert tokens to integer

4.5. Decoding

5. Handling multiple sequences

5.1. Models expect a batch of inputs

앞서배운 내용으로 코드를 작성하고 실행하게 되면 오류가 발생한다.

그 이유는 model의 parameter로 input_ids 즉 list가 들어와야 하기 때문이다.

위에서는 입력문장이 1개여서 변환이 필요했지만, 여러 문장을 가지고 생각하면 더 간단하게 느껴질 수 있다. 모델이 처리할 문장을 batch에 담아서 input parameter로 전달한다고 생각하면 된다.

5.2. Padding the inputs

입력값들의 size를 동일하게 맞춰주기 위한 padding 작업이다.

실제로는 tokenizer.pad_token_id를 가지고 사용한다.

여기서 참고할만한 내용은 두번째 입력값에 대한 마지막 출력값이 다르게 나오는데 이는 문맥의 흐름에 대한 가중치가 포함되기 때문이다. 이를 만약 같은 값을 추출하고 싶다면 attention mask 를 사용하면 된다.

5.3. Attention Masks

[Mask] Token을 사용하여 학습에 영향을 주지않도록 제외 시킨다.

5.4. Longer sequences

너무 문장의 길이가 긴 경우, 긴 문장을 감당할 수 있는 모델을 사용하거나 최고 길이 만큼 잘라서 사용하기도 한다.

6. Putting it all together

6.1. Tokenizer

6.2. Special tokens

6.3. 한줄로 보기

Last updated

Was this helpful?