반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

Azure OpenAI를 사용하려면 해당 서비스를 사용할 수 있는 권한을 Microsoft 사로부터 얻어야 합니다.

저는 공부 목적으로 필요하다고 신청했는데 거부 됐습니다.

 

 

실제 이 Azure OpenAI를 이용해서 제품을 개발하고자 한다면 한번 신청해 보세요.

 

신청 방법은 아래 글에 정리 해 놨습니다.

 

https://coronasdk.tistory.com/1304

 

Azure OpenAI 를 사용하기 위한 사전 요구 사항들 - 사용 요청 거부 됨

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다. https://github.com/openai/openai-cookbook GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API Examples and guides for using the OpenAI API. C

coronasdk.tistory.com

 

저는 일단 실습은 못하고 Cookbook에 있는 글로 공부해 보겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

 

참고로 Azure OpenAI Embeddings + Search 관련 유투브 클립입니다.

 

https://www.youtube.com/watch?v=ocxq84ocYi0 

 

아래부터 Cookbook 내용입니다.

 

Azure embeddings example

 

In this example we'll try to go over all operations for embeddings that can be done using the Azure endpoints.
This example focuses on embeddings but also touches some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial.

 

이 예제에서는 Azure endpoints를 사용하여 수행할 수 있는 embeddings 에 대한 작업을 살펴보겠습니다.
이 예제는 임베딩에 중점을 두지만 API를 사용하여 사용할 수 있는 다른 작업도 다룹니다. 이 예제는 간단한 작업을 보여주는 빠른 방법이며 튜토리얼이 아닙니다.

 

import openai
from openai import cli

Setup

For the following sections to work properly we first have to setup some things. Let's start with the api_base and api_version. To find your api_base go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for the "Endpoint" value.

 

다음 섹션이 제대로 작동하려면 먼저 몇 가지를 설정해야 합니다. api_base 및 api_version부터 시작하겠습니다. api_base를 찾으려면 https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints" 에서 "Endpoint" 값을 찾습니다.

 

openai.api_version = '2022-12-01'
openai.api_base = '' # Please add your endpoint here

다음으로 api_type 및 api_key를 설정해야 합니다. 포털에서 키를 얻거나 Microsoft Active Directory 인증을 통해 얻을 수 있습니다. 이에 따라 api_type은 azure 또는 azure_ad입니다.

 

Setup: Portal

Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for one of the "Keys" values.

 

먼저 포털에서 키를 가져오는 방법을 살펴보겠습니다. https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints"에서 "Keys" 값 중 하나를 찾습니다.

 

openai.api_type = 'azure'
openai.api_key = ''  # Please add your api key here

(Optional) Setup: Microsoft Active Directory Authentication

Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal.

 

(선택 사항) 설정: Microsoft Active Directory 인증
이제 Microsoft Active Directory 인증을 통해 키를 얻는 방법을 살펴보겠습니다. 포털의 키 대신 Active Directory 인증을 사용하려면 다음 코드의 주석을 제거하십시오.

 

# from azure.identity import DefaultAzureCredential

# default_credential = DefaultAzureCredential()
# token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

# openai.api_type = 'azure_ad'
# openai.api_key = token.token

 

Deployments

In this section we are going to create a deployment that we can use to create embeddings.

이 섹션에서는 embeddings을 만드는 데 사용할 수 있는 deployment 를 만들 것입니다.

 

Deployments: Create manually

Let's create a deployment using the text-similarity-curie-001 model. Create a new deployment by going to your Resource in your portal under "Resource Management" -> "Model deployments".

text-similarity-curie-001 모델을 사용하여 배포를 생성해 보겠습니다. "Resource Management" -> "Model deployments"에서 포털의 리소스로 이동하여 새 deployment를 만듭니다.

 

(Optional) Deployments: Create programatically

We can also create a deployment using code:

코드를 사용하여 deployment 를 만들 수도 있습니다.

 

model = "text-similarity-curie-001"

# Now let's create the deployment
print(f'Creating a new deployment with model: {model}')
result = openai.Deployment.create(model=model, scale_settings={"scale_type":"standard"})
deployment_id = result["id"]

 

(Optional) Deployments: Retrieving

Now let's check the status of the newly created deployment

이제 새로 생성된 배포의 상태를 확인하겠습니다.

print(f'Checking for deployment status.')
resp = openai.Deployment.retrieve(id=deployment_id)
status = resp["status"]
print(f'Deployment {deployment_id} is with status: {status}')

 

Deployments: Listing

Now because creating a new deployment takes a long time, let's look in the subscription for an already finished deployment that succeeded.

이제 새 deployment 를 만드는 데 시간이 오래 걸리므로 이미 완료된 deployment 에 대한 subscription 을 살펴보겠습니다.

 

print('While deployment running, selecting a completed one that supports embeddings.')
deployment_id = None
result = openai.Deployment.list()
for deployment in result.data:
    if deployment["status"] != "succeeded":
        continue
    
    model = openai.Model.retrieve(deployment["model"])
    if model["capabilities"]["embeddings"] != True:
        continue
    
    deployment_id = deployment["id"]
    break

if not deployment_id:
    print('No deployment with status: succeeded found.')
else:
    print(f'Found a succeeded deployment that supports embeddings with id: {deployment_id}.')

 

Embeddings

Now let's send a sample embedding to the deployment.

이제 배포에 샘플 임베딩을 보내겠습니다.

 

embeddings = openai.Embedding.create(deployment_id=deployment_id,
                                     input="The food was delicious and the waiter...")
                                
print(embeddings)

 

(Optional) Deployments: Delete

Finally let's delete the deployment

 

마지막으로 deployment를 삭제하겠습니다.

 

 

 

 

반응형


반응형

Azure OpenAI를 사용하려면 해당 서비스를 사용할 수 있는 권한을 Microsoft 사로부터 얻어야 합니다.

저는 공부 목적으로 필요하다고 신청했는데 거부 됐습니다.

 

 

실제 이 Azure OpenAI를 이용해서 제품을 개발하고자 한다면 한번 신청해 보세요.

 

신청 방법은 아래 글에 정리 해 놨습니다.

 

https://coronasdk.tistory.com/1304

 

Azure OpenAI 를 사용하기 위한 사전 요구 사항들 - 사용 요청 거부 됨

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다. https://github.com/openai/openai-cookbook GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API Examples and guides for using the OpenAI API. C

coronasdk.tistory.com

 

저는 일단 실습은 못하고 Cookbook에 있는 글로 공부해 보겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/azure/completions.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Azure completions example

 

In this example we'll try to go over all operations needed to get completions working using the Azure endpoints.
This example focuses on completions but also touches on some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial.

 

이 예제에서는 Azure 엔드포인트를 사용하여 작업을 completions 하는 데 필요한 모든 작업을 살펴보겠습니다.
이 예제는 completions 에 중점을 두지만 API를 사용하여 사용할 수 있는 다른 작업도 다룹니다. 이 예제는 간단한 작업을 보여주는 빠른 방법이며 튜토리얼이 아닙니다.

 

import openai
from openai import cli

 

Setup

For the following sections to work properly we first have to setup some things. Let's start with the api_base and api_version. To find your api_base go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for the "Endpoint" value.

 

다음 섹션이 제대로 작동하려면 먼저 몇 가지를 설정해야 합니다. api_base 및 api_version부터 시작하겠습니다. api_base를 찾으려면 https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "리소스 관리" -> ""Keys and Endpoints""에서 "Endpoint" 값을 찾습니다.

 

==> 이 부분이 Azure OpenAI 사용 권한이 필요한 부분 입니다.

 

openai.api_version = '2022-12-01'
openai.api_base = '' # Please add your endpoint here

 

다음으로 api_type 및 api_key를 설정해야 합니다. 포털에서 키를 얻거나 Microsoft Active Directory 인증을 통해 얻을 수 있습니다. 이에 따라 api_type은 azure 또는 azure_ad입니다.

 

Setup: Portal

Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under "Resource Management" -> "Keys and Endpoints" look for one of the "Keys" values.

 

먼저 포털에서 키를 가져오는 방법을 살펴보겠습니다. https://portal.azure.com으로 이동하여 리소스를 찾은 다음 "Resource Management" -> "Keys and Endpoints"에서 "Keys" 값 중 하나를 찾습니다.

 

openai.api_type = 'azure'
openai.api_key = ''  # Please add your api key here

 

(Optional) Setup: Microsoft Active Directory Authentication

Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal.

 

(선택 사항) 설정: Microsoft Active Directory 인증
이제 Microsoft Active Directory 인증을 통해 키를 얻는 방법을 살펴보겠습니다. 포털의 키 대신 Active Directory 인증을 사용하려면 다음 코드의 주석을 제거하십시오.

 

# from azure.identity import DefaultAzureCredential

# default_credential = DefaultAzureCredential()
# token = default_credential.get_token("https://cognitiveservices.azure.com/.default")

# openai.api_type = 'azure_ad'
# openai.api_key = token.token

 

Deployments

In this section we are going to create a deployment using the text-davinci-002 model that we can then use to create completions.

이 섹션에서는 completions 를 생성하는 데 사용할 수 있는 text-davinci-002 모델을 사용하여 배포를 생성할 것입니다.

 

 

Deployments: Create manually

Create a new deployment by going to your Resource in your portal under "Resource Management" -> "Model deployments". Select text-davinci-002 as the model.

 

"리소스 관리" -> "모델 배포"에서 포털의 리소스로 이동하여 새 배포를 만듭니다. text-davinci-002를 모델로 선택합니다.

 

(Optional) Deployments: Create programatically

We can also create a deployment using code:

코드를 사용하여 배포를 만들 수도 있습니다.

 

model = "text-davinci-002"

# Now let's create the deployment
print(f'Creating a new deployment with model: {model}')
result = openai.Deployment.create(model=model, scale_settings={"scale_type":"standard"})
deployment_id = result["id"]
print(f'Successfully created deployment with id: {deployment_id}')

 

(Optional) Deployments: Wait for deployment to succeed

Now let's check the status of the newly created deployment and wait till it is succeeded.

 

이제 새로 생성된 배포의 상태를 확인하고 성공할 때까지 기다리겠습니다.

 

print(f'Checking for deployment status.')
resp = openai.Deployment.retrieve(id=deployment_id)
status = resp["status"]
print(f'Deployment {deployment_id} has status: {status}')
while status not in ["succeeded", "failed"]:
    resp = openai.Deployment.retrieve(id=deployment_id)
    status = resp["status"]
    print(f'Deployment {deployment_id} has status: {status}')

 

Completions

Now let's send a sample completion to the deployment.

 

이제 배포에 샘플 완료를 보내겠습니다.

 

prompt = "The food was delicious and the waiter"
completion = openai.Completion.create(deployment_id=deployment_id,
                                     prompt=prompt, stop=".", temperature=0)
                                
print(f"{prompt}{completion['choices'][0]['text']}.")

 

(Optional) Deployments: Delete

Finally let's delete the deployment

 

print(f'Deleting deployment: {deployment_id}')
openai.Deployment.delete(sid=deployment_id)

 

이 과정을 보니까 Azure OpenAI를 사용하는 것은 그냥 OpenAI API 를 사용하기 이전에 openai.Deployment.create() API를 사용해서 Deployment 부터 하네요.

 

