Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@

[comment]: # "generic breaking changes if not covered in following sections."
* (Java) Flink runner: batch pipelines now assign source splits to readers statically by default instead of lazily. Set `--sourceStaticSplitThresholdMb=0` to restore lazy assignment ([#40607](https://github.com/apache/beam/issues/40607)).
* (Python) Datatable support in the XGBoost model handler has been removed. ([#41586](https://github.com/apache/beam/issues/41586)).
* X behavior was changed ([#X](https://github.com/apache/beam/issues/X)).

### Package upgrades
Expand Down
63 changes: 1 addition & 62 deletions sdks/python/apache_beam/ml/inference/xgboost_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
from typing import Optional
from typing import Union

import datatable
import numpy
import pandas
import scipy
Expand All @@ -42,8 +41,7 @@
'XGBoostModelHandler',
'XGBoostModelHandlerNumpy',
'XGBoostModelHandlerPandas',
'XGBoostModelHandlerSciPy',
'XGBoostModelHandlerDatatable'
'XGBoostModelHandlerSciPy'
]

XGBoostInferenceFn = Callable[[
Expand Down Expand Up @@ -315,62 +313,3 @@ def get_num_bytes(self, batch: Sequence[scipy.sparse.csr_matrix]) -> int:
The number of bytes of data for a batch.
"""
return sum(sys.getsizeof(element) for element in batch)


@deprecated(
since='2.78.0',
extra_message=(
'datatable has not had a release since 2023 and has no wheels for '
'Python 3.13+. XGBoostModelHandlerDatatable and the datatable '
'dependency will be removed in Beam 2.79.0.'))
class XGBoostModelHandlerDatatable(XGBoostModelHandler[datatable.Frame,
PredictionResult,
Union[xgboost.Booster,
xgboost.XGBModel]]
):
"""Implementation of the ModelHandler interface for XGBoost
using datatable dataframes as input.

Example Usage::

pcoll | RunInference(
XGBoostModelHandlerDatatable(
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
"""
def run_inference(
self,
batch: Sequence[datatable.Frame],
model: Union[xgboost.Booster, xgboost.XGBModel],
inference_args: Optional[dict[str, Any]] = None
) -> Iterable[PredictionResult]:
"""Runs inferences on a batch of datatable dataframe.

Args:
batch: A sequence of examples as datatable dataframes. Each
row in a dataframe 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 datatable dataframe.
inference_args: Any additional arguments for an inference.

Returns:
An Iterable of type PredictionResult.
"""
return self._inference_fn(batch, model, inference_args)

def get_num_bytes(self, batch: Sequence[datatable.Frame]) -> int:
"""
Returns:
The number of bytes of data for a batch.
"""
return sum(sys.getsizeof(element) for element in batch)
109 changes: 0 additions & 109 deletions sdks/python/apache_beam/ml/inference/xgboost_inference_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
from typing import Any

try:
import datatable
import numpy
import pandas
import pytest
Expand Down Expand Up @@ -74,8 +73,6 @@ def predict_fn(self, data):
self.inference_calls = getattr(self, 'inference_calls', 0) + 1
if isinstance(data, pandas.DataFrame):
data = data.to_numpy()
if isinstance(data, datatable.Frame):
data = data.to_numpy()
if isinstance(data, scipy.sparse.csr_matrix):
data = data.toarray()
return sum(sum(array) for array in data)
Expand Down Expand Up @@ -180,27 +177,6 @@ def test_num_bytes_pandas(self):
batched_examples_float[1].memory_usage(deep=True).sum(),
inference_runner.get_num_bytes(batched_examples_float))

def test_num_bytes_datatable(self):
inference_runner = XGBoostModelHandlerDatatable(
model_class=xgboost.XGBClassifier, model_state='unused')
batched_examples_int = [
datatable.Frame([[1, 1], [2, 2]]),
datatable.Frame([[2, 4], [6, 8]]),
]
self.assertEqual(
sys.getsizeof(batched_examples_int[0]) +
sys.getsizeof(batched_examples_int[1]),
inference_runner.get_num_bytes(batched_examples_int))

batched_examples_float = [
datatable.Frame([[1.0, 1.0], [2.0, 2.0]]),
datatable.Frame([[2.0, 4.0], [6.0, 8.0]]),
]
self.assertEqual(
sys.getsizeof(batched_examples_float[0]) +
sys.getsizeof(batched_examples_float[1]),
inference_runner.get_num_bytes(batched_examples_float))

def test_num_bytes_scipy(self):
inference_runner = XGBoostModelHandlerSciPy(
model_class=xgboost.XGBClassifier, model_state='unused')
Expand Down Expand Up @@ -315,52 +291,6 @@ def test_pipeline_pandas_sets_env_vars_correctly(self):
self.assertTrue('FOO' in os.environ)
self.assertTrue((os.environ['FOO']) == 'bar')

def test_pipeline_datatable(self):
model = build_monkeypatched_xgboost_classifier()
model_state = self.tmpdir + os.sep + 'model.json'
model.save_model(model_state)

with TestPipeline() as pipeline:
examples = [
datatable.Frame([[1, 1], [2, 2]]),
datatable.Frame([[2, 4], [6, 8]]),
]

pcoll = pipeline | 'start' >> beam.Create(examples)
actual = pcoll | RunInference(
XGBoostModelHandlerDatatable(
model_class=xgboost.XGBClassifier, model_state=model_state))
expected = [
PredictionResult(datatable.Frame([[1, 1], [2, 2]]), 6),
PredictionResult(datatable.Frame([[2, 4], [6, 8]]), 20)
]
assert_that(
actual, equal_to(expected, equals_fn=_compare_prediction_result))

def test_pipeline_datatable_sets_env_vars_correctly(self):
model = build_monkeypatched_xgboost_classifier()
model_state = self.tmpdir + os.sep + 'model.json'
model.save_model(model_state)
os.environ.pop('FOO', None)
self.assertFalse('FOO' in os.environ)

with TestPipeline() as pipeline:
examples = [
datatable.Frame([[1, 1], [2, 2]]),
datatable.Frame([[2, 4], [6, 8]]),
]
handler_with_vars = XGBoostModelHandlerDatatable(
env_vars={'FOO': 'bar'},
model_class=xgboost.XGBClassifier,
model_state=model_state)
_ = (
pipeline
| 'start' >> beam.Create(examples)
| RunInference(handler_with_vars))
pipeline.run()
self.assertTrue('FOO' in os.environ)
self.assertTrue((os.environ['FOO']) == 'bar')

def test_pipeline_scipy(self):
model = build_monkeypatched_xgboost_classifier()
model_state = self.tmpdir + os.sep + 'model.json'
Expand Down Expand Up @@ -409,21 +339,6 @@ def test_pipeline_scipy_sets_env_vars_correctly(self):
self.assertTrue('FOO' in os.environ)
self.assertTrue((os.environ['FOO']) == 'bar')

def test_bad_model_file_raises(self):
model_state = self.tmpdir + os.sep + 'bad_file_name.json'

with self.assertRaises(RuntimeError):
with TestPipeline() as pipeline:
examples = [
datatable.Frame([[1, 1], [2, 2]]),
datatable.Frame([[2, 4], [6, 8]]),
]

pcoll = pipeline | 'start' >> beam.Create(examples)
_ = pcoll | RunInference(
XGBoostModelHandlerNumpy(xgboost.XGBClassifier, model_state))
pipeline.run()

def test_bad_input_type_raises(self):
model = build_monkeypatched_xgboost_classifier()
model_state = self.tmpdir + os.sep + 'model.json'
Expand Down Expand Up @@ -512,30 +427,6 @@ def test_pipeline_pandas_with_keys(self):
actual,
equal_to(expected, equals_fn=_compare_keyed_prediction_result))

def test_pipeline_datatable_with_keys(self):
model = build_monkeypatched_xgboost_classifier()
model_state = self.tmpdir + os.sep + 'model.json'
model.save_model(model_state)

with TestPipeline() as pipeline:
examples = [
('0', datatable.Frame([[1, 1], [2, 2]])),
('1', datatable.Frame([[2, 4], [6, 8]])),
]

pcoll = pipeline | 'start' >> beam.Create(examples)
actual = pcoll | RunInference(
KeyedModelHandler(
XGBoostModelHandlerDatatable(
model_class=xgboost.XGBClassifier, model_state=model_state)))
expected = [
('0', PredictionResult(datatable.Frame([[1, 1], [2, 2]]), 6)),
('1', PredictionResult(datatable.Frame([[2, 4], [6, 8]]), 20))
]
assert_that(
actual,
equal_to(expected, equals_fn=_compare_keyed_prediction_result))


if __name__ == '__main__':
unittest.main()
7 changes: 0 additions & 7 deletions sdks/python/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,6 @@ def cythonize(*args, **kwargs):
# in tox.ini.
xgboost_dependency = [
'xgboost>=2.0.0,<4',
# apache_beam.ml.inference.xgboost_inference imports datatable directly.
# 1.1.0 is the first release with Python 3.10+ wheels; no release has
# wheels for Python 3.13+.
'datatable>=1.1.0,<2',
]

# tensorflow-transform 1.21 (via tfx-bsl 1.21) requires
Expand Down Expand Up @@ -617,7 +613,6 @@ def get_portability_package_data():
# extras. Keeping the bounds open as much as possible so that we
# can find out early when Beam doesn't work with new versions.
'ml_test': [
'datatable',
# tensorflow-transform requires dill, but doesn't set dill as a
# hard requirement in setup.py.
'dill', # match tft extra.
Expand All @@ -630,8 +625,6 @@ def get_portability_package_data():
# which tensorflow-transform 1.21 requires.
'tf2onnx>=1.17.0,<1.18',
] + ml_base_core,
# xgboost_dependency includes datatable, which only has wheels for
# Python <=3.12, so it is limited to the 3.11 and 3.12 test extras.
'p311_ml_test': ml_base + xgboost_dependency + qdrant_dependency,
'p312_ml_test': [
'typesafe-sdk>=0.7.1,<0.8',
Expand Down
Loading