damccorm commented on code in PR #24965:
URL: https://github.com/apache/beam/pull/24965#discussion_r1129514487


##########
sdks/python/apache_beam/ml/inference/xgboost_inference.py:
##########
@@ -0,0 +1,362 @@
+#
+# 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.
+#
+
+import sys
+from abc import ABC
+from typing import Any
+from typing import Callable
+from typing import Dict
+from typing import Iterable
+from typing import Optional
+from typing import Sequence
+from typing import Union
+
+import numpy
+import pandas
+import scipy
+
+import datatable
+import xgboost
+from apache_beam.io.filesystems import FileSystems
+from apache_beam.ml.inference.base import ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+
+__all__ = [
+    'XGBoostModelHandler',
+    'XGBoostModelHandlerNumpy',
+    'XGBoostModelHandlerPandas',
+    'XGBoostModelHandlerSciPy',
+    'XGBoostModelHandlerDatatable'
+]
+
+XGBoostInferenceFn = Callable[[
+    Sequence[object],
+    Union[xgboost.Booster, xgboost.XGBModel],
+    Optional[Dict[str, Any]]
+],
+                              Iterable[PredictionResult]]
+
+
+def default_xgboost_inference_fn(
+    batch: Sequence[object],
+    model: Union[xgboost.Booster, xgboost.XGBModel],
+    inference_args: Optional[Dict[str,
+                                  Any]] = None) -> Iterable[PredictionResult]:
+  inference_args = {} if not inference_args else inference_args
+
+  if type(model) == xgboost.Booster:
+    batch = [xgboost.DMatrix(array) for array in batch]
+  predictions = [model.predict(el, **inference_args) for el in batch]
+
+  return [PredictionResult(x, y) for x, y in zip(batch, predictions)]
+
+
+class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_class: Union[Callable[..., xgboost.Booster],
+                         Callable[..., xgboost.XGBModel]],
+      model_state: str,
+      inference_fn: XGBoostInferenceFn = default_xgboost_inference_fn):
+    """Implementation of the ModelHandler interface for XGBoost.
+
+    Example Usage::
+
+        pcoll | RunInference(
+                    XGBoostModelHandler(
+                        model_class="XGBoost Model Class",
+                        model_state="my_model_state.json")))
+
+    See https://xgboost.readthedocs.io/en/stable/tutorials/saving_model.html
+    for details
+
+    Args:
+      model_class: class of the XGBoost model that defines the model
+        structure.
+      model_state: path to a json file that contains the model's
+        configuration.
+      inference_fn: the inference function to use during RunInference.
+        default=default_xgboost_inference_fn
+
+    **Supported Versions:** RunInference APIs in Apache Beam have been tested
+    with XGBoost 1.6.0 and 1.7.0
+
+    XGBoost 1.0.0 introduced support for using JSON to save and load
+    XGBoost models. XGBoost 1.6.0, additional support for Universal Binary 
JSON.
+    It is recommended to use a model trained in XGBoost 1.6.0 or higher.
+    While you should be able to load models created in older versions, there
+    are no guarantees this will work as expected.
+
+    This class is the superclass of all the various XGBoostModelhandlers
+    and should not be instantiated directly. (See instead
+    XGBoostModelHandlerNumpy, XGBoostModelHandlerPandas, etc.)
+    """
+    self._model_class = model_class
+    self._model_state = model_state
+    self._inference_fn = inference_fn
+
+  def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]:
+    model = self._model_class()
+    model_state_file_handler = FileSystems.open(self._model_state, 'rb')
+    model_state_bytes = model_state_file_handler.read()
+    # Convert into a bytearray so that the
+    # model state can be loaded in XGBoost
+    model_state_bytearray = bytearray(model_state_bytes)
+    model.load_model(model_state_bytearray)
+    return model
+
+  def get_metrics_namespace(self) -> str:
+    return 'BeamML_XGBoost'
+
+
+class XGBoostModelHandlerNumpy(XGBoostModelHandler[numpy.ndarray,
+                                                   PredictionResult,
+                                                   Union[xgboost.Booster,
+                                                         xgboost.XGBModel]]):
+  def __init__(
+      self,
+      model_class: Union[Callable[..., xgboost.Booster],
+                         Callable[..., xgboost.XGBModel]],
+      model_state: str,
+      inference_fn: XGBoostInferenceFn = default_xgboost_inference_fn):
+    """ Implementation of the ModelHandler interface for XGBoost
+    using numpy arrays as input.
+
+    Example Usage::
+
+        pcoll | RunInference(
+                    XGBoostModelHandlerNumpy(
+                        model_class="XGBoost Model Class",
+                        model_state="my_model_state.json")))
+
+    Args:
+      model_class: class of the XGBoost model that defines the model
+        structure.
+      model_state: path to a json file that contains the model's
+        configuration.
+      inference_fn: the inference function to use during RunInference.
+        default=default_xgboost_inference_fn
+    """

Review Comment:
   I think removing the super.__init__() call broke the tests (and the 
functionality). Tests are now failing with errors like: `AttributeError: 
'XGBoostModelHandlerSciPy' object has no attribute '_model_class'` 
(https://ci-beam.apache.org/job/beam_PostCommit_Python37_PR/520/consoleFull#gradle-task-435).
   
   Instead of having the comment for the pydoc on the init function, could we 
just have it on the class itself (like 
https://github.com/apache/beam/blob/5d1bcfbae18272e54574fe718428d2f7a6cfff50/sdks/python/apache_beam/transforms/core.py#L531)?
 Then we should be able to omit the __init__ function entirely.



-- 
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