04장. GPT를 활용한 작문 (문제17-23)
4장에서는 Hugging Face의 다양한 GPT 모델을 다루는 방법을 배우고 학습 예제를 제공한다. 각 모델의 특징과 활용 사례를 살펴보며, 이를 활용한 작문과 자연어 처리 기법을 배울 수 있다.
문제17. GPT-Neo 작문 환경 설정
허깅페이스 모델 헙(hub)에는 Eleuther AI/gpt-neo repository에 의해 공개된 사전학습 모델인 Eleuther AI/gpt-neo-1.3B 모델이 있습니다. 이는 GPT2 혹은 GPT3의 오픈소스 버전입니다. 이를 사용하기 위해 관련 라이브러리인 트랜스포머스와 sentencepiece를 설치하라. 그리고 모델과 토크나이저를 불러오세요.
GPT-Neo란?
GPT-Neo는 EleutherAI에서 개발한 오픈소스 언어 모델로, GPT-2 및 GPT-3과 유사한 아키텍처를 가지고 있다. 주로 연구자와 개발자가 자유롭게 사용할 수 있는 대규모 사전학습 언어 모델로 활용된다.
GPTNeoForCasuallLM과 GPT2Tokenizer를 통해서 사전학습된 GPT-Neo를 불러오자.
# 런타임 3분 소요
!pip install transformers sentencepiece
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
# 모델 및 토크나이저 불러오기
model = GPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B")
tokenizer = GPT2Tokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B")
문제18. GPT-Neo 토크나이징
GPT-Neo 계열 모델 Eleuther AI/gpt-neo-1.3B의 토크나이저를 사용해서, 다음 문장을 인코딩하세요. 반환 형식은 파이토치 센서 타입이어야 합니다.
"I evaluated the performance of GPT-Neo developed by OpenAI"
토크나이징 특징
GPT 모델에서 텍스트를 입력하기 전에 텍스트를 숫자로 변환해야 한다. 이 과정에서 토크나이저가 활용된다.. tokenizer.encode는 한 문장을, batch_encode_plus는 여러 문장을 처리할 때 사용됩니다.
[단일 문장 처리]
# 토크나이징을 통한 인코딩(입력문이 하나인 경우)
input = tokenizer.encode("I evaluated the performance of GPT-Neo developed by OpenAI.", return_tensors="pt")
# 첫번째 인코딩 결과(결과적으로 하나의 입력문장)를 확인
print(input[0])
# 첫번째 인코딩 결과를 디코딩
print(tokenizer.decode(input[0]))
[다중 문장 처리]
두 개 이상의 문장을 인코딩하기 위해서, pad_token을 설정한 후 padding=True, truncation=True 설정값을 가진 tokenizer.batch_encoder_plus()를 사용한다.
# 토크나이징을 통한 인코딩(입력문이 복수인 경우)
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
input = tokenizer.batch_encode_plus(["I evaluated the performance of GPT-Neo developed by OpenAI.","I evaluated the performance of GPT developed by OpenAI."], padding=True, truncation=True, return_tensors="pt")
# 인코딩 결과 확인
print(input['input_ids'])
# 디코딩
print([tokenizer.decode(input['input_ids'][i]) for i in range(len(input['input_ids']))])
문제19. GPT-Neo 작문
문제 17과 18에서 불러온 사전학습 모델과 토크나이저를 사용해서 다음 문장의 후속 문장을 생성하세요. 인코딩 할 때 처음 다섯개 토큰만 사용하는 것에 주의하세요.
- "I evaluated the performance of GPT2 developed by OpenAI"
- "Vaccine for new coronavirus in the UK"
- "3.1415926535"
tokenizer.batch_encode_plus()와 model.generate를 사용해서 이 작업을 한번에 실행할 수 있다. 모델은 입력된 원주율 3.1415926532 이후에 완벽한 추론 결과를 출력한다.
# 토크나이징
input = tokenizer.batch_encode_plus(["I evaluated the performance of GPT2 developed by OpenAI.", "Vaccine for new coronavirus in the UK","3.1415926535"], max_length=5, truncation=True, padding=True, return_tensors="pt")
# 인코딩 결과 확인
input['input_ids']
# tensor([[ 40, 16726, 262, 2854, 286],
# [ 53, 4134, 500, 329, 649],
# [ 18, 13, 1415, 19707, 22980]])
# 인코딩 결과를 model.generate( )에 투입
generated = model.generate(input['input_ids'])
# 디코딩
generated_text = tokenizer.batch_decode(generated)
# enumerate( )는 변수 generated_text에 있는 키값(value)에
# 0, 1, 2,...로 시작하는 숫자 키(key)를 부여
for i, sentence in enumerate(generated_text):
print(f'No.{i+1}')
print(f"{sentence}\n")
# No.1
# I evaluated the performance of the proposed method on the real-world dataset. The results are shown in
# No.2
# Vaccine for new-borns
# The vaccine for new-borns is a vaccine
# No.3
# 3.1415926535897932384626433832795028841971693
결과를 보면 두 번째 문장 생성(No.2) 시 입력문을 반복하는 성향을 보인다. 그러나 다른 두 경우는 매우 자연스러운 문장 생성 결과를 보인다.
문제20. DistilGPT2 환경 설정
distilled GPT2 모델, 즉 DistilGPT2 모델을 huggingface.co/models에서 사용 가능합니다. 이를 사용하기 위해 모델과 토크나이저를 불러옵니다.
DistilGPT2란?
DistilGPT2는 GPT-2를 경량화하여 만든 모델로, 처리 속도와 메모리 효율성이 뛰어나다. 작은 규모의 작업이나 실시간 처리를 위한 환경에 적합하다.
# 코랩 메모리가 clear된 경우만 transformers 재설치
# !pip install transformers
# 모델 및 토크나이저 불러오기
from transformers import AutoTokenizer, AutoModelWithLMHead
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
model = AutoModelWithLMHead.from_pretrained("distilgpt2")
문제21. DistilGPT2 작문
다음 문장을 distilgpt2에 입력하고 이 모델을 사용해서 후속 문장을 생성하세요.
- "I like gpt because it's" (나는 gpt가 좋습니다. 왜냐하면...)
생성할 토큰의 최대 개수는 max_length를 통해 설정할 수 있다. 결과로서 후속 문장으로 "a good thing to have" (~이 있으면 좋으니까요)가 생성되었다.
# 토크나이징. 출력은 파이토치 텐서(pt)로 받음
input_ids = tokenizer.encode("I like gpt because it's", return_tensors='pt')
# max-length 값을 12로 설정
greedy_output = model.generate(input_ids, max_length=12)
# *표시를 100번 실행하여 *로 구성된 줄 만들기
print("Output:\n" + 100 * '-')
# 인코딩 결과 디코딩
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))
# Output: I like gpt because it's a good thing to have
문제22. DialoGPT 환경 설정
huggingface.co/models에서 Microsoft/DialoGPT-small을 검색하여 찾을 수 있습니다. 이는 마이크로소프트가 소셜 뉴스 웹 사이트인 reddict 등에 올라온 텍스트를 GPT 모델에 투입하여 사전학습시킨 모델입니다. 이 모델을 사용하기 위해 모델과 토크나이저를 불러옵니다.
DialoGPT란?
DialoGPT는 Microsoft에서 개발한 대화형 언어 모델로, 대화 데이터를 기반으로 학습되었다. 자연스러운 대화 톤으로 문장을 생성하는 데 적합하다.
AutoTokenizer와 AutoModelWithLMHead를 통해 DialoGPT-small을 불러온다.
# 모델 및 토크나어지 불러오기
from transformers import AutoTokenizer, AutoModelWithLMHead
tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-small")
model = AutoModelWithLMHead.from_pretrained("microsoft/DialoGPT-small")
문제23. DialoGPT 작문
문제22에서 불로운 DialoGPT에 다음 문장을 입력하고 후속 문장을 생성하세요.
- "I like gpt because it's"
후속 문장으로 "I like gpt because it's a good way to get a feel for the game" (게임감을 느끼기 좋아서 나는 gpt를 좋아합니다)가 생성되었다. 문체가 DistilGPT2 모델 대비 부드러운 걸 느낄 수 있다.
# 토크나이징
input_ids = tokenizer.encode("I like gpt because it's", return_tensors='pt')
# max-length 값을 30으로 설정
greedy_output = model.generate(input_ids, max_length=30)
print("Output:\n" + 100 * '-')
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))
# Output: I like gpt because it's a good way to get a feel for the game.