Bento ML Quick Example

Tutorial

Model Training

Model 생성

  • Iris  Dataset 과  SVM을 이용해서 모델을 만들어주고 저장한다. 이 때 저장 파일은 환경변수 BENTOML_HOME에 지정된 곳을 루트 디렉토리 아래 모델이 생성된다.
import bentoml
from sklearn import svm, datasets

# Load training data
iris = datasets.load_iris()
X, y = iris.data, iris.target

# Model Training
clf = svm.SVC()
clf.fit(X, y)

# Save model to BentoML local model store
bentoml.sklearn.save_model("iris_clf", clf)

생성된 모델에 대해서는 Shell 상에서도 아래 명령어를 통해서 확인할 수 있고, Model이 새롭게 저장될 때마다  Version을 통해서 형상관리가 된다. 그래서 List로 모델을 직접 선택해서 볼 수 있다.

bentoml models get iris_clf:latest

bentoml models list

bentoml models --help

Model Inference를 위해서 BentoML 은 Runner를 사용할 것을 권한다.  그냥 모델을 아래 명령어로 Load한 다음에 Inference 하는 것도 가능하나,

 bentoml.sklearn.load_model("iris_clf:latest")

Scheduling이나 보다 유연하게 리소스 할당을 하고 싶다면 제공되는 Runner를 이용하는 것을 권장한다.

import bentoml

# Create a Runner instance:
iris_clf_runner = bentoml.sklearn.get("iris_clf:latest").to_runner()

# Runner#init_local initializes the model in current process, this is meant for development and testing only:
iris_clf_runner.init_local()

# This should yield the same result as the loaded model:
iris_clf_runner.predict.run([[5.9, 3., 5.1, 1.8]])

Model Serving

아래내용을 service.py로 저장한다. 자세히 보면 Decorator가 API 입출력에 관한 부분을 잡아주고, 비동기로 Predict를 하는 구조이다.

import numpy as np
import bentoml
from bentoml.io import NumpyNdarray

iris_clf_runner = bentoml.sklearn.get("iris_clf:latest").to_runner()

svc = bentoml.Service("iris_classifier", runners=[iris_clf_runner])

@svc.api(input=NumpyNdarray(), output=NumpyNdarray())
async def classify(input_series: np.ndarray) -> np.ndarray:
    return await iris_clf_runner.predict.async_run(input_series)

위에서 만든 service.py를 실행하는 스크립트이다. 실행 이후에 http://127.0.0.1:3000을 열어보면 테스트 결과를 볼 수 있고 curl 로 결과를 볼 수도 있다.

bentoml serve service.py:svc --reload
curl -X POST -H "content-type: application/json" --data "[[5.9, 3, 5.1, 1.8]]" http://127.0.0.1:3000/classify

Deployment & Containerize

  • 이 일련의 과정을 "bentofile.yaml" 로 묶어서 한 번에 처리할 수도 있다.
service: "service.py:svc"
labels:
  owner: bentoml-team
  project: gallery
include:
- "*.py"
python:
  packages:
    - scikit-learn
    - pandas
bentoml build
  • Docker로 Containerize해서 K8s에 태워서 리소스를 유연하게 조절하면서 서빙할 수도 있다.
bentoml containerize iris_classifier:latest

References

Read more

[책]Reshuffle: Who wins when AI restacks the knowledge economy

[책]Reshuffle: Who wins when AI restacks the knowledge economy

원래는 Amazon에 가서 Personal Knowledge Managment에 관한 책을 사려고 했다. Sketch Your Mind라는 책이었는데, 그 때 이 책 “Reshuffle”을 발견하였다. AI가 어떻게 Knowledge Economy를 흔들 것가? 라는 부제를 훑어보면서 저자가 쓴 다른 책을 보게 되었는데 거기에 내가 좋아했던 책을쓴 저자라는 것을 알게 되었다. 그래서 크게 고민하지 않고 구매를 하고

By Bongho, Lee
[책]올라운드투자, 누군가의 투자일기

[책]올라운드투자, 누군가의 투자일기

“올라운드 투자”라는 제목을 보았을 때는, “올라운드 플레이어”가 생각이 났다. “올라운드”라는 표현을 오랜만에 들어본 까닭이었다. 그럼에도 불구하고 이 책을 고른 것은 저자가 그간 보여준 컨텐츠에 대한 신뢰가 있던 까닭이었다. 컨텐츠를 다양하게 보는 편이지만 깊이가 아주 있지는 않았다. 여기서 깊이라 함은 기존 전문적인 정량적 분석의 내용의 수준을 말하는 것이다.

By Bongho, Lee
내가 놓치고 있던 미래, 먼저 온 미래를 읽고

내가 놓치고 있던 미래, 먼저 온 미래를 읽고

장강명 작가의 책은, 유학시절 읽고 처음이었다. 유학시절 "한국이 싫어서"라는 책은 동기부여가 상당히 되는 책이었다. 한국을 떠나 새로운 정채성을 학생으로서 Build up 해나가고 있던 상황에서 이 책은 제목부터 꽤 솔깃하였다. 물론 결말이 기억날 정도로 인상깊은 책은 아니었지만 말이다. 그렇게 시간이 흘러 장강명 작가의 책은 더 이상 읽지 않던

By Bongho, Lee