VLM_Math [3] SFT한거 구현확인

Leejaegun·2025년 4월 13일

VLM_reasoning

목록 보기
3/3

📌 1. 테스트 스크립트 작성 및 초기 테스트 (math_test.py)

① 스크립트 작성

  • 학습 완료된 모델을 로드하여 간단한 추론 테스트 코드 작성
  • 예시 스크립트 구조 (math_test.py):
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_name = "Qwen-VL-SFT-finetuned"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name).cuda()

prompt = "Solve this math problem: What is the derivative of x^2?"
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.cuda()

with torch.no_grad():
    outputs = model.generate(input_ids)
    result = tokenizer.decode(outputs[0], skip_special_tokens=True)

print(result)

② 문제 발생

  • math_test.py를 직접 실행 시 오류 발생
    • CUDA indexing 오류
    • 모델 로딩 후 inference가 제대로 수행되지 않는 현상 발생
    IndexError: index out of range in self
    ../aten/src/ATen/native/cuda/Indexing.cu:1255

📌 2. 원인 분석 및 문제 해결

문제상황원인 분석해결방법
CUDA Indexing 오류 발생transformers 라이브러리 inference 시 token index mismatch 및 tensor 크기 문제 발생transformers 대신 최적화된 vLLM 라이브러리를 사용하여 추론 수행

📌 3. vLLM 라이브러리 적용하여 정상 동작

① vLLM 설치

pip install vllm

② vLLM을 이용한 정상 동작 확인

  • 명령어 예시 (CLI 기반 테스트):
python -m vllm.entrypoints.api_server \
  --model Qwen-VL-SFT-finetuned \
  --host 0.0.0.0 --port 8000
  • vLLM API 요청 확인 (HTTP 요청 예시):
curl -X POST http://localhost:8000/generate \
-H "Content-Type: application/json" \
-d '{"prompt": "Solve this math problem: What is the derivative of x^2?"}'
  • 위 요청 시 정상 결과 확인:
{
  "text": "The derivative of x^2 is 2x."
}

📌 4. 최종 배포 구조 설계 및 설정

최종 배포 구조는 다음과 같은 형태로 구축:

Frontend (React, port:3000)
    ↳ Backend API (FastAPI, port:8001)
        ↳ vLLM Server (port:8000)

① vLLM API 서버 구축 (8000 포트)

  • Qwen-VL 모델 추론 전담 서버

② FastAPI 서버 구축 (8001 포트)

  • React에서 받은 요청을 vLLM 서버로 중계 및 응답 가공
  • 코드 예시 (main.py):
from fastapi import FastAPI
import requests
from pydantic import BaseModel

app = FastAPI()

class PromptRequest(BaseModel):
    prompt: str

@app.post("/generate")
def generate_text(request: PromptRequest):
    vllm_url = "http://localhost:8000/generate"
    payload = {"prompt": request.prompt}

    response = requests.post(vllm_url, json=payload)
    response_json = response.json()

    return {"result": response_json["text"]}
  • FastAPI 서버 실행 명령:
uvicorn main:app --host 0.0.0.0 --port 8001

③ React 프론트엔드 구축 (3000 포트)

  • 간단한 입력폼과 출력 결과를 화면에 표시하는 UI 구축
  • 예시 코드(App.jsx):
import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [prompt, setPrompt] = useState('');
  const [result, setResult] = useState('');

  const handleSubmit = async () => {
    const response = await axios.post('http://localhost:8001/generate', { prompt });
    setResult(response.data.result);
  };

  return (
    <div>
      <textarea value={prompt} onChange={e => setPrompt(e.target.value)} />
      <button onClick={handleSubmit}>Submit</button>
      <div>{result}</div>
    </div>
  );
}

export default App;
  • React 서버 실행 명령:
npm run dev

📌 최종 흐름도

graph TD
A[React 프론트엔드 3000] --> B[FastAPI API 서버 8001]
B --> C[vLLM API 서버 8000]
C --> B --> A

이러한 과정을 통해, SFT 이후 모델 추론 환경 구축 및 안정적인 배포가 성공적으로 완료됩니다.

profile
Lee_AA

0개의 댓글