🚀 FastAPI 기반 MLOps 모델 서빙 구현
from contextlib import asynccontextmanager
from fastapi import FastAPI
from simplet5 import SimpleT5
from pydantic import BaseModel
class Input(BaseModel):
text: str="""summarize: Twitter’s interim resident grievance officer for India has stepped down, leaving the micro-blogging site without a grievance official as mandated by the new IT rules to address complaints from Indian subscribers, according to a source.
The source said that Dharmendra Chatur, who was recently appointed as interim resident grievance officer for India by Twitter, has quit from the post.
The social media company’s website no longer displays his name, as required under Information Technology (Intermediary Guidelines and Digital Media Ethics Code) Rules 2021.
Twitter declined to comment on the development.
The development comes at a time when the micro-blogging platform has been engaged in a tussle with the Indian government over the new social media rules. The government has slammed Twitter for deliberate defiance and failure to comply with the country’s new IT rules.
"""
def load_model():
print("start model load")
model = SimpleT5()
model.load_model("t5", "/model", use_gpu=False)
print("finished model load")
return model
ml_models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the ML model
ml_models["nlp_model"] = load_model()
yield
# Clean up the ML models and release the resources
ml_models.clear()
app = FastAPI(lifespan=lifespan)
@app.post("/predict")
async def predict(input: Input):
result = ml_models["nlp_model"].predict(input.text)[0]
return {"result": result}
1️⃣ FastAPI를 활용한 머신러닝 모델 서빙
- FastAPI를 사용하여 NLP 모델을 배포하는 API를 구축
- lifespan을 이용해 모델을 서버 실행 시 로드하고, 종료 시 리소스를 해제
2️⃣ SimpleT5를 이용한 NLP 모델 로드 및 예측
- SimpleT5를 활용해 사전 학습된 Transformer 모델 로드
- 모델을 /model 디렉터리에서 불러와 예측 수행
3️⃣ 비동기 라이프사이클 관리 (lifespan)
- @asynccontextmanager를 사용하여 FastAPI의 애플리케이션 수명 주기 관리
- 서버 시작 시 모델을 로드하고, 종료 시 메모리를 해제
4️⃣ FastAPI 엔드포인트 구현 (/predict)
- POST /predict 엔드포인트에서 JSON 입력을 받아 예측 수행
- 입력 데이터는 pydantic의 BaseModel을 사용해 유효성 검사
5️⃣ Docker 및 CI/CD 적용 가능
- 해당 FastAPI 애플리케이션을 Docker 컨테이너로 패키징하여 배포 가능
- GitHub Actions와 함께 사용하면 MLOps 파이프라인을 자동화할 수 있음
6️⃣ MLOps 파이프라인 확장 가능
- 현재는 단일 모델을 로드하고 예측하는 구조지만, 다중 모델 서빙 및 모델 버전 관리 적용 가능
- MLflow와 같은 툴과 연동하여 모델 추적 및 실험 관리 가능
FastAPI 모델 서빙을 위한 Dockerfile
#
FROM python:3.9
#
WORKDIR /code
#
COPY ./requirements.txt /code/requirements.txt
#
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
#
COPY ./app /code/app
COPY ./model /model
#
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
- Python 3.9 환경을 기반으로 컨테이너 생성
- /code 디렉터리를 작업 디렉터리로 설정
- requirements.txt를 복사하여 패키지를 설치
- 애플리케이션 코드(app/)와 모델(model/)을 컨테이너에 복사
- Uvicorn을 사용해 FastAPI 서버 실행
# Docker 이미지 빌드
docker build -t mlops-app .
# Docker 컨테이너 실행
docker run -it -p 80:80 mlops -mlops
'시스템 개발 및 관리 > 이커머스 효율화: NLP 모델 적용' 카테고리의 다른 글
[Kubernetes 배포 환경 구축] GCP Docker 이미지 빌드 (0) | 2025.03.01 |
---|---|
[Kubernetes 배포 환경 구축] Kubernetes 클러스터 생성 (0) | 2025.03.01 |
Cloud Storage 기반 모델 관리 - 라이브러리 패키지 (0) | 2025.02.21 |
GCP Cloud Storage 기반 모델 관리 (0) | 2025.02.20 |
MLOps CI/CD 자동화: 모델 개발부터 배포까지 (0) | 2025.02.20 |