Hugging Face 모델을 FastAPI로 배포하기
목표
이 튜토리얼을 완료하면:
- Hugging Face 모델을 FastAPI 서버로 래핑
- HTTP POST 요청으로 추론 결과 수신
- 백그라운드로 서버를 실행하고 외부에서 접근
사전 준비
- ECI 계정 및 GPU 인스턴스 할당량
- SSH 클라이언트 (macOS/Linux 기본 제공, Windows는 WSL 또는 PuTTY)
1단계: 가상머신 생성
-
컴퓨트 > 가상머신 목록에서 가상 머신 생성을 클릭합니다.
-
다음 설정을 사용합니다.
항목 권장값 이미지 Ubuntu 24.04 LTS (AI/GPU)(CUDA 사전 설치)인스턴스 타입 G-NHHS-80(H100 80GB SXM × 1)공인 IP 새로 생성 -
생성을 클릭하고 상태가 실행 중이 될 때까지 기다린 뒤 SSH로 접속합니다.
2단계: 환경 준비
python3 -m pip install fastapi uvicorn transformers torch accelerate
3단계: 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"}
4단계: 서버 실행
# 포그라운드 실행 (테스트용)
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 &
5단계: 방화벽 및 테스트
가상머신이 속한 가상 네트워크 상세 페이지의 방화벽 규칙에서 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
다음 단계
- Hugging Face 모델 테스트: 다양한 모델 동작 검증
- 방화벽 설정: 외부에 API 포트 허용하기