mcpField
M
ml-cloud-deployment

ml-cloud-deployment

github.com/josiahsiegelクラウド・DevOps5951 回インストール19 週間前に更新
リポジトリ

ml-cloud-deployment について

マネージドクラウド、Kubernetes、サーバーレス、GPU プロバイダー、レイクハウス環境での ML デプロイを扱うスキルです。ML エンジニア向けに、基盤の選定やハードウェア、エンドポイント、セキュリティ、コストの検討を支援します。

主な機能

  1. 01マネージドクラウドと Kubernetes の比較
  2. 02ボトルネックに応じたハードウェア選定
  3. 03エンドポイントのスケーリングとリリース計画
  4. 04セキュリティとコンプライアンスの確認
  5. 05コスト最適化の適用
  6. 06デプロイ準備チェックリストの活用

活用シーン

  1. 01モデルの学習・推論基盤の選定
  2. 02モデル処理に必要な GPU 容量の計画
  3. 03本番 ML エンドポイントの準備
  4. 04デプロイのセキュリティとコストの確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill ml-cloud-deployment

インストール後、Claude Code で/ml-cloud-deploymentを入力して読み込まれたか確認します。

詳細

ML クラウドデプロイ

概要

このスキルは、マネージドプラットフォーム、Kubernetes、サーバーレスシステム、GPU/TPU プロバイダー、レイクハウス環境に ML ワークロードをデプロイするときに使用します。まず、ワークロードの要件を確認します。学習か推論か、バッチかオンラインか、レイテンシ 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 中心の MLMLflow、Delta、Feature Store、Workflows を備えた AWS/Azure/GCP 上の Databricks
Kubernetes による制御Kubeflow、KServe、Seldon、Ray、Triton、カスタムオペレーターを備えた EKS/GKE/AKS
サーバーレスまたは高速な 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 CustomJob 仕様(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 の伝播、ポインターブロブ、プライベートストレージのファイアウォール処理については、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:従来型の ML、前処理、小規模モデル、レイテンシーが重視されないバッチジョブ。
  • T4/L4/A10 クラスの GPU:費用対効果の高い推論、小規模モデルのファインチューニング、ノートブック。
  • A100/H100/H200/B200 クラスの GPU:大規模モデルのトレーニング、高スループット推論、大容量メモリを必要とするワークロード。
  • TPU:大規模な、サポート対象の密なテンソルワークロード。特に JAX/TensorFlow エコシステム。
  • Inferentia/Trainium:モデルの演算子とフレームワークのサポートが成熟している場合に、AWS でコストパフォーマンスを向上できます。

起動前に、モデルの重み、オプティマイザーの状態、勾配、アクティベーション、KV キャッシュ、バッチサイズ、シーケンス長、ランタイムのオーバーヘッドを考慮してメモリを見積もります。推論では、現実的な同時実行数とペイロードサイズで p50/p95/p99 のレイテンシーをベンチマークします。

エンドポイント設計

リクエストスキーマ、レスポンススキーマ、タイムアウト、最大ペイロード、認証、レート制限、自動スケーリングポリシー、ヘルスチェック、ログ記録、ロールバックを定義します。本番環境では、カナリアリリースまたはブルーグリーンデプロイを使用します。GPU エンドポイントでは、動的バッチ処理と同時実行数を慎重に調整します。同時実行数が多すぎると、テールレイテンシーの増大や OOM の発生につながることがあります。マルチリージョンでデプロイする場合は、アーティファクトを複製し、モデルのバージョンを統一して、データレジデンシーとフェイルオーバーを計画します。

セキュリティとコンプライアンス

モデルが機密データにアクセスする場合は、プライベートネットワークを使用します。シークレットはクラウドのシークレットマネージャーに保存します。最小権限の IAM/サービスアカウント/マネージド ID を使用します。データとアーティファクトを暗号化します。アクセスイベントとデプロイイベントを記録します。コンテナをスキャンします。認証情報をイメージに埋め込まないようにします。パブリックエンドポイントには、認証、入力検証、不正利用対策、レート制限、LLM/RAG システム向けのプロンプトインジェクション対策を適用します。

コストの最適化

チェックポイントを使用するトレーニングやステートレスなバッチジョブには、スポットインスタンスまたはプリエンプティブルインスタンスを使用します。許容できる場合は、ゼロまでスケールする自動スケーリングエンドポイントを使用します。リアルタイムでないワークロードには、バッチ推論を優先します。レプリカをスケールする前に、モデルを量子化または蒸留します。GPU の台数だけでなく、GPU メモリも適正化します。ワークロードの特性が安定してから、予約容量または確約容量を使用します。実行ごと、モデルバージョンごと、予測 1,000 件ごとのコストを追跡します。

デプロイ準備チェックリスト

  • モデルアーティファクト、前処理、トークナイザー、設定がまとめてバージョン管理されている。
  • 入力スキーマが検証され、トレーニング時の特徴量と互換性がある。
  • 評価レポートに、関連するデータ区分とレイテンシー/コストのベンチマークが含まれている。
  • エンドポイントに、ヘルスチェック、自動スケーリング、ログ、メトリクス、アラート、ロールバックが備わっている。
  • セキュリティ対策で、ID、シークレット、ネットワーク、暗号化、監査を網羅している。
  • モニタリングで、ドリフト、データ品質、予測分布、結果、インシデントを把握できる。

参考資料

コメント