|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# Copyright 2023 Google LLC |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | +"""Streaming prediction functions.""" |
| 18 | + |
| 19 | +from typing import Any, Dict, Iterator, List, Optional, Sequence |
| 20 | + |
| 21 | +from google.cloud.aiplatform_v1.services import prediction_service |
| 22 | +from google.cloud.aiplatform_v1.types import ( |
| 23 | + prediction_service as prediction_service_types, |
| 24 | +) |
| 25 | +from google.cloud.aiplatform_v1.types import ( |
| 26 | + types as aiplatform_types, |
| 27 | +) |
| 28 | + |
| 29 | + |
| 30 | +def value_to_tensor(value: Any) -> aiplatform_types.Tensor: |
| 31 | + """Converts a Python value to `Tensor`. |
| 32 | +
|
| 33 | + Args: |
| 34 | + value: A value to convert |
| 35 | +
|
| 36 | + Returns: |
| 37 | + A `Tensor` object |
| 38 | + """ |
| 39 | + if value is None: |
| 40 | + return aiplatform_types.Tensor() |
| 41 | + elif isinstance(value, int): |
| 42 | + return aiplatform_types.Tensor(int_val=[value]) |
| 43 | + elif isinstance(value, float): |
| 44 | + return aiplatform_types.Tensor(float_val=[value]) |
| 45 | + elif isinstance(value, bool): |
| 46 | + return aiplatform_types.Tensor(bool_val=[value]) |
| 47 | + elif isinstance(value, str): |
| 48 | + return aiplatform_types.Tensor(string_val=[value]) |
| 49 | + elif isinstance(value, bytes): |
| 50 | + return aiplatform_types.Tensor(bytes_val=[value]) |
| 51 | + elif isinstance(value, list): |
| 52 | + return aiplatform_types.Tensor(list_val=[value_to_tensor(x) for x in value]) |
| 53 | + elif isinstance(value, dict): |
| 54 | + return aiplatform_types.Tensor( |
| 55 | + struct_val={k: value_to_tensor(v) for k, v in value.items()} |
| 56 | + ) |
| 57 | + raise TypeError(f"Unsupported value type {type(value)}") |
| 58 | + |
| 59 | + |
| 60 | +def tensor_to_value(tensor_pb: aiplatform_types.Tensor) -> Any: |
| 61 | + """Converts `Tensor` to a Python value. |
| 62 | +
|
| 63 | + Args: |
| 64 | + tensor_pb: A `Tensor` object |
| 65 | +
|
| 66 | + Returns: |
| 67 | + A corresponding Python object |
| 68 | + """ |
| 69 | + list_of_fields = tensor_pb.ListFields() |
| 70 | + if not list_of_fields: |
| 71 | + return None |
| 72 | + descriptor, value = tensor_pb.ListFields()[0] |
| 73 | + if descriptor.name == "list_val": |
| 74 | + return [tensor_to_value(x) for x in value] |
| 75 | + elif descriptor.name == "struct_val": |
| 76 | + return {k: tensor_to_value(v) for k, v in value.items()} |
| 77 | + if not isinstance(value, Sequence): |
| 78 | + raise TypeError(f"Unexpected non-list tensor value {value}") |
| 79 | + if len(value) == 1: |
| 80 | + return value[0] |
| 81 | + else: |
| 82 | + return value |
| 83 | + |
| 84 | + |
| 85 | +def predict_stream_of_tensor_lists_from_single_tensor_list( |
| 86 | + prediction_service_client: prediction_service.PredictionServiceClient, |
| 87 | + endpoint_name: str, |
| 88 | + tensor_list: List[aiplatform_types.Tensor], |
| 89 | + parameters_tensor: Optional[aiplatform_types.Tensor] = None, |
| 90 | +) -> Iterator[List[aiplatform_types.Tensor]]: |
| 91 | + """Predicts a stream of lists of `Tensor` objects from a single list of `Tensor` objects. |
| 92 | +
|
| 93 | + Args: |
| 94 | + tensor_list: Model input as a list of `Tensor` objects. |
| 95 | + parameters_tensor: Optional. Prediction parameters in `Tensor` form. |
| 96 | + prediction_service_client: A PredictionServiceClient object. |
| 97 | + endpoint_name: Resource name of Endpoint or PublisherModel. |
| 98 | +
|
| 99 | + Yields: |
| 100 | + A generator of model prediction `Tensor` lists. |
| 101 | + """ |
| 102 | + request = prediction_service_types.StreamingPredictRequest( |
| 103 | + endpoint=endpoint_name, |
| 104 | + inputs=tensor_list, |
| 105 | + parameters=parameters_tensor, |
| 106 | + ) |
| 107 | + for response in prediction_service_client.server_streaming_predict(request=request): |
| 108 | + yield response.outputs |
| 109 | + |
| 110 | + |
| 111 | +def predict_stream_of_dict_lists_from_single_dict_list( |
| 112 | + prediction_service_client: prediction_service.PredictionServiceClient, |
| 113 | + endpoint_name: str, |
| 114 | + dict_list: List[Dict[str, Any]], |
| 115 | + parameters: Optional[Dict[str, Any]] = None, |
| 116 | +) -> Iterator[List[Dict[str, Any]]]: |
| 117 | + """Predicts a stream of lists of dicts from a stream of lists of dicts. |
| 118 | +
|
| 119 | + Args: |
| 120 | + dict_list: Model input as a list of `dict` objects. |
| 121 | + parameters: Optional. Prediction parameters `dict` form. |
| 122 | + prediction_service_client: A PredictionServiceClient object. |
| 123 | + endpoint_name: Resource name of Endpoint or PublisherModel. |
| 124 | +
|
| 125 | + Yields: |
| 126 | + A generator of model prediction dict lists. |
| 127 | + """ |
| 128 | + tensor_list = [value_to_tensor(d) for d in dict_list] |
| 129 | + parameters_tensor = value_to_tensor(parameters) if parameters else None |
| 130 | + for tensor_list in predict_stream_of_tensor_lists_from_single_tensor_list( |
| 131 | + prediction_service_client=prediction_service_client, |
| 132 | + endpoint_name=endpoint_name, |
| 133 | + tensor_list=tensor_list, |
| 134 | + parameters_tensor=parameters_tensor, |
| 135 | + ): |
| 136 | + yield [tensor_to_value(tensor._pb) for tensor in tensor_list] |
| 137 | + |
| 138 | + |
| 139 | +def predict_stream_of_dicts_from_single_dict( |
| 140 | + prediction_service_client: prediction_service.PredictionServiceClient, |
| 141 | + endpoint_name: str, |
| 142 | + instance: Dict[str, Any], |
| 143 | + parameters: Optional[Dict[str, Any]] = None, |
| 144 | +) -> Iterator[Dict[str, Any]]: |
| 145 | + """Predicts a stream of dicts from a single instance dict. |
| 146 | +
|
| 147 | + Args: |
| 148 | + instance: A single input instance `dict`. |
| 149 | + parameters: Optional. Prediction parameters `dict`. |
| 150 | + prediction_service_client: A PredictionServiceClient object. |
| 151 | + endpoint_name: Resource name of Endpoint or PublisherModel. |
| 152 | +
|
| 153 | + Yields: |
| 154 | + A generator of model prediction dicts. |
| 155 | + """ |
| 156 | + for dict_list in predict_stream_of_dict_lists_from_single_dict_list( |
| 157 | + prediction_service_client=prediction_service_client, |
| 158 | + endpoint_name=endpoint_name, |
| 159 | + dict_list=[instance], |
| 160 | + parameters=parameters, |
| 161 | + ): |
| 162 | + if len(dict_list) > 1: |
| 163 | + raise ValueError( |
| 164 | + f"Expected to receive a single output, but got {dict_list}" |
| 165 | + ) |
| 166 | + yield dict_list[0] |
0 commit comments