|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""BigFrames general remote models.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from typing import Mapping, Optional, Union |
| 20 | +import warnings |
| 21 | + |
| 22 | +import bigframes |
| 23 | +from bigframes import clients |
| 24 | +from bigframes.core import log_adapter |
| 25 | +from bigframes.ml import base, core, globals, utils |
| 26 | +import bigframes.pandas as bpd |
| 27 | + |
| 28 | +_SUPPORTED_DTYPES = ( |
| 29 | + "bool", |
| 30 | + "string", |
| 31 | + "int64", |
| 32 | + "float64", |
| 33 | + "array<bool>", |
| 34 | + "array<string>", |
| 35 | + "array<int64>", |
| 36 | + "array<float64>", |
| 37 | +) |
| 38 | + |
| 39 | +_REMOTE_MODEL_STATUS = "remote_model_status" |
| 40 | + |
| 41 | + |
| 42 | +@log_adapter.class_logger |
| 43 | +class VertexAIModel(base.BaseEstimator): |
| 44 | + """Remote model from a Vertex AI https endpoint. User must specify https endpoint, input schema and output schema. |
| 45 | + How to deploy a model in Vertex AI https://cloud.google.com/bigquery/docs/bigquery-ml-remote-model-tutorial#Deploy-Model-on-Vertex-AI. |
| 46 | +
|
| 47 | + Args: |
| 48 | + endpoint (str): |
| 49 | + Vertex AI https endpoint. |
| 50 | + input ({column_name: column_type}): |
| 51 | + Input schema. Supported types are "bool", "string", "int64", "float64", "array<bool>", "array<string>", "array<int64>", "array<float64>". |
| 52 | + output ({column_name: column_type}): |
| 53 | + Output label schema. Supported the same types as the input. |
| 54 | + session (bigframes.Session or None): |
| 55 | + BQ session to create the model. If None, use the global default session. |
| 56 | + connection_name (str or None): |
| 57 | + Connection to connect with remote service. str of the format <PROJECT_NUMBER/PROJECT_ID>.<LOCATION>.<CONNECTION_ID>. |
| 58 | + if None, use default connection in session context. BigQuery DataFrame will try to create the connection and attach |
| 59 | + permission if the connection isn't fully setup. |
| 60 | + """ |
| 61 | + |
| 62 | + def __init__( |
| 63 | + self, |
| 64 | + endpoint: str, |
| 65 | + input: Mapping[str, str], |
| 66 | + output: Mapping[str, str], |
| 67 | + session: Optional[bigframes.Session] = None, |
| 68 | + connection_name: Optional[str] = None, |
| 69 | + ): |
| 70 | + self.endpoint = endpoint |
| 71 | + self.input = input |
| 72 | + self.output = output |
| 73 | + self.session = session or bpd.get_global_session() |
| 74 | + |
| 75 | + self._bq_connection_manager = clients.BqConnectionManager( |
| 76 | + self.session.bqconnectionclient, self.session.resourcemanagerclient |
| 77 | + ) |
| 78 | + connection_name = connection_name or self.session._bq_connection |
| 79 | + self.connection_name = self._bq_connection_manager.resolve_full_connection_name( |
| 80 | + connection_name, |
| 81 | + default_project=self.session._project, |
| 82 | + default_location=self.session._location, |
| 83 | + ) |
| 84 | + |
| 85 | + self._bqml_model_factory = globals.bqml_model_factory() |
| 86 | + self._bqml_model: core.BqmlModel = self._create_bqml_model() |
| 87 | + |
| 88 | + def _create_bqml_model(self): |
| 89 | + # Parse and create connection if needed. |
| 90 | + if not self.connection_name: |
| 91 | + raise ValueError( |
| 92 | + "Must provide connection_name, either in constructor or through session options." |
| 93 | + ) |
| 94 | + connection_name_parts = self.connection_name.split(".") |
| 95 | + if len(connection_name_parts) != 3: |
| 96 | + raise ValueError( |
| 97 | + f"connection_name must be of the format <PROJECT_NUMBER/PROJECT_ID>.<LOCATION>.<CONNECTION_ID>, got {self.connection_name}." |
| 98 | + ) |
| 99 | + self._bq_connection_manager.create_bq_connection( |
| 100 | + project_id=connection_name_parts[0], |
| 101 | + location=connection_name_parts[1], |
| 102 | + connection_id=connection_name_parts[2], |
| 103 | + iam_role="aiplatform.user", |
| 104 | + ) |
| 105 | + |
| 106 | + options = { |
| 107 | + "endpoint": self.endpoint, |
| 108 | + } |
| 109 | + |
| 110 | + def standardize_type(v: str): |
| 111 | + v = v.lower() |
| 112 | + v = v.replace("boolean", "bool") |
| 113 | + |
| 114 | + if v not in _SUPPORTED_DTYPES: |
| 115 | + raise ValueError( |
| 116 | + f"Data type {v} is not supported. We only support {', '.join(_SUPPORTED_DTYPES)}." |
| 117 | + ) |
| 118 | + |
| 119 | + return v |
| 120 | + |
| 121 | + self.input = {k: standardize_type(v) for k, v in self.input.items()} |
| 122 | + self.output = {k: standardize_type(v) for k, v in self.output.items()} |
| 123 | + |
| 124 | + return self._bqml_model_factory.create_remote_model( |
| 125 | + session=self.session, |
| 126 | + connection_name=self.connection_name, |
| 127 | + input=self.input, |
| 128 | + output=self.output, |
| 129 | + options=options, |
| 130 | + ) |
| 131 | + |
| 132 | + def predict( |
| 133 | + self, |
| 134 | + X: Union[bpd.DataFrame, bpd.Series], |
| 135 | + ) -> bpd.DataFrame: |
| 136 | + """Predict the result from the input DataFrame. |
| 137 | +
|
| 138 | + Args: |
| 139 | + X (bigframes.dataframe.DataFrame or bigframes.series.Series): |
| 140 | + Input DataFrame or Series, which needs to comply with the input parameter of the model. |
| 141 | +
|
| 142 | + Returns: |
| 143 | + bigframes.dataframe.DataFrame: DataFrame of shape (n_samples, n_input_columns + n_prediction_columns). Returns predicted values. |
| 144 | + """ |
| 145 | + |
| 146 | + (X,) = utils.convert_to_dataframe(X) |
| 147 | + |
| 148 | + df = self._bqml_model.predict(X) |
| 149 | + |
| 150 | + # unlike LLM models, the general remote model status is null for successful runs. |
| 151 | + if (df[_REMOTE_MODEL_STATUS].notna()).any(): |
| 152 | + warnings.warn( |
| 153 | + f"Some predictions failed. Check column {_REMOTE_MODEL_STATUS} for detailed status. You may want to filter the failed rows and retry.", |
| 154 | + RuntimeWarning, |
| 155 | + ) |
| 156 | + |
| 157 | + return df |
0 commit comments