メインコンテンツまでスキップ

Hugging Face 모델을 FastAPI로 배포하기

목표

이 튜토리얼을 완료하면:

  • Hugging Face 모델을 FastAPI 서버로 래핑
  • HTTP POST 요청으로 추론 결과 수신
  • 백그라운드로 서버를 실행하고 외부에서 접근

1단계: 환경 준비

pip install fastapi uvicorn transformers torch accelerate

2단계: API 서버 코드

# server.py
from fastapi import FastAPI
from pydantic import BaseModel
from transformers import pipeline
import torch

app = FastAPI()

# 모델 초기화 (서버 시작 시 1회)
device = 0 if torch.cuda.is_available() else -1
classifier = pipeline(
"text-classification",
model="snunlp/KR-FinBert-SC",
device=device
)

class TextRequest(BaseModel):
text: str

class PredictionResponse(BaseModel):
label: str
score: float

@app.post("/predict", response_model=PredictionResponse)
def predict(req: TextRequest):
result = classifier(req.text)[0]
return PredictionResponse(label=result["label"], score=result["score"])

@app.get("/health")
def health():
return {"status": "ok"}

3단계: 서버 실행

# 포그라운드 실행 (테스트용)
uvicorn server:app --host 0.0.0.0 --port 8000

# 백그라운드 실행
nohup uvicorn server:app --host 0.0.0.0 --port 8000 >> server.log 2>&1 &

4단계: 방화벽 및 테스트

가상머신이 속한 가상 네트워크 상세 페이지의 방화벽 규칙에서 TCP 8000을 허용하는 규칙을 추가합니다 (자세한 설정은 방화벽 참고). 변경 사항은 최대 1분 이내에 적용됩니다.

# 헬스 체크
curl http://<PUBLIC_IP>:8000/health

# 추론 요청
curl -X POST http://<PUBLIC_IP>:8000/predict \
-H "Content-Type: application/json" \
-d '{"text": "오늘 주가가 크게 올랐습니다."}'

Python 클라이언트:

import requests

response = requests.post(
"http://<PUBLIC_IP>:8000/predict",
json={"text": "오늘 주가가 크게 올랐습니다."}
)
print(response.json())
# {"label": "positive", "score": 0.98}

자동 시작 설정 (systemd)

서버 재시작 시에도 자동으로 시작하려면:

USER_NAME=$(whoami)
sudo tee /etc/systemd/system/ml-api.service >/dev/null <<EOF
[Unit]
Description=ML API Server
After=network.target

[Service]
User=${USER_NAME}
WorkingDirectory=/home/${USER_NAME}
ExecStart=/usr/bin/python3 -m uvicorn server:app --host 0.0.0.0 --port 8000
Restart=always

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl enable --now ml-api

다음 단계