그리고 추가적으로 Deployment 가 완료 되는지 여부를 openai.Deployment.retrieve() 를 사용해서 체크하는 부분이 있구요.

 

이렇게 한번 Deployment가 완료 되면 다른 openai API를 사용하는 방법과 똑 같이 openai.Completion.create() API를 사용해서 prompt 를 전달하고 응답을 받습니다.

 

그리고 마지막으로 해당 Deployment를 Delete 하는 과정이 있구요.

이때는 openai.Deployment.delete() API 를 사용합니다.

 

그냥 OpenAI API 를 사용할 때는 (Azure) 를 거치지 않고) 이 Deployment 단계들은 필요 없습니다. 그냥 openai api key 만 전달 한 후 openAI API를 사용하시면 됩니다.

 

참고로 실제로 실습을 하는 모습을 보려면 아래 유투브 클립을 보시면 됩니다.

 

https://www.youtube.com/watch?v=lHw1tZhXlEo 

 

 

반응형


반응형

OpenAI CookBook 을 거의 다 공부하고 Azure OpenAI 를 공부할 차례 입니다.

 

https://github.com/openai/openai-cookbook

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

첫 예제의 Setup 부터 막히더라구요.

 

 

api_base 와 api_version 을 구하는 방법도 모르겠어서 여기 저기 구글링을 해 보았습니다.

(이제는 Binging 을 한다고 말해야 하나?)

 

우선 Microsoft Azure 로 들어가서 Azure OpenAI 서비스를 선택합니다.

(Microsoft Azure 에 가입 돼 있어야 합니다. 일단 가입은 무료입니다.)

 

Azure OpenAI 라고 검색을 하시면 위와 같은 아이콘을 보실 수 있습니다.

 

클릭하면 이런 화면이 뜹니다.

 

여기서 Create 을 클릭하시면 ......

 

 

이런 화면이 뜹니다.

 

밑에 붉은 background 에 있는 글을 보세요.

 

Azure OpenAI Service is currently available to customers via an application form. The selected subscription has not been enabled for use of the service and does not have quota for any pricing tiers. Click here to request access to Azure OpenAI service.

 

Azure OpenAI 서비스는 현재 신청 양식을 통해 고객에게 제공됩니다. 선택한 구독은 서비스 사용을 위해 활성화되지 않았으며 가격 책정 계층에 대한 할당량이 없습니다. Azure OpenAI 서비스에 대한 액세스를 요청하려면 여기를 클릭하십시오.

 

Azure OpenAI 를 사용하려면 따로 신청을 하셔야 합니다.

여기서 링크를 클릭하면 아래와 같은 페이지로 갑니다.

 

저는 여기서 신청서 양식을 다 작성을 하고 마지막에 긴 설문도 다 작성을 하고 Submit을 눌렀습니다.

 

그러면 아래와 같은 화면이 나옵니다.

 

신청은 했는데 이게 승인이 될지 거부가 될지 그리고 승인이 되면 언제 될지 모르겠네요.

 

일단 현재로서는 실습을 하지는 못 하겠고 Cookbook 에 있는 글을 통해서 공부만 해 둬야 겠습니다.

 

 

아래는 Azure OpenAI 를 사용해서 Azure에서 리소스를 생성하고 배치하는 방법을 알려 주는 How-to 페이지 입니다.

여기서도 Prerequisites 로 Auzre 에 가입하고 위 신청서를 작성해야 한다고 나오네요.

 

How-to - Create a resource and deploy a model using Azure OpenAI Service - Azure OpenAI | Microsoft Learn

 

How-to - Create a resource and deploy a model using Azure OpenAI Service - Azure OpenAI

Walkthrough on how to get started with Azure OpenAI and make your first resource and deploy your first model.

learn.microsoft.com

 

아래는 신청서 작성하는 페이지 입니다.

https://aka.ms/oai/access

 

Dynamics 365 Customer Voice

 

customervoice.microsoft.com

 

이상 Azure OpenAI 를 사용하기 위한 Prerequisites 에 대한 Research 내용 공유글 이었습니다.

 

==============================

 

이 글 작성하고 이메일을 확인 했더니 금방 Microsoft 에서 답변 이메일이 왔네요.

 

 

요청은 거부 됐습니다.

 

저는 그냥 솔직하게 공부할 목적으로 사용하고 싶다라고 했는데 이런 경우는 받아들여지지 않네요.

그냥 Cookbook 글만을 통해서 공부만 해야 겠습니다.

반응형


반응형

 

You can now access GPT-4 models with 8K context via the existing OpenAI API.

이제 기존 OpenAI API를 통해 8K 컨텍스트로 GPT-4 모델에 액세스할 수 있습니다.

 

As an early customer we'd love to hear about your experience. Feel free to share feedback on our community forum or reach out directly to our team.

 

General API discussion

Welcome to the General Discussion! We encourage you to use this thread to discuss your experiences using the OpenAI API and to meet other users.

community.openai.com

초기 고객으로서 귀하의 경험에 대해 듣고 싶습니다. 커뮤니티 포럼에서 자유롭게 의견을 공유하거나 팀에 직접 연락하세요.

 

Best,
The OpenAI team

 

이런 내용입니다.

 

저는 GPT-4 API 사용 권한을 waiting list 에 3월 14일 신청 했었습니다.

 

 

Thank you for joining the waitlist to build with GPT-4!

 

GPT-4로 빌드하기 위한 대기자 명단에 등록해 주셔서 감사합니다!

 

To balance capacity with demand, we'll be sending invites gradually over time.

 

용량과 수요의 균형을 맞추기 위해 시간이 지남에 따라 점진적으로 초대장을 보낼 것입니다.

 

While we ramp up, invites will be prioritized to developers who have previously build with the OpenAI API. You can also gain priority access if you contribute model evaluations to OpenAI Evals that get merged, as this will help us improve the models for everyone.

 

확장하는 동안 초대는 이전에 OpenAI API로 빌드한 개발자에게 우선순위가 부여됩니다. 병합되는 OpenAI Eval에 모델 평가를 제공하면 모든 사람을 위해 모델을 개선하는 데 도움이 되므로 우선 액세스 권한을 얻을 수 있습니다.


Once you’re off the waitlist, you’ll receive an email with further instructions on how to get started. We will process requests for the 8K and 32K models at different rates based on capacity, so you can expect to receive 8K access first.

 

대기자 명단에서 제외되면 시작하는 방법에 대한 추가 지침이 포함된 이메일을 받게 됩니다. 용량에 따라 다른 속도로 8K 및 32K 모델에 대한 요청을 처리하므로 먼저 8K 액세스를 받을 수 있습니다.


We appreciate your interest, and look forward to having you build with GPT-4 soon. In the meantime, we suggest getting started with gpt-3.5-turbo, the model powering ChatGPT.

 

귀하의 관심에 감사드리며 곧 GPT-4로 빌드할 수 있기를 기대합니다. 그동안 ChatGPT를 지원하는 모델인 gpt-3.5-turbo를 시작하는 것이 좋습니다.


– The OpenAI Team


P.S. You can also preview GPT-4 on chat.openai.com if you’re a ChatGPT Plus subscriber. We expect to be severely capacity constrained, so there will be a usage cap for the model depending on demand and system performance.

 

추신 ChatGPT Plus 구독자인 경우 chat.openai.com에서 GPT-4를 미리 볼 수도 있습니다. 용량이 심각하게 제한될 것으로 예상되므로 수요 및 시스템 성능에 따라 모델에 대한 사용 한도가 있을 것입니다.

 

지금은 GPT-4 API 8k 용량에 대한 접근권만 허용이 된 것이네요.

 

어쨌든 공부를 시작할 수 있을 것 같습니다.

 

저는 2023년 1월 3일부터 GPT-3 API 관련해서 공부를 시작했습니다.

일종의 New Year's Resolution 이 돼 버렸는데요.

 

공부 거의 마칠 무렵인 3월 1일에 GPT-3.5 turbo API (ChatGPT API) 가 발표 됐습니다.

 

그래서 며칠동안 Update 된 API 를 다시 공부 해야 됐는데요.

 

14일 후인 3월 14일 Open AI 에서는 GPT-4 가 발표 됐습니다.

 

정말 정신 없이 발전하는 것 같습니다.

 

원래 계획은 OpenAI API Cookbook을 마치고 개인 프로젝트를 구상해서 추진하려고 했습니다.

 

이제 Cookbook을 거의 다 마치고 Azure 와 연결해서 사용할 수 있는 방법에 대한 글 3가지만 남아 있었는데...

이제 CPT-4 가 발표 됐으니 update 된 내용도 다시 수정하거나 추가해서 정리 해야 될 것 같습니다.

 

개인적으로 이번달 (3월) 안으로 Cookbook 공부 다 마치고 4월부터 개인 프로젝트 구상에 들어가야 겠습니다.

 

정말 따라가기 벅찰 정도로 발전하는군요.

 

반응형


반응형

오늘은 그림을 그리는 OpenAI의 AI 화가 DALL-E API 입니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/dalle/Image_generations_edits_and_variations_with_DALL-E.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

DALL-E

This notebook shows how to use OpenAI's DALL-E image API endpoints.

이 노트북은 OpenAI의 DALL-E 이미지 API endpoints를 사용하는 방법을 보여줍니다.

 

There are three API endpoints:

세 가지 API endpoints가 있습니다.

  • Generations: generates an image or images based on an input caption
  • Generations: 입력 캡션을 기반으로 이미지를 생성합니다.
  • Edits: edits or extends an existing image
  • 편집: 기존 이미지를 편집하거나 확장합니다.
  • Variations: generates variations of an input image
  • 변형: 입력 이미지의 변형을 생성합니다.

Setup

  • Import the packages you'll need
  • 필요한 패키지 가져오기
  • Import your OpenAI API key: You can do this by running ``export OPENAI_API_KEY="your API key"\ in your terminal.
  • OpenAI API key 가져오기 
  • Set a directory to save images to
  • 이미지를 저장할 디렉토리 설정

이제 소스 코드를 보겠습니다.

# imports
import openai  # OpenAI Python library to make API calls
import requests  # used to download images
import os  # used to access filepaths
from PIL import Image  # used to print and edit images

# set API key
openai.api_key = os.environ.get("OPENAI_API_KEY")

 

먼저 필요한 모듈들을 import 합니다.

openai를 import 해 openaai api를 사용할 수 있도록 합니다.

그 다음에 requests 모듈을 import 했습니다. 이 모듈은 openai 에 이미지가 생성 된 후 이 이미지를 나의 local 컴퓨터로 다운로드 받기 위해 필요합니다. 

이 모듈은 파이썬에서 HTTP request를 보낼 수 있도록 합니다. HTTP를 사용해서 OpenAI쪽에 생성돼 있는 이미지를 다운 로드 받게 됩니다.

https://www.w3schools.com/python/module_requests.asp

 

Python Requests Module

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

그 다음은 os 모듈 입니다. 나의 local computer에 있는 환경 변수 값도 불러 오고 이미지가 저장될 폴더 위치도 설정하고 저장되는 이미지 파일 이름도 설정하는 등의 일들을 하는데 사용 됩니다.

