본문 바로가기
일기

GPT-3 실행해보기

by Whiimsy 2021. 5. 17.

Google Colaboratory 환경에서 GPT3 실행하기

🍟 환경 세팅하기

!git clone 혹은 레포지토리 다운로드 후 드라이브에 저장하기

https://github.com/shreyashankar/gpt3-sandbox

 

GitHub - shreyashankar/gpt3-sandbox: The goal of this project is to enable users to create cool web demos using the newly releas

The goal of this project is to enable users to create cool web demos using the newly released OpenAI GPT-3 API with just a few lines of Python. - GitHub - shreyashankar/gpt3-sandbox: The goal of th...

github.com

코랩 환경에서 GPT3를 실행시키기 위해선 위 레포지토리가 필요하다. !git clone을 하는 방법도 있지만 나는 레포지토리를 zip으로 다운로드하여 압출을 푼 후, 내 드라이브 > Colab Notebooks에 저장했다.

 

드라이브의 gpt3-sandbox-master 폴더 안에 새 Google Colaboratory 생성하기

gpt3-sandbox-master 폴더 안에 새로운 ipynb 파일을 만들어준다.

 

아래 코드를 실행시켜 openai 모듈을 설치한다.

!pip install openai​

 

requirenments 준비하기

저장한 gpt3-sandbox-master 폴더 > api 모듈requirements를 설치한다.

!pip install -r /content/drive/MyDrive/ColabNotebooks/gpt3-sandbox-master/api/requirements.txt

 

requirements 파일을 살펴보면 다음과 같다.

astroid==2.4.2
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
Flask==1.1.2
idna==2.10
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
openai==0.2.4
pylint==2.5.3
python-dotenv==0.14.0
requests==2.24.0
six==1.15.0
urllib3==1.25.9
Werkzeug==1.0.1

 

API 시크릿키 입력하기

필요한 모듈을 import하고 발급받은 시크릿키를 입력한다. 이 과정은 공식 홈페이지를 참고하면 된다.

 

import openai
import json
openai.api_key = 'sk-시크릿키를입력하세요!'
response = openai.Completion.create(engine="davinci", prompt="This is a test", max_tokens=5)

 

모듈과 변수 불러오기

api 폴더의 gpt.py, ui_config.py, demo_web_app.py에서 각각 GPT/Example, UIConfig, demo_web_app 클래스를 불러오기 위해 다음 코드를 실행시킨다.

%cd /content/drive/MyDrive/ColabNotebooks/gpt3-sandbox-master/api

from gpt import GPT,Example
from ui_config import UIConfig
from demo_web_app import demo_web_app

( demo_web_app 모듈에서 에러가 나는 경우 10, 11번째 라인의 .gpt, .ui_configgpt, ui_config로 변경해주면 된다. )

 

이렇게 하면 GPT3를 실행시키기 위한 환경 설정은 끝난 셈이다! 이제 학습을 시켜보자.

 

🍟 GPT3 학습시키기

GPT 초기값 설정

gpt.py > GPT 클래스의 __init__ 함수를 살펴보면 다음과 같다. 이를 참고해 사용할 엔진, temperature 값, max_tokens 값 등을 설정한다. ( openai의 Playground에서 사용했던 Frequency Penalty, Presence Penalty 변수도 사용해보고 싶었는데 이 함수에선 정의되어 있지 않다. 기회가 되면 추가해보고 싶지만 어려울 것 같다..! )

 

함수를 살펴보면, inputoutput의 접두사(prefix), 접미사(suffix)를 설정할 수도 있다.

gpt = GPT(engine="davinci",
          temperature=0.6938,
          max_tokens=500)

 

예제 학습시키기

gpt.py > GPT 클래스의 add_example 함수와 Example 클래스를 참고해 학습시킬 예제를 추가시켜 준다. Example(input, output) 형식으로 넣어주면 된다. 나는 자연어로 원하는 HTML 구성 요소를 설명하면 HTML 코드를 만들어주는 모델을 만들기 위해 다음과 같은 예제를 추가시켰다.

gpt.add_example(Example('a red button that says stop', 
'<button style="color: white; background-color: red;">Stop</button>'))
gpt.add_example(Example('a blue box that contains 3 yellow circles with red borders', 
'<div style="background-color: blue; padding: 20;">
<div style="background-color: yellow; border: 5px solid red; border-radius:50%; 
padding: 20; width: 100px; height:100px;"></div><div style="background-color: yellow; 
border: 5px solid red; border-radius:50%; padding: 20; width: 100px; height:100px;">
</div><div style="background-color: yellow; border: 5px solid red; border-radius:50%; 
padding: 20; width: 100px; height:100px;"></div>'))

 

Prompt 값 입력하기

내가 입력하고 싶은 값을 정의해주면 된다. Example의 입력값(첫번째 파라미터)을 생각하면 편하다. 난 파란색 박스 안의 노란색 원을 입력해보았다!

prompt = "A yellow circle in a blue box"

 

Output 출력하기

gpt.py > GPT 클래스의 submit_request 함수를 참고해 위에 정의한 prompt를 전달 인자로 입력하고 output을 출력한다.

output = gpt.submit_request(prompt)
output

 

🍟 출력 확인하기

위와 같이 GPT3를 학습시키고 실행하면 다음과 같은 결과를 얻을 수 있다.

<OpenAIObject text_completion id=cmpl-2KAGrL3lFXj0gcmNa8Zy40FuiVw88 at 0x7fdaa96dcf10> 
JSON: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": "output: <div style="background-color: blue; padding: 20;"> 
      <div style="background-color: yellow; border: 5px solid red; border-radius:50%;
      padding: 20; width: 100px; height:100px;"></div>"
    }
  ],
  "created": 1611158717,
  "id": "cmpl-2KAGrL3lFXj0gcmNa8Zy40FuiVw88",
  "model": "davinci:2020-05-03",
  "object": "text_completion"
}

 

출력된 코드를 HTML 파일 안에 넣어 확인해보면,

정말 파란 박스 안에 노란 원이 생긴 걸 볼 수 있다! 단 두 개의 예제만 가지고 HTML 코드를 뚝딱 작성하다니.. 진짜 하나를 가르쳐주면 열 이상을 알아내는 것 같은 무서움이다. 동요 텍스트도 넣어보고 방정식도 넣어보며 여러 가지 테스트를 해봤는데 재밌고 신기했다. 여러 테스트는 여기서 확인할 수 있고 앞으로 다른 것들도 해볼 예정이다!

 

 

'일기' 카테고리의 다른 글

2022-05-26  (0) 2022.05.26
2022-05-25  (0) 2022.05.25
2021-01-20  (0) 2021.05.17
2021-01-21  (0) 2021.01.21
2021-01-17  (0) 2021.01.18