Blog

ChatGPT 파인튜닝 파이썬 코드

2024-11-17

아래는 OpenAI의 GPT 모델을 파인튜닝하는 Python 코드 예제입니다. 이 코드는 OpenAI의 API를 사용하여 데이터 업로드, 파인튜닝 실행, 결과 테스트를 포함합니다.

1. 준비사항

  • OpenAI API 키를 발급받습니다.

  • JSONL 형식의 데이터셋을 준비합니다. (예: dataset.jsonl)

파인튜닝을 위한 Python 코드

python코드 복사import openai

# OpenAI API 키 설정
openai.api_key = "YOUR_API_KEY"

# 1. 데이터 업로드
def upload_file(file_path):
    print("Uploading file...")
    response = openai.File.create(
        file=open(file_path, "rb"),
        purpose="fine-tune"
    )
    print(f"File uploaded. File ID: {response['id']}")
    return response['id']

# 2. 파인튜닝 실행
def start_fine_tune(file_id, model="davinci"):
    print("Starting fine-tuning...")
    response = openai.FineTune.create(
        training_file=file_id,
        model=model
    )
    print(f"Fine-tune started. Fine-tune ID: {response['id']}")
    return response

# 3. 파인튜닝 상태 확인
def check_fine_tune_status(fine_tune_id):
    print("Checking fine-tune status...")
    response = openai.FineTune.retrieve(id=fine_tune_id)
    print(f"Status: {response['status']}")
    return response

# 4. 파인튜닝된 모델 테스트
def test_fine_tuned_model(model_id, prompt):
    print("Testing fine-tuned model...")
    response = openai.Completion.create(
        model=model_id,
        prompt=prompt,
        max_tokens=100
    )
    print(f"Response: {response['choices'][0]['text'].strip()}")
    return response['choices'][0]['text']

# 실행 순서
if __name__ == "__main__":
    # 1. 데이터 파일 업로드 (JSONL 파일 경로 설정)
    file_path = "dataset.jsonl"
    file_id = upload_file(file_path)

    # 2. 파인튜닝 시작
    fine_tune_response = start_fine_tune(file_id)
    fine_tune_id = fine_tune_response['id']

    # 3. 파인튜닝 상태 확인 (필요시 반복 실행)
    import time
    while True:
        fine_tune_status = check_fine_tune_status(fine_tune_id)
        if fine_tune_status['status'] == "succeeded":
            break
        elif fine_tune_status['status'] == "failed":
            raise Exception("Fine-tuning failed.")
        time.sleep(30)  # 30초 대기

    # 4. 파인튜닝된 모델로 테스트
    fine_tuned_model_id = fine_tune_status['fine_tuned_model']
    prompt = "Blazor란 무엇인가요?"
    response = test_fine_tuned_model(fine_tuned_model_id, prompt)
    print(f"Fine-tuned Model Response: {response}")

코드 설명

  1. upload_file 함수: JSONL 형식의 데이터 파일을 OpenAI 서버에 업로드합니다.

  2. start_fine_tune 함수: 업로드된 데이터를 기반으로 지정한 모델(Davinci 등)에서 파인튜닝을 시작합니다.

  3. check_fine_tune_status 함수: 파인튜닝 상태를 확인합니다. 성공, 실패, 진행 중 여부를 알 수 있습니다.

  4. test_fine_tuned_model 함수: 파인튜닝이 완료된 모델 ID를 사용해 테스트 질문에 대한 응답을 확인합니다.

필수 JSONL 데이터 예제

dataset.jsonl

json코드 복사{"prompt": "Blazor란 무엇인가요?", "completion": "Blazor는 .NET 기반의 웹 프레임워크입니다."}
{"prompt": "C#의 장점은 무엇인가요?", "completion": "C#은 강력한 타입 시스템과 넓은 라이브러리 생태계를 갖추고 있습니다."}
{"prompt": "프로젝트 관리는 어떻게 시작해야 하나요?", "completion": "목표를 설정하고 팀 구성원과의 협업 계획을 수립하세요."}

결과 확인

위 코드를 실행하면 다음과 같은 과정을 거칩니다:

  1. 데이터 업로드 → 파일 ID 생성

  2. 파인튜닝 시작 → Fine-tune ID 생성

  3. 상태 확인 → 모델이 준비되면 완료

  4. Fine-tuned 모델로 질문에 대한 맞춤형 응답 확인

인클루드웹 솔루션이 궁금하신가요?

건설관리, 프로젝트관리, 영업관리 솔루션 도입을 무료로 상담해 드립니다.