https://docs.python.org/3/library/os.html

 

os — Miscellaneous operating system interfaces

Source code: Lib/os.py This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, s...

docs.python.org

 

그리고 마지막으로 Image PIL 모듈에 있는 Image 함수를 import 합니다.

이 PIL 모듈은 파이썬에서 이미지를 다룰 때 사용하는 모듈입니다.

https://pillow.readthedocs.io/en/stable/

 

Pillow

Pillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors. Pillow for enterprise is available via the Tidelift Subscription...

pillow.readthedocs.io

https://pillow.readthedocs.io/en/stable/handbook/tutorial.html

 

Tutorial

Using the Image class: The most important class in the Python Imaging Library is the Image class, defined in the module with the same name. You can create instances of this class in several ways; e...

pillow.readthedocs.io

 

# set a directory to save DALL-E images to
image_dir_name = "images"
image_dir = os.path.join(os.curdir, image_dir_name)

# create the directory if it doesn't yet exist
if not os.path.isdir(image_dir):
    os.mkdir(image_dir)

# print the directory to save to
print(f"{image_dir=}")

그 다음은 생성한 이미지를 저장할 폴더의 위치를 정해 줍니다.

폴더 이름은 images 가 되고 그 위치는 현재 디렉토리에 있습니다.

 

if 문은 만약에 현재 디렉토리 안에 images라는 폴더가 없다면 mkdir() 을 이용해서 폴더를 생성하게 됩니다.

print() 결과는 아래와 같습니다.

image_dir='.\\images'

 

Generations

The generation API endpoint creates an image based on a text prompt.

 

generation API endpoint는 텍스트 프롬프트를 기반으로 이미지를 생성합니다.

 

Required inputs:

  • prompt (str): A text description of the desired image(s). The maximum length is 1000 characters.
  • 프롬프트(str): 원하는 이미지에 대한 텍스트 설명입니다. 최대 길이는 1000자입니다.

Optional inputs:

  • n (int): The number of images to generate. Must be between 1 and 10. Defaults to 1.
  • n (int): 생성할 이미지의 수. 1에서 10 사이여야 합니다. 기본값은 1입니다.
  • size (str): The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. Defaults to "1024x1024".
  • size (str): 생성된 이미지의 크기. "256x256", "512x512" 또는 "1024x1024" 중 하나여야 합니다.이미지가 작으면 더 빠릅니다.. 기본값은 "1024x1024"입니다.
  • response_format (str): The format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
  • response_format(str): 생성된 이미지가 반환되는 형식입니다. "url" 또는 "b64_json" 중 하나여야 합니다. 기본값은 "url"입니다.
  • user (str): A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. Learn more.

* user(str): OpenAI가 남용을 모니터링하고 감지하는 데 도움이 되는 최종 사용자를 나타내는 고유 식별자입니다. 

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

# create an image

# set the prompt
prompt = "Create picture for a Youtube channel Banner image named AI Madang, express the concept of Artificial Intellegent state-of-the-art technology and the concept of a play ground where human can play happily."

# call the OpenAI API
generation_response = openai.Image.create(
    prompt=prompt,
    n=1,
    size="1024x1024",
    response_format="url",
)

# print response
print(generation_response)

이 코드는 OpenAI 의 openai.Image.create() API를 사용해서 원하는 이미지를 만드는 과정입니다.

 

일단 내가 원하는 이미지를 prompt 변수에 담습니다.

저는 AI Madang 이라는 유투브 채널을 만들려고 하는데 그 채널의 Banner image로 사용할 최첨단 기술과 인간들의 놀이터 느낌이 나는 그림을 만들어 달라고 할 계획입니다.

 

그 다음은 openai.Image.create() API call 을 하는 부분 입니다. prompt가 들어가고 n은 그림 갯수를 나타내니까 그림은 1개만 만들라는 겁니다. 그리고 size는 1024X1024 입니다. response_format 은 url 이구요.

 

이 url을 이용해서 requests 모듈로 HTTP를 통해 이미지를 가져 오고 이것을 os 모듈을 이용해서 내 컴퓨터의 원하는 폴더에 저장 하는 작업을 할 겁니다.

그 이미지를 display 할 때 PIL 모듈의 Image 함수를 사용할 거구요.

 

저 같은 경우는 print 결과가 아래와 같이 나왔습니다.

 

 

OpenAI 에서 이미지가 생성 돼 있고 그 이미지가 위치해 있는 URL 을 받았습니다.

 

저 URL을 클릭하면 openai가 생성한 이미지가 나옵니다.

 

 

이미지가 마음에 안 들어서 몇 번 반복 했는데..... 여전히 마음에 안 드네요.

아직까지 저런 어려운 내용은 제대로 소화를 못 하는 것 같습니다.

 

어쨌든 오늘은 DALL-E API 를 공부하는 과정이니 그냥 넘어 가겠습니다.

 

Note: If you get this error - AttributeError: module 'openai' has no attribute 'Image' - you'll need to upgrade your OpenAI package to the latest version. You can do this by running pip install openai --upgrade in your terminal.

 

참고: AttributeError: module 'openai' has no attribute 'Image' 오류가 발생하면 OpenAI 패키지를 최신 버전으로 업그레이드해야 합니다. 터미널에서 pip install openai --upgrade를 실행하여 이를 수행할 수 있습니다.

 

# save the image
generated_image_name = "generated_image2.png"  # any name you like; the filetype should be .png
generated_image_filepath = os.path.join(image_dir, generated_image_name)
generated_image_url = generation_response["data"][0]["url"]  # extract image URL from response
generated_image = requests.get(generated_image_url).content  # download the image

with open(generated_image_filepath, "wb") as image_file:
    image_file.write(generated_image)  # write the image to the file

이제 이 이미지를 로컬에 저장하는 과정입니다.

generated_image2.png 라고 이름을 정할 생각입니다.

 

generated_image_filepath 라는 변수에 위에서 만들었던 images 라는 폴더 경로와 여기서 만들었던 이미지 파일 이름을 결합 시킵니다.

 

그리고 이미지가 있는 url 주소를 generated_image_url 에 담습니다.

 

그리고 requests 모듈의 get() 함수를 사용해서 그 이미지를 위 generated_image_url 로 다운로드 합니다.

 

그 다음 open() 메소드는 PIL 모듈에 있는 함수 입니다. 

 

https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open

 

Image Module

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, a...

pillow.readthedocs.io

 

wb 는 binary format으로 열라는 겁니다.

 

파이썬에서는 기본적으로 text 모드로 열게 되어 있는데 b 라는 의미는 이 텍스트가 아니라 바이너리 모드라는 의미 입니다. w 는 writing 입니다. 이와 반대로 r 은 reading 입니다. 읽기 모드가 아닌 쓰기 모드로 열라는 겁니다.

이렇게 하면 나중에 수정할 수 있습니다.

 

write() 함수를 사용해서 파일로 저장합니다. 이 함수는 Python 함수 입니다.

https://www.w3schools.com/python/ref_file_write.asp

 

Python File write() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

이제 생성된 이미지가 내 컴퓨터 안에 완전히 다운로드 됐습니다.

맨 오른쪽에 이 이미지가 있습니다. 나머지는 전에 연습 할 때 생성한 이미지들입니다.

# print the image
print(generated_image_filepath)
display(Image.open(generated_image_filepath))

이제 이 그림을 JupyterLab 화면에 display 해 보겠습니다.

print() 로는 파일 경로와 이름을 표시하고 display()는 이미지를 표시합니다.

 

실행 결과 입니다.

 

 

 

Variations

The variations endpoint generates new images (variations) similar to an input image.

 

변형(variation) endpoint 는 입력 이미지와 유사한 새 이미지(변형)를 생성합니다.

 

Here we'll generate variations of the image generated above.

 

여기서는 위에서 생성된 이미지의 변형을 생성합니다.

 

Required inputs:

  • image (str): The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
  • image(str): 변형의 기초로 사용할 이미지입니다. 유효한 PNG 파일이어야 하며 4MB 미만의 정사각형이어야 합니다.
  •  

Optional inputs:

  • n (int): The number of images to generate. Must be between 1 and 10. Defaults to 1.
  • n (int): 생성할 이미지의 수. 1에서 10 사이여야 합니다. 기본값은 1입니다.
  • size (str): The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. Defaults to "1024x1024".
  • size (str): 생성된 이미지의 크기. "256x256", "512x512" 또는 "1024x1024" 중 하나여야 합니다. 작은 이미지가 더 빠릅니다. 기본값은 "1024x1024"입니다.
  • response_format (str): The format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
  • response_format(str): 생성된 이미지가 반환되는 형식입니다. "url" 또는 "b64_json" 중 하나여야 합니다. 기본값은 "url"입니다.
  • user (str): A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. Learn more.
 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

user(str): OpenAI가 남용을 모니터링하고 감지하는 데 도움이 되는 최종 사용자를 나타내는 고유 식별자입니다. 

 

# create variations

# call the OpenAI API, using `create_variation` rather than `create`
variation_response = openai.Image.create_variation(
    image=generated_image,  # generated_image is the image generated above
    n=2,
    size="1024x1024",
    response_format="url",
)

# print response
print(variation_response)

 

이 코드는 위에서 생성된 이미지를 openai.Image.create_variation() API 를 사용해서 변형 시키는 겁니다.

이미지는 2개를 생성하고 크기는 1024X1024 입니다. response_format 은 url이구요.

 

프린트한 결과는 아래와 같습니다.

 

 

이미지를 2개 만들라고 했더니 URL도 두개가 나오네요.

 

클릭해 봤더니 다음과 같은 이미지들이 나옵니다.

 

 

 

# save the images
variation_urls = [datum["url"] for datum in variation_response["data"]]  # extract URLs
variation_images = [requests.get(url).content for url in variation_urls]  # download images
variation_image_names = [f"variation_image_{i}.png" for i in range(len(variation_images))]  # create names
variation_image_filepaths = [os.path.join(image_dir, name) for name in variation_image_names]  # create filepaths
for image, filepath in zip(variation_images, variation_image_filepaths):  # loop through the variations
    with open(filepath, "wb") as image_file:  # open the file
        image_file.write(image)  # write the image to the file

다음 코드는 이 두 이미지 파일을 로컬에 save 하는 과정입니다.

 

위의 과정과 똑 같은데 이미지가 두개 이므로 이것을 처리하기 위해 for 문을 사용했습니다.

 

실행 결과 입니다.

 

내 컴퓨터 안에 두개의 파일이 추가 됐습니다.

깜빡하고 이름을 바꾸지 않았더니 기존에 있는 이미지에 덮어 썼네요.

기존 이미지 두개는 날아갔습니다. 뭐 지금은 공부하는 중이니 상관은 없습니다.

실전에서는 아주 조심해야 겠네요. 자동으로 이름에 surfix 나 prefix 같은 것을 달아 주고 또 기존에 같은 이미지가 있으면 새 이미지에 surfix나 prefix 를 붙여주는 로직을 만들어야 겠죠.

 

# print the original image
print(generated_image_filepath)
display(Image.open(generated_image_filepath))

# print the new variations
for variation_image_filepaths in variation_image_filepaths:
    print(variation_image_filepaths)
    display(Image.open(variation_image_filepaths))

 

