AnandInguva commented on code in PR #25368: URL: https://github.com/apache/beam/pull/25368#discussion_r1100290371
########## sdks/python/apache_beam/ml/inference/tensorflow_inference.py: ########## @@ -0,0 +1,226 @@ +# +# 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. +# + +# pytype: skip-file + +from cmath import inf +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence + +import sys +import numpy +import tensorflow as tf + +from apache_beam.ml.inference import utils +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +__all__ = [ + 'TFModelHandlerNumpy', + 'TFModelHandlerTensor', +] + +TensorInferenceFn = Callable[[ + tf.Module, Sequence[numpy.ndarray], Optional[Dict[str, Any]], Optional[str] +], + Iterable[PredictionResult]] + + +def _load_model(model_uri): + return tf.keras.models.load_model(model_uri) + + +def default_numpy_inference_fn( + model: tf.Module, + batch: Sequence[numpy.ndarray], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = numpy.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) Review Comment: ```suggestion batch, model.predict(vectorized_batch, **inference_args), model_id) ``` ########## sdks/python/apache_beam/ml/inference/tensorflow_inference.py: ########## @@ -0,0 +1,226 @@ +# +# 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. +# + +# pytype: skip-file + +from cmath import inf +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence + +import sys +import numpy +import tensorflow as tf + +from apache_beam.ml.inference import utils +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +__all__ = [ + 'TFModelHandlerNumpy', + 'TFModelHandlerTensor', +] + +TensorInferenceFn = Callable[[ + tf.Module, Sequence[numpy.ndarray], Optional[Dict[str, Any]], Optional[str] +], + Iterable[PredictionResult]] + + +def _load_model(model_uri): + return tf.keras.models.load_model(model_uri) + + +def default_numpy_inference_fn( + model: tf.Module, + batch: Sequence[numpy.ndarray], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = numpy.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +def default_tensor_inference_fn( + model: tf.Module, + batch: Sequence[tf.Tensor], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = tf.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +class TFModelHandlerNumpy(ModelHandler[numpy.ndarray, + PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_numpy_inference_fn): + """Implementation of the ModelHandler interface for Tensorflow. + + Example Usage:: + + pcoll | RunInference(TFModelHandlerNumpy(model_uri="my_uri")) + + See https://www.tensorflow.org/tutorials/keras/save_and_load for details. + + Args: + model_uri (str): path to the trained model. + inference_fn (TensorInferenceFn, optional): inference function to use + during RunInference. Defaults to default_numpy_inference_fn. + + **Supported Versions:** RunInference APIs in Apache Beam have been tested + with Tensorflow 2.11. + """ + self._model_uri = model_uri + self._inference_fn = inference_fn + + def load_model(self) -> tf.Module: + """Loads and initializes a Tensorflow model for processing.""" + return _load_model(self._model_uri) + + def update_model_path(self, model_path: Optional[str] = None): + self._model_uri = model_path if model_path else self._model_uri + + def run_inference( + self, + batch: Sequence[numpy.ndarray], + model: tf.Module, + inference_args: Optional[Dict[str, Any]] = None + ) -> Iterable[PredictionResult]: + """ + Runs inferences on a batch of numpy array and returns an Iterable of + numpy array Predictions. + + This method stacks the n-dimensional numpy array in a vectorized format to + optimize the inference call. + + Args: + batch: A sequence of numpy nd-array. These should be batchable, as this + method will call `numpy.stack()` and pass in batched numpy nd-array + with dimensions (batch_size, n_features, etc.) into the model's + predict() function. + model: A Tensorflow model. + inference_args: any additional arguments for an inference. + + Returns: + An Iterable of type PredictionResult. + """ + inference_args = {} if not inference_args else inference_args + + return self._inference_fn(model, batch, inference_args, self._model_uri) + + def get_num_bytes(self, batch: Sequence[numpy.ndarray]) -> int: + """ + Returns: + The number of bytes of data for a batch of numpy arrays. + """ + return sum(sys.getsizeof(element) for element in batch) + + def get_metrics_namespace(self) -> str: + """ + Returns: + A namespace for metrics collected by the RunInference transform. + """ + return 'BeamML_TF_Numpy' + + def validate_inference_args(self, inference_args: Optional[Dict[str, Any]]): + pass + + +class TFModelHandlerTensor(ModelHandler[tf.Tensor, PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_tensor_inference_fn): Review Comment: TensorInferenceFn: Signature of this is different when the input is tf.Tensor. TensorInferenceFn expects Sequence[numpy.ndarray]. let's add Union[numpy, tensor]? ########## sdks/python/apache_beam/ml/inference/tensorflow_inference.py: ########## @@ -0,0 +1,226 @@ +# +# 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. +# + +# pytype: skip-file + +from cmath import inf +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence + +import sys +import numpy +import tensorflow as tf + +from apache_beam.ml.inference import utils +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +__all__ = [ + 'TFModelHandlerNumpy', + 'TFModelHandlerTensor', +] + +TensorInferenceFn = Callable[[ + tf.Module, Sequence[numpy.ndarray], Optional[Dict[str, Any]], Optional[str] +], + Iterable[PredictionResult]] + + +def _load_model(model_uri): + return tf.keras.models.load_model(model_uri) + + +def default_numpy_inference_fn( + model: tf.Module, + batch: Sequence[numpy.ndarray], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = numpy.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +def default_tensor_inference_fn( + model: tf.Module, + batch: Sequence[tf.Tensor], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = tf.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) Review Comment: ```suggestion batch, model.predict(vectorized_batch, **inference_args), model_id) ``` ########## sdks/python/apache_beam/ml/inference/tensorflow_inference.py: ########## @@ -0,0 +1,226 @@ +# +# 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. +# + +# pytype: skip-file + +from cmath import inf +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence + +import sys +import numpy +import tensorflow as tf + +from apache_beam.ml.inference import utils +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +__all__ = [ + 'TFModelHandlerNumpy', + 'TFModelHandlerTensor', +] + +TensorInferenceFn = Callable[[ + tf.Module, Sequence[numpy.ndarray], Optional[Dict[str, Any]], Optional[str] +], + Iterable[PredictionResult]] + + +def _load_model(model_uri): + return tf.keras.models.load_model(model_uri) + + +def default_numpy_inference_fn( + model: tf.Module, + batch: Sequence[numpy.ndarray], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = numpy.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +def default_tensor_inference_fn( + model: tf.Module, + batch: Sequence[tf.Tensor], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = tf.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +class TFModelHandlerNumpy(ModelHandler[numpy.ndarray, + PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_numpy_inference_fn): + """Implementation of the ModelHandler interface for Tensorflow. + + Example Usage:: + + pcoll | RunInference(TFModelHandlerNumpy(model_uri="my_uri")) + + See https://www.tensorflow.org/tutorials/keras/save_and_load for details. + + Args: + model_uri (str): path to the trained model. + inference_fn (TensorInferenceFn, optional): inference function to use + during RunInference. Defaults to default_numpy_inference_fn. + + **Supported Versions:** RunInference APIs in Apache Beam have been tested + with Tensorflow 2.11. + """ + self._model_uri = model_uri + self._inference_fn = inference_fn + + def load_model(self) -> tf.Module: + """Loads and initializes a Tensorflow model for processing.""" + return _load_model(self._model_uri) + + def update_model_path(self, model_path: Optional[str] = None): + self._model_uri = model_path if model_path else self._model_uri + + def run_inference( + self, + batch: Sequence[numpy.ndarray], + model: tf.Module, + inference_args: Optional[Dict[str, Any]] = None + ) -> Iterable[PredictionResult]: + """ + Runs inferences on a batch of numpy array and returns an Iterable of + numpy array Predictions. + + This method stacks the n-dimensional numpy array in a vectorized format to + optimize the inference call. + + Args: + batch: A sequence of numpy nd-array. These should be batchable, as this + method will call `numpy.stack()` and pass in batched numpy nd-array + with dimensions (batch_size, n_features, etc.) into the model's + predict() function. + model: A Tensorflow model. + inference_args: any additional arguments for an inference. + + Returns: + An Iterable of type PredictionResult. + """ + inference_args = {} if not inference_args else inference_args + + return self._inference_fn(model, batch, inference_args, self._model_uri) + + def get_num_bytes(self, batch: Sequence[numpy.ndarray]) -> int: + """ + Returns: + The number of bytes of data for a batch of numpy arrays. + """ + return sum(sys.getsizeof(element) for element in batch) + + def get_metrics_namespace(self) -> str: + """ + Returns: + A namespace for metrics collected by the RunInference transform. + """ + return 'BeamML_TF_Numpy' + + def validate_inference_args(self, inference_args: Optional[Dict[str, Any]]): + pass + + +class TFModelHandlerTensor(ModelHandler[tf.Tensor, PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_tensor_inference_fn): + """Implementation of the ModelHandler interface for Tensorflow. + + Example Usage:: + + pcoll | RunInference(TFModelHandlerTensor(model_uri="my_uri")) + + See https://www.tensorflow.org/tutorials/keras/save_and_load for details. + + Args: + model_uri (str): path to the trained model. + inference_fn (TensorInferenceFn, optional): inference function to use + during RunInference. Defaults to default_numpy_inference_fn. + + **Supported Versions:** RunInference APIs in Apache Beam have been tested + with Tensorflow 2.11. + """ + self._model_uri = model_uri + self._inference_fn = inference_fn + + def load_model(self) -> tf.Module: + """Loads and initializes a tensorflow model for processing.""" + return _load_model(self._model_uri) + + def update_model_path(self, model_path: Optional[str] = None): + self._model_uri = model_path if model_path else self._model_uri + + def run_inference( + self, + batch: Sequence[tf.Tensor], + model: tf.Module, + inference_args: Optional[Dict[str, Any]] = None, + ) -> Iterable[PredictionResult]: + """ + Runs inferences on a batch of tf.Tensor and returns an Iterable of + Tensor Predictions. + + This method stacks the list of Tensors in a vectorized format to optimize + the inference call. + + Args: + batch: A sequence of Tensors. These Tensors should be batchable, as this + method will call `tf.stack()` and pass in batched Tensors with + dimensions (batch_size, n_features, etc.) into the model's predict() + function. + model: A Tensorflow model. + inference_args: Non-batchable arguments required as inputs to the model's + forward() function. Unlike Tensors in `batch`, these parameters will + not be dynamically batched + Returns: + An Iterable of type PredictionResult. + """ + return self._inference_fn(model, batch, inference_args, self._model_uri) + + def get_num_bytes(self, batch: Sequence[tf.Tensor]) -> int: + """ + Returns: + The number of bytes of data for a batch of Tensors. + """ + return sum(sys.getsizeof(element) for element in batch) + + def get_metrics_namespace(self) -> str: + """ + Returns: + A namespace for metrics collected by the RunInference transform. + """ + return 'BeamML_TF_Tensors' Review Comment: ```suggestion return 'BeamML_TF_Tensor' ``` ########## sdks/python/apache_beam/ml/inference/tensorflow_inference.py: ########## @@ -0,0 +1,226 @@ +# +# 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. +# + +# pytype: skip-file + +from cmath import inf +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence + +import sys +import numpy +import tensorflow as tf + +from apache_beam.ml.inference import utils +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +__all__ = [ + 'TFModelHandlerNumpy', + 'TFModelHandlerTensor', +] + +TensorInferenceFn = Callable[[ + tf.Module, Sequence[numpy.ndarray], Optional[Dict[str, Any]], Optional[str] +], + Iterable[PredictionResult]] + + +def _load_model(model_uri): + return tf.keras.models.load_model(model_uri) + + +def default_numpy_inference_fn( + model: tf.Module, + batch: Sequence[numpy.ndarray], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = numpy.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +def default_tensor_inference_fn( + model: tf.Module, + batch: Sequence[tf.Tensor], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = tf.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +class TFModelHandlerNumpy(ModelHandler[numpy.ndarray, + PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_numpy_inference_fn): + """Implementation of the ModelHandler interface for Tensorflow. + + Example Usage:: + + pcoll | RunInference(TFModelHandlerNumpy(model_uri="my_uri")) + + See https://www.tensorflow.org/tutorials/keras/save_and_load for details. + + Args: + model_uri (str): path to the trained model. + inference_fn (TensorInferenceFn, optional): inference function to use + during RunInference. Defaults to default_numpy_inference_fn. + + **Supported Versions:** RunInference APIs in Apache Beam have been tested + with Tensorflow 2.11. + """ + self._model_uri = model_uri + self._inference_fn = inference_fn + + def load_model(self) -> tf.Module: + """Loads and initializes a Tensorflow model for processing.""" + return _load_model(self._model_uri) + + def update_model_path(self, model_path: Optional[str] = None): + self._model_uri = model_path if model_path else self._model_uri + + def run_inference( + self, + batch: Sequence[numpy.ndarray], + model: tf.Module, + inference_args: Optional[Dict[str, Any]] = None + ) -> Iterable[PredictionResult]: + """ + Runs inferences on a batch of numpy array and returns an Iterable of + numpy array Predictions. + + This method stacks the n-dimensional numpy array in a vectorized format to + optimize the inference call. + + Args: + batch: A sequence of numpy nd-array. These should be batchable, as this + method will call `numpy.stack()` and pass in batched numpy nd-array + with dimensions (batch_size, n_features, etc.) into the model's + predict() function. + model: A Tensorflow model. + inference_args: any additional arguments for an inference. + + Returns: + An Iterable of type PredictionResult. + """ + inference_args = {} if not inference_args else inference_args + + return self._inference_fn(model, batch, inference_args, self._model_uri) + + def get_num_bytes(self, batch: Sequence[numpy.ndarray]) -> int: + """ + Returns: + The number of bytes of data for a batch of numpy arrays. + """ + return sum(sys.getsizeof(element) for element in batch) + + def get_metrics_namespace(self) -> str: + """ + Returns: + A namespace for metrics collected by the RunInference transform. + """ + return 'BeamML_TF_Numpy' + + def validate_inference_args(self, inference_args: Optional[Dict[str, Any]]): + pass + + +class TFModelHandlerTensor(ModelHandler[tf.Tensor, PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_tensor_inference_fn): Review Comment: or we can have two variables. `TensorInferenceFn` and `NumpyInferenceFn` ########## sdks/python/apache_beam/ml/inference/tensorflow_inference.py: ########## @@ -0,0 +1,226 @@ +# +# 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. +# + +# pytype: skip-file + +from cmath import inf +from typing import Any +from typing import Callable +from typing import Dict +from typing import Iterable +from typing import Optional +from typing import Sequence + +import sys +import numpy +import tensorflow as tf + +from apache_beam.ml.inference import utils +from apache_beam.ml.inference.base import ModelHandler +from apache_beam.ml.inference.base import PredictionResult + +__all__ = [ + 'TFModelHandlerNumpy', + 'TFModelHandlerTensor', +] + +TensorInferenceFn = Callable[[ + tf.Module, Sequence[numpy.ndarray], Optional[Dict[str, Any]], Optional[str] +], + Iterable[PredictionResult]] + + +def _load_model(model_uri): + return tf.keras.models.load_model(model_uri) + + +def default_numpy_inference_fn( + model: tf.Module, + batch: Sequence[numpy.ndarray], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = numpy.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +def default_tensor_inference_fn( + model: tf.Module, + batch: Sequence[tf.Tensor], + inference_args: Optional[Dict[str, Any]] = None, + model_id: Optional[str] = None) -> Iterable[PredictionResult]: + vectorized_batch = tf.stack(batch, axis=0) + return utils._convert_to_result( + batch, model.predict(vectorized_batch), model_id) + + +class TFModelHandlerNumpy(ModelHandler[numpy.ndarray, + PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_numpy_inference_fn): + """Implementation of the ModelHandler interface for Tensorflow. + + Example Usage:: + + pcoll | RunInference(TFModelHandlerNumpy(model_uri="my_uri")) + + See https://www.tensorflow.org/tutorials/keras/save_and_load for details. + + Args: + model_uri (str): path to the trained model. + inference_fn (TensorInferenceFn, optional): inference function to use + during RunInference. Defaults to default_numpy_inference_fn. + + **Supported Versions:** RunInference APIs in Apache Beam have been tested + with Tensorflow 2.11. + """ + self._model_uri = model_uri + self._inference_fn = inference_fn + + def load_model(self) -> tf.Module: + """Loads and initializes a Tensorflow model for processing.""" + return _load_model(self._model_uri) + + def update_model_path(self, model_path: Optional[str] = None): + self._model_uri = model_path if model_path else self._model_uri + + def run_inference( + self, + batch: Sequence[numpy.ndarray], + model: tf.Module, + inference_args: Optional[Dict[str, Any]] = None + ) -> Iterable[PredictionResult]: + """ + Runs inferences on a batch of numpy array and returns an Iterable of + numpy array Predictions. + + This method stacks the n-dimensional numpy array in a vectorized format to + optimize the inference call. + + Args: + batch: A sequence of numpy nd-array. These should be batchable, as this + method will call `numpy.stack()` and pass in batched numpy nd-array + with dimensions (batch_size, n_features, etc.) into the model's + predict() function. + model: A Tensorflow model. + inference_args: any additional arguments for an inference. + + Returns: + An Iterable of type PredictionResult. + """ + inference_args = {} if not inference_args else inference_args + + return self._inference_fn(model, batch, inference_args, self._model_uri) + + def get_num_bytes(self, batch: Sequence[numpy.ndarray]) -> int: + """ + Returns: + The number of bytes of data for a batch of numpy arrays. + """ + return sum(sys.getsizeof(element) for element in batch) + + def get_metrics_namespace(self) -> str: + """ + Returns: + A namespace for metrics collected by the RunInference transform. + """ + return 'BeamML_TF_Numpy' + + def validate_inference_args(self, inference_args: Optional[Dict[str, Any]]): + pass + + +class TFModelHandlerTensor(ModelHandler[tf.Tensor, PredictionResult, + tf.Module]): + def __init__( + self, + model_uri: str, + *, + inference_fn: TensorInferenceFn = default_tensor_inference_fn): + """Implementation of the ModelHandler interface for Tensorflow. + + Example Usage:: + + pcoll | RunInference(TFModelHandlerTensor(model_uri="my_uri")) + + See https://www.tensorflow.org/tutorials/keras/save_and_load for details. + + Args: + model_uri (str): path to the trained model. + inference_fn (TensorInferenceFn, optional): inference function to use + during RunInference. Defaults to default_numpy_inference_fn. + + **Supported Versions:** RunInference APIs in Apache Beam have been tested + with Tensorflow 2.11. Review Comment: Can we also add tests for previous versions as well? ########## sdks/python/tox.ini: ########## @@ -329,3 +329,15 @@ commands = # Run all PyTorch unit tests # Allow exit code 5 (no tests run) so that we can run this command safely on arbitrary subdirectories. /bin/sh -c 'pytest -o junit_suite_name={envname} --junitxml=pytest_{envname}.xml -n 6 -m uses_pytorch {posargs}; ret=$?; [ $ret = 5 ] && exit 0 || exit $ret' + +[testenv:py{37,38,39,310}-tf-{211}] Review Comment: I think you would also need to add tox info similar to this https://github.com/apache/beam/blob/b90ed15146791e6dd04b468250acb4f406cf49f8/sdks/python/test-suites/tox/py38/build.gradle#L125 ########## sdks/python/apache_beam/ml/inference/tensorflow_inference_test.py: ########## @@ -0,0 +1,123 @@ +# +# 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. +# + +# pytype: skip-file + +import unittest + +import numpy +import pytest + +try: + import tensorflow as tf + from apache_beam.ml.inference.sklearn_inference_test import _compare_prediction_result + from apache_beam.ml.inference.base import KeyedModelHandler, PredictionResult + from apache_beam.ml.inference.tensorflow_inference import TFModelHandlerNumpy, TFModelHandlerTensor +except ImportError: + raise unittest.SkipTest('Tensorflow dependencies are not installed') + + +class FakeTFNumpyModel: + def predict(self, input: numpy.ndarray): + return numpy.multiply(input, 10) + + +class FakeTFTensorModel: Review Comment: Can we have a test for inference args? ``` class FakeTfTensorModel: def predict(self, input: tf.Tensor, add=False): if not add: return tf.math.multiply(input, 10) return tf.math.multiply(input, 10) + 10 # something like this should be fine ``` -- 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]
