PMLE 学習ハブ
🎯 公式ドキュメント準拠 / 深掘り

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
TaskComponent に input を渡したインスタンスpreprocess(data_path="gs://...")
ArtifactTask の入出力(モデル・データセット・メトリクス)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],
    )

コンパイル → 実行のフロー

[Python pipeline 関数 (@dsl.pipeline)] ↓ kfp.compiler.Compiler().compile(pipeline_func, "pipeline.json") [Intermediate Representation (YAML/JSON)] ↓ Vertex AI に submit [Pipeline Run] ├─ component を並列実行(依存性により自動順序) ├─ Artifact を ML Metadata に登録 ├─ Cache 判定(入力ハッシュ) └─ 失敗時は retry_policy / failure_policy に従う
並列実行が default 公式:「By default, pipeline tasks run in parallel. You can link the tasks to execute them in series.」依存性のないタスクは勝手に並列化されるため、リソース競合・課金スパイクに注意。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.

自動収集されるもの

Knowledge Catalog 連携

search for a pipeline artifact and view its lineage graph」 in Knowledge Catalog。fully qualified names を使うので、複数プロジェクト・複数 Pipeline のアーティファクトが衝突しない設計。

Lineage の使いどころ
  • 監査:「この本番モデルはどの訓練データ・どのコードコミットから?」を辿る
  • 影響分析:「この訓練データセットを使ったモデル・推論結果はどれ?」(影響範囲特定)
  • 再現性:本番障害時の同条件再現

⏰ トリガーと 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 に押し込めず、適切なエンジンへ。

失敗時の戦略

監視・通知

📡 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 v1Model Monitoring v2
状態GAPreview
単位EndpointModel Version
対応シーンOnline Endpoint のみOnline + Batch + 外部 (Vertex 外)
検知Feature skew/drift + (任意) attributionInput/Output drift + Feature Attribution drift(v1+)
料金通常課金Preview 中は v2 自体は 無料(関連サービスは課金)
推奨「production-level support」が必要 + Vertex Endpoint 監視それ以外の全ケース
移行戦略 公式:「You can maintain both versions concurrently until you have fully migrated to v2 to help you avoid monitoring gaps during your transition.」両方同時稼働でモニタリング空白を防ぐのが推奨パターン。

設定の流れ(v2)

  1. Model Registry にモデルを登録
  2. Model Monitor リソースを 特定の model version に関連付け 作成
  3. モデルスキーマ定義(AutoML は自動検出)
  4. デフォルトの monitoring config(objectives / training dataset / output location / notifications)
  5. 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 ExposureIP・PII の漏洩防止SDP 連携、Basic / Advanced モード
Malicious URLフィッシング・マルウェア URLscans 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 する。

公式推奨の導入手順Inspect only」で開始 →「understand potential block rates and efficacy for your specific use case」を把握 → 安心して「Inspect and Block」へ移行。いきなり Block を有効化すると正当リクエストが大量に拒否される事故が起きる。

サポート対象とリミット

ドキュメント形式

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(公式記載)
試験は「2026/6/1 以降の新ガイド」準拠なので、Explainable AI の手法概念は出題対象。「Vertex Explainable AI」という固有名称ではなく、「Agent Platform Inference の Explainability」として理解 しておくこと。

📐 3 手法の使い分け

手法原理適するモデル適するデータ
Sampled ShapleyShapley 値のサンプリング近似(協力ゲーム理論)Non-differentiable(決定木・XGBoost・アンサンブル)Tabular、AutoML Tables
Integrated Gradients入力勾配を baseline からの積分で積算(Gaussian quadrature)Differentiable(NN)Tabular + 画像(低コントラスト画像、X 線に強い)
XRAIIntegrated Gradients + Felzenswalb 領域分割 + 領域単位の寄与度ランキングNN(特に CNN)自然画像(複数オブジェクト)

主要パラメータ

path_count (Sampled Shapley)

サンプリングパス数。多いほど精度↑、計算コスト↑、レイテンシ↑。本番は 25〜50 が現実的。

steps_count (Integrated Gradients)

勾配積分のステップ数。多いほど精度↑、レイテンシ↑。50〜100 が標準。

Local vs Global Explanation

公式の本質的な限界の警告
  1. Feature attributions are subject to similar adversarial attacks as inferences in complex models.」— 攻撃者は属性スコアも操作できる
  2. attributions are specific to individual inferences ... the insight may not be generalizable」— Local 結果を class 全体に拡張するのは危険
  3. Attributions don't definitively diagnose whether issues stem from data or model」— 「データの問題か モデルの問題か」を断言する道具ではない

Example-Based Explanation(補助手法)

⚠️ リスクと注意点

本番でよく踏むリスク 12 選
  1. Pipelines の並列実行で課金スパイク:依存性のないタスクは勝手に並列化される。GPU タスク多発で月末に意外な請求
  2. Pipeline cache 有効のまま本番:最新データを使うべき本番で前回結果が返ってしまう。本番では明示的に無効化
  3. Schedule 設定忘れの retry policy:失敗時のリトライ無しで sleep するシナリオ多発
  4. Pipeline 内で重 ETL 実行:Pipelines 内に押し込めず、Dataflow / BigQuery / Managed Spark に委譲する
  5. Model Monitoring v2 = GA 前提:実態は Preview。本番 SLA が必要な Endpoint 監視は v1 推奨
  6. カテゴリ特徴の skew 検知漏れ:v2 は categorical に L-Infinity + JS Divergence 両方使う設計。1 つだけ見ていると急変を漏らす
  7. Feature Attribution Drift を無視:Data Drift が出なくても重要度の入れ替わりは精度劣化の前触れ
  8. Model Armor をいきなり Block モード:正当リクエスト大量拒否事故。必ず Inspect Only から開始
  9. Model Armor の URL スキャン上限 40:プロンプト内 41 番目以降の URL はスキャン対象外。攻撃者は URL を後方に置く
  10. Model Armor 入出力で同テンプレート:「Decoupling templates」が公式推奨。入力は厳しく、出力は緩く(または逆)
  11. Explainable AI の deprecation を無視:2027/3/16 でアクセス停止。新規プロジェクトは Agent Platform 経由で
  12. Local explanation を class に一般化:「この患者が陽性 = 全患者で同じ特徴が重要」は誤り

📚 参考リンク(一次情報)