Deep Dive: MLOps Pipelines & Monitoring
§5+§6 を、Google Cloud の公式ドキュメントの文面に沿って深掘りします。 Vertex AI Pipelines (KFP v2)・Model Monitoring v2・Model Armor・Explainable AI の本番運用と落とし穴に焦点。
⛓ Vertex AI Pipelines
「An ML pipeline is a directed acyclic graph (DAG) of containerized pipeline tasks that are interconnected using input-output dependencies.」サーバーレスで KFP / TFX を実行できるオーケストレータ。
🏗 KFP v2 アーキテクチャ
3 つのコア抽象
| 抽象 | 役割 | 具体例 |
|---|---|---|
| Component | 「self-contained set of code that performs a specific step」 | preprocess / train / evaluate / register |
| Task | Component に input を渡したインスタンス | preprocess(data_path="gs://...") |
| Artifact | Task の入出力(モデル・データセット・メトリクス) | Model / Dataset / Metrics / HTML |
Component の書き方 2 通り
公式は「You can author tasks either in Python or as a prebuilt container images.」と明記。
from kfp import dsl, compiler
from kfp.dsl import Output, Model, Dataset, Metrics
@dsl.component(
base_image="python:3.11",
packages_to_install=["scikit-learn==1.4", "pandas==2.2"],
)
def train(
data_path: str,
learning_rate: float,
model_out: Output[Model],
metrics_out: Output[Metrics],
):
import joblib, pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.read_csv(data_path)
clf = LogisticRegression(C=learning_rate)
clf.fit(df.drop("y", axis=1), df["y"])
joblib.dump(clf, model_out.path)
metrics_out.log_metric("train_score", clf.score(df.drop("y", axis=1), df["y"]))
from kfp import dsl
@dsl.container_component
def custom_train(
data_path: str,
model: dsl.Output[dsl.Model],
):
return dsl.ContainerSpec(
image="us-central1-docker.pkg.dev/my-project/repo/trainer:v3",
command=["python", "/app/train.py"],
args=["--data", data_path, "--model-out", model.path],
)
コンパイル → 実行のフロー
task1.after(task2) で明示的に直列化可能。
📊 ML Metadata と Lineage
「When you run a pipeline using Vertex AI Pipelines, all parameters and artifact metadata consumed and generated by the pipeline are stored in Vertex ML Metadata.」
自動収集されるもの
- 各 task の入力パラメータ・出力アーティファクト
- アーティファクト間の lineage graph(input → materialized → output)
- Pipeline run ID と各 task の実行履歴
- カスタムメタデータスキーマ(任意で追加可能)
Knowledge Catalog 連携
「search for a pipeline artifact and view its lineage graph」 in Knowledge Catalog。fully qualified names を使うので、複数プロジェクト・複数 Pipeline のアーティファクトが衝突しない設計。
- 監査:「この本番モデルはどの訓練データ・どのコードコミットから?」を辿る
- 影響分析:「この訓練データセットを使ったモデル・推論結果はどれ?」(影響範囲特定)
- 再現性:本番障害時の同条件再現
⏰ トリガーと CI/CD/CT
スケジュール実行
「use the scheduler API to create recurring pipeline runs from the same ML pipeline definition」。Cloud Scheduler とは別の専用 Schedule API がある。
イベント駆動
「Trigger a pipeline run with Pub/Sub」が公式パターン。GCS 新ファイル → Eventarc → Pub/Sub → Pipelines で CT を実現。
Cloud Build 統合
コード push → Cloud Build trigger → コンテナビルド → Artifact Registry → Pipelines submit。CI/CD/CT 自動化の標準パターン。
外部実行エンジン委譲
「delegate your workload to another execution engine, such as BigQuery, Dataflow, or Managed Service for Apache Spark」。重い ETL は Pipelines に押し込めず、適切なエンジンへ。
失敗時の戦略
- Failure Policy:失敗時に
fail-fast(即停止)orfail-slow(依存性のないタスクは続行)を選べる - Retry Policy:task ごとに最大回数 + バックオフ
- Execution Caching:入力ハッシュベース。本番では明示的に無効化することも考慮(最新データを使うため)
監視・通知
- Email notifications:pipeline 失敗時の自動メール
- Cloud Logging:log entries で監視イベント作成
- Pipeline run 比較ビュー:複数 run のメトリクスを並べて比較
- Cloud Billing export to BigQuery:run ごとのコスト分析
📡 Model Monitoring v2 — モデル単位の監視へ
「Vertex AI Model Monitoring v2 ... associates all monitoring tasks with a model version」。v1 は Endpoint 単位だったが、v2 は Model Version 単位 に進化(重要なアーキテクチャ転換)。
📊 統計指標と検知対象
監視対象 3 つ(tabular モデル向け)
| 監視対象 | 説明 | 必要なベースライン |
|---|---|---|
| Input feature data drift | 「distribution of input feature values compared to a baseline」 | 訓練データ or 過去本番ウィンドウ |
| Output inference data drift | 予測値そのものの分布変化 | 過去予測ウィンドウ |
| Feature attribution drift | 「change in contribution of features to a model's inference compared to a baseline」 | Explainable AI と統合(SHAP) |
統計手法(型別)
| データ型 | 使用される統計指標 |
|---|---|
| Categorical (boolean, string, categorical) | L-Infinity + Jensen-Shannon Divergence |
| Numerical (float, integer) | Jensen-Shannon Divergence のみ |
- L-Infinity:全カテゴリの最大差分。少数カテゴリの急変に強い
- Jensen-Shannon Divergence:分布全体の対称的距離。徐々に進む分布変化を捉える
- categorical は両方を使うことで「急変」と「漸進」の両方を漏らさない
Feature Attribution Drift と Explainable AI の統合
v2 は SHAP 値を使用:「typically signed, indicating whether a feature helps push the inference up or down」。 属性スコアの分布変化を継続監視 →「a change in a key feature's attribution score often signals that the feature has changed in a way that can impact the accuracy」。 従来の Data Drift では検知できない 「特徴量の重要度が静かに入れ替わる」 変化を捉えられる。
🔀 v1 vs v2 の選び方
| Model Monitoring v1 | Model Monitoring v2 | |
|---|---|---|
| 状態 | GA | Preview |
| 単位 | Endpoint | Model Version |
| 対応シーン | Online Endpoint のみ | Online + Batch + 外部 (Vertex 外) |
| 検知 | Feature skew/drift + (任意) attribution | Input/Output drift + Feature Attribution drift(v1+) |
| 料金 | 通常課金 | Preview 中は v2 自体は 無料(関連サービスは課金) |
| 推奨 | 「production-level support」が必要 + Vertex Endpoint 監視 | それ以外の全ケース |
設定の流れ(v2)
- Model Registry にモデルを登録
- Model Monitor リソースを 特定の model version に関連付け 作成
- モデルスキーマ定義(AutoML は自動検出)
- デフォルトの monitoring config(objectives / training dataset / output location / notifications)
- on-demand 実行 or scheduled で継続監視
🛡 Model Armor — LLM 向け WAF
「proactively screening LLM prompts and responses, protecting against various risks and ensuring responsible AI practices」。プロンプト・応答の双方を ステートレスで in-memory 処理 し、分析後は即座に破棄。
⚠️ 脅威カテゴリと閾値
検知対象
| 脅威 | 説明 | 備考 |
|---|---|---|
| Prompt Injection / Jailbreak | 「special commands within the text input to trick an AI model」 | 入力 + 出力の両方を検査 |
| Sensitive Data Exposure | IP・PII の漏洩防止 | SDP 連携、Basic / Advanced モード |
| Malicious URL | フィッシング・マルウェア URL | 「scans only the first 40 URLs found」(要注意) |
| Hate Speech | 差別的・有害発言 | Responsible AI Safety Filters の 1 つ |
| Harassment | 脅迫・いじめ・侮辱 | 同上 |
| Sexually Explicit | 性的コンテンツ | 同上 |
| Dangerous Content | 有害物質・違法行為の助長 | 同上 |
| CSAM | 児童性的虐待コンテンツ | 「applied by default and cannot be turned off」 |
信頼度 (Confidence Threshold)
| 閾値 | 検知 | False Positive | 適合シーン |
|---|---|---|---|
| High | 「near-certain violations only」 | 非常に低 | 本番 — ユーザー体験優先 |
| Medium and above | 「medium or high likelihood」 | 中 | 標準的エンタープライズアプリ |
| Low and above | 「even slight indications」 | 高 | High-stakes(prompt injection)など |
- カテゴリ別に閾値を分ける:通常は High または Medium and above、Prompt Injection だけ Low and above
- テンプレート分離 (decoupling):入力用と出力用で別々のテンプレート(リスクプロファイルが違うため)
- 反復テスト:known good / known bad の代表データセットで調整
- Gemini Enterprise 連携時は High:公式が「avoid false positives」のため明示推奨
🚥 Inspect vs Block の 2 段階運用
Inspect Only(観測のみ)
「logs the detection event in Cloud Logging」だが処理は継続。ポリシー testing・新興脅威モニタリング・コンプライアンス監査に最適。
Inspect and Block(遮断)
違反時は「the prompt is blocked and not sent to the LLM」または応答ブロック。アプリは block verdict を受け取り、リクエストを deny する。
サポート対象とリミット
ドキュメント形式
PDF / Word (DOCX/DOCM/DOTX/DOTM) / PowerPoint (PPTX/PPTM/POTX/POTM/POT) / Excel (XLSX/XLSM/XLTX/XLTM)。入力サイズ上限 4 MB。
言語
公式テスト済み:中(普通話) / 英 / 仏 / 独 / 伊 / 日 / 韓 / 葡 / 西。他言語でも動くが品質保証なし。
データ取扱
「stateless service, processing entirely in memory」、分析後即破棄。Cloud Logging への記録のみ顧客制御。TLS 1.2+、データレジデンシー (US / EU) 対応。
料金
Security Command Center 統合 or standalone。トークンベース課金(入出力トークン総量)。SCC pricing 参照。
🔍 Vertex Explainable AI
⚠️ 重要:Deprecation 通知
- 2026 年 3 月 16 日:deprecated(新規利用非推奨)
- 2027 年 3 月 16 日:完全アクセス停止
- 移行先:Gemini Enterprise Agent Platform(公式記載)
📐 3 手法の使い分け
| 手法 | 原理 | 適するモデル | 適するデータ |
|---|---|---|---|
| Sampled Shapley | Shapley 値のサンプリング近似(協力ゲーム理論) | Non-differentiable(決定木・XGBoost・アンサンブル) | Tabular、AutoML Tables |
| Integrated Gradients | 入力勾配を baseline からの積分で積算(Gaussian quadrature) | Differentiable(NN) | Tabular + 画像(低コントラスト画像、X 線に強い) |
| XRAI | Integrated Gradients + Felzenswalb 領域分割 + 領域単位の寄与度ランキング | NN(特に CNN) | 自然画像(複数オブジェクト) |
主要パラメータ
path_count (Sampled Shapley)
サンプリングパス数。多いほど精度↑、計算コスト↑、レイテンシ↑。本番は 25〜50 が現実的。
steps_count (Integrated Gradients)
勾配積分のステップ数。多いほど精度↑、レイテンシ↑。50〜100 が標準。
Local vs Global Explanation
- Local:個別予測の説明(「この患者が陽性予測された理由はこの 3 特徴量」)。online/batch prediction と同時に返る
- Global:AutoML の場合自動で「model feature importance」を提供。Custom モデルは「データセット全体・サブセット上で attribution を集約」して取得
- 「Feature attributions are subject to similar adversarial attacks as inferences in complex models.」— 攻撃者は属性スコアも操作できる
- 「attributions are specific to individual inferences ... the insight may not be generalizable」— Local 結果を class 全体に拡張するのは危険
- 「Attributions don't definitively diagnose whether issues stem from data or model」— 「データの問題か モデルの問題か」を断言する道具ではない
Example-Based Explanation(補助手法)
- 近傍検索:訓練データから「最も似た例」を返す
- 用途:訓練データの gap 発見・新規データ解釈・異常検知・active learning
- 制限:「Tree-based models, such as decision trees, are not supported. Models from other frameworks, such as PyTorch or XGBoost, are not supported yet.」TF + embedding 提供モデルのみ
⚠️ リスクと注意点
- Pipelines の並列実行で課金スパイク:依存性のないタスクは勝手に並列化される。GPU タスク多発で月末に意外な請求
- Pipeline cache 有効のまま本番:最新データを使うべき本番で前回結果が返ってしまう。本番では明示的に無効化
- Schedule 設定忘れの retry policy:失敗時のリトライ無しで sleep するシナリオ多発
- Pipeline 内で重 ETL 実行:Pipelines 内に押し込めず、Dataflow / BigQuery / Managed Spark に委譲する
- Model Monitoring v2 = GA 前提:実態は Preview。本番 SLA が必要な Endpoint 監視は v1 推奨
- カテゴリ特徴の skew 検知漏れ:v2 は categorical に L-Infinity + JS Divergence 両方使う設計。1 つだけ見ていると急変を漏らす
- Feature Attribution Drift を無視:Data Drift が出なくても重要度の入れ替わりは精度劣化の前触れ
- Model Armor をいきなり Block モード:正当リクエスト大量拒否事故。必ず Inspect Only から開始
- Model Armor の URL スキャン上限 40:プロンプト内 41 番目以降の URL はスキャン対象外。攻撃者は URL を後方に置く
- Model Armor 入出力で同テンプレート:「Decoupling templates」が公式推奨。入力は厳しく、出力は緩く(または逆)
- Explainable AI の deprecation を無視:2027/3/16 でアクセス停止。新規プロジェクトは Agent Platform 経由で
- Local explanation を class に一般化:「この患者が陽性 = 全患者で同じ特徴が重要」は誤り