关于 ml-cloud-deployment
面向 ML 工程师的部署技能,涵盖托管云平台、Kubernetes、无服务器系统、GPU 服务商和 Lakehouse 环境。内容帮助选择基础设施,并规划硬件、端点、安全与成本。
主要功能
- 01比较托管云与 Kubernetes 方案
- 02按工作负载瓶颈选择硬件
- 03规划端点扩缩容与发布策略
- 04检查安全与合规控制
- 05采用成本优化方法
- 06使用部署就绪检查清单
适用场景
- 01为模型训练或推理选择基础设施
- 02规划模型工作负载的 GPU 容量
- 03准备可用于生产的 ML 端点
- 04检查部署的安全与成本
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ josiahsiegel/ claude-plugin-marketplace --skill ml-cloud-deployment安装后在 Claude Code 中输入/ml-cloud-deployment确认已加载。
详细介绍
ML 云部署
概述
使用此技能将 ML 工作负载部署到托管平台、Kubernetes、无服务器系统、GPU/TPU 提供商和湖仓环境。首先明确工作负载需求:训练或推理、批处理或在线、延迟 SLO、吞吐量、模型大小、数据重力、合规性、区域、硬件、团队专业能力和预算。
平台选择
| 需求 | 优选方案 |
|---|---|
| AWS 原生托管生命周期 | SageMaker Studio、Training、Processing、Pipelines、Model Registry、Endpoints、Feature Store、Clarify、Model Monitor |
| GCP 原生托管生命周期 | Vertex AI Training、Pipelines、Endpoints、Feature Store、Model Monitoring、AutoML、Matching Engine、TPU |
| Azure 原生托管生命周期 | Azure ML 工作区、计算集群、管道、注册表、托管在线/批处理端点、AutoML、Responsible ML |
| 以湖仓/Spark 为中心的 ML | AWS/Azure/GCP 上的 Databricks,搭配 MLflow、Delta、Feature Store、Workflows |
| Kubernetes 控制能力 | EKS/GKE/AKS,搭配 Kubeflow、KServe、Seldon、Ray、Triton、自定义运算符 |
| 无服务器或快速 GPU 应用 | Modal、Replicate、可用时支持 GPU 的 Cloud Run、用于小型 CPU 推理的 Lambda |
| 灵活租用 GPU | Lambda Labs、RunPod、自行管理的云 GPU VM |
| Ray 原生横向扩展 | Anyscale,或 Kubernetes/云 VM 上的 Ray 集群 |
当治理、可观测性和团队效率比运行时自定义更重要时,优先选择托管服务。当自定义网络、专用运行时或成本/性能调优占主导时,优先选择 Kubernetes 或 VM。
AWS 模式
SageMaker 负责托管训练任务、特征存储以及实时或无服务器端点。AWS CLI(aws sagemaker 和 aws sagemaker-runtime)用于以编程方式编排这些系统。
AWS SageMaker 端点变体配置(endpoint_config.json)
{
"EndpointConfigName": "production-llm-classifier-v1-cfg",
"ProductionVariants": [
{
"VariantName": "AllTraffic",
"ModelName": "llm-classifier-model-v1",
"InitialInstanceCount": 2,
"InstanceType": "ml.g5.2xlarge",
"InitialVariantWeight": 1.0,
"VolumeSizeInGB": 50,
"ManagedInstanceScaling": {
"MinInstanceCount": 2,
"MaxInstanceCount": 10,
"Status": "ENABLED"
},
"RoutingConfig": {
"RoutingStrategy": "LEAST_OUTSTANDING_REQUESTS"
}
}
]
}
AWS CLI SageMaker 生命周期管理
# 1. Setup Domain and default IAM Role/VPC settings
aws sagemaker create-domain \
--domain-name ProdMLDomain \
--auth-mode IAM \
--default-user-settings ExecutionRole=arn:aws:iam::123456789012:role/SageMakerExecutionRole \
--subnet-ids subnet-1a2b3c,subnet-4d5e6f \
--vpc-id vpc-0abc123 \
--app-network-access-type PublicInternetOnly
# 2. Provision and start/stop an interactive notebook instance
aws sagemaker create-notebook-instance \
--notebook-instance-name dev-notebook-instance \
--instance-type ml.t3.medium \
--role-arn arn:aws:iam::123456789012:role/SageMakerExecutionRole
aws sagemaker start-notebook-instance --notebook-instance-name dev-notebook-instance
aws sagemaker stop-notebook-instance --notebook-instance-name dev-notebook-instance
# 3. Submit a managed GPU training job
aws sagemaker create-training-job \
--training-job-name custom-pytorch-train-job \
--algorithm-specification TrainingImage=763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-training:1.12.0-gpu-py38-cu113-ubuntu20.04,TrainingInputMode=File \
--role-arn arn:aws:iam::123456789012:role/SageMakerExecutionRole \
--input-data-config '[{"ChannelName": "training", "DataSource": {"S3DataSource": {"S3DataType": "S3Prefix", "S3Uri": "s3://my-ml-bucket/train-data/", "S3DataDistributionType": "FullyReplicated"}}}]' \
--output-data-config S3OutputPath=s3://my-ml-bucket/checkpoints/ \
--resource-config InstanceType=ml.g5.2xlarge,InstanceCount=1,VolumeSizeInGB=50 \
--stopping-condition MaxRuntimeInSeconds=86400
# 4. Register a model in the SageMaker Model Registry
aws sagemaker create-model-package-group \
--model-package-group-name credit-scoring-group \
--model-package-group-description "Model registry group for credit scoring neural nets"
aws sagemaker create-model \
--model-name credit-scoring-v1 \
--primary-container Image=763104351884.dkr.ecr.us-east-1.amazonaws.com/pytorch-inference:1.12.0-gpu-py38,ModelDataUrl=s3://my-ml-bucket/checkpoints/custom-pytorch-train-job/output/model.tar.gz \
--execution-role-arn arn:aws:iam::123456789012:role/SageMakerExecutionRole
# 5. Create Endpoint Configuration and Deploy Endpoint
aws sagemaker create-endpoint-config \
--endpoint-config-name credit-scoring-v1-cfg \
--production-variants '[{"VariantName": "AllTraffic", "ModelName": "credit-scoring-v1", "InitialInstanceCount": 2, "InstanceType": "ml.m5.xlarge", "InitialVariantWeight": 1.0}]'
aws sagemaker create-endpoint \
--endpoint-name credit-scoring-prod-endpoint \
--endpoint-config-name credit-scoring-v1-cfg
# 6. Invoke/Test Endpoint via CLI
aws sagemaker-runtime invoke-endpoint \
--endpoint-name credit-scoring-prod-endpoint \
--content-type application/json \
--body '{"features": [0.25, 1.4, 0.9]}' \
response_output.json
GCP 模式
Vertex AI 通过 gcloud ai 管理训练管道、超参数调优扫描、自定义任务、模型注册表和预测。
GCP Vertex AI TPU 自定义任务规范(tpu_job.yaml)
displayName: vertex-ai-tpu-training-job
studySpec:
metrics:
- metricId: val_loss
goal: MINIMIZE
parameters:
- parameterId: learning_rate
doubleValueSpec:
minValue: 1e-5
maxValue: 1e-3
scaleType: UNIT_LOG_SCALE
trialJobSpec:
workerPoolSpecs:
- machineSpec:
machineType: n1-standard-8
replicaCount: 1
containerSpec:
imageUri: gcr.io/my-project/ml-trainer:latest
- machineSpec:
machineType: cloud-tpu-v4-podslice
acceleratorType: TPU_V4
acceleratorCount: 4
replicaCount: 1
containerSpec:
imageUri: gcr.io/my-project/ml-tpu-trainer:latest
args: [
"--data_path", "gs://my-bucket/dataset-v1",
"--epochs", "10"
]
GCP Vertex AI CLI 操作
# 1. Create a user-managed Jupyter Workbench instance
gcloud notebooks instances create dev-workbench-instance \
--location=us-central1-a \
--vm-image-project=deeplearning-platform-release \
--vm-image-family=common-gpu \
--machine-type=n1-standard-4
# 2. Submit containerized custom training job
gcloud ai custom-jobs create \
--region=us-central1 \
--display-name=gpu-pytorch-training-run \
--worker-pool-spec=replica-count=1,machine-type=n1-standard-8,accelerator-type=nvidia-tesla-t4,accelerator-count=1,container-image-uri=gcr.io/my-gcp-project/pytorch-train-custom:v1 \
--args="--epochs=20,--data-path=gs://my-bucket/training-gold"
# 3. Upload model artifact to Model Registry
gcloud ai models upload \
--region=us-central1 \
--display-name=iris-classifier-v1 \
--container-image-uri=us-docker.pkg.dev/vertex-ai/prediction/pytorch-cpu.1-11:latest \
--artifact-uri=gs://my-bucket/models/iris-classifier/
# 4. Provision endpoint and deploy model with 100% traffic allocation
# Note: replace <ENDPOINT-ID> and <MODEL-ID> with their UUIDs
gcloud ai endpoints create \
--region=us-central1 \
--display-name=production-iris-endpoint
gcloud ai endpoints deploy-model <ENDPOINT-ID> \
--region=us-central1 \
--model=<MODEL-ID> \
--display-name=iris-v1-blue-deployment \
--machine-type=n1-standard-4 \
--min-replica-count=2 \
--max-replica-count=10 \
--traffic-split=0=100
# 5. Predict via Vertex AI Endpoint CLI
gcloud ai endpoints predict <ENDPOINT-ID> \
--region=us-central1 \
--json-request=sample_payload.json
Azure 模式
Azure AI Foundry / Azure Machine Learning Workspace 可编排整个 ML 生命周期。可使用 Azure CLI ml 扩展原生管理工作区、计算资源、环境、数据资产、训练任务、模型和端点。若要从 CI 注册 Azure ML 代码资产、使用 ADF 编排、配置 ADF WebActivity 网络、传播 result.version、使用指针 Blob,或处理私有存储防火墙,请加载 ml-azureml-adf-automation。
Azure ML v2 CLI 在线端点与部署 YAML(azure_deploy.yaml)
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: credit-risk-endpoint
auth_mode: key
---
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: credit-risk-blue
endpoint_name: credit-risk-endpoint
model: azureml:credit-risk-model:1
code_configuration:
code: ./src
scoring_script: score.py
environment: azureml:credit-risk-env:1
instance_type: Standard_DS3_v2
instance_count: 2
request_settings:
request_timeout_ms: 3000
max_concurrent_requests_per_instance: 10
scale_settings:
type: default
Azure AI Foundry / Azure ML Workspace CLI 管理(az ml)
# Add/update the Machine Learning CLI extension
az extension add -n ml -y
az login
# 1. Create a Resource Group and Azure ML Workspace (Azure AI Foundry Hub)
az group create --name my-ml-rg --location eastus
az ml workspace create --name my-ml-workspace --resource-group my-ml-rg --location eastus
# 2. Provision Computes (Instance, Training Cluster, CPU cluster)
az ml compute create --name dev-compute-ci --type ComputeInstance --size Standard_DS3_v2 -g my-ml-rg -w my-ml-workspace
az ml compute create --name gpu-train-cluster --type AmlCompute --size Standard_NC6s_v3 --min-instances 0 --max-instances 4 -g my-ml-rg -w my-ml-workspace
az ml compute create --name cpu-proc-cluster --type AmlCompute --size Standard_DS12_v2 --min-instances 0 --max-instances 8 -g my-ml-rg -w my-ml-workspace
# 3. Create a URI Data Asset
az ml data create --file data.yaml -g my-ml-rg -w my-ml-workspace
# 4. Create an Environment definition
az ml environment create --file env.yaml -g my-ml-rg -w my-ml-workspace
# 5. Submit, Monitor, and Stream a Command Job
az ml job create --file job.yaml -g my-ml-rg -w my-ml-workspace --web --stream
# View, list and monitor jobs
az ml job list -g my-ml-rg -w my-ml-workspace --output table
az ml job stream --name <job-id> -g my-ml-rg -w my-ml-workspace
az ml job download --name <job-id> --download-path ./outputs -g my-ml-rg -w my-ml-workspace
# 6. Register a Model
az ml model create --file model.yaml -g my-ml-rg -w my-ml-workspace
# 7. Create Endpoint, Deploy, Test, and Cleanup
az ml online-endpoint create --file endpoint.yaml -g my-ml-rg -w my-ml-workspace
az ml online-deployment create --file deployment.yaml --all-traffic -g my-ml-rg -w my-ml-workspace
# List and monitor endpoints:
az ml online-endpoint show --name credit-risk-endpoint -g my-ml-rg -w my-ml-workspace
# Test endpoint with a sample payload file:
az ml online-endpoint invoke --name credit-risk-endpoint --request-file ./sample_request.json -g my-ml-rg -w my-ml-workspace
# Delete endpoint:
az ml online-endpoint delete --name credit-risk-endpoint --yes -g my-ml-rg -w my-ml-workspace
本地和混合云提供商(MLflow 和 Kubernetes/KServe)
对于本地开发或自定义多云 Kubernetes 集群,MLflow 和 KServe 可提供标准化能力。
MLflow 本地 CLI 管理
# 1. Start a local tracking and model registry server
mlflow server \
--host 127.0.0.1 \
--port 5000 \
--backend-store-uri sqlite:///mlflow.db \
--default-artifact-root ./mlflow_artifacts_store
# 2. Run a packaged local MLflow Project with runtime parameters
mlflow run . -P alpha=0.1 -P l1_ratio=0.2 --experiment-name iris-training
# 3. Serve a registered model locally
mlflow models serve \
--model-uri models:/iris-classifier/Production \
--port 5001 \
--no-conda
# 4. Invoke the local serving endpoint
curl -X POST -H "Content-Type: application/json" \
-d '{"dataframe_split": {"columns": ["sepal_len", "sepal_wid"], "data": [[5.1, 3.5]]}}' \
http://127.0.0.1:5001/invocations
Kubernetes 原生服务 CLI(KServe)
# kserve-inference.yaml
apiVersion: "serving.kserve.io/v1beta1"
kind: "InferenceService"
metadata:
name: "sklearn-iris"
namespace: "ml-serving"
spec:
predictor:
model:
modelFormat:
name: sklearn
storageUri: "gs://kfserving-examples/models/sklearn/1.0/model"
resources:
limits:
cpu: "1"
memory: 2Gi
requests:
cpu: "500m"
memory: 1Gi
# 1. Apply inference manifests via kubectl
kubectl apply -f kserve-inference.yaml -n ml-serving
# 2. Monitor status and readiness of inference service
kubectl get inferenceservice sklearn-iris -n ml-serving
# 3. Port forward or direct payload query through Istio ingress gateway
SERVICE_HOSTNAME=$(kubectl get inferenceservice sklearn-iris -n ml-serving -o jsonpath='{.status.url}' | cut -d/ -f3)
INGRESS_IP=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http2")].port}')
curl -v -H "Host: ${SERVICE_HOSTNAME}" \
http://${INGRESS_IP}:${INGRESS_PORT}/v1/models/sklearn-iris:predict \
-d @sample_payload.json
无服务器 GPU 服务(Modal 模式)
对于在隔离 GPU 上进行无服务器部署并优化冷启动延迟的场景,请使用 Modal。
import modal
app = modal.App("serverless-image-classifier")
# Pre-packaged CUDA image with dependencies
image = (
modal.Image.debian_slim()
.pip_install("torch", "torchvision", "transformers")
)
@app.cls(gpu="A10G", image=image)
class ImageClassifier:
@modal.enter()
def load_model(self):
import torch
from transformers import ViTForImageClassification, ViTImageProcessor
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
self.model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224").to(self.device)
@modal.method()
def predict(self, image_bytes: bytes):
from PIL import Image
import io
image = Image.open(io.BytesIO(image_bytes))
inputs = self.processor(images=image, return_tensors="pt").to(self.device)
outputs = self.model(**inputs)
logits = outputs.logits
predicted_class_idx = logits.argmax(-1).item()
return self.model.config.id2label[predicted_class_idx]
硬件选择
根据瓶颈匹配硬件:
- CPU:传统机器学习、预处理、小型模型,以及对延迟不敏感的批处理作业。
- T4/L4/A10 级 GPU:经济高效的推理、较小模型的微调、笔记本环境。
- A100/H100/H200/B200 级 GPU:大型模型训练、高吞吐量推理、内存密集型工作负载。
- TPU:大规模运行受支持的稠密张量工作负载,尤其适用于 JAX/TensorFlow 生态系统。
- Inferentia/Trainium:当模型算子和框架支持成熟时,可在 AWS 上实现高性价比。
启动前估算内存:模型权重、优化器状态、梯度、激活值、KV 缓存、批量大小、序列长度和运行时开销。对于推理,应在符合实际情况的并发量和负载大小下,对 p50/p95/p99 延迟进行基准测试。
端点设计
定义请求架构、响应架构、超时时间、最大负载、身份验证、速率限制、自动扩缩策略、运行状况检查、日志记录和回滚方案。在生产环境中使用金丝雀发布或蓝绿发布。对于 GPU 端点,应谨慎调整动态批处理和并发;并发过高可能增加尾延迟或导致 OOM。对于多区域部署,应复制制品、保持模型版本一致,并规划数据驻留和故障转移。
安全与合规
当模型需要访问敏感数据时,使用专用网络。在云端密钥管理服务中存储密钥。遵循 IAM/服务账号/托管标识的最小权限原则。对数据和制品进行加密。记录访问和部署事件。扫描容器。避免将凭据写入镜像。对于公共端点,应实施身份验证、输入验证、滥用防护、速率限制,以及针对 LLM/RAG 系统的提示词注入防护。
成本优化
对带检查点的训练和无状态批处理作业使用 Spot/可抢占实例。在可接受的情况下,使用可缩减至零的自动扩缩端点。对于非实时工作负载,优先采用批量推理。在扩增副本前先对模型进行量化或蒸馏。合理配置 GPU 内存,而不只是 GPU 数量。只有在工作负载形态稳定后,才使用预留/承诺容量。按运行、模型版本以及每 1,000 次预测跟踪成本。
部署就绪检查清单
- 模型制品、预处理、分词器和配置一并进行版本管理。
- 输入架构经过验证,并与训练特征兼容。
- 评估报告包含相关切片以及延迟/成本基准测试。
- 端点具备运行状况检查、自动扩缩、日志、指标、告警和回滚机制。
- 安全控制覆盖身份、密钥、网络、加密和审计。
- 监控涵盖漂移、数据质量、预测分布、结果和事件。
来源
- AWS SageMaker 文档:https://docs.aws.amazon.com/sagemaker/
- Google Vertex AI 文档:https://cloud.google.com/vertex-ai/docs
- Azure Machine Learning 文档:https://learn.microsoft.com/azure/machine-learning/
- Databricks Machine Learning 文档:https://docs.databricks.com/machine-learning/
- Ray 和 Anyscale 文档:https://docs.ray.io/ 和 https://docs.anyscale.com/