Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Lab 1: Your First Model Service on Kubernetes

MLOps Foundations & Cloud Native AI — Lab 1(講義 p.49–52)

用 scikit-learn 訓練 Iris 分類模型,並用 MLflow 記錄實驗。接著以 FastAPI 包裝成 REST API,打包成 Docker image 後部署到本機 kind 叢集,最後用 HorizontalPodAutoscaler 依 CPU 使用率自動擴展。

架構

Developer laptop                                kind cluster "mlops"
┌──────────────────────────────┐               ┌───────────────────────────────────────┐
│ train.py ──► MLflow          │               │ Deployment iris-api (1 → 5 Pods)  ◄── HPA (cpu 50%)
│    │       (params/metrics/  │  kind load    │   requests: cpu 100m                  │    ▲
│    ▼        model)           │  docker-image │   readinessProbe: /healthz            │    │
│ model.pkl ─► app.py ─► image ├──────────────►│        ▲                              │ metrics-server
│              (FastAPI)  iris-api:v1          │ Service iris-api  ClusterIP :80→8080  │
│ curl / load_test.py ─────────┼─ port-forward─►                                       │
└──────────────────────────────┘               └───────────────────────────────────────┘

Repository 結構

檔案 說明
train.py 訓練 RandomForest,以 MLflow 記錄 param / metric / model,並輸出 model.pkl
app.py FastAPI 預測服務:POST /predict、GET /healthz
requirements.txt 容器內套件(版本與訓練環境一致)
Dockerfile 建置 iris-api:v1 image
k8s/deployment.yaml Deployment + Service(含 resource requests/limits、readinessProbe)
k8s/hpa.yaml HorizontalPodAutoscaler(CPU 50%,1 → 5 replicas)
load_test.py 壓力測試腳本,等同 hey -z 60s -c 50
screenshots/ MLflow 與 HPA 執行結果截圖

環境

工具 版本
OS Windows 11 + Docker Desktop(WSL 2)
kind v0.33.0(node image kindest/node:v1.37.0)
Python 3.12
scikit-learn / MLflow 1.9.1 / 3.18.0
FastAPI / uvicorn 0.165.0 / 0.54.0

執行步驟

Step 1 — 建立本機叢集

kind create cluster --name mlops

Step 2 — 訓練模型並以 MLflow 追蹤

pip install scikit-learn joblib mlflow fastapi uvicorn
python train.py          # accuracy=1.0000 -> saved model.pkl
mlflow ui --backend-store-uri sqlite:///mlflow.db   # http://127.0.0.1:5000

Step 3 — 包裝成 FastAPI 服務、建置 image 並載入 kind

docker build -t iris-api:v1 .
kind load docker-image iris-api:v1 --name mlops

Step 4 — 部署並以 curl 測試

kubectl apply -f k8s/deployment.yaml
kubectl get pods -w

kubectl port-forward svc/iris-api 8080:80 &
curl -X POST localhost:8080/predict \
  -H "Content-Type: application/json" \
  -d '{"instances": [[5.1, 3.5, 1.4, 0.2]]}'
# {"predictions":[0]}

Step 5 — 安裝 metrics-server、建立 HPA、壓測

# kind 預設沒有 metrics-server;kind 的 kubelet 使用自簽憑證,需加 --kubelet-insecure-tls
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
kubectl -n kube-system patch deployment metrics-server --type=json \
  -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'

# 等同 kubectl autoscale deployment iris-api --cpu-percent=50 --min=1 --max=5
kubectl apply -f k8s/hpa.yaml

python load_test.py -z 120 -c 50     # 等同 hey -z 120s -c 50 ...
kubectl get hpa iris-api -w

結果

MLflow Run

實驗 iris 中的 run:n_estimators = 100,accuracy = 1.0,模型以 artifact 記錄。

MLflow runs MLflow run detail MLflow artifacts

HPA Scaling

壓測開始後,CPU 使用率升至 500%(以 request 100m 為基準),HPA 將副本數從 1 → 4 → 5。負載結束約 5 分鐘後自動縮回 1。兩輪壓測共 8,023 個請求,全部回傳 200。完整紀錄見 screenshots/hpa-scaling-log.txt。

HPA scaling Pods after scale-out

與講義的差異與說明

  1. MLflow 3.x 的 log_model:新版改用 name= 參數(取代 artifact_path),並預設以 skops 格式儲存。skops 要求明確宣告受信任的型別,所以加上 skops_trusted_types=["sklearn.tree._tree.Tree"],否則會拋出 MlflowException。
  2. 固定套件版本:requirements.txt 固定 scikit-learn 等套件版本,訓練環境也使用 Python 3.12,與容器 python:3.12-slim 一致。這樣可以避免 model.pkl 因版本不同而無法載入。
  3. metrics-server:kind 預設未安裝,需另外安裝,並加上 --kubelet-insecure-tls。
  4. HPA 以 YAML 宣告:除了講義的 kubectl autoscale 指令,另外提供等價的 k8s/hpa.yaml(autoscaling/v2)。
  5. 以 load_test.py 取代 hey:hey 官方的 Windows 執行檔下載點已失效(S3 回傳 AccessDenied),所以改用只依賴 Python 標準函式庫的腳本,行為與 hey -z <秒> -c <併發數> -m POST 相同。
  6. port-forward 的限制:kubectl port-forward svc/... 實際上只會連到其中一個 Pod,所以壓測流量不會平均分散到新增的 Pod。這不影響 HPA 依平均 CPU 使用率擴展的展示,但在正式環境中應透過 Ingress / LoadBalancer 分流。

清除

kind delete cluster --name mlops

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages