-
Notifications
You must be signed in to change notification settings - Fork 348
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: support raw_predict for Endpoint #1620
Merged
Merged
Changes from 29 commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
b42a47f
feat: support raw_predict for Endpoints
rosiezou 9f850b2
formatting
rosiezou 5e32858
Merge branch 'main' into raw-predict
rosiezou f6e7241
fixed broken unit test
rosiezou 07796ae
Merge branch 'main' into raw-predict
rosiezou 5df7af8
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] 3ed3e06
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] 516771e
Merge branch 'raw-predict' of https://github.com/googleapis/python-ai…
gcf-owl-bot[bot] 4586da2
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] f5c7dea
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] 007595f
Merge branch 'raw-predict' of https://github.com/googleapis/python-ai…
gcf-owl-bot[bot] ffd5a75
Merge branch 'main' into raw-predict
rosiezou 4dd2472
remove commented out code blocks
rosiezou 3818bf6
removing debug print statements
rosiezou ca30449
removing extra prints
rosiezou 07cc2f0
update copyright header date
rosiezou 6d6e173
Merge branch 'main' into raw-predict
rosiezou f53ee8a
removing automatically added python 3.6 support for kokoro
rosiezou 267e803
Merge branch 'main' into raw-predict
nayaknishant 474654c
Merge branch 'main' into raw-predict
rosiezou f2386c3
Merge branch 'main' into raw-predict
rosiezou 60ea5f9
addressed PR comments
rosiezou ee319fd
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] eef9e6f
adding unit test
rosiezou 19c853e
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] bfac52c
removed unused import
rosiezou d6e8ef7
Merge branch 'main' into raw-predict
rosiezou 2175a2c
renamed raw predict constants
rosiezou 748b0ed
modified error messages
rosiezou bc80e81
added doc strings
rosiezou f0f1e7a
fixed typo in doc strings
rosiezou be8d4de
removed extra space
rosiezou 1264f33
Merge branch 'main' into raw-predict
rosiezou File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,6 +20,7 @@ | |
import re | ||
import shutil | ||
import tempfile | ||
import requests | ||
from typing import ( | ||
Any, | ||
Dict, | ||
|
@@ -35,9 +36,11 @@ | |
from google.api_core import operation | ||
from google.api_core import exceptions as api_exceptions | ||
from google.auth import credentials as auth_credentials | ||
from google.auth.transport import requests as google_auth_requests | ||
|
||
from google.cloud import aiplatform | ||
from google.cloud.aiplatform import base | ||
from google.cloud.aiplatform import constants | ||
from google.cloud.aiplatform import explain | ||
from google.cloud.aiplatform import initializer | ||
from google.cloud.aiplatform import jobs | ||
|
@@ -69,6 +72,8 @@ | |
_DEFAULT_MACHINE_TYPE = "n1-standard-2" | ||
_DEPLOYING_MODEL_TRAFFIC_SPLIT_KEY = "0" | ||
_SUCCESSFUL_HTTP_RESPONSE = 300 | ||
_RAW_PREDICT_DEPLOYED_MODEL_ID_KEY = "X-Vertex-AI-Deployed-Model-Id" | ||
_RAW_PREDICT_MODEL_RESOURCE_KEY = "X-Vertex-AI-Model" | ||
|
||
_LOGGER = base.Logger(__name__) | ||
|
||
|
@@ -200,6 +205,8 @@ def __init__( | |
location=self.location, | ||
credentials=credentials, | ||
) | ||
self.authorized_session = None | ||
self.raw_predict_request_url = None | ||
Comment on lines
+208
to
+209
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should these attributes be public? |
||
|
||
def _skipped_getter_call(self) -> bool: | ||
"""Check if GAPIC resource was populated by call to get/list API methods | ||
|
@@ -1481,6 +1488,7 @@ def predict( | |
instances: List, | ||
parameters: Optional[Dict] = None, | ||
timeout: Optional[float] = None, | ||
use_raw_predict: Optional[bool] = False, | ||
) -> Prediction: | ||
"""Make a prediction against this Endpoint. | ||
|
||
|
@@ -1505,29 +1513,71 @@ def predict( | |
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata] | ||
``parameters_schema_uri``. | ||
timeout (float): Optional. The timeout for this request in seconds. | ||
use_raw_predict (bool): | ||
Optional. Default value is False. If set to True, the underlying prediction call will be made | ||
against Endpoint.raw_predict(). Note that model version information will | ||
not be available in the prediciton response using raw_predict. | ||
|
||
Returns: | ||
prediction (aiplatform.Prediction): | ||
Prediction with returned predictions and Model ID. | ||
""" | ||
self.wait() | ||
if use_raw_predict: | ||
raw_predict_response = self.raw_predict( | ||
body=json.dumps({"instances": instances, "parameters": parameters}), | ||
headers={"Content-Type": "application/json"}, | ||
) | ||
json_response = json.loads(raw_predict_response.text) | ||
return Prediction( | ||
predictions=json_response["predictions"], | ||
deployed_model_id=raw_predict_response.headers[ | ||
_RAW_PREDICT_DEPLOYED_MODEL_ID_KEY | ||
], | ||
model_resource_name=raw_predict_response.headers[ | ||
_RAW_PREDICT_MODEL_RESOURCE_KEY | ||
], | ||
) | ||
else: | ||
prediction_response = self._prediction_client.predict( | ||
endpoint=self._gca_resource.name, | ||
instances=instances, | ||
parameters=parameters, | ||
timeout=timeout, | ||
) | ||
|
||
prediction_response = self._prediction_client.predict( | ||
endpoint=self._gca_resource.name, | ||
instances=instances, | ||
parameters=parameters, | ||
timeout=timeout, | ||
) | ||
return Prediction( | ||
predictions=[ | ||
json_format.MessageToDict(item) | ||
for item in prediction_response.predictions.pb | ||
], | ||
deployed_model_id=prediction_response.deployed_model_id, | ||
model_version_id=prediction_response.model_version_id, | ||
model_resource_name=prediction_response.model, | ||
) | ||
|
||
return Prediction( | ||
predictions=[ | ||
json_format.MessageToDict(item) | ||
for item in prediction_response.predictions.pb | ||
], | ||
deployed_model_id=prediction_response.deployed_model_id, | ||
model_version_id=prediction_response.model_version_id, | ||
model_resource_name=prediction_response.model, | ||
) | ||
def raw_predict( | ||
self, body: bytes, headers: Dict[str, str] | ||
) -> requests.models.Response: | ||
"""Makes a prediction request using arbitrary headers. | ||
|
||
Args: | ||
body (bytes): | ||
The body of the prediction request in bytes. This must not exceed 1.5 mb per request. | ||
headers (Dict[str, str]): | ||
The header of the request as a dictionary. There are no restrictions on the header. | ||
|
||
Returns: | ||
A requests.models.Response object containing the status code and prediction results. | ||
""" | ||
if not self.authorized_session: | ||
self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES | ||
self.authorized_session = google_auth_requests.AuthorizedSession( | ||
self.credentials | ||
) | ||
self.raw_predict_request_url = f"https://{self.location}-{constants.base.API_BASE_PATH}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:rawPredict" | ||
|
||
return self.authorized_session.post(self.raw_predict_request_url, body, headers) | ||
|
||
def explain( | ||
self, | ||
|
@@ -2004,7 +2054,7 @@ def _http_request( | |
def predict(self, instances: List, parameters: Optional[Dict] = None) -> Prediction: | ||
"""Make a prediction against this PrivateEndpoint using a HTTP request. | ||
This method must be called within the network the PrivateEndpoint is peered to. | ||
The predict() call will fail otherwise. To check, use `PrivateEndpoint.network`. | ||
Otherwise, the predict() call will fail with error code 404. To check, use `PrivateEndpoint.network`. | ||
|
||
Example usage: | ||
response = my_private_endpoint.predict(instances=[...]) | ||
|
@@ -2062,6 +2112,30 @@ def predict(self, instances: List, parameters: Optional[Dict] = None) -> Predict | |
deployed_model_id=self._gca_resource.deployed_models[0].id, | ||
) | ||
|
||
def raw_predict( | ||
self, body: bytes, headers: Dict[str, str] | ||
) -> requests.models.Response: | ||
"""Make a prediction request using arbitrary headers. | ||
This method must be called within the network the PrivateEndpoint is peered to. | ||
Otherwise, the predict() call will fail with error code 404. To check, use `PrivateEndpoint.network`. | ||
|
||
Args: | ||
body (bytes): | ||
The body of the prediction request in bytes. This must not exceed 1.5 mb per request. | ||
headers (Dict[str, str]): | ||
The header of the request as a dictionary. There are no restrictions on the header. | ||
|
||
Returns: | ||
A requests.models.Response object containing the status code and prediction results. | ||
""" | ||
self.wait() | ||
return self._http_request( | ||
method="POST", | ||
url=self.predict_http_uri, | ||
body=body, | ||
headers=headers, | ||
) | ||
|
||
def explain(self): | ||
raise NotImplementedError( | ||
f"{self.__class__.__name__} class does not support 'explain' as of now." | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
# Copyright 2022 Google LLC | ||
# | ||
# Licensed 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. | ||
# | ||
|
||
import json | ||
|
||
from google.cloud import aiplatform | ||
|
||
from tests.system.aiplatform import e2e_base | ||
|
||
_PERMANENT_IRIS_ENDPOINT_ID = "4966625964059525120" | ||
_PREDICTION_INSTANCE = { | ||
"petal_length": "3.0", | ||
"petal_width": "3.0", | ||
"sepal_length": "3.0", | ||
"sepal_width": "3.0", | ||
} | ||
|
||
|
||
class TestModelInteractions(e2e_base.TestEndToEnd): | ||
_temp_prefix = "" | ||
endpoint = aiplatform.Endpoint(_PERMANENT_IRIS_ENDPOINT_ID) | ||
|
||
def test_prediction(self): | ||
# test basic predict | ||
prediction_response = self.endpoint.predict(instances=[_PREDICTION_INSTANCE]) | ||
assert len(prediction_response.predictions) == 1 | ||
|
||
# test predict(use_raw_predict = True) | ||
prediction_with_raw_predict = self.endpoint.predict( | ||
instances=[_PREDICTION_INSTANCE], use_raw_predict=True | ||
) | ||
assert ( | ||
prediction_with_raw_predict.deployed_model_id | ||
== prediction_response.deployed_model_id | ||
) | ||
assert ( | ||
prediction_with_raw_predict.model_resource_name | ||
== prediction_response.model_resource_name | ||
) | ||
|
||
# test raw_predict | ||
raw_prediction_response = self.endpoint.raw_predict( | ||
json.dumps({"instances": [_PREDICTION_INSTANCE]}), | ||
{"Content-Type": "application/json"}, | ||
) | ||
assert raw_prediction_response.status_code == 200 | ||
assert len(json.loads(raw_prediction_response.text)) == 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These attribute names start with underscores, but the attributes in
models.py
do not have leading underscores. Is this correct?