Advanced Model Serving sử dụng Seldon Core (P.2)
2022-04-07 16:15:16

Hello cả nhà =)) sau bao nhiêu ngày ở ẩn, mình đã quyết định trở lại với phần 2 của model serving sử dụng Seldon Core. Phần này sẽ có những chủ đề sau:

  • Autoscale model serving với KEDA
  • Customize metrics cho Prometheus
  • REST Health endpoint

Prerequisites

1. Horizontal Pod Autoscaler (HPA)

HPA object trong Kubernetes (k8s) được sử dụng để tự động tăng/giảm số lượng pod trong 1 deployment, replica set, hoặc statefulset dựa trên các metrics được định nghĩa sẵn trong manifest bao gồm CPU/memory utilization, hoặc một custom metric khác. Loại scale này gọi là horizontal scale, còn tăng cấu hình CPU, memory, storage, .v.v. thì gọi là vertical scale.
Dưới đây là ví dụ về một HPA manifest:

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: hello-world
namespace: default
spec:
maxReplicas: 10
minReplicas: 1
scaleTargetRef:
apiVersion: extensions/v1beta1
kind: Deployment
name: hello-world
targetCPUUtilizationPercentage: 50

HPA trên sẽ tự động thay đổi số lượng pod cho deployment hello-world dựa trên mean CPU utilization percentage của tất cả các pod. HPA cũng đảm bảo số lượng pod tối thiếu là 1, và tối đa là 10. Về cơ chế scale của HPA, mọi người xem thêm tại đây

2. KEDA

KEDA (Kubernetes-based Event Driven Autoscaler) mở rộng HPA, cho phép scale workload thông qua external metrics, ví dụ metrics từ Prometheus query.
KEDA có 3 thành phần chính:

  • Scaler: kết nối với external source và fetch metrics
  • Controller: scale pod từ/xuống 0 và tạo HPA
  • Metrics Adapter: biên dịch external metrics sang dạng HPA có thể hiểu được, mình cảm thấy đây là một chức năng khá quan trọng, cho phép người dùng không cần tự viết custom metrics phức tạp trực tiếp trên HPA
KEDA arch

I. Horizontal scale model deployment với KEDA

1. Cài đặt KEDA

Cài đặt KEDA khá đơn giản chỉ với một vài command như sau:

1
2
3
4
5
helm repo add kedacore https://kedacore.github.io/charts
helm repo update

kubectl create namespace keda
helm install keda kedacore/keda --namespace keda

Để sử dụng KEDA với Seldon Core thì mọi người thêm flag --set keda.enabled=true lúc cài đặt

1
2
3
4
5
6
helm install seldon-core seldon-core-operator \
--repo https://storage.googleapis.com/seldon-charts \
--set usageMetrics.enabled=true \
--set istio.enabled=true \
--namespace seldon-system \
--set keda.enabled=true

2. Sử dụng KEDA

Sử dụng KEDA để autoscale các Seldon deployments khá đơn giản, chỉ cần thêm kedaSpec để mô tả cách mà mọi người muốn scale

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# seldon.yaml
apiVersion: machinelearning.seldon.io/v1alpha2
kind: SeldonDeployment
metadata:
name: sklearn
namespace: models
spec:
name: iris
predictors:
- componentSpecs:
- spec:
containers:
- name: classifier
image: yourdockerusername/demo-seldon:0.0.1
serviceAccountName: yourserviceaccount
kedaSpec:
pollingInterval: 15 # Optional. Default: 30 seconds
minReplicaCount: 1 # Optional. Default: 0
maxReplicaCount: 3 # Optional. Default: 100
triggers:
- type: prometheus
metadata:
# Required
serverAddress: http://prometheus-server.monitoring.svc.cluster.local
metricName: access_frequency
threshold: '10'
query: rate(seldon_api_executor_client_requests_seconds_count{seldon_app=~"sklearn"}[10s]
graph:
children: []
endpoint:
type: REST
name: classifier
type: MODEL
name: default

Sau khi apply manifest trên, seldon-controller-manager sẽ khởi tạo 1 object Seldon Deployment. Object này sẽ tạo 1 ScaledObject tương đương với cấu hình scale được định nghĩa trong kedaSpec: số pod tối thiếu là 1 và tối đa là 3, thực hiện query prometheus-server 15s một lần, và threshold để quyết định scale là 10.

II. Customize metrics cho Prometheus

Bên cạnh default metrics expose bởi service orchestrator (executor), ví dụ seldon_api_executor_client_requests_seconds_count ở trên, chúng ta hoàn toàn có thể thêm custom metrics bằng cách thêm 1 method metrics như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ModelWithMetrics(object):

def __init__(self):
print("Initialising")

def predict(self,X,features_names):
print("Predict called")
return X

def metrics(self):
return [
{"type": "COUNTER", "key": "mycounter", "value": 1}, # a counter which will increase by the given value
{"type": "GAUGE", "key": "mygauge", "value": 100}, # a gauge which will be set to given value
{"type": "TIMER", "key": "mytimer", "value": 20.2}, # a timer which will add sum and count metrics - assumed millisecs
]

III. REST health endpoint

Health checks hay probes được sử dụng bởi kubelet để xác định khi nào restart 1 container (liveness probe), sử dụng bởi các services và deployments để xác định pod đã sẵn sàng nhận traffic chưa.

Chúng ta có thể implement method health_status như sau:

1
2
3
4
5
6
7
8
class ModelWithHealthEndpoint(object):
def predict(self, X, features_names):
return X

def health_status(self):
response = self.predict([1, 2], ["f1", "f2"])
assert len(response) == 2, "health check returning bad predictions" # or some other simple validation
return response

Và ghi đè cấu hình default liveness/readiness probes mặc định:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
kind: SeldonDeployment
spec:
name: sklearn
predictors:
- componentSpecs:
- spec:
containers:
- image: yourdockerusername/demo-seldon:0.0.1
name: classifier
livenessProbe:
failureThreshold: 3
initialDelaySeconds: 60
periodSeconds: 5
successThreshold: 1
httpGet:
path: /health/status
port: http
scheme: HTTP
timeoutSeconds: 1
readinessProbe:
failureThreshold: 3
initialDelaySeconds: 20
periodSeconds: 5
successThreshold: 1
httpGet:
path: /health/status
port: http
scheme: HTTP
timeoutSeconds: 1

Chúng ta cũng có thể tự xác định xem model vừa deploy có chạy ngon lành không bằng cách gọi tới route /health/status hoặc /health/ping.

References

[1] https://cloud.redhat.com/blog/kubernetes-autoscaling-3-common-methods-explained
[2] https://cloudblogs.microsoft.com/opensource/2020/05/12/scaling-kubernetes-keda-intro-kubernetes-based-event-driven-autoscaling/
[3] https://viblo.asia/p/kubernetes-practice-kubernetes-based-event-driven-autoscaler-3Q75wAG9ZWb
[4] https://kubebyexample.com/en/concept/health-checks

Prev
2022-04-07 16:15:16
Next