이 그림을 display 하는 스크립트 입니다.

위에서 한것과 똑 같은데 2개를 display 하기 때문에 for 문을 사용했습니다.

 

원본 파일을 display 하고 for 문 안에서는 변형 이미지 파일 2개를 display 합니다.

결과는 생성했던 3개 파일 모두 display 됩니다.

 

 

 

 

Edits

The edit endpoint uses DALL-E to generate a specified portion of an existing image. Three inputs are needed: the image to edit, a mask specifying the portion to be regenerated, and a prompt describing the desired image.

edit endpoint는 DALL-E를 사용하여 기존 이미지의 지정된 부분을 generate 합니다. 편집할 이미지, 재생성할 부분을 지정하는 마스크, 원하는 이미지를 설명하는 프롬프트의 세 가지 입력이 필요합니다.

 

 

Required inputs:

  • image (str): The image to edit. Must be a valid PNG file, less than 4MB, and square.
  • image (str): 편집할 이미지. 유효한 PNG 파일이어야 하며 4MB 미만의 정사각형이어야 합니다.
  • mask (str): An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where image should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as image.
  • 마스크(str): 완전히 투명한 영역(예: 알파가 0인 경우)이 이미지를 편집해야 하는 위치를 나타내는 추가 이미지입니다. 4MB 미만의 유효한 PNG 파일이어야 하며 이미지와 크기가 같아야 합니다.
  • prompt (str): A text description of the desired image(s). The maximum length is 1000 characters.
  • 프롬프트(str): 원하는 이미지에 대한 텍스트 설명입니다. 최대 길이는 1000자입니다.

 

Optional inputs:

  • n (int): The number of images to generate. Must be between 1 and 10. Defaults to 1.
  • n (int): 생성할 이미지의 수. 1에서 10 사이여야 합니다. 기본값은 1입니다.
  • size (str): The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. Defaults to "1024x1024".
  • size (str): 생성된 이미지의 크기. "256x256", "512x512" 또는 "1024x1024" 중 하나여야 합니다. 작은 이미지가 더 빠릅니다. 기본값은 "1024x1024"입니다.
  • response_format (str): The format in which the generated images are returned. Must be one of "url" or "b64_json". Defaults to "url".
  • response_format(str): 생성된 이미지가 반환되는 형식입니다. "url" 또는 "b64_json" 중 하나여야 합니다. 기본값은 "url"입니다.
  • user (str): A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. Learn more.
 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

user(str): OpenAI가 남용을 모니터링하고 감지하는 데 도움이 되는 최종 사용자를 나타내는 고유 식별자입니다. 

 

Set Edit Area

An edit requires a "mask" to specify which portion of the image to regenerate. Any pixel with an alpha of 0 (transparent) will be regenerated. The code below creates a 1024x1024 mask where the bottom half is transparent.

편집에는 재생성할 이미지 부분을 지정하는 "마스크"가 필요합니다. 알파가 0(투명)인 모든 픽셀이 재생성됩니다. 아래 코드는 아래쪽 절반이 투명한 1024x1024 마스크를 만듭니다.

# create a mask
width = 1024
height = 1024
mask = Image.new("RGBA", (width, height), (0, 0, 0, 1))  # create an opaque image mask

# set the bottom half to be transparent
for x in range(width):
    for y in range(height // 2, height):  # only loop over the bottom half of the mask
        # set alpha (A) to zero to turn pixel transparent
        alpha = 0
        mask.putpixel((x, y), (0, 0, 0, alpha))

# save the mask
mask_name = "bottom_half_mask.png"
mask_filepath = os.path.join(image_dir, mask_name)
mask.save(mask_filepath)

이렇게 생성한 마스크는 아래 반쪽만 알파갑을 준 것입니다. 그냥 눈으로 보면 별 티는 안 납니다.

 

Perform Edit

Now we supply our image, caption and mask to the API to get 5 examples of edits to our image

 

이제 이미지, 캡션 및 마스크를 API에 제공하여 이미지 편집의 5가지 예를 얻습니다.

 

# edit an image

# call the OpenAI API
edit_response = openai.Image.create_edit(
    image=open(generated_image_filepath, "rb"),  # from the generation section
    mask=open(mask_filepath, "rb"),  # from right above
    prompt=prompt,  # from the generation section
    n=1,
    size="1024x1024",
    response_format="url",
)

# print response
print(edit_response)

openai.Image.create_edit() API 를 사용해서 원본 이미지를 편집을 합니다.

 

결과는 아래와 같습니다.

 

 

URL을 클릭을 하니 아래와 같은 이미지가 나옵니다.

 

# save the image
edited_image_name = "edited_image.png"  # any name you like; the filetype should be .png
edited_image_filepath = os.path.join(image_dir, edited_image_name)
edited_image_url = edit_response["data"][0]["url"]  # extract image URL from response
edited_image = requests.get(edited_image_url).content  # download the image

with open(edited_image_filepath, "wb") as image_file:
    image_file.write(edited_image)  # write the image to the file

 

이 이미지 파일을 로컬에 저장합니다.

 

edited_image.png 파일이 생겼습니다.

사실은 기존에 있던 파일에 덮어 쓰기를 했습니다.

 

보시면 원본파일은 generated_image2.png 에서 아래 절반이 바뀐 것을 보실 수 있습니다.

 

# print the original image
print(generated_image_filepath)
display(Image.open(generated_image_filepath))

# print edited image
print(edited_image_filepath)
display(Image.open(edited_image_filepath))

이 부분은 Jupyterlab에 display 하는 부분 입니다.

원본과 편집본 두개를 display 합니다.

 

 

이렇게 하니까 아래 절 반이 바뀐 것을 쉽게 알 수가 있네요.

 

여기까지 OpenAI 의 DALL-E API 를 공부해 봤습니다.

반응형

OpenAI Update - Silicon Valley Bank (SVB)

2023. 3. 16. 22:44 | Posted by 솔웅


반응형

어제 (3/15/2023) OpenAI 에서 이메일이 하나 왔습니다.

이번에 문제가 되고 있는 Silicon Valley Bank (SVB) 파산과 관련 OpenAI는 영향을 받지 않았다는 메일 입니다.

이와 관련해서 OpenAI에서 요청하는 것처럼 속이고 사용 요금 등을 청구하는 사기에 조심하라는 내용 입니다.

Dear customer,

We want to inform you that OpenAI has not been impacted by the evolving situation at Silicon Valley Bank. 

 

OpenAI는 Silicon Valley Bank의 진화하는 상황에 영향을 받지 않았음을 알려드립니다.

 

In light of this fact we wanted to remind our customers to be vigilant of any requests for payment that appear suspicious or unusual; 

 

이 사건에 비추어 우리는 고객님들께 의심스럽거나 비정상적으로 보이는 요금 지불 요청에 대해 경계해 주실것을 상기시켜 드리고자 이 이메일을 드립니다.

 

official communications about payments will originate from AR@openai.com or our payment processor, Stripe, and we encourage customers to reach out to us at any time with questions or to verify payment instructions.

 

요금과 관련된 공식적인 커뮤니케이션은 AR@openai.com 이메일 이나 저희 시스템 상의 payment processor 인 Stripe 에서만 진행 됩니다.  고객님들께서 요금 지불 요청에 대해 검증을 원하시거나 어떠한 질문이 있으시면 저희에게 언제든지 연락 해 주세요.

We acknowledge the stress many are facing and extend our empathy and assistance.

 

우리는 많은 분들이 직면하고 있는 이 스트레스적인 상황을 인지하고 그 어려움에 대해 공감하며 가능한 지원을 확대해 나갈 것 입니다.

Best,
OpenAI

 

반응형

Open AI 의 GPT-4 Over view page

2023. 3. 15. 23:56 | Posted by 솔웅


반응형

어제 받았던 GPT-4 발표 이메일에 있는 GPT-4 Overview 페이지를 살펴 봤습니다.

 

https://openai.com/product/gpt-4

 

GPT-4

GPT-4 is more creative and collaborative than ever before. It can generate, edit, and iterate with users on creative and technical writing tasks, such as composing songs, writing screenplays, or learning a user’s writing style.

openai.com

 

제목에서는 GPT-4 가 Open AI의 가장 진보된 시스템이고 더 안전하고 유용한 답변을 한다고 돼 있습니다.

이 GPT-4 API를 사용하려면 API waitlist에 등록 해야 합니다.

 

 

GPT-4는 폭넓은 일반 지식과 문제 해결 능력 덕분에 어려운 문제를 더 정확하게 풀 수 있습니다.

라고 말을 하고 있고 그 아래 GPT-4에서 개선 된 부분들에 대해 나옵니다.

우선 Creativity와 Visual input 그리고 Longer context 이렇게 3개의 탭이 있습니다.

 

Creativity 부터 볼까요?

 

GPT4 is more creative and collaborative than ever before. It can generate, edit, and iterate with users on creative and technical writing tasks, such as composing songs, writing screenplays, or learning a user’s writing style.

 

GPT-4는 그 어느 때보다 창의적이고 협력적입니다. 노래 작곡, 시나리오 작성 또는 사용자의 작문 스타일 학습과 같은 창의적이고 기술적인 작문 작업에서 사용자와 함께 생성, 편집 및 반복할 수 있습니다.

 

Input
Explain the plot of Cinderella in a sentence where each word has to begin with the next letter in the alphabet from A to Z, without repeating any letters.

 

Output
A beautiful Cinderella, dwelling eagerly, finally gains happiness; inspiring jealous kin, love magically nurtures opulent prince; quietly rescues, slipper triumphs, uniting very wondrously, xenial youth zealously.

 

input으로 아래와 같은 요구를 했습니다.

문자를 반복하지 않고 A부터 Z까지 알파벳의 다음 문자로 각 단어가 시작되어야 하는 문장으로 신데렐라의 줄거리를 설명합니다.

 

그랬더니 신데렐라의 줄거리를 진짜 A 부터 Z까지 시작하는 단어들을 차례대로 사용해서 설명을 했습니다.

 

두번째는 Visual input 분야 입니다.

 

이미지 파일을 주고 이 재료들을 가지고 무엇을 만들 수 있냐고 물었더니...

 

이런 답변을 했네요. 그림만 보고 그 안에 있는 재료들을 판단해서 거기에 맞는 가능한 요리들을 보여 줬습니다.

 

그 다음은 아주 긴 input 값을 받을 수 있다는 내용입니다.

 

GPT-4 is capable of handling over 25,000 words of text, allowing for use cases like long form content creation, extended conversations, and document search and analysis.

 

GPT-4는 25,000단어 이상의 텍스트를 처리할 수 있어 긴 형식의 콘텐츠 생성, 확장된 대화, 문서 검색 및 분석과 같은 사용 사례를 허용합니다.

 

예제로는 리하나의 위키피디아의 내용을 입력값으로 주고 이번 Super Bowl 공연에 대해 물어보고 GPT-4 가 대답하는 내용이 있습니다.

 

그 다음에는  GPT-4 는 작년 말에 발표 되서 센세이션을 일으켰던 ChatGPT 보다 더 성능이 좋다는 내용이 있습니다.

 

ChatGPT가 제대로 답을 못한 것을 CPT-4 는 대답한 예 입니다.

이건 ChatGPT가 오답을 냈던게 문제 아니었을까요? 하여간 GPT-4는 정답을 얘기 했네요.

 

Uniform Bar Exam 과 Biology Olympiad 라는 테스트 경진 대회에서 GPT-4 가 ChatGPT 보다 더 높은 점수를 기록했다는 내용 입니다.

참고로 ChatGPT는 GPT-3.5 버전입니다.

 

밑의 설명은 GPT가 버전 2, 3, 3.5, 4 이렇게 진행돼 오면서 점점 더 정교하고 유능한 모델이 되어 가고 있다는 내용입니다.

 

We spent 6 months making GPT-4 safer and more aligned. GPT4 is 82% less likely to respond to requests for disallowed content and 40% more likely to produce factual responses than GPT-3.5 on our internal evaluations.

 

우리는 6개월 동안 GPT-4를 더 안전하고 더 잘 정렬되도록 만들었습니다. GPT-4는 허용되지 않는 콘텐츠에 대한 요청에 응답할 가능성이 82% 적고 내부 평가에서 GPT-3.5보다 사실에 입각한 응답을 할 가능성이 40% 더 높습니다.

 

Safety & alignment

 

Training with human feedback
We incorporated more human feedback, including feedback submitted by ChatGPT users, to improve GPT-4’s behavior. We also worked with over 50 experts for early feedback in domains including AI safety and security.

 

GPT-4의 동작을 개선하기 위해 ChatGPT 사용자가 제출한 피드백을 포함하여 더 많은 사람의 피드백을 통합했습니다. 또한 AI 안전 및 보안을 포함한 도메인의 초기 피드백을 위해 50명 이상의 전문가와 협력했습니다.

Continuous improvement from real-world use
We’ve applied lessons from real-world use of our previous models into GPT-4’s safety research and monitoring system. Like ChatGPT, we’ll be updating and improving GPT-4 at a regular cadence as more people use it.

 

우리는 이전 모델의 실제 사용에서 얻은 교훈을 GPT-4의 안전 연구 및 모니터링 시스템에 적용했습니다. ChatGPT와 마찬가지로 더 많은 사람들이 사용함에 따라 정기적으로 GPT-4를 업데이트하고 개선할 것입니다.

GPT-4-assisted safety research
GPT-4’s advanced reasoning and instruction-following capabilities expedited our safety work. We used GPT-4 to help create training data for model fine-tuning and iterate on classifiers across training, evaluations, and monitoring.

 

GPT-4의 고급 추론 및 지시에 따른 기능은 우리의 안전 작업을 가속화했습니다. GPT-4를 사용하여 모델 미세 조정을 위한 훈련 데이터를 생성하고 훈련, 평가 및 모니터링 전반에 걸쳐 분류기를 반복했습니다.

 

그 다음 아래 부터는 실제 이 GPT-4를 사용해서 제품을 생산 판매 하고 있는 회사와 그 제품을 나열 했습니다.

나머지 회사와 제품들은 직접 한번 보세요.

 

이 중에서 Speak 라는 업체는 한국 업체인 것으로 알고 있습니다.

 

다음 단락에서는 GPT-4 에 대한 몇가지 추가적인 정보를 주고 있습니다.

 

Research

 

GPT-4는 OpenAI의 딥 러닝 확장 노력의 최신 이정표입니다.

https://openai.com/research/gpt-4

 

GPT-4

We’ve created GPT-4, the latest milestone in OpenAI’s effort in scaling up deep learning. GPT-4 is a large multimodal model (accepting image and text inputs, emitting text outputs) that, while less capable than humans in many real-world scenarios, exhi

openai.com

 

위 페이지에서는 GPT-4 관련 한 방대한 Research 내용을 보실 수 있습니다.

 

 

Infrastructure

GPT-4는 Microsoft Azure AI 슈퍼컴퓨터에서 교육을 받았습니다. Azure의 AI 최적화 인프라를 통해 전 세계 사용자에게 GPT-4를 제공할 수도 있습니다.

 

Limitations

GPT-4에는 사회적 편견, 환각, 적대적 프롬프트와 같이 우리가 해결하기 위해 노력하고 있는 많은 알려진 한계가 있습니다. 우리는 사회가 이러한 모델을 채택함에 따라 투명성, 사용자 교육 및 광범위한 AI 활용 능력을 장려하고 촉진합니다. 우리는 또한 우리 모델을 형성하는 데 사람들이 입력할 수 있는 방법을 확장하는 것을 목표로 합니다.

 

Availability

GPT-4는 ChatGPT Plus에서 사용할 수 있으며 개발자가 애플리케이션 및 서비스를 구축하기 위한 API로 사용할 수 있습니다.

 

https://openai.com/contributions/gpt-4

 

GPT-4 contributions

Core contributorsTrevor Cai Execution leadMark Chen Vision team co-lead, Deployment leadCasey Chu Initial prototype leadChris Hesse Data load balancing & developer tooling leadShengli Hu Vision Safety Evaluations leadYongjik Kim GPU performance

openai.com

https://chat.openai.com/

 

 

https://openai.com/waitlist/gpt-4-api

 

GPT-4 API waitlist

We’re making GPT-4 available as an API for developers to build applications and services.

openai.com

 

저는 이메일 받자마자 GPT-4 API waitlist에 등록 했습니다.

 

지금 GPT-3 API 의 Cookbook을 공부하고 있는데 그 와중에 3월 1일에 GPT 3.5 (ChatGPT) API 가 공개 됐고 이제 3월 14일에 GPT-4 API 가 공개 됐네요.

 

따라가면서 공부하기에도 벅차게 발전하고 있습니다.

 

하여간 계속 공부해 보겠습니다.

반응형


반응형

요즘은 Cook Book의 Fine-tuning을 공부하고 있는데요.

어제 OpenAI에서 GPT-4가 나와서 업데이트 이메일이 왔습니다.

 

 

간단하게 살펴 보겠습니다.

 

우선 live demo link는 아래와 같습니다.

 

https://www.youtube.com/live/outcGtbnMuQ?feature=share 

여기서는 GPT-4에 대해 설명하는데 모든 단어를 G로 시작하는 단어를 사용해서 설명해 봐.. 뭐 이런 작업도 보여 주고 시를 쓰는 장면도 보여 주고 하더라구요. GPT-3 에서는 하지 못했던 좀 더 성장한 GPT 기능을 보여 줬구요.

뭐니뭐니해서 GPT-4에서 가장 달라진 점은 Language 이외의 멀티미디어 기능 지원등이 있었습니다.

GPT-4 가 이미지를 인식해서 그 이미지에 대한 설명도 하고 작업도 하고 그러더라구요.

자세한 사항은 위 유투브 클립을 한번 보세요.

 

이메일 내용은 아래와 같았습니다.

 

We’ve created GPT-4, our most capable model. We are starting to roll it out to API users today.
Please join us today, March 14th, at 1 pm PDT for a live demo of GPT-4.
우리는 GPT-4를 만들었습니다. 가장 유능한 모델이죠. 우리는 오늘부터 API 사용자들에게 이 모델을 배포하기 시작했습니다.
 
About GPT-4
GPT-4 can solve difficult problems with greater accuracy, thanks to its broader general knowledge and advanced reasoning capabilities.
GPT-4는 광범위한 일반 지식과 고급 추론 기능 덕분에 어려운 문제를 더 정확하게 풀 수 있습니다.

 

 

You can learn more through: 아래 글들을 통해서 이를 배울 수 있습니다.

  • Overview page of GPT-4 and what early customers have built on top of the model.
  • GPT-4의 개요 페이지 - 초기 고객이 모델 위에 구축한 것.
  • Blog post with details on the model’s capabilities and limitations, including eval results.
  • 평가 결과를 포함하여 모델의 기능 및 제한 사항에 대한 세부 정보가 포함된 블로그 게시물

 

Availability

  • API Waitlist: Please sign up for our waitlist to get rate-limited access to the GPT-4 API – which uses the same ChatCompletions API as gpt-3.5-turbo. We’ll start inviting some developers today, and scale up availability and rate limits gradually to balance capacity with demand.
  • API 대기자 명단: gpt-3.5-turbo와 동일한 ChatCompletions API를 사용하는 GPT-4 API에 대한 rate-limited 액세스 권한을 얻으려면 대기자 명단에 등록하십시오. 오늘 일부 개발자를 초대하고 용량과 수요의 균형을 맞추기 위해 가용성 및 rate-limited을 점진적으로 확장할 것입니다.
  • Priority Access: Developers can get prioritized API access to GPT-4 for contributing model evaluations to OpenAI Evals that get merged, which will help us improve the model for everyone.
  • Priority Access: 개발자는 병합되는 OpenAI 평가에 대한 모델 평가에 기여하기 위해 GPT-4에 대한 prioritized  API 액세스를 얻을 수 있으며, 이는 모든 사람을 위해 모델을 개선하는 데 도움이 됩니다.
  • ChatGPT Plus: ChatGPT Plus subscribers will get GPT-4 access on chat.openai.com with a dynamically adjusted usage cap. We expect to be severely capacity constrained, so the usage cap will depend on demand and system performance. API access will still be through the waitlist.
  • ChatGPT Plus: ChatGPT Plus 가입자는 chat.openai.com에서 동적으로 조정된 사용 한도와 함께 GPT-4 액세스 권한을 얻습니다. 용량이 심각하게 제한될 것으로 예상되므로 사용량 한도는 수요와 시스템 성능에 따라 달라집니다. API 액세스는 여전히 대기자 명단을 통해 이루어집니다.

 

API Pricing

gpt-4 with an 8K context window (about 13 pages of text) will cost $0.03 per 1K prompt tokens, and $0.06 per 1K completion tokens.
 
8K 컨텍스트 창(약 13페이지의 텍스트)이 있는 gpt-4는 1K 프롬프트 토큰당 $0.03, completion  토큰 1K당 $0.06입니다.

gpt-4-32k with a 32K context window (about 52 pages of text) will cost $0.06 per 1K prompt tokens, and $0.12 per 1K completion tokens.
 
32K 컨텍스트 창(약 52페이지의 텍스트)이 있는 gpt-4-32k는 프롬프트 토큰 1,000개당 $0.06, completion  토큰 1,000개당 $0.12입니다.

 

Livestream
Please join us for a live demo of GPT-4 at 1pm PDT today, where Greg Brockman (co-founder & President of OpenAI) will showcase GPT-4’s capabilities and the future of building with the OpenAI API.
오늘 오후 1시(PDT) GPT-4 라이브 데모에 참여하세요. Greg Brockman(OpenAI 공동 창립자 겸 사장)이 GPT-4의 기능과 OpenAI API로 구축하는 미래를 선보일 예정입니다.
 

—The OpenAI team

반응형


반응형

오늘은 오랜만에 실습 예제 입니다.

 

Fine-tunning을 실제로 해 보도록 하겠습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

Fine tuning classification example

아래 예제는 ada 모델을 이용해서 이메일 내용을 보고 이게 Baseball과 연관 돼 있는지 아니면 Hockey와 연관 돼 있는 건지 GPT-3 가 인지할 수 있도록 Fine-Tuning을 사용해서 훈련시키고 새로운 모델을 만드는 과정을 보여 줍니다.

 

from sklearn.datasets import fetch_20newsgroups
import pandas as pd
import openai

categories = ['rec.sport.baseball', 'rec.sport.hockey']
sports_dataset = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, categories=categories)

 

