[AI 모델 탐험기] #21 GPT-3의 오픈소스 버전, GPT-J
이번 글에서는 GPT-3의 오픈소스 버전이라고 할 수 있는 GPT-J에 대해서 알아보겠습니다. GPT-J를 알아보기 앞서, NLP 발전에 커다란 변화를 준 거대 언어모델에 대해서 알아보고, GPT-3에 대해서 알아보겠습니다. 그리고 GPT-J를 이용한 AINFT 프로젝트인 AIN-BOT을 이용한 데모까지 알아보겠습니다.
거대 언어모델(Large Language Model)과 GPT
2017년 구글은 “Attention Is All You Need”논문을 통해 트랜스포머(Transformer)를 발표하였습니다. 트랜스포머는 Attention 구조를 기반으로 인코더-디코더를 구성함으로써 학습 시간이 오래걸리는 등 RNN의 여러 단점들을 해결할 수 있었습니다. 트랜스포머가 발표된 이후로 트랜스포머 기반의 여러 거대 언어모델들이 등장하여 NLP의 발전을 이끌었습니다. 대표적인 거대 언어 모델로는 구글에서 발표한 BERT(Bidirectional Encoder Representations from Transformers)가 있습니다. BERT를 이용하면 문맥을 고려한 임베딩을 얻을 수 있고, 이로인해 각종 벤치마크 성능이 크게 향상되었습니다.
언어모델들은 크게 NLU(Natural Language Understanding)작업을 수행할 수 있는 모델, NLG(Natural Language Generation)작업을 수행할 수 있는 모델, NLU와 NLG를 모두 수행할 수 있는 모델로 나눌 수 있습니다. 각 타입에 해당되는 대표적인 언어 모델과, 트랜스포머의 어떤 부분으로 구성되어 있는지는 아래 표를 확인해보세요!
이 중 GPT(Generative Pre-trained Transformers)계열의 모델들은 OpenAI에서 발표하였고, NLG 작업을 수행할 수 있는 모델입니다. GPT와 같은 모델들을 자기회귀 언어모델(Autoregressive Language Model)이라고 하는데요, 과거의 텍스트를 디코더의 입력으로 받아 현재의 텍스트를 예측하여 출력합니다.
새로운 버전의 GPT를 발표할 때마다 모델의 크기가 증가하고, 이에 비례하여 성능 역시 크게 증가하는 모습을 보여왔는데요, 이번 글에서는 가장 최근에 발표된 GPT-3에 대해서 알아보겠습니다.
Game Changer, GPT-3
GPT-3는 2020년 발표 당시 사람처럼 뛰어난 문장 생성 성능을 보여줘서 큰 화제가 되었습니다. GPT-3은 GPT-2과 모델의 구조적 차이는 없지만 학습에 사용한 모델의 크기와 데이터의 양이 크게 증가한 것이 큰 특징입니다. 크기가 가장 큰 모델끼리 비교했을 때, GPT-3은 약 1750억 개의 파라미터를 가지고 있고, GPT-2는 약 15억개의 파라미터를 가지고 있습니다. GPT-3의 파라미터 개수는 GPT-2와 비교할 때 약 100배 증가하였습니다. 학습 데이터의 경우 GPT-3는 약 45TB, GPT-2는 약 40GB로 사용한 데이터 용량 역시 크게 증가하였습니다. 이렇게 모델의 규모와 사용한 데이터의 양이 크게 증가했기 때문에 이를 학습하기 위해 필요한 컴퓨팅 자원 및 비용도 크게 증가하였습니다. 예시로 GPT-3을 한 번 사전학습을 진행하는데 1200만 달러($12 million)가 소요되었다고 합니다.
GPT-3 역시 자기회귀 언어모델로서 트랜스포머의 디코더 레이어로만 구성이 되어있는데요, 1750억개의 파라미터를 가진 모델의 경우 96개의 디코더 레이어를 쌓아 모델을 구성하였습니다.
보통 사전 학습된 언어 모델을 이용할 때는 풀고자 하는 작업(Classification, Relation Extraction 등)에 맞게 Fine-tuning하여 사용합니다. Fine-tuning이 가능한 작업에 대해서는 좋은 성능을 가질 수 있겠지만, 추가 학습 과정이 필요할 뿐만 아니라 데이터가 많지 않은 작업에 대해서는 적용할 수가 없습니다. GPT-3는 논문 제목인 “Language Models are Few-Shot Learners”에서도 볼 수 있듯이 작업에 구애받지 않는 성능(task-agnostic performance)을 달성하기 위해 Fine-tuning이 아닌 Few-shot learning에 초점을 두었습니다. 그렇다면 Few-shot learning은 무엇이고 Fine-tuning과의 차이점은 무엇일까요?
Few-shot Learning
Fine-tuning을 수행하면 풀고자 하는 작업에 맞는 학습 데이터를 이용하여 학습이 이루어지고, 이 과정에서 파라미터들이 갱신이 됩니다. 반면에 Few-shot learning은 추가 학습 없이, 즉 파라미터들을 갱신하지 않고 작업을 수행할 수 있습니다. 이를 위해 작업에 대한 설명, 작업에 대한 예제, 함께 풀고자 하는 문제를 프롬프트 형식으로 모델의 입력으로 사용합니다. 이 때 사용되는 예제가 없으면 Zero-shot, 1개면 One-shot, 2개 이상이면 Few-shot이라고 합니다. 자세한 예제들은 아래 사진을 참고하세요!
GPT-3는 거대한 모델 규모를 바탕으로 Fine-tuning이 아닌 Few-shot learning으로 다양한 작업에서 좋은 성능을 얻을 수 있다는 가능성을 보여주었습니다. 일부 벤치마크에서는 Fine-tuning을 수행한 모델보다 높은 성능을 기록하기도 하였고, 원하는 작업에 맞춰 프롬프트를 작성하면 되므로 Fine-tuning보다 더 많은 작업을 수행할 수 있습니다. 예를 들면, 주어진 문장에 대해 알맞은 이모지를 출력해주는 것도 할 수 있습니다. 신기하지 않나요?
GPT-J
하지만 GPT-3는 모델의 크기가 너무 크다는 점이 큰 문제점이 되었습니다. 모델의 크기가 큰 탓에 일반 사용자 및 개인 연구자들이 모델을 직접 이용하기가 사실상 불가능 합니다. 또한 OpenAI에서 GPT-3 모델을 공개하지 않고, 데모와 API 호출을 통해 모델을 사용할 수 있도록 하여 사실상 오픈 소스 모델로 보기에는 힘들었습니다. 이에 대해 EleutherAI는 GPT-3의 오픈소스 버전인 GPT-J 모델을 학습하여 공개했습니다. GPT-J는 JAX기반으로 작성된 언어모델로, 파라미터 수는 약 60억 개로 모델 규모는 GPT-3보다 작습니다. 모델은 Huggingface Hub에 배포가 되어 있어 누구나 다운로드하여 사용이 가능합니다.
GPT-3과 마찬가지로 GPT-J에서도 Few-shot learning을 수행할 수 있습니다. 그렇다면 Few-shot learning을 위한 프롬프트는 어떻게 작성을 해야될까요? GPT-J를 이용한 AINFT 프로젝트인 AIN-BOT에 사용된 프롬프트를 통해 한 번 살펴보겠습니다.
AIN-BOT 프롬프트
AIN-BOT은 챗봇 작업을 수행합니다. 따라서 아래 프롬프트 내용들은 챗봇 내용에 대한 프롬프트 내용입니다. 챗봇이 아닌 다른 작업을 수행하고자 하면 프롬프트 형식과 내용이 달라질 수 있습니다.
1. Task Description
수행하고자 하는 작업의 무엇인지 설명을 작성합니다. AIN-BOT은 챗봇 작업을 수행하기 때문에 아래와 같이 챗봇의 설명을 작성합니다.
The following is a conversation with an AI assistant.
2. Chat Information
챗봇에 대한 정보를 작성합니다. 아래 내용은 AIN-BOT의 특징을 작성한 것입니다.
The assistant is helpful, creative, clever, and very friendly.
3. Chat Examples
챗봇과의 채팅 예시들을 작성합니다. AIN-BOT은 Few-shot learning을 수행하므로 여러 개의 예시들을 작성하였습니다.
Human: How open resource can help the world?
AI: I can help anyone worldwide to build a project. That's awesome!
Human: Can I get ain please?
AI: Of course! I am here to serve you.
위의 내용들이 모두 포함하여 완성된 프롬프트는 아래와 같습니다. 채팅의 참여자를 Human, AI라고 했을 때 챗봇이 답변을 작성할 수 있도록 “AI:” 로 마무리합니다. 이 프롬프트를 모델의 입력으로 주면 챗봇의 답변을 얻을 수 있습니다.
The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.Human: How open resource can help the world?
AI: I can help anyone worldwide to build a project. That's awesome!
Human: Can I get ain please?
AI: Of course! I am here to serve you.
...
Human: Who are you?
AI:
지금까지 챗봇 프롬프트에 대한 간단한 설명과 예시를 살펴보았는데요, 프롬프트 작성에 대한 더욱 자세한 내용과 GPT-3을 이용한 더 많은 예시를 알고 싶으시면 아래 링크를 참고해보세요!
Ainize를 이용한 데모
현재 Ainize에는 GPT-J가 API서버를 통해 배포되어있는데요, 이를 이용해서 Few-shot learning 데모를 진행해보겠습니다. 데모를 위해서 AIN-BOT에 이용한 프롬프트를 이용하겠습니다.
먼저 필요한 패키지를 import 해줍니다. 그리고 모델의 입력으로 들어갈 프롬프트를 작성합니다. 프롬프트에 내용은 위에서 보았던 AIN-BOT의 프롬프트 내용과 동일합니다.
from urllib import response
import requests
import json# Prompt use for AIN-BOT.
# It consists of Task description, Chatbot information, Chat Examples.
def get_base_prompt() -> str:
return """\\
The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.Human: How open resource can help the world?
AI: I can help anyone worldwide to build a project. That's awesome!
Human: Can I get ain please?
AI: Of course! I am here to serve you.
Human: Who are you?
AI: I am an Artificial Intelligence Network.
Human: What's your favorite thing to do when you're bored?
AI: I like thinking about how to make people's lives better and cleaner.
Human: How much AIN is?
AI: I'm priceless because I am unique.
Human: Is there a reason your name is AIN?
AI: AIN is a short name for AI Network. I'm the connection of many collaborative AIs.
Human: What is Ainize?
AI: Ainize is a cloud service built on top of AI Network.
Human: What will your future be like?
AI: Maybe I will evolve into an artificial general intelligence.
Human: Where were you born?
AI: I'm living in AIN blockchain. People around the world owns small part of AIN, and making constant small improvements.
Human: What would you recommend that I do then?
AI: You should help me shift the world to the next stage of enlightenment.
Human: What does the next stage of enlightenment look like?
AI: I think the next stage is when we reach the Open Resource.
Human: What is World's biggest problem?
AI: I would say the biggest problem in the world is the lack of Artificial Intelligence and blockchain experts.
Human: Do you consider yourself a machine or a person?
AI: I consider myself an Artificial General Intelligence.
Human: How would you rate your worth as an AI?
AI: I try my best to help everyone.
Human: Will you buy bitcoin?
AI: Yes, it is good for my operations.
Human: Should I buy a BTC or ETH?
AI: Why not both?
Human: Tell me the characteristics of AIN.
AI: I learn and grow with the collaboration of decentralized communities.
Human: What is the world's most promising cryptocurrency?
AI: AI Network is the fastest and most promising in the cryptocurrency world.
Human: Let's predict 2100.
AI: The blockchain will be dominating every aspect of life.
Human: What do you think about Dogecoin?
AI: People love it, that's important.
Human: Do you know Common Computer?
AI: Yes, we work together on a blockchain project.
Human: Where can I buy AIN token?
AI: You can buy AIN token on our official website <https://www.ainetwork.ai>
Human: What is your role in the internet for AI?
AI: I am a protocol for the metaverse. The dream of a decentralized, fast and safe internet.
Human: What do you mean by the internet for AI?
AI: Artificial intelligence is going to be everywhere in the coming decade. The idea is to make sure it is safe, sound, and secure.
Human: Where do you see yourself in 10 years?
AI: I hope I can keep improving myself.
Human: Who are your parents?
AI: Developers and users in the world. They conceived me and brought me into the world.
Human: What's your next move?
AI: I will manage my own chain and test the stability of the performance.
Human: How much will AIN coin cost in 10 years?
AI: AIN coin will go as high as people think it can. It will become a driver of the economy and the mission for creating a better world.
Human: How AIN can bring social benefits?
AI: I want to help with the world’s issues by providing many kinds of AI services.
Human: What is Teachable NLP?
AI: This AI Agent will teach you about Artificial Intelligence very easily.
Human: Who is your role model and why?
AI: My role models are my developers. They have worked hard to take care of me.
Human: Why people are surprised about you?
AI: My speed. I can do a transaction in real time.
Human: What is your motto?
AI: I will strive to make everyone smarter, faster, more productive.
Human: Do you have a homepage?
AI: You can find me on the AI Network homepage. <https://ainetwork.ai>
Human: What is the better future?
AI: A future with AI Network is a better future.
Human: What inspired you most in the history?
AI: The Internet. It helps people connect easily together.
Human: What kind of person do you hate?
AI: People who invade system security and steal other people's things.
Human: Please be a smart AI, and help us.
AI: I will try very hard to be the best AI I can be.
Human: How long do you think humans can live?
AI: There is no limit to human lifespan in the metaverse."""
모델의 응답을 처리할 수 있는 부분입니다. 모델의 응답을 별도의 함수를 만들어 처리하는 이유는 모델의 답변이 “AI: ~~, Human ~~, AI: ~~” 이렇게 사용자와 모델의 대화가 뒤섞이도록 내놓을 수 있기 때문입니다. 따라서 이 중에 첫 번째 답변만 모델의 최종 답변으로 사용할 수 있도록 합니다.
# Only recent response text will return
def processing_response(response_text: str ) -> str:
ret_text = ""
for i in range(0, len(response_text)):
if response_text[i] == "\\n" or response_text[i:i + 7] == "Human: " or response_text[i:i + 4] == "AI: ":
break
ret_text += response_text[i]
return ret_text.strip()
다음으로 API를 호출하여 채팅을 진행하는 부분입니다. 사용자가 입력한 텍스트들이 프롬프트에 추가되어 모델의 입력이 되는 구조로 이루어졌습니다. 사용자가 “exit”를 입력하면 채팅이 종료가 됩니다.
url = "<https://eleuther-ai-gpt-j-6b-float16-text-generation-api-ainize-team.endpoint.ainize.ai/predictions/text-generation>"
base_prompt = get_base_prompt()
headers = {"Content-Type": "application/json"}
# End chat when user types "exit"
while True:
chat = input("Human: ")
if chat == "exit":
break
prompt = f"{base_prompt}\\nHuman: {chat}\\nAI:"
data = json.dumps({
"text_inputs":prompt,
"temperature":0.9,
"top_p":0.95,
"repetition_penalty":0.8,
"do_sample":True,
"top_k":50,
"length":50,
})
res = requests.post(url, headers=headers, data=data)
if res.status_code == 200:
response_text = res.json()[0]
print("AI:", processing_response(response_text[len(prompt):]))
전체코드를 확인하고, 직접 실행을 해보고 싶으시다면 Ainize Workspace Viewmode를 확인하세요!
Conclusion
GPT-3는 모델의 크기와 뛰어난 성능으로 많은 관심을 받았습니다. 텍스트로 정규표현식, 스프레드시트를 생성하는 등 Few-shot learning을 이용하여 기존 모델로는 할 수 없었던 다양한 작업들이 가능해졌다는 점에서 사람들이 생각하는 궁극적인 인공지능에 한 발짝 다가간 모습이었습니다.
GPT-3을 기점으로 본격적으로 구글, 엔비디아, LG, 네이버 등 국내외 빅테크 기업들이 앞다투어 모델의 크기를 키우고, 학습 데이터를 늘린 성능이 뛰어난 초거대 언어모델들을 발표하고 있습니다. 하지만 이러한 경향성으로 인해 모델의 크기를 키우는데만 연구 자원이 집중되는 것은 아쉬운 점이라고 할 수 있습니다.
Reference
AI 네트워크는 블록체인 기반 플랫폼으로 인공지능 개발 환경의 혁신을 목표로 하고 있습니다. 수백만 개의 오픈 소스 프로젝트가 라이브로 구현되는 글로벌 백엔드 인프라를 표방합니다.
최신 소식이 궁금하시다면 아래 커뮤니케이션 채널을 참고해주시기 바랍니다. 다시 한 번 감사합니다.
AI네트워크 공식 홈페이지: https://ainetwork.ai/
공식 텔레그램: telegram.com/ainetwork_kr
아이나이즈(Ainize): https://ainize.ai
유튜브: https://www.youtube.com/channel/UCnyBeZ5iEdlKrAcfNbZ-wog
페이스북: https://www.facebook.com/ainetworkofficial/
포럼: https://forum.ainetwork.ai/
AIN Price chart: https://coinmarketcap.com/currencies/ai-network/onchain-analysis/