Hugging Face의 Transformers의 모델 인풋을 살펴봅니다.
1. 인풋 형태 : Batch Input
Transformer는 배치 입력을 받습니다. 즉, 한번에 문장을 입력할 수 있습니다.
from transformers import AutoTokenizer, AutoModelForSequenceClassification
checkpoint = "bert-base-multilingual-cased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(checkpoint)
sequence = "첫번째 문장입니다."
tokenizer_inputs = tokenizer(sequence, return_tensors="pt")
print(tokenizer_inputs["input_ids"])
# tensor([[ 101, 9750, 48506, 9297, 13890, 58303, 48345, 119, 102]])
tokenizer가 반환한 input_ids를 보면, 입력 시퀀스의 ID 리스트에 차원을 추가했음을 알 수 있습니다.
즉, input_ids의 첫번째 리스트는 첫번째 문장의 토큰 ID, 두번째 리스트는 두번째 문장의 토큰 ID입니다.
import torch
tokens = tokenizer.tokenize(sequence)
ids = tokenizer.convert_tokens_to_ids(tokens)
# error
# input_ids = torch.tensor(ids)
# success
input_ids = torch.tensor([ids])
print(input_ids)
# tensor([[ 9750, 48506, 9297, 13890, 58303, 48345, 119]])
2. 길이가 다른 시퀀스 처리 : Padding Token
길이가 다른 시퀀스는 padding token을 추가해서 길이를 맞춰야합니다.
sequence1_ids = [[200, 200, 200]]
sequence2_ids = [[200, 200]]
batched_ids = [[200, 200, 200],
[200, 200, tokenizer.pad_token_id]]
sequence1과 sequence2를 batch로 만들때, 길이가 부족한 두번째 시퀀스에는 padding 토큰을 추가해서 길이를 맞춰줬습니다.
각각의 모델 출력 로짓값을 확인해보겠습니다.
print(model(torch.tensor(sequence1_ids)).logits)
print(model(torch.tensor(sequence2_ids)).logits)
print(model(torch.tensor(batched_ids)).logits)
# 출력
# tensor([[-0.1015, -0.0846]], grad_fn=<AddmmBackward0>)
# tensor([[-0.0988, -0.0817]], grad_fn=<AddmmBackward0>)
# tensor([[-0.1015, -0.0846],
# [-0.0970, -0.0854]], grad_fn=<AddmmBackward0>)
sequence2의 결과와 batched_ids의 두번째 행이 같아야할 것 같지만 다른 것을 확인할 수 있습니다.
3. 패딩 토큰 제외 : Attention masks
이는 Transformer 모델의 어텐션 매커니즘은 입력 시퀀스 내의 각 토큰에 대한 문맥을 이해하고 처리할 수 있도록 합니다. 어텐션 레이어는 토큰과 다른 토큰 간의 상호작용을 캡쳐하는데, 이를 "contextualize"라고 합니다. 하지만 이런 어텐션 레이어는 패딩 토큰까지 고려하는 문제가 있습니다.
패딩토큰을 고려하지 않기 위해서 어텐션 마스크(attention mask)를 사용합니다. 이는 어텐션 레이어에 패딩 토큰에 대한 정보를 전달하지 않도록합니다.
attention_mask = [[1, 1, 1],
[1, 1, 0]]
outputs = model(torch.tensor(batched_ids), attention_mask=torch.tensor(attention_mask))
print(outputs.logits)
# tensor([[-0.1015, -0.0846],
# [-0.0988, -0.0817]], grad_fn=<AddmmBackward0>)
4. 긴 시퀀스 처리
Transformer 모델은 시퀀스 길이의 제한이 있습니다.
대부분의 모델은 최대 512개 또는 1024개 토큰 시퀀스 처리를 하며, 더 긴 시퀀스를 입력하게 되면 충돌이 발생합니다.
매우 긴 시퀀스를 처리하는 모델(Longformer, LED 등)을 사용하거나,
"max_sequence_length"를 설정하여 시퀀스를 잘라야 합니다.
sequence = sequence[:max_sequence_length]
※ 본 포스트는 Hugging Face NLP Course를 번역하고, 일부 내용을 추가하여 작성하였습니다.
Handling multiple sequences - Hugging Face NLP Course
In the previous section, we explored the simplest of use cases: doing inference on a single sequence of a small length. However, some questions emerge already: Let’s see what kinds of problems these questions pose, and how we can solve them using the
huggingface.co
'금융 데이터 분석가 > text-analysis' 카테고리의 다른 글
[NLP] XLNet 토크나이저 처음부터 학습하기 (0) | 2023.11.07 |
---|---|
[NLP] 한국어 모델 fine-tuning (0) | 2023.11.05 |
[NLP Transformers] NLP 작업 순서 - Tokenizer, Model, Post Processing (0) | 2023.11.03 |
[NLP Transformers] Encoder, Decoder, Encoder-Decoder 모델 (3) | 2023.11.02 |
[NLP Transformers] Transformer 개념 정리 (1) | 2023.11.02 |