이 예제에서 사용하는 데이터는 sklearn에서 제공하는 샘플 데이터인 fetch_20newsgroups를 사용합니다.

 

fetch_20newsgroups 는 데이터를 다루는 연습용으로 만들어진 데이터 세트 입니다.

20개의 newsgroup에서 데이터를 가져온 겁니다. 이 뉴스그룹들은 대부분 게시판이고 사용자들이 올른 글들이 데이터가 되는 겁니다. 예를 들어 내가 낚시에 관심이 있어서 낚시 관련된 카페 같은 뉴스 그룹에 가입하고 거기에 글을 올리듯이 사람들이 글을 올린 데이터 들 입니다.

 

여기에는 20개의 주제들이 있습니다. 그리고 총 샘플들은 18846개가 있고 1차원 배열이고 text로 이뤄져 있습니다.

 

이 중에서 Baseball 과 Hockey 관련된 데이터를 가지고 이 예제에서는 Fine-Tuning을 연습하는 소스코드를 만들게 됩니다.

 

https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_20newsgroups.html

 

sklearn.datasets.fetch_20newsgroups

Examples using sklearn.datasets.fetch_20newsgroups: Biclustering documents with the Spectral Co-clustering algorithm Biclustering documents with the Spectral Co-clustering algorithm Topic extractio...

scikit-learn.org

참고로 이 데이터세트에는 아래와 같은 주제들의 글들이 있습니다.

 

'alt.atheism',
 'comp.graphics',
 'comp.os.ms-windows.misc',
 'comp.sys.ibm.pc.hardware',
 'comp.sys.mac.hardware',
 'comp.windows.x',
 'misc.forsale',
 'rec.autos',
 'rec.motorcycles',
 'rec.sport.baseball',
 'rec.sport.hockey',
 'sci.crypt',
 'sci.electronics',
 'sci.med',
 'sci.space',
 'soc.religion.christian',
 'talk.politics.guns',
 'talk.politics.mideast',
 'talk.politics.misc',
 'talk.religion.misc'

https://scikit-learn.org/stable/datasets/real_world.html#newsgroups-dataset

 

7.2. Real world datasets

scikit-learn provides tools to load larger datasets, downloading them if necessary. They can be loaded using the following functions: The Olivetti faces dataset: This dataset contains a set of face...

scikit-learn.org

 

그리고 Pandas와 openai 모듈을 import 합니다.

 

관련 모듈을 import 한 다음에 한 일은 이 예제에서 다룰 topic들을 선택하는 겁니다. 이 두 topic들을 categories라는 배열 변수에 아이템으로 넣습니다.

그리고 sports_dataset 라는 변수에 이 fetch_20newsgroups에 있는 데이터 들 중 위에서 선택한 rec.sport.baseball과 rec.sport.hockey 뉴스그룹에 있는 데이터들만 담습니다.

 

데이터를 다루려면 우선 그 데이터으 구조를 잘 알아야 합니다.

 

이 데이터의 첫번째 데이터만 한번 출력해 보겠습니다.

print(sports_dataset['data'][0])

그러면 결과는 이렇게 나옵니다.

From: dougb@comm.mot.com (Doug Bank)
Subject: Re: Info needed for Cleveland tickets
Reply-To: dougb@ecs.comm.mot.com
Organization: Motorola Land Mobile Products Sector
Distribution: usa
Nntp-Posting-Host: 145.1.146.35
Lines: 17

In article <1993Apr1.234031.4950@leland.Stanford.EDU>, bohnert@leland.Stanford.EDU (matthew bohnert) writes:

|> I'm going to be in Cleveland Thursday, April 15 to Sunday, April 18.
|> Does anybody know if the Tribe will be in town on those dates, and
|> if so, who're they playing and if tickets are available?

The tribe will be in town from April 16 to the 19th.
There are ALWAYS tickets available! (Though they are playing Toronto,
and many Toronto fans make the trip to Cleveland as it is easier to
get tickets in Cleveland than in Toronto.  Either way, I seriously
doubt they will sell out until the end of the season.)

-- 
Doug Bank                       Private Systems Division
dougb@ecs.comm.mot.com          Motorola Communications Sector
dougb@nwu.edu                   Schaumburg, Illinois
dougb@casbah.acns.nwu.edu       708-576-8207

데이터는 글을 올린사람, 주제, Reply-To,, Organization, Distribution, 아이피 주소. 라인 수, 내용 등등등 ...

대충 어떤 식으로 데이터들이 구성 돼 있는지 알 수 있을 것 같습니다.

 

이건 sports_dataset 의 data라는 아이템에 들어 있는 첫 번째 데이터인 것이고 이 sports_dataset은 어떤 구조로 돼 있는지 한번 알아 볼까요?

 

#print(sports_dataset['data'][0])
print(sports_dataset)

결과의 일 부분인데요. sports_dataset 배열은 첫번째 item 이 data 입니다. 그리고 이 data 안에는 여러 글들이 있습니다. 각 글들은 From: 으로 시작합니다. 첫번째 글은 바로 위에서 출력한 그 글입니다. dougb@comm.mot.com으로 시작해서 708-576-8207 로 끝납니다.

data는 이렇게 구성이 돼 있고 그렇다면 다른 아이템에는 무엇이 있을 까요?

 

그 다음에는 target_names인데 이 변수에는 baseball과 hockey 토픽만 들어 있다는걸 확인 할 수 있습니다.

