damccorm commented on code in PR #24965: URL: https://github.com/apache/beam/pull/24965#discussion_r1067143048
########## sdks/python/apache_beam/ml/inference/xgboost_inference.py: ########## @@ -0,0 +1,212 @@ +# +# 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 datatable +import numpy +import pandas +import scipy +import xgboost + +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 + + +class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC): Review Comment: Since users aren't supposed to directly use this class, could we make this `_XGBoostModelHandler`? ########## sdks/python/apache_beam/ml/inference/xgboost_inference.py: ########## @@ -0,0 +1,212 @@ +# +# 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 datatable +import numpy +import pandas +import scipy +import xgboost + +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 + + +class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC): + def __init__( + self, + model_class: Union[Callable[..., xgboost.Booster], + Callable[..., xgboost.XGBModel]], + model_state: str): + self.model_class = model_class + self.model_state = model_state + + def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]: + model = self.model_class() + model.load_model(self.model_state) + return model + + def get_metrics_namespace(self) -> str: + return 'BeamML_XGBoost' + + +class XGBoostModelHandlerNumpy(XGBoostModelHandler[numpy.ndarray, + PredictionResult, + Union[xgboost.Booster, + xgboost.XGBModel]]): + def run_inference( + self, + batch: Sequence[numpy.ndarray], + model: Union[xgboost.Booster, xgboost.XGBModel], + inference_args: Optional[Dict[str, Any]] = None) -> Iterable[PredictionT]: + """Runs inferences on a batch of 2d numpy arrays. + + Args: + batch: A sequence of examples as 2d numpy arrays. Each + row in an array is a single example. The dimensions + must match the dimensions of the data used to train + the model. + model: XGBoost booster or XBGModel (sklearn interface). Must + implement predict(X). Where the parameter X is a 2d numpy array. + inference_args: Any additional arguments for an inference. + + Returns: + An Iterable of type 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] Review Comment: Are there cases where we want functions other than `predict` called? I'd imagine yes, if so can we add an option for a custom inference fn following the pattern here - https://github.com/apache/beam/blob/c0e689331c2a6573ecf267b9bef133a85ea8a36c/sdks/python/apache_beam/ml/inference/pytorch_inference.py#L165 ########## sdks/python/apache_beam/ml/inference/xgboost_inference.py: ########## @@ -0,0 +1,212 @@ +# +# 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 datatable +import numpy +import pandas +import scipy +import xgboost + +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 + + +class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC): + def __init__( + self, + model_class: Union[Callable[..., xgboost.Booster], + Callable[..., xgboost.XGBModel]], + model_state: str): + self.model_class = model_class + self.model_state = model_state + + def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]: + model = self.model_class() + model.load_model(self.model_state) + return model + + def get_metrics_namespace(self) -> str: + return 'BeamML_XGBoost' + + +class XGBoostModelHandlerNumpy(XGBoostModelHandler[numpy.ndarray, Review Comment: Could you please add class level comments similar to https://beam.apache.org/releases/pydoc/current/apache_beam.ml.inference.pytorch_inference.html that have expected usage of these classes? ########## sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py: ########## @@ -0,0 +1,169 @@ +# Review Comment: This might be covered as part of your TODO, but please add a brief description of this example/usage to https://github.com/apache/beam/blob/0c9999a6faaf7dd64e2abbbe96dac6c68c79d2d5/sdks/python/apache_beam/examples/inference/README.md ########## sdks/python/apache_beam/ml/inference/xgboost_inference.py: ########## @@ -0,0 +1,212 @@ +# +# 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 datatable +import numpy +import pandas +import scipy +import xgboost + +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 + + +class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC): + def __init__( + self, + model_class: Union[Callable[..., xgboost.Booster], + Callable[..., xgboost.XGBModel]], + model_state: str): + self.model_class = model_class + self.model_state = model_state + + def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]: + model = self.model_class() + model.load_model(self.model_state) + return model + + def get_metrics_namespace(self) -> str: + return 'BeamML_XGBoost' + + +class XGBoostModelHandlerNumpy(XGBoostModelHandler[numpy.ndarray, Review Comment: Generally, this and other comments apply to all the Model Handlers implemented here. ########## sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py: ########## @@ -0,0 +1,169 @@ +# +# 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 argparse +import logging +from typing import Callable +from typing import Iterable +from typing import List +from typing import Tuple +from typing import Union + +import datatable +import numpy +import pandas +import scipy +import xgboost +from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split + +import apache_beam as beam +from apache_beam.ml.inference.base import KeyedModelHandler +from apache_beam.ml.inference.base import PredictionResult +from apache_beam.ml.inference.base import RunInference +from apache_beam.ml.inference.xgboost_inference import XGBoostModelHandlerDatatable +from apache_beam.ml.inference.xgboost_inference import XGBoostModelHandlerNumpy +from apache_beam.ml.inference.xgboost_inference import XGBoostModelHandlerPandas +from apache_beam.ml.inference.xgboost_inference import XGBoostModelHandlerSciPy +from apache_beam.options.pipeline_options import PipelineOptions +from apache_beam.options.pipeline_options import SetupOptions +from apache_beam.runners.runner import PipelineResult + + +def _train_model(model_state_output_path: str = '/tmp/model.json', seed=999): + """Function to train an XGBoost Classifier using the sklearn Iris dataset""" + dataset = load_iris() + x_train, _, y_train, _ = train_test_split( + dataset['data'], dataset['target'], test_size=.2, random_state=seed) + booster = xgboost.XGBClassifier( + n_estimators=2, max_depth=2, learning_rate=1, objective='binary:logistic') + booster.fit(x_train, y_train) + booster.save_model(model_state_output_path) + return booster + + +class PostProcessor(beam.DoFn): + """Process the PredictionResult to get the predicted label. + Returns a comma separated string with true label and predicted label. + """ + def process(self, element: Tuple[int, PredictionResult]) -> Iterable[str]: + label, prediction_result = element + prediction = prediction_result.inference + yield '{},{}'.format(label, prediction) + + +def parse_known_args(argv): + """Parses args for the workflow.""" + parser = argparse.ArgumentParser() + parser.add_argument( + '--input-type', + dest='input_type', + required=True, + choices=['numpy', 'pandas', 'scipy', 'datatable'], + help= + 'Datatype of the input data.' + ) + parser.add_argument( + '--output', + dest='output', + required=True, + help='Path to save output predictions.') + parser.add_argument( + '--model-state', + dest='model_state', + required=True, + help='Path to the state of the XGBoost model loaded for Inference.' + ) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument('--split', action='store_true', dest='split') + group.add_argument('--no-split', action='store_false', dest='split') + return parser.parse_known_args(argv) + + +def load_sklearn_iris_test_data( + data_type: Callable, + split: bool = True, + seed: int = 999) -> List[Union[numpy.array, pandas.DataFrame]]: + """ + Loads test data from the sklearn Iris dataset in a given format, + either in a single or multiple batches. + Args: + data_type: Datatype of the iris test dataset. + split: Split the dataset in different batches or return single batch. + seed: Random state for splitting the train and test set. + """ + dataset = load_iris() + _, x_test, _, _ = train_test_split( + dataset['data'], dataset['target'], test_size=.2, random_state=seed) + + if split: + return [(index, data_type(sample.reshape(1, -1))) for index, + sample in enumerate(x_test)] + return [(0, data_type(x_test))] + + +def run( + argv=None, save_main_session=True, test_pipeline=None) -> PipelineResult: + """ + Args: + argv: Command line arguments defined for this example. + save_main_session: Used for internal testing. + test_pipeline: Used for internal testing. + """ + known_args, pipeline_args = parse_known_args(argv) + pipeline_options = PipelineOptions(pipeline_args) + pipeline_options.view_as(SetupOptions).save_main_session = save_main_session + + data_types = { + 'numpy': (numpy.array, XGBoostModelHandlerNumpy), + 'pandas': (pandas.DataFrame, XGBoostModelHandlerPandas), + 'scipy': (scipy.sparse.csr_matrix, XGBoostModelHandlerSciPy), + 'datatable': (datatable.Frame, XGBoostModelHandlerDatatable), + } + + input_data_type, model_handler = data_types[known_args.input_type] + + xgboost_model_handler = KeyedModelHandler( + model_handler( + model_class=xgboost.XGBClassifier, + model_state=known_args.model_state)) + + input_data = load_sklearn_iris_test_data( + data_type=input_data_type, split=known_args.split) + + pipeline = test_pipeline + if not test_pipeline: + pipeline = beam.Pipeline(options=pipeline_options) + + predictions = ( + pipeline + | "ReadInputData" >> beam.Create(input_data) + | "RunInference" >> RunInference(xgboost_model_handler) + | "PostProcessOutputs" >> beam.ParDo(PostProcessor())) + + _ = predictions | "WriteOutput" >> beam.io.WriteToText( + known_args.output, shard_name_template='', append_trailing_newlines=True) + + result = pipeline.run() + result.wait_until_finish() + return result + + +if __name__ == '__main__': + logging.getLogger().setLevel(logging.INFO) + _train_model() Review Comment: Could we move this to `run()` and parameterize the path that's getting saved to? Then in tests we can train the model in a temporary directory to avoid conflicts ########## sdks/python/container/py310/base_image_requirements.txt: ########## @@ -154,4 +155,5 @@ urllib3==1.26.13 websocket-client==1.4.2 Werkzeug==2.2.2 wrapt==1.14.1 +xgboost==1.7.1 Review Comment: Instead of manually updating this file (and the other similar ones), please update https://github.com/apache/beam/blob/0c9999a6faaf7dd64e2abbbe96dac6c68c79d2d5/sdks/python/container/base_image_requirements_manual.txt and run `./gradlew :sdks:python:container:generatePythonRequirementsAll` - see https://github.com/apache/beam/blob/0c9999a6faaf7dd64e2abbbe96dac6c68c79d2d5/sdks/python/container/py310/base_image_requirements.txt#LL17C7-L17C69 ########## sdks/python/apache_beam/ml/inference/xgboost_inference.py: ########## @@ -0,0 +1,212 @@ +# +# 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 datatable +import numpy +import pandas +import scipy +import xgboost + +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 + + +class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC): + def __init__( + self, + model_class: Union[Callable[..., xgboost.Booster], + Callable[..., xgboost.XGBModel]], + model_state: str): + self.model_class = model_class + self.model_state = model_state + + def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]: + model = self.model_class() + model.load_model(self.model_state) Review Comment: Could we extend this so that it can accept arbitrary Beam Filesystem locations (e.g. gcs) so that it can easily be used on remote runners? You should be able to do that by using the Filesystem IO utilities - https://github.com/apache/beam/blob/c0e689331c2a6573ecf267b9bef133a85ea8a36c/sdks/python/apache_beam/io/filesystem.py#L810 - if there's not a good way to load the model via file stream, its ok to save the model locally before loading ########## sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py: ########## @@ -0,0 +1,169 @@ +# Review Comment: Note - I'd ask that to be part of this PR, the remaining documentation would ideally come in a separate PR though, that way we can merge this before the cut and publish the documentation once the release has been published. ########## sdks/python/apache_beam/ml/inference/xgboost_inference.py: ########## @@ -0,0 +1,212 @@ +# +# 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 datatable +import numpy +import pandas +import scipy +import xgboost + +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 + + +class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC): + def __init__( + self, + model_class: Union[Callable[..., xgboost.Booster], + Callable[..., xgboost.XGBModel]], + model_state: str): + self.model_class = model_class + self.model_state = model_state + + def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]: + model = self.model_class() + model.load_model(self.model_state) + return model + + def get_metrics_namespace(self) -> str: + return 'BeamML_XGBoost' + + +class XGBoostModelHandlerNumpy(XGBoostModelHandler[numpy.ndarray, Review Comment: Discussing versioning in this comment would be helpful as well - IIRC we're requiring a minimum XGBoost version to use this, right? -- 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: github-unsubscr...@beam.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org