🤖 AI/ML

BentoML

ML 모델 서빙 프레임워크

📖 상세 설명

BentoML은 머신러닝 모델을 프로덕션 환경에 배포하기 위한 오픈소스 프레임워크입니다. 모델 패키징, API 서버 생성, 컨테이너화, 배포까지의 전 과정을 단순화하여 ML 엔지니어가 서빙 인프라보다 모델 개발에 집중할 수 있게 합니다.

2019년 처음 공개되어 빠르게 성장했으며, 2023년 기준 GitHub 스타 5,000개 이상을 기록했습니다. TensorFlow, PyTorch, scikit-learn, XGBoost, Hugging Face Transformers 등 주요 ML 프레임워크를 모두 지원하며, AWS, GCP, Azure 등 클라우드와 Kubernetes 환경에 쉽게 배포할 수 있습니다.

핵심 개념은 'Bento'입니다. Bento는 모델, 의존성, API 정의를 하나의 표준화된 아티팩트로 패키징한 것으로, Docker 이미지처럼 이식 가능합니다. bentoml.save_model()로 모델을 저장하고, @bentoml.service 데코레이터로 API를 정의하면, bentoml build로 배포 가능한 Bento가 생성됩니다.

실무에서 BentoML은 MLOps 파이프라인의 핵심 도구로 활용됩니다. 특히 adaptive batching(동적 배칭), 멀티모델 서빙, GPU 리소스 관리 등 고급 기능을 제공해 대규모 서비스에도 적합합니다. FastAPI나 Flask로 직접 서버를 구축하는 것보다 설정이 간편하고 성능 최적화가 자동으로 이루어집니다.

💻 코드 예제

# BentoML로 ML 모델 서빙하기
# pip install bentoml scikit-learn

# 1. 모델 학습 및 저장 (train.py)
import bentoml
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris

# 모델 학습
iris = load_iris()
model = RandomForestClassifier(n_estimators=100)
model.fit(iris.data, iris.target)

# BentoML에 모델 저장
saved_model = bentoml.sklearn.save_model(
    "iris_classifier",
    model,
    signatures={"predict": {"batchable": True}},
    metadata={"accuracy": 0.96}
)
print(f"모델 저장됨: {saved_model}")

# 2. 서비스 정의 (service.py)
import bentoml
import numpy as np
from bentoml.io import NumpyNdarray, JSON

# 저장된 모델 로드
iris_model = bentoml.sklearn.get("iris_classifier:latest")
runner = iris_model.to_runner()

# BentoML 서비스 생성
svc = bentoml.Service("iris_classifier_service", runners=[runner])

@svc.api(input=NumpyNdarray(), output=JSON())
async def predict(input_array: np.ndarray) -> dict:
    """꽃받침/꽃잎 치수로 붓꽃 품종 예측"""
    predictions = await runner.predict.async_run(input_array)
    species = ["setosa", "versicolor", "virginica"]
    return {
        "predictions": [species[p] for p in predictions],
        "count": len(predictions)
    }

# 3. 로컬 테스트
# bentoml serve service:svc --reload

# 4. Bento 빌드 (bentofile.yaml)
"""
service: "service:svc"
include:
  - "*.py"
python:
  packages:
    - scikit-learn
    - numpy
docker:
  distro: debian
  python_version: "3.10"
"""

# 5. 빌드 및 컨테이너화
# bentoml build
# bentoml containerize iris_classifier_service:latest

# 6. API 호출 테스트
import requests
response = requests.post(
    "http://localhost:3000/predict",
    headers={"Content-Type": "application/json"},
    json=[[5.1, 3.5, 1.4, 0.2], [6.7, 3.0, 5.2, 2.3]]
)
print(response.json())

🗣️ 실무 대화 예시

MLOps 도구 선정 회의에서

"모델 서빙을 FastAPI로 직접 구현하면 배칭, 캐싱, GPU 스케줄링을 다 수동으로 해야 해요. BentoML은 adaptive batching이 기본 제공되고, 멀티모델 서빙도 설정 한 줄이면 됩니다. 개발 속도를 고려하면 BentoML이 더 효율적입니다."

배포 파이프라인 설계 중

"BentoML로 Bento 아티팩트를 만들고, GitHub Actions에서 자동으로 containerize해서 ECR에 푸시합니다. EKS에는 Yatai나 bentoctl로 배포하면 되고요. 모델 버전 관리도 Bento tag로 자연스럽게 되니까 롤백도 쉽습니다."

기술 면접에서

"BentoML의 장점은 모델과 서빙 로직을 하나의 패키지로 묶어서 환경 의존성 문제를 해결한다는 점입니다. 다만 커스터마이징이 제한적일 수 있고, 특수한 요구사항이 있으면 TensorFlow Serving이나 Triton이 더 적합할 수 있습니다."

⚠️ 주의사항

1
버전 호환성

BentoML 1.x는 0.x와 호환되지 않습니다. 기존 코드 마이그레이션 시 API 변경 사항을 꼼꼼히 확인하세요. 특히 @bentoml.env, @bentoml.artifacts 같은 구문이 크게 바뀌었습니다.

2
대형 모델 처리

LLM 같은 대형 모델은 Bento 아티팩트 크기가 수십 GB가 될 수 있습니다. 이 경우 모델을 별도 저장소에 두고 런타임에 로드하는 방식을 고려하세요.

3
프로덕션 모니터링

BentoML 자체는 모니터링 기능이 제한적입니다. Prometheus, Grafana, Datadog 등 외부 모니터링 도구와 연동하고, 헬스체크 엔드포인트를 설정해두세요.

🔗 관련 용어

📚 더 배우기