jrmccluskey commented on code in PR #39738:
URL: https://github.com/apache/beam/pull/39738#discussion_r3816328240


##########
sdks/python/apache_beam/ml/inference/vertex_ai_model_monitoring_v2.py:
##########
@@ -0,0 +1,405 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""A PTransform for integrating Vertex AI Model Monitoring v2 with Apache Beam 
RunInference.
+
+Vertex AI Model Monitoring v2 provides drift and skew detection on arbitrary
+models by evaluating input features, predictions, and attribution stats logged
+to BigQuery against a training baseline.
+"""
+
+import logging
+import time
+from collections.abc import Callable
+from typing import Any
+from typing import Optional
+from typing import Union
+
+import apache_beam as beam
+from apache_beam.io.gcp.bigquery import WriteResult
+from apache_beam.io.gcp.bigquery import WriteToBigQuery
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.options.pipeline_options import StandardOptions
+from apache_beam.transforms.util import WaitOn
+
+try:
+  from google.api_core import exceptions
+  from vertexai.resources.preview import ml_monitoring
+except ImportError:
+  exceptions = None
+  ml_monitoring = None
+
+__all__ = [
+    'VertexModelMonitoringV2',
+]
+
+
+class _V2JobManager(beam.DoFn):
+  """Base DoFn for managing Vertex AI Model Monitoring v2 lifecycle."""
+  def __init__(
+      self,
+      project_id: str,
+      location: str,
+      display_name: str,
+      model_name: str,
+      model_version_id: str,
+      model_monitoring_schema: Any,
+      training_dataset: Any,
+      tabular_objective_spec: Any,
+      model_monitor_id: Optional[str] = None,
+      explanation_spec: Optional[Any] = None,
+      output_spec: Optional[Any] = None,
+      notification_spec: Optional[Any] = None,
+      credentials: Optional[Any] = None,
+  ):
+    self.project_id = project_id
+    self.location = location
+    self.display_name = display_name
+    self.model_name = model_name
+    self.model_version_id = model_version_id
+    self.model_monitoring_schema = model_monitoring_schema
+    self.training_dataset = training_dataset
+    self.tabular_objective_spec = tabular_objective_spec
+    self.model_monitor_id = model_monitor_id
+    self.explanation_spec = explanation_spec
+    self.output_spec = output_spec
+    self.notification_spec = notification_spec
+    self.credentials = credentials
+    self.manager = None
+
+  def create_model_monitor(self):
+    """Creates a ModelMonitor with a deterministic ID or retrieves existing 
one."""
+    if ml_monitoring is None:
+      raise ImportError(
+          'Vertex AI Model Monitoring v2 dependencies are not installed.')
+
+    try:
+      return ml_monitoring.model_monitors.ModelMonitor.create(
+          model_name=self.model_name,
+          model_version_id=self.model_version_id,
+          training_dataset=self.training_dataset,
+          display_name=self.display_name,
+          model_monitoring_schema=self.model_monitoring_schema,
+          tabular_objective_spec=self.tabular_objective_spec,
+          output_spec=self.output_spec,
+          notification_spec=self.notification_spec,
+          explanation_spec=self.explanation_spec,
+          project=self.project_id,
+          location=self.location,
+          credentials=self.credentials,
+          model_monitor_id=self.model_monitor_id,
+      )
+    except (exceptions.AlreadyExists, exceptions.Conflict):
+      logging.info(
+          "Model monitor '%s' already exists; retrieving existing instance.",
+          self.model_monitor_id or self.display_name,
+      )
+      if self.model_monitor_id:
+        return ml_monitoring.model_monitors.ModelMonitor(
+            model_monitor_name=self.model_monitor_id,
+            project=self.project_id,
+            location=self.location,
+            credentials=self.credentials,
+        )
+      monitors = ml_monitoring.model_monitors.ModelMonitor.list(

Review Comment:
   In my experience the creation happens pretty quickly, but adding a little 
backoff in the Conflict case is a reasonable way to mitigate potential race 
conditions. Added.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to