随着机器学习(ML)和深度学习(DL)技术的快速发展,MLOps(机器学习运维)的概念应运而生,旨在将机器学习模型的开发、测试、部署和监控流程自动化。在本文中,将探讨如何使用GoogleKubernetesEngine (GKE) 集群来部署机器学习模型,这是MLOps流程中的一个重要环节。
在Kubernetes中,Jobs用于执行一次性任务,完成后自动终止。而Deployments则用于持续运行的服务,除非显式终止。在项目中,Jobs将执行模型训练和测试等任务,而Deployments将保持预测API服务运行。
让来看一下处理AutomaticTraining-CodeCommit任务的YAML文件示例:
apiVersion: batch/v1
kind: Job
metadata:
  name: gke-training-code-commit
spec:
  backoffLimit: 1
  activeDeadlineSeconds: 900
  ttlSecondsAfterFinished: 60
  template:
    spec:
      containers:
      - name: code-commit
        image: gcr.io/automatictrainingcicd/code-commit:latest
        env:
          - name: gmail_password
            valueFrom:
              secretKeyRef:
                name: gmail-secrets
                key: gmail_password
          - name: email_address
            value: svirahonda@gmail.com
      restartPolicy: OnFailure
    
在这个文件中,kind字段明确指出部署类型是"Job"。name字段定义了Kubernetes集群中的作业名称。backoffLimit字段设置为"1",表示如果作业失败,将重试一次。activeDeadlineSeconds字段设置为"900",表示如果执行时间超过900秒,作业将被终止。ttlSecondsAfterFinished字段设置为"60",表示作业完成后60秒内将自动删除。这些声明有助于在程序无法正常结束时控制资源使用。
name字段为容器指定了一个名称,image字段指定了从GCR注册表中使用的镜像。env字段将secrets.yaml文件中存储的数据作为环境变量传递给容器。restartPolicy字段设置为"OnFailure",表示如果容器失败,执行作业的Pod将重新启动。
接下来,来看一下Automatic-Training-PredictionAPI部署的YAML文件中最关键的标签:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gke-api
  labels:
    app: api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: gcr.io/automatictrainingcicd/prediction-api:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 5000
          env:
            - name: gmail_password
              valueFrom:
                secretKeyRef:
                  name: gmail-secrets
                  key: gmail_password
            - name: email_address
              value: svirahonda@gmail.com
---
apiVersion: v1
kind: Service
metadata:
  name: gke-api
  labels:
    app: api
spec:
  clusterIP: 10.127.240.120
  ports:
    - port: 5000
      protocol: TCP
  selector:
    app: api
  type: LoadBalancer
    
在这个文件中,kind字段声明了执行类型为"Deployment"。name字段为部署命名。replicas字段设置为"2",定义了将执行程序的Pod副本数量。image字段指定了从GCR使用的容器镜像。imagePullPolicy字段设置为"Always",强制容器构建过程不使用缓存容器。containerPort字段打开容器的5000端口。
env字段将secrets.yaml文件中存储的信息作为环境变量传递给容器。此外,文件中还有一个"LoadBalancer"类型的"service"块,该服务将通过固定的API地址和套接字将集群内的流量路由到Deployment Pods。
可能想知道这些YAML文件应该保存在哪里。YAML文件应该与.py文件保存在同一个目录中,并带有.yaml扩展名,然后推送到相应的仓库。这样,每个仓库都将有自己的.yaml文件,指示Kubernetes如何操作。AutomaticTraining-PredictionAPI的文件结构应该如下所示:
可以在这里找到项目的所有YAML文件:AutomaticTraining-CodeCommit、AutomaticTraining-DataCommit、AutomaticTraining-UnitTesting、AutomaticTraining-PredictionAPI和AutomaticTraining-Interface(可选)。