그리고 'target' : array(0,1,0...,... 이렇게 돼 있는 것은 data의 첫번째 데이터는 baseball 뉴스그룹에서 온 것이고 두번째 데이터는 hockey 그룹에서 그리고 세번째는 baseball 그룹에서 온 것이라는 것을 말합니다.

data에 있는 데이터 가지고는 이것이 어느 뉴스그룹 소속인지 알 수 없는데 이 target_names 라는 두번째 아이템에서 그 정보를 얻을 수 있네요.

 

오늘 다룰 Fine-Tunning 예제에서는 이 두가지 정보만 있으면 GPT-3 AI 를 훈련 시킬 수 있습니다.

 

참고로 target_names의 아이템만 알 수 있는 방법은 아래와 같습니다.

 

sports_dataset.target_names[sports_dataset['target'][0]]

그러면 결과 값은 아래와 같습니다.

'rec.sport.baseball'

 

그러면 전체 데이터와 각 주제별 데이터 갯수를 한번 알아 보겠습니다.

 

len_all, len_baseball, len_hockey = len(sports_dataset.data), len([e for e in sports_dataset.target if e == 0]), len([e for e in sports_dataset.target if e == 1])
print(f"Total examples: {len_all}, Baseball examples: {len_baseball}, Hockey examples: {len_hockey}")

len(sports_dataset.data) 는 이 sports_dataset에 있는 data 아이템에 있는 데이터 수를 가져 옵니다.

len([e for e in sports_dataset.target if e == 0] 는 data에 있는 데이터 중 target 이 0인 데이터 즉 rec.sport.baseball에 속한 데이터만 가져 옵니다. 

같은 방법으로 Hockey 에 속한 데이터만 가져 오려면 이러헥 사용 합니다. len([e for e in sports_dataset.target if e == 1]

결과는 아래와 같습니다.

Total examples: 1197, Baseball examples: 597, Hockey examples: 600

전체 데이터 갯수는 1197개이고 야구와 관련된 글은 597개 그리고 하키와 관련된 글은 600개 입니다.

 

이제 이 데이터의 구조에 대해서 어느정도 파악을 했습니다.

 

그러면 이 데이터를 Fune-Tuning 시키기 위한 구조로 바꾸어 주어야 합니다.

Fine-Tunning은 AI를 교육 시키는 겁니다. 이 AI를 교육시키기 위해서는 데이터를 제공해야 합니다.

GPT-3라는 AI가 알아 들을 수 있는 데이터 구조는 이전 Guide에서 설명 된 부분이 있습니다.

 

GPT-3는 Prompt 와 Completion 이 두 부분으로 나뉘어진 데이터세트를 제공하면 됩니다.

그러면 이 아이는 그것을 보고 패턴을 찾아내서 학습하게 되는 겁니다.

이런 내용의 글은 야구와 관련 돼 있고 또 저런 내용의 글은 하키와 관련 돼 있다는 것을 알아 내는 것이죠.

 

예를 들어 위에서 출력한 첫번째 글을 보시죠.

 

여기에는 이 글이 야구와 관련돼 있는지 하키와 관련 돼 있는지에 대한 명시적인 정보는 없습니다.

다면 이 글에는 Cleveland에 갈거고 팬들끼리 좀 모이자는 내용이 있습니다. 그리고 상대팀 이름도 있고 어디서 경기가 열리는지 뭐 이런 정보가 있습니다.

미국에서 야구에 대해 관심 있는 사람이라면 이 글은 야구와 관련된 글이라는 것을 알겠죠.

이렇게 주어진 정보만 가지고 이게 야구와 관련된 글인지 하키와 관련된 글인지 알아 내도록 GPT-3를 훈련 시킬 겁니다.

그 훈련된 AI모델은 나만의 모델이 될 겁니다.

그래서 앞으로 내가 어떤 글을 그 모델에게 보내면 그 Custom AI Model은 그게 야구와 관련된 글인지 하키와 관련된 글인지를 저에게 알려 줄 것입니다.

 

Fine Tuning과 관련 한 기초적인 내용을 아시려면 아래 블로그 글을 참조하세요.

 

https://coronasdk.tistory.com/1221

 

Guides - Fine tuning

https://beta.openai.com/docs/guides/fine-tuning OpenAI API An API for accessing new AI models developed by OpenAI beta.openai.com Fine-tuning Learn how to customize a model for your application. 당신의 어플리케이션을 위해 어떻게 모델을

coronasdk.tistory.com

 

그러면 GPT-3를 훈련 시키기 위한 데이터 세트 형식으로 위 데이터를 변경 시켜 보겠습니다.

Prompt 와 Completion 이 두가지 컬럼이 있어야 합니다.

Prompt에는 data 정보들이 있고 Completion에는 그 글이 야구와 관련된 글인지 하키와 관련된 글인지에 대한 정보들이 들거 갈 겁니다.

 

import pandas as pd

labels = [sports_dataset.target_names[x].split('.')[-1] for x in sports_dataset['target']]
texts = [text.strip() for text in sports_dataset['data']]
df = pd.DataFrame(zip(texts, labels), columns = ['prompt','completion']) #[:300]
df.head()

파이썬에서 데이터를 다루는 모델은 pandas를 많이 사용 합니다.

 

labels 부분을 보겠습니다.

위에서 sports_dataset['target'] 에는 0 과 1이라는 정보들이 있고 이 정보는 data에 있는 정보가 targetnames 의 첫번째 인수에 속하는 건지 두번째 인수에 속하는 건지를 알려 주는 것이라고 했습니다.

첫번째 인수는 rec.sport.baseball이고 두번째 인수는 rec.sport.hockey 입니다.

 

이 target 값에 대한 for 문이 도는데요 data 갯수가 1197이고 target의 각 인수들 (0,1) 은 각 데이터의 인수들과 매핑 돼 있으니까 이 for 문은 1197번 돌 겁니다. 이렇게 돌면서 target_names에서 해당 인수를 가져 와서 . 으로 그 텍스트를 분리 한 다음에 -1 번째 즉 맨 마지막 글자를 가지고 오게 됩니다. 그러면 baseball과 hockey라는 글자만 선택 되게 되죠.

즉 labels에는 baseball 과 hockey라는 글자들이 들어가게 되는데 이는 target 에 0이 있으면 baseball 1이 있으면 hockey가 들어가는 1197개의 인수를 가지고 있는 배열이 순서대로 들어가게 되는 겁니다.

 

그러면 이제 data에 있는 각 데이터를 순서대로 배열로 집어 넣으면 되겠죠?

texts = [text.strip() for text in sports_dataset['data']]

이 부분이 그 일을 합니다.

sports_dataset 에 있는 data 만큼 for 문을 돕니다. data는 1197개의 인수를 가지고 있으니 이 for 문도 1197번 돌 겁니다.

이 데이터를 그냥 texts 라는 변수에 배열 형태로 집어 넣는 겁니다. text.strip()은 해당 text의 앞 뒤에 있는 공백들을 제거 하는 겁니다.

이 부분도 중요 합니다. 데이터의 앞 뒤 공백을 제거해서 깨끗한 데이터를 만듭니다.

 

이제 data의 각 글을 가지고 있는 배열과 각 글들이 어느 주제에 속하는지에 대한 정보를 가지고 있는 배열들이 완성 됐습니다.

이 정보를 가지고 pandas로 GPT-3 AI 를 훈련 시킬 수 있는 형태의 데이터 세트로 만들겠습니다.

 

파이썬에서 zip() 함수는 두 배열을 튜플 형식으로 짝 지어 주는 함수 입니다. 

https://www.w3schools.com/python/ref_func_zip.asp

 

Python zip() Function

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

아래와 같이 두 배열의 인수들을 짝 지어 줍니다.

zip(texts, labels) <- 이렇게 하면 데이터와 topic이 짝 지어 지겠죠.

이 값은 pandas의 DataFrame의 첫번째 인수로 전달 되고 두번째 인수로는 컬럼 이름이 전달 됩니다. (columns = ['prompt','completion'])

 

그 다음 df.head() 로 이렇게 만들어진 DataFrame에서 처음에 오는 5개의 데이터를 출력해 봅니다.

 

의도한 대로 각 게시글과 그 게시글이 baseball에 속한 것인지 hockey에 속한 것인지에 대한 정보가 있네요.

 

이 cookbook에는 300개의 데이터만 사용할 것이라고 돼 있는데 어디에서 그게 돼 있는지 모르겠네요.

len() 을 찍어봐도 1197 개가 찍힙니다.

cookbook 설명대로 300개의 데이터만 사용하려면 아래와 같이 해야 할 것 같습니다.

 

import pandas as pd

labels = [sports_dataset.target_names[x].split('.')[-1] for x in sports_dataset['target']]
texts = [text.strip() for text in sports_dataset['data']]
df = pd.DataFrame(zip(texts, labels), columns = ['prompt','completion']) #[:300]
df = df.head(300)
print(df)

저는 이 300개의 데이터만 이용하겠습니다.

GPT-3 의 Fine-tuning 을 사용할 때 데이터 크기에 따라서 과금 될 거니까.. 그냥 조금만 하겠습니다. 지금은 공부하는 단계이니까 Custom model의 정확도 보다는 Custom model을 Fine tuning을 사용해서 만드는 과정을 배우면 되니까요.

 

그 다음은 이 DataFrame을 json 파일로 만드는 겁니다.

 

df.to_json("sport2.jsonl", orient='records', lines=True)

to_json() 함수를 사용해서 sport2.jsonl 이라는 파일을 만듭니다. 

orient='records' 라는 말은 리스트 형태가 된다는 얘기입니다.

 

orient   str

Indication of expected JSON string format.

  • Series:
    • default is ‘index’
    • allowed values are: {‘split’, ‘records’, ‘index’, ‘table’}.
  • DataFrame:
    • default is ‘columns’
    • allowed values are: {‘split’, ‘records’, ‘index’, ‘columns’, ‘values’, ‘table’}.
  • The format of the JSON string:
    • ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
    • ‘records’ : list like [{column -> value}, … , {column -> value}]
    • ‘index’ : dict like {index -> {column -> value}}
    • ‘columns’ : dict like {column -> {index -> value}}
    • ‘values’ : just the values array
    • ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}}

    Describing the data, where data component is like orient='records'.

     

    lines = True는 orient가 records일 경우 True로 설정해야 합니다.

     

    linesbool, default False

    If ‘orient’ is ‘records’ write out line-delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not list-like.

     

    https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html

 

pandas.DataFrame.to_json — pandas 1.5.3 documentation

The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively. For on-the-fly compression of the output data. If ‘infer’ and ‘path_o

pandas.pydata.org

 

이 부분을 실행하면 해당 디렉토리에 sport2.jsonl 파일이 생성됩니다.

 

이 파일 내용은 아래와 같습니다.

 

prompt 에는 내용이 있고 completion에는 baseball나 hockey가 들어 있습니다. 총 300개의 prompt - completion 쌍이 있습니다.

 

Cookbook에는 다음 단계로 openai 를 업데이트 하라고 돼 있습니다. 

!pip install --upgrade openai

이렇게 해 줍니다. 저같은 경우는 자주 업데이트를 해 줘서 별로 변경되는 내용은 없었습니다.

 

이제 openai의 fine_tunes 함수를 사용할 차례입니다.

 

!openai tools fine_tunes.prepare_data -f sport2.jsonl -q

주피터 노트북에서는 위와 같이 입력하고 Command 창을 사용할 경우에는 !를 없앤 나머지 부분을 타이핑 하면 됩니다.

 

만약 이것을 실행했는데 아래와 같은 메세지가 보인다면 Environment Variable을 설정해 주면 됩니다.

이 문제를 해결하려면 아래 블로그 글을 확인하세요.

https://coronasdk.tistory.com/1295

 

openai 명령어를 command 창에서 인식을 하지 못 할 때...

아래와 같이 command 창에서 openai 를 인식하지 못하는 문제를 해결하는 방법을 알아 보겠습니다. 'openai' is not recognized as an internal or external command, operable program or batch file. 저같은 경우는 Windows에서 P

coronasdk.tistory.com

문제가 없다면 아래와 같은 결과가 나옵니다.

 

 

openai aools fine_tunes.prepare_data는 데이터를 검증하고 제안하고 형식을 다시 지정해 주는 툴입니다.

위 결과를 보면 Analyzing... (분석중)으로 시작해서 이 파일에는 총 300개의 prompt-completion 쌍이 있고 모델을 fine-tune 하려고 하는 것 같은데 저렴한 ada 모델을 사용하세요... 뭐 이렇게 분석과 제안내용이 표시됩니다.

그리고 너무 긴 글이 3개 있고 134, 200,281 번째 줄. .....이렇게 나오고 이 3개는 너무 길어서 제외한다고 나오네요.

 

이 결과로 sport2_prepared_train.jsonl 과 sport2_prepared_valid.jsonl 파일 두개를 만들어 냅니다.

그리고 이제 fine_tunes.create을 사용해서 fine-tuning을 하면 된다고 나오네요.

 

Fine-tuning을 하게 되면 curie 모델을 사용하면 대략 9분 46초 정도 걸릴 것이고 ada 모델을 사용하면 그보다 더 조금 걸릴 거라네요.

 

폴더를 다시 봤더니 정말 두개의 jsonl 파일이 더 생성 되었습니다.

 

sport2_prepared_train.jsonl에는 위에 너무 길다는 3개의 데이터를 없앤 나머지 297개의 데이터가 있습니다.

sport2_prepared_valid.jsonl에는 60개의 데이터가 있습니다.

 

train 데이터와 valid 데이터 이렇게 두개가 생성 되었네요. 이 두개를 생성한 이유는 나중에 새 데이터에 대한 예상 성능을 쉽게 측정하기 위해서 GPT-3 의 fine_tunes.prepare_data 함수가 만든 겁니다.

 

Fine-tuning

이제 다 준비가 됐습니다. 실제로 Fine tuning을 하면 됩니다.

참고로 지금 우리는 내용을 주면 이 내용이 야구에 대한건지 하키에 대한건지 분류 해 주는 fine tuned 된 모델을 생성하려고 합니다.

이 작업은 classification task에 속합니다.

그래서 train 과 valid 두 데이터 세트가 위에서 생성된 거구요.

 

이제 Fine-tuning을 하기 위해 아래 명령어를 사용하면 됩니다.

 

!openai api fine_tunes.create -t "sport2_prepared_train.jsonl" -v "sport2_prepared_valid.jsonl" --compute_classification_metrics --classification_positive_class " baseball" -m ada

 

fine_tunes.create 함수를 사용했고 training data로는 sport2_prepared_train.jsonl 파일이 있고 valid data로는 sport2.prepared_valid_jsonl이 제공된다고 돼 있습니다.

그 다음엔 compute_classification_metrics와 classification_positive_class "baseball" 이 주어 졌는데 이는 위에서 fine_tunes.prepare_data 에서 추천한 내용입니다. classification metics를 계산하기 위해 필요하기 때문에 추천 했습니다.

 

그리고 마지막에 -m ada는 ada 모델을 사용하겠다는 겁니다.

 

이 부분을 실행하면 요금이 청구가 됩니다.

Fine-tuning models 같은 경우 과금은 아래와 같이 됩니다.

 

ada 모델을 사용하니까 토큰 1천개당 0.0004불이 training 과정에 들게 됩니다.

Usage도 있네요 나중에 Fine Tune 된 Custom Model을 사용하게 되면 토큰 1천개당 0.0016 불이 과금 됩니다.

 

https://openai.com/pricing

 

Pricing

Simple and flexible. Only pay for what you use.

openai.com

 

저는 이 fine_tunes.create를 실행하고 30분이 넘었는데도 아무런 응답이 없어서 fine_tunes.list로 체크해 봤습니다.

 

 

그런데 이것도 답변이 없더라구요.

그래서 한참을 더 기다렸습니다.

결국 이날 되지 않아서 GPT-4 발표를 유투브에서 하길래 그 내용만 살펴 보다 끝났네요.

다음날 다시 Jupyterlab 실행 시키고 나서 !openai api fine_tunes.list 를 해 보았습니다.

이제 나왔네요.

저는 11일에도 한번 공부하다가 만든게 있어서 모델이 2개 나왔는데요.

그건 delete로 지워 버렸습니다.

!openai api models.delete -i ada:ft-personal-2023-03-11-15-30-13

결과는 아래와 같이나왔습니다.

{
  "deleted": true,
  "id": "ada:ft-personal-2023-03-11-15-30-13",
  "object": "model"
}

그 후 나온 list 에 대한 결과 입니다.

{
  "data": [
    {
      "created_at": 1678817966,
      "fine_tuned_model": "ada:ft-personal-2023-03-14-18-36-10",
      "hyperparams": {
        "batch_size": 1,
        "classification_positive_class": " baseball",
        "compute_classification_metrics": true,
        "learning_rate_multiplier": 0.1,
        "n_epochs": 4,
        "prompt_loss_weight": 0.01
      },
      "id": "ft-GI4Lb4z2d7TrYstNw15SXhlN",
      "model": "ada",
      "object": "fine-tune",
      "organization_id": "org-어카운트 organization ID",
      "result_files": [
        {
          "bytes": 51539,
          "created_at": 1678818971,
          "filename": "compiled_results.csv",
          "id": "file-5QHkdzACEhvgPxFAopnL4KUe",
          "object": "file",
          "purpose": "fine-tune-results",
          "status": "processed",
          "status_details": null
        }
      ],
      "status": "succeeded",
      "training_files": [
        {
          "bytes": 391121,
          "created_at": 1678817965,
          "filename": "sport2_prepared_train.jsonl",
          "id": "file-pxuc7tJA3rJ5mVI8HKWNe62p",
          "object": "file",
          "purpose": "fine-tune",
          "status": "processed",
          "status_details": null
        }
      ],
      "updated_at": 1678818971,
      "validation_files": [
        {
          "bytes": 89587,
          "created_at": 1678817966,
          "filename": "sport2_prepared_valid.jsonl",
          "id": "file-IDNYZdlWRpi6jhlKhqVs3OaQ",
          "object": "file",
          "purpose": "fine-tune",
          "status": "processed",
          "status_details": null
        }
      ]
    }
  ],
  "object": "list"
}

이번에 만든 모델 이름은 ada:ft-personal-2023-03-14-18-36-10 입니다.

result_files 에 보면 compiled_results.csv 을 생성했다고 하네요.

제 컴퓨터의 폴더를 보니까 아무것도 없더라구요. 아마 OpenAI 내에 보관 되 있는 것 같습니다.

그 다음은 training_files 와 validation_files에 대한 정보를 보여 줍니다.

 

참고로 Cook Book에서는 fine_tunes.create이 진행되는 과정에서 아래와 같은 메세지를 보여 준다고 합니다.

(저는 중간에 끄고 다른일을 봐서 이런 메세지는 못 봤습니다.)

 

 

참고로 이날 300개를 fine-tuning 한 가격은 0.21 달러입니다.

며칠 전에 1197개를 fine tuning 했을 때는 0.78 달러가 나왔었습니다.

 

 

[Advanced] Results and expected model performance

아래 명령어로 생성된 result 파일을 다운 받을 수 있습니다.

 

처음엔 result_files에 있는 ID를 넣었더니 No fine-tune job 이라는 에러 메세지가 나오네요.

여기에는 Fine tune id 를 넣어야 합니다.

그런데 저 같은 경우는 Bad file descriptor 에러 메세지가 나왔습니다.

jupyterlab을 껐다 다시 켜고 했는데도 똑 같더라구요.

 

그런데 제 컴터 폴더에 가 보니까 csv 파일이 생성 돼 있었습니다. 그런데 파일 사이즈는 0이더라구요. 내용이 아무것도 없는거죠.

 

그래서 fine_tunes.create을 다시 해 봤습니다. 새로운 모델을 생성해서 해 보려구요. 

 

이 작업은 시간이 많이 걸릴 것 같습니다.

fine_tunes.create은 일단 걸어 놨고 이 작업이 언제 끝날 지 모르겠네요.

 

GPT-4 에 대한 새로운 글들을 읽어보고 다시 시작해 봤습니다.

Jupyterlab에서 하지 않고 Command 창에서 해 봤는데 여기서도 똑 같네요.

 

 

직접 실습은 어려울 것 같고 Cookbook에 있는 설명을 보면서 공부해야 겠습니다.

 

results = pd.read_csv('result.csv')
results[results['classification/accuracy'].notnull()].tail(1)

일단 result.csv 파일을 생성하는데 성공하면 그 데이터를 pandas의 read_csv를 사용해서 읽어 옵니다.

그 다음줄은 그냥 한 줄 출력해 보는 라인 입니다.

 

결과는 아래와 같습니다.

The accuracy reaches 99.6%. On the plot below we can see how accuracy on the validation set increases during the training run.

정확도는 99.6%에 이릅니다. 아래 플롯에서 훈련 실행 중에 유효성 검사 세트의 정확도가 어떻게 증가하는지 확인할 수 있습니다.

results[results['classification/accuracy'].notnull()]['classification/accuracy'].plot()

그 다음은 이 데이터를 plot 해 봅니다. 결과 화면은 아래와 같습니다.

 

result.csv 파일을 살펴 봤구요.

이제 Fine-tuning으로 만든 새로운 모델을 직접 사용할 차례 입니다.

 

Using the model

We can now call the model to get the predictions.

이제 이 새로운 모델을 call 해서 예측을 해 볼 수 있습니다.

 

test = pd.read_json('sport2_prepared_valid.jsonl', lines=True)
test.head()

 

We need to use the same separator following the prompt which we used during fine-tuning. In this case it is \n\n###\n\n. Since we're concerned with classification, we want the temperature to be as low as possible, and we only require one token completion to determine the prediction of the model.

 

fine-tuning 중에 사용한 프롬프트 다음에 동일한 구분 기호를 사용해야 합니다. 이 경우 \n\n###\n\n입니다. 우리는 분류와 관련이 있기 때문에 temperature 가 가능한 한 낮아지기를 원하며 모델의 예측을 결정하기 위해 하나의 token completion만 필요합니다.

 

ft_model = 'ada:ft-openai-2021-07-30-12-26-20'
res = openai.Completion.create(model=ft_model, prompt=test['prompt'][0] + '\n\n###\n\n', max_tokens=1, temperature=0)
res['choices'][0]['text']

Cookbook 에서 Fine tuning으로 생성한 모델 이름을 ft_model 변수에 넣습니다.

 

그리고 위에 test에 있는 첫번째 prompt를 전달합니다. (우리는 이미 이 내용이 hockey 와 관련 돼 있다는 걸 알고 있습니다.)

이렇게 하면 결과는 이렇습니다.

' hockey'

새로 만든 모델을 써서 정답을 얻어 냈습니다.

 

To get the log probabilities, we can specify logprobs parameter on the completion request

로그 확률을 얻기 위해 완료 요청에 logprobs 매개변수를 지정할 수 있습니다.

 

res = openai.Completion.create(model=ft_model, prompt=test['prompt'][0] + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res['choices'][0]['logprobs']['top_logprobs'][0]
<OpenAIObject at 0x7fe114e435c8> JSON: {
  " baseball": -7.6311407,
  " hockey": -0.0006307676
}

이 결과는 입력값이 어느것과 더 가까운지를 숫자로 보여 줍니다. 

Baseball 보다는 hockey 에 훨썬 더 가깝다는 것을 알 수 있습니다.

 

We can see that the model predicts hockey as a lot more likely than baseball, which is the correct prediction. By requesting log_probs, we can see the prediction (log) probability for each class.

 

모델이 야구보다 하키를 훨씬 더 많이 예측한다는 것을 알 수 있습니다. 이것이 정확한 예측입니다. log_probs를 요청하면 각 클래스에 대한 예측(로그) 확률을 볼 수 있습니다.

 

Generalization

Interestingly, our fine-tuned classifier is quite versatile. Despite being trained on emails to different mailing lists, it also successfully predicts tweets.

 

흥미롭게도 fine-tuned classifier는 매우 다재다능합니다. 다른 메일링 리스트에 대한 이메일에 대한 교육을 받았음에도 불구하고 트윗을 성공적으로 예측합니다.

sample_hockey_tweet = """Thank you to the 
@Canes
 and all you amazing Caniacs that have been so supportive! You guys are some of the best fans in the NHL without a doubt! Really excited to start this new chapter in my career with the 
@DetroitRedWings
 !!"""
res = openai.Completion.create(model=ft_model, prompt=sample_hockey_tweet + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res['choices'][0]['text']

 

이 내용은 이전에 없던 내용 입니다..

내용에 NHL이라는 단어가 있네요. National Hockey league 겠죠?

그러면 이 이메일은 하키와 관련한 이메일 일 겁니다.

Fine tuning으로 만든 새로운 모델도 이것을 정확하게 맞춥니다.

 

' hockey'
sample_baseball_tweet="""BREAKING: The Tampa Bay Rays are finalizing a deal to acquire slugger Nelson Cruz from the Minnesota Twins, sources tell ESPN."""
res = openai.Completion.create(model=ft_model, prompt=sample_baseball_tweet + '\n\n###\n\n', max_tokens=1, temperature=0, logprobs=2)
res['choices'][0]['text']

그 다음 예제에서는 Tampa Bay Rays , Minnesota Twins 라는 내용이 나옵니다.

Minnesota Twins 는 한 때 박병호 선수가 있었던 메이저리그 야구 팀입니다.

당시에 제가 미네소타에 살고 있어서 구경하러 갔던 기억이 있네요.

 

' baseball'

GPT-3 도 이 내용이 야구와 관련 돼 있다는 걸 알아 차리네요.

 

이상으로 Fine tuning 하는 방법을 알아 봤습니다.

반응형


반응형

윈도우즈의 명령창 (Command Prompt) 에서 OpenAI 를 사용할 때 아래와 같은 에러 메세지가 뜰 수 있습니다.

 

 

이것은 fine_tunes.create 을 사용할 때 나온 에러입니다.

자세한 내용은 아래 페이지에 있습니다.

 

https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

 

에러 메세지는 아래와 같습니다.

 

Error: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions.

 

오류: API 키가 제공되지 않았습니다. 'openai.api_key = <API-KEY>'를 사용하여 코드에서 API 키를 설정하거나 환경 변수 OPENAI_API_KEY=<API-KEY>)를 설정할 수 있습니다. API 키가 파일에 저장되어 있는 경우 'openai.api_key_path = <PATH>'로 openai 모듈을 가리킬 수 있습니다. OpenAI 웹 인터페이스에서 API 키를 생성할 수 있습니다. 자세한 내용은 https://onboard.openai.com을 참조하거나 질문이 있는 경우 support@openai.com으로 이메일을 보내십시오.

 

해결 방법이 몇가지 나오는데 저 같은 경우는 환경변수를 세팅 해서 해결 했습니다.

 

 

System Properties에서 Environment Variables 버튼을 클릭합니다.

그 다음 밑에 있는 패널인 System variables에서 New 버튼을 클릭합니다.

 

이렇게 환경 변수에 OPENAI_API_KEY 를 세팅 한 후 모두 OK 버튼을 눌러서 닫습니다.

 

이렇게 하면 OpenAI CLI 를 사용할 수 있게 됩니다.

 

사용하기 전에 기존에 실행중이던 JupyterNotebook 이나 JupyterLab local server 는 shutdown 하시고 윈도우즈 Command Prompt 창도 닫습니다.

 

그리고 새로운 윈도우즈 명령창 (Command Prompt) 에서 Jupyter 를 실행하신 다음에 사용하시면 됩니다.

 

그러면 아래와 같이 에러 없이 사용할 수 있습니다.

 

반응형
이전 1 2 3 4 5 6 7 ··· 11 다음