diff --git a/.github/trigger_files/beam_PostCommit_Python.json b/.github/trigger_files/beam_PostCommit_Python.json index 79c7b053685e..ab4daeae2349 100644 --- a/.github/trigger_files/beam_PostCommit_Python.json +++ b/.github/trigger_files/beam_PostCommit_Python.json @@ -1,5 +1,4 @@ { "comment": "Modify this file in a trivial way to cause this test suite to run.", - "pr": "40241", - "modification": 2 + "modification": 3 } diff --git a/build.gradle.kts b/build.gradle.kts index 40d2f8c05da7..ea92fcafa757 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -810,6 +810,8 @@ tasks.register("python313PostCommit") { dependsOn(":sdks:python:test-suites:direct:py313:postCommitIT") dependsOn(":sdks:python:test-suites:direct:py313:hdfsIntegrationTest") dependsOn(":sdks:python:test-suites:portable:py313:postCommitPy313") + dependsOn(":sdks:python:test-suites:direct:py313:inferencePostCommitIT") + dependsOn(":sdks:python:test-suites:dataflow:py313:inferencePostCommitIT") } tasks.register("python314PostCommit") { diff --git a/sdks/python/apache_beam/examples/inference/README.md b/sdks/python/apache_beam/examples/inference/README.md index f14b531c21a2..0172f9524220 100644 --- a/sdks/python/apache_beam/examples/inference/README.md +++ b/sdks/python/apache_beam/examples/inference/README.md @@ -782,7 +782,7 @@ The pipeline reads sentences, performs basic preprocessing to convert the last w To use this transform, you need a dataset and model for language modeling. -1. Choose a checkpoint to load from Hugging Face Hub, eg:[MaskedLanguageModel](https://huggingface.co/stevhliu/my_awesome_eli5_mlm_model). +1. Choose a checkpoint to load from Hugging Face Hub, eg:[MaskedLanguageModel](https://huggingface.co/FacebookAI/roberta-base). 2. (Optional) Create a file named `SENTENCES.txt` that contains sentences to feed into the model. The content of the file should be similar to the following example: ``` The capital of France is Paris . @@ -807,13 +807,13 @@ For example, if you've followed the naming conventions recommended above: python -m apache_beam.examples.inference.huggingface_language_modeling \ --input SENTENCES.txt \ --output predictions.csv \ - --model_name "stevhliu/my_awesome_eli5_mlm_model" + --model_name "FacebookAI/roberta-base" ``` Or, using the default example sentences: ```sh python -m apache_beam.examples.inference.huggingface_language_modeling \ --output predictions.csv \ - --model_name "stevhliu/my_awesome_eli5_mlm_model" + --model_name "FacebookAI/roberta-base" ``` This writes the output to the `predictions.csv` with contents like: diff --git a/sdks/python/apache_beam/examples/inference/huggingface_language_modeling.py b/sdks/python/apache_beam/examples/inference/huggingface_language_modeling.py index 69c2eacc593d..131329c4ef0f 100644 --- a/sdks/python/apache_beam/examples/inference/huggingface_language_modeling.py +++ b/sdks/python/apache_beam/examples/inference/huggingface_language_modeling.py @@ -30,8 +30,11 @@ from collections.abc import Iterable from collections.abc import Iterator -import apache_beam as beam import torch +from transformers import AutoModelForMaskedLM +from transformers import AutoTokenizer + +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 @@ -39,8 +42,6 @@ from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.runners.runner import PipelineResult -from transformers import AutoModelForMaskedLM -from transformers import AutoTokenizer def add_mask_to_last_word(text: str) -> tuple[str, str]: @@ -52,7 +53,7 @@ def tokenize_sentence( text_and_mask: tuple[str, str], tokenizer: AutoTokenizer) -> tuple[str, dict[str, torch.Tensor]]: text, masked_text = text_and_mask - tokenized_sentence = tokenizer.encode_plus(masked_text, return_tensors="pt") + tokenized_sentence = tokenizer(masked_text, return_tensors="pt") # Workaround to manually remove batch dim until we have the feature to # add optional batching flag. diff --git a/sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py b/sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py index fa0582905e94..6fedd6ee5183 100644 --- a/sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py +++ b/sdks/python/apache_beam/examples/inference/xgboost_iris_classification.py @@ -24,16 +24,14 @@ 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 -import datatable -import xgboost 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 @@ -59,7 +57,7 @@ def parse_known_args(argv): '--input_type', dest='input_type', required=True, - choices=['numpy', 'pandas', 'scipy', 'datatable'], + choices=['numpy', 'pandas', 'scipy'], help='Datatype of the input data.') parser.add_argument( '--output', @@ -122,7 +120,6 @@ def run( '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] diff --git a/sdks/python/apache_beam/ml/inference/huggingface_inference.py b/sdks/python/apache_beam/ml/inference/huggingface_inference.py index daea76b5163c..960309519b11 100644 --- a/sdks/python/apache_beam/ml/inference/huggingface_inference.py +++ b/sdks/python/apache_beam/ml/inference/huggingface_inference.py @@ -621,8 +621,12 @@ def get_metrics_namespace(self) -> str: def _default_pipeline_inference_fn( batch, pipeline, inference_args) -> Iterable[PredictionResult]: - predicitons = pipeline(batch, **inference_args) - return predicitons + predictions = pipeline(batch, **inference_args) + # Some Hugging Face pipelines (e.g. QuestionAnsweringPipeline) return a + # single dict instead of a list of dicts when given a single-element batch. + if isinstance(predictions, dict) and len(batch) == 1: + predictions = [predictions] + return predictions class HuggingFacePipelineModelHandler(ModelHandler[str, diff --git a/sdks/python/apache_beam/ml/inference/huggingface_inference_it_test.py b/sdks/python/apache_beam/ml/inference/huggingface_inference_it_test.py index dd675d1935a7..f691ffca9c0f 100644 --- a/sdks/python/apache_beam/ml/inference/huggingface_inference_it_test.py +++ b/sdks/python/apache_beam/ml/inference/huggingface_inference_it_test.py @@ -36,6 +36,16 @@ "Check if transformers, torch, and tensorflow " "is installed.") +_EXPECTED_MASKED_LM_OUTPUTS = { + 'The capital of France is Paris .': 'paris', + 'It is raining cats and dogs .': 'dogs', + 'Today is Monday and tomorrow is Tuesday .': 'tuesday', + 'There are 5 coconuts on this palm tree .': 'tree', + 'The strongest person in the world is not famous .': 'me', + 'The secret ingredient to his wonderful life was gratitude .': 'love', + 'The biggest animal in the world is the whale .': 'elephant', +} + @pytest.mark.uses_transformers @pytest.mark.it_postcommit @@ -48,7 +58,7 @@ def test_hf_language_modeling(self): output_file_dir = 'gs://apache-beam-ml/testing/predictions' output_file = '/'.join([output_file_dir, str(uuid.uuid4()), 'result.txt']) - model_name = 'stevhliu/my_awesome_eli5_mlm_model' + model_name = 'FacebookAI/roberta-base' extra_opts = { 'input': file_of_sentences, @@ -62,18 +72,13 @@ def test_hf_language_modeling(self): self.assertEqual(FileSystems().exists(output_file), True) predictions = pytorch_inference_it_test.process_outputs( filepath=output_file) - actuals_file = 'gs://apache-beam-ml/testing/expected_outputs/test_hf_run_inference_for_masked_lm_actuals.txt' # pylint: disable=line-too-long - actuals = pytorch_inference_it_test.process_outputs(filepath=actuals_file) predictions_dict = {} for prediction in predictions: text, predicted_text = prediction.split(';') predictions_dict[text] = predicted_text.strip().lower() - for actual in actuals: - text, actual_predicted_text = actual.split(';') - predicted_predicted_text = predictions_dict[text] - self.assertEqual(actual_predicted_text, predicted_predicted_text) + self.assertEqual(_EXPECTED_MASKED_LM_OUTPUTS, predictions_dict) def test_hf_language_modeling_large_model(self): test_pipeline = TestPipeline(is_integration_test=True) @@ -82,7 +87,7 @@ def test_hf_language_modeling_large_model(self): output_file_dir = 'gs://apache-beam-ml/testing/predictions' output_file = '/'.join([output_file_dir, str(uuid.uuid4()), 'result.txt']) - model_name = 'stevhliu/my_awesome_eli5_mlm_model' + model_name = 'FacebookAI/roberta-base' extra_opts = { 'input': file_of_sentences, @@ -97,18 +102,13 @@ def test_hf_language_modeling_large_model(self): self.assertEqual(FileSystems().exists(output_file), True) predictions = pytorch_inference_it_test.process_outputs( filepath=output_file) - actuals_file = 'gs://apache-beam-ml/testing/expected_outputs/test_hf_run_inference_for_masked_lm_actuals.txt' # pylint: disable=line-too-long - actuals = pytorch_inference_it_test.process_outputs(filepath=actuals_file) predictions_dict = {} for prediction in predictions: text, predicted_text = prediction.split(';') predictions_dict[text] = predicted_text.strip().lower() - for actual in actuals: - text, actual_predicted_text = actual.split(';') - predicted_predicted_text = predictions_dict[text] - self.assertEqual(actual_predicted_text, predicted_predicted_text) + self.assertEqual(_EXPECTED_MASKED_LM_OUTPUTS, predictions_dict) def test_hf_pipeline(self): test_pipeline = TestPipeline(is_integration_test=True) diff --git a/sdks/python/apache_beam/ml/inference/huggingface_inference_test.py b/sdks/python/apache_beam/ml/inference/huggingface_inference_test.py index e8de5c4e9f8f..89868b381111 100644 --- a/sdks/python/apache_beam/ml/inference/huggingface_inference_test.py +++ b/sdks/python/apache_beam/ml/inference/huggingface_inference_test.py @@ -314,6 +314,53 @@ def test_framework_detection_does_not_import_tensorflow(self): self.assertFalse(huggingface_inference._is_tensorflow_tensor([1])) self.assertEqual(attempted_imports, []) + def test_pipeline_run_inference_single_dict_prediction(self): + # Pipelines like QuestionAnsweringPipeline return a single dict rather than + # a list of dicts for a batch of size 1. + fake_pipeline = lambda batch, **kwargs: { + 'score': 0.99, 'start': 0, 'end': 5, 'answer': 'Paris' + } + model_handler = HuggingFacePipelineModelHandler( + task='question-answering', model='unused') + results = list(model_handler.run_inference(['example1'], fake_pipeline)) + self.assertEqual(len(results), 1) + self.assertEqual(results[0].example, 'example1') + self.assertEqual( + results[0].inference, { + 'score': 0.99, 'start': 0, 'end': 5, 'answer': 'Paris' + }) + + def test_pipeline_run_inference_batched_list_predictions(self): + fake_pipeline = lambda batch, **kwargs: [{ + 'score': 0.99, 'answer': 'Paris' + }, { + 'score': 0.85, 'answer': 'NYC' + }] + model_handler = HuggingFacePipelineModelHandler( + task='question-answering', model='unused') + results = list( + model_handler.run_inference(['example1', 'example2'], fake_pipeline)) + self.assertEqual(len(results), 2) + self.assertEqual(results[0].example, 'example1') + self.assertEqual(results[0].inference, {'score': 0.99, 'answer': 'Paris'}) + self.assertEqual(results[1].example, 'example2') + self.assertEqual(results[1].inference, {'score': 0.85, 'answer': 'NYC'}) + + def test_pipeline_run_inference_custom_columnar_dict_inference_fn(self): + # A custom inference_fn returning a columnar dict (as used by Beam YAML) + # must still be transposed by utils._convert_to_result for batch size 1. + def custom_inference_fn(batch, pipeline, inference_args): + return {'label': ['POSITIVE'], 'score': [0.99]} + + model_handler = HuggingFacePipelineModelHandler( + task='text-classification', + model='unused', + inference_fn=custom_inference_fn) + results = list(model_handler.run_inference(['I love Beam!'], object())) + self.assertEqual(len(results), 1) + self.assertEqual(results[0].example, 'I love Beam!') + self.assertEqual(results[0].inference, {'label': 'POSITIVE', 'score': 0.99}) + if __name__ == '__main__': unittest.main() diff --git a/sdks/python/apache_beam/ml/inference/huggingface_tests_requirements.txt b/sdks/python/apache_beam/ml/inference/huggingface_tests_requirements.txt index 9b9e9bdd55f1..757b4b5ef64b 100644 --- a/sdks/python/apache_beam/ml/inference/huggingface_tests_requirements.txt +++ b/sdks/python/apache_beam/ml/inference/huggingface_tests_requirements.txt @@ -15,6 +15,9 @@ # limitations under the License. # -torch>=1.7.1 +# torch>=2.12 Linux wheels require triton>=3.7, which aborts with an LLVM +# option registration collision when imported alongside tensorflow. +torch>=2.3.0,<2.12.0 transformers==4.53.0 -tensorflow>=2.12.0 \ No newline at end of file +tensorflow>=2.12.0,<2.22 +tf-keras>=2.16.0; python_version >= '3.12' diff --git a/sdks/python/apache_beam/ml/inference/pytorch_inference_it_test.py b/sdks/python/apache_beam/ml/inference/pytorch_inference_it_test.py index c9c3d06434a7..672e4c9c29a1 100644 --- a/sdks/python/apache_beam/ml/inference/pytorch_inference_it_test.py +++ b/sdks/python/apache_beam/ml/inference/pytorch_inference_it_test.py @@ -17,6 +17,8 @@ """End-to-End test for Pytorch Inference""" +import ast +import collections import logging import os import unittest @@ -67,6 +69,24 @@ def process_outputs(filepath): 'Missing dependencies. ' 'Test depends on torch, torchvision, pillow, and transformers') class PyTorchInference(unittest.TestCase): + def _assert_labels_match(self, actual_labels_str, predicted_labels_str): + # MaskRCNN returns all detections above score 0.05 sorted by confidence, so + # minor rounding differences across Pillow/PyTorch versions can reorder + # nearly-tied predictions or toggle borderline detections near 0.05. + expected = ast.literal_eval(actual_labels_str) + predicted = ast.literal_eval(predicted_labels_str) + top_k = min(5, len(expected)) + self.assertEqual(expected[:top_k], predicted[:top_k]) + expected_counts = collections.Counter(expected) + predicted_counts = collections.Counter(predicted) + intersection = sum((expected_counts & predicted_counts).values()) + union = sum((expected_counts | predicted_counts).values()) + self.assertGreaterEqual( + intersection / union, + 0.8, + f'Prediction overlap too low: expected={expected}, ' + f'predicted={predicted}') + @pytest.mark.uses_pytorch @pytest.mark.it_postcommit def test_torch_run_inference_imagenet_mobilenetv2(self): @@ -127,7 +147,7 @@ def test_torch_run_inference_coco_maskrcnn_resnet50_fpn(self): for actual in actuals: filename, actual_labels = actual.split(';') prediction_labels = predictions_dict[filename] - self.assertEqual(actual_labels, prediction_labels) + self._assert_labels_match(actual_labels, prediction_labels) @pytest.mark.uses_pytorch @pytest.mark.it_postcommit @@ -173,8 +193,16 @@ def test_torch_run_inference_coco_maskrcnn_resnet50_fpn_v1_and_v2(self): v1actuals = a[1] v2actuals = a[2] v1prediction_labels, v2prediction_labels = predictions_dict[filename] - self.assertEqual(v1actuals, v1prediction_labels) - self.assertEqual(v2actuals, v2prediction_labels) + self.assertTrue( + v1prediction_labels.strip().startswith('v1 predictions: ')) + self.assertTrue( + v2prediction_labels.strip().startswith('v2 predictions: ')) + self._assert_labels_match( + v1actuals.split('v1 predictions: ', 1)[1].strip(), + v1prediction_labels.split('v1 predictions: ', 1)[1].strip()) + self._assert_labels_match( + v2actuals.split('v2 predictions: ', 1)[1].strip(), + v2prediction_labels.split('v2 predictions: ', 1)[1].strip()) @pytest.mark.uses_pytorch @pytest.mark.it_postcommit diff --git a/sdks/python/apache_beam/ml/inference/tensorflow_tests_requirements.txt b/sdks/python/apache_beam/ml/inference/tensorflow_tests_requirements.txt index 7a21e908dc17..c354b802d735 100644 --- a/sdks/python/apache_beam/ml/inference/tensorflow_tests_requirements.txt +++ b/sdks/python/apache_beam/ml/inference/tensorflow_tests_requirements.txt @@ -15,8 +15,10 @@ # limitations under the License. # -keras<3.0.0 -tensorflow>=2.12.0 +keras<3.0.0; python_version < '3.12' +tensorflow>=2.12.0,<2.16; python_version < '3.12' +tf-keras>=2.16.0; python_version >= '3.12' +tensorflow>=2.16.0,<2.22; python_version >= '3.12' tensorflow_hub>=0.10.0 Pillow>=9.0.0 typing-extensions>=4.8.0 diff --git a/sdks/python/apache_beam/ml/inference/torch_tests_requirements.txt b/sdks/python/apache_beam/ml/inference/torch_tests_requirements.txt index df6273038f1a..7440c90a4e87 100644 --- a/sdks/python/apache_beam/ml/inference/torch_tests_requirements.txt +++ b/sdks/python/apache_beam/ml/inference/torch_tests_requirements.txt @@ -15,8 +15,10 @@ # limitations under the License. # -torch>=1.7.1 +# torch>=2.12 Linux wheels require triton>=3.7, which aborts with an LLVM +# option registration collision when imported alongside tensorflow. +torch>=2.3.0,<2.12.0 torchvision>=0.8.2 pillow>=8.0.0 transformers>=4.18.0 -google-cloud-monitoring>=2.27.0 \ No newline at end of file +google-cloud-monitoring>=2.27.0 diff --git a/sdks/python/apache_beam/ml/inference/xgboost_inference_it_test.py b/sdks/python/apache_beam/ml/inference/xgboost_inference_it_test.py index 73becf4ff104..12e8e503c628 100644 --- a/sdks/python/apache_beam/ml/inference/xgboost_inference_it_test.py +++ b/sdks/python/apache_beam/ml/inference/xgboost_inference_it_test.py @@ -77,7 +77,7 @@ def process_outputs(filepath): @unittest.skipIf( os.getenv('FORCE_XGBOOST_IT') is None and xgboost is None, 'Missing dependencies. ' - 'Test depends on xgboost and datatable') + 'Test depends on xgboost') @pytest.mark.uses_xgboost @pytest.mark.it_postcommit class XGBoostInference(unittest.TestCase): @@ -214,39 +214,6 @@ def test_iris_classification_scipy_single_batch(self): true_label, expected_prediction = expected_output.split(',') self.assertEqual(predictions_dict[true_label], expected_prediction) - def test_iris_classification_datatable_single_batch(self): - test_pipeline = TestPipeline(is_integration_test=True) - input_type = 'datatable' - output_file_dir = '/tmp' - output_file = '/'.join( - [output_file_dir, str(uuid.uuid4()), 'datatable_single_batch.txt']) - model_state_path = 'gs://apache-beam-ml/models/xgboost.iris_classifier.json' - extra_opts = { - 'input_type': input_type, - 'output': output_file, - 'model_state': model_state_path, - 'no_split': True - } - - xgboost_iris_classification.run( - test_pipeline.get_full_options_as_args(**extra_opts), - save_main_session=False) - self.assertEqual(FileSystems().exists(output_file), True) - - expected_outputs = EXPECTED_OUTPUT_SINGLE_BATCHES - - predicted_outputs = process_outputs(output_file) - self.assertEqual(len(expected_outputs), len(predicted_outputs)) - - predictions_dict = {} - for predicted_output in predicted_outputs: - true_label, prediction = predicted_output.split(',') - predictions_dict[true_label] = prediction - - for expected_output in expected_outputs: - true_label, expected_prediction = expected_output.split(',') - self.assertEqual(predictions_dict[true_label], expected_prediction) - def test_iris_classification_numpy_multi_batch(self): test_pipeline = TestPipeline(is_integration_test=True) input_type = 'numpy' @@ -346,39 +313,6 @@ def test_iris_classification_scipy_multi_batch(self): true_label, expected_prediction = expected_output.split(',') self.assertEqual(predictions_dict[true_label], expected_prediction) - def test_iris_classification_datatable_multi_batch(self): - test_pipeline = TestPipeline(is_integration_test=True) - input_type = 'datatable' - output_file_dir = '/tmp' - output_file = '/'.join( - [output_file_dir, str(uuid.uuid4()), 'datatable_multi_batch.txt']) - model_state_path = 'gs://apache-beam-ml/models/xgboost.iris_classifier.json' - extra_opts = { - 'input_type': input_type, - 'output': output_file, - 'model_state': model_state_path, - 'split': True - } - - xgboost_iris_classification.run( - test_pipeline.get_full_options_as_args(**extra_opts), - save_main_session=False) - self.assertEqual(FileSystems().exists(output_file), True) - - expected_outputs = EXPECTED_OUTPUT_MULTIPLE_BATCHES - - predicted_outputs = process_outputs(output_file) - self.assertEqual(len(expected_outputs), len(predicted_outputs)) - - predictions_dict = {} - for predicted_output in predicted_outputs: - true_label, prediction = predicted_output.split(',') - predictions_dict[true_label] = prediction - - for expected_output in expected_outputs: - true_label, expected_prediction = expected_output.split(',') - self.assertEqual(predictions_dict[true_label], expected_prediction) - if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) diff --git a/sdks/python/apache_beam/ml/inference/xgboost_inference_test.py b/sdks/python/apache_beam/ml/inference/xgboost_inference_test.py index 33b70c737d07..15ff7e436428 100644 --- a/sdks/python/apache_beam/ml/inference/xgboost_inference_test.py +++ b/sdks/python/apache_beam/ml/inference/xgboost_inference_test.py @@ -34,7 +34,6 @@ from apache_beam.ml.inference import RunInference from apache_beam.ml.inference.base import KeyedModelHandler from apache_beam.ml.inference.base import PredictionResult - 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 diff --git a/sdks/python/apache_beam/ml/inference/xgboost_tests_requirements.txt b/sdks/python/apache_beam/ml/inference/xgboost_tests_requirements.txt index b1936b4149e4..d90af4070d75 100644 --- a/sdks/python/apache_beam/ml/inference/xgboost_tests_requirements.txt +++ b/sdks/python/apache_beam/ml/inference/xgboost_tests_requirements.txt @@ -15,5 +15,4 @@ # limitations under the License. # -datatable>=1.1.0,<2 xgboost>=2.0.0,<4 diff --git a/sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_it_test.py b/sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_it_test.py index a57e340945e7..892bf20ddf7e 100644 --- a/sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_it_test.py +++ b/sdks/python/apache_beam/transforms/enrichment_handlers/bigquery_it_test.py @@ -369,7 +369,8 @@ def test_bigquery_enrichment_no_results_throws_exception(self): throw_exception_on_empty_results=True, ) - with self.assertRaisesRegex(ValueError, "no matching row found for query"): + with self.assertRaisesRegex((ValueError, RuntimeError), + "no matching row found for query"): with TestPipeline(is_integration_test=True) as test_pipeline: _ = (test_pipeline | beam.Create(requests) | Enrichment(handler)) @@ -455,7 +456,8 @@ def test_bigquery_enrichment_no_results_with_query_fn_throws_exception(self): throw_exception_on_empty_results=True, ) - with self.assertRaisesRegex(ValueError, "no matching row found for query"): + with self.assertRaisesRegex((ValueError, RuntimeError), + "no matching row found for query"): with TestPipeline(is_integration_test=True) as test_pipeline: _ = (test_pipeline | beam.Create(requests) | Enrichment(handler)) @@ -494,7 +496,8 @@ def test_bigquery_enrichment_partial_results_throws_exception_batched(self): throw_exception_on_empty_results=True, ) - with self.assertRaisesRegex(ValueError, "no matching row found for query"): + with self.assertRaisesRegex((ValueError, RuntimeError), + "no matching row found for query"): with TestPipeline(is_integration_test=True) as test_pipeline: _ = (test_pipeline | beam.Create(requests) | Enrichment(handler)) diff --git a/sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store_it_test.py b/sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store_it_test.py index 8e3819d71c39..4366d99fd457 100644 --- a/sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store_it_test.py +++ b/sdks/python/apache_beam/transforms/enrichment_handlers/feast_feature_store_it_test.py @@ -29,18 +29,35 @@ import apache_beam as beam from apache_beam.testing.test_pipeline import TestPipeline +from apache_beam.testing.util import BeamAssertException # pylint: disable=ungrouped-imports try: from apache_beam.transforms.enrichment import Enrichment from apache_beam.transforms.enrichment_handlers.feast_feature_store import FeastFeatureStoreEnrichmentHandler - from apache_beam.transforms.enrichment_handlers.vertex_ai_feature_store_it_test import \ - ValidateResponse # pylint: disable=line-too-long except ImportError: raise unittest.SkipTest( 'Feast feature store test dependencies are not installed.') +class ValidateResponse(beam.DoFn): + """ValidateResponse validates if a PCollection of `beam.Row` + has the required fields.""" + def __init__(self, expected_fields): + self.expected_fields = expected_fields + + def process(self, element: beam.Row, *args, **kwargs): + element_dict = element.as_dict() + if len(self.expected_fields) != len(element_dict.keys()): + raise BeamAssertException( + "Expected %d fields in enriched PCollection:" % + len(self.expected_fields)) + for field in self.expected_fields: + if field not in element_dict: + raise BeamAssertException( + f"Expected to fetch field: {field} from feature store") + + def _entity_row_fn(request: beam.Row) -> Mapping[str, Any]: entity_value = request.user_id # type: ignore[attr-defined] return {'user_id': entity_value} diff --git a/sdks/python/apache_beam/transforms/enrichment_handlers/feast_tests_requirements.txt b/sdks/python/apache_beam/transforms/enrichment_handlers/feast_tests_requirements.txt index 3e0c1f50bd75..f2fbe95a632d 100644 --- a/sdks/python/apache_beam/transforms/enrichment_handlers/feast_tests_requirements.txt +++ b/sdks/python/apache_beam/transforms/enrichment_handlers/feast_tests_requirements.txt @@ -15,4 +15,10 @@ # limitations under the License. # -feast[gcp] \ No newline at end of file +# Install feast without the [gcp] extra because feast[gcp] pins +# google-cloud-storage<3, which conflicts with Beam's google-cloud-storage>=3,<4 +# requirement and downgrades it in the shared test virtualenv. The remaining GCP +# client packages are already installed by apache-beam[gcp]. +feast +fsspec>=2024.1.0 +google-cloud-bigquery[pandas]<4,>=2 diff --git a/sdks/python/test-suites/direct/common.gradle b/sdks/python/test-suites/direct/common.gradle index 27de0a455472..e12bb91b5057 100644 --- a/sdks/python/test-suites/direct/common.gradle +++ b/sdks/python/test-suites/direct/common.gradle @@ -220,7 +220,7 @@ task torchInferenceTest { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "torchInferenceTest-direct-py${pythonVersionSuffix}", "collect": "uses_pytorch and it_postcommit", "runner": "TestDirectRunner" ] @@ -237,19 +237,11 @@ task torchInferenceTest { task sklearnInferenceTest { dependsOn 'installGcpTest' dependsOn ':sdks:python:sdist' - // TODO(https://github.com/apache/beam/issues/24787) - // Scikit learn tests fails from version 1.2.0 - doFirst { - exec { - executable 'sh' - args '-c', ". ${envdir}/bin/activate && pip install 'scikit-learn<1.2.0'" - } - } doLast { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "sklearnInferenceTest-direct-py${pythonVersionSuffix}", "collect": "uses_sklearn and it_postcommit" , "runner": "TestDirectRunner" ] @@ -276,7 +268,7 @@ task tfxInferenceTest { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "tfxInferenceTest-direct-py${pythonVersionSuffix}", "collect": "uses_tensorflow and it_postcommit" , "runner": "TestDirectRunner" ] @@ -303,14 +295,14 @@ task tensorflowInferenceTest { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "tensorflowInferenceTest-direct-py${pythonVersionSuffix}", "collect": "uses_tf and it_postcommit" , "runner": "TestDirectRunner" ] def cmdArgs = mapToArgString(argMap) exec { executable 'sh' - args '-c', ". ${envdir}/bin/activate && ${runScriptsDir}/run_integration_test.sh $cmdArgs" + args '-c', ". ${envdir}/bin/activate && export TF_USE_LEGACY_KERAS=1 && ${runScriptsDir}/run_integration_test.sh $cmdArgs" } } } @@ -330,7 +322,7 @@ task xgboostInferenceTest { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "xgboostInferenceTest-direct-py${pythonVersionSuffix}", "collect": "uses_xgboost and it_postcommit", "runner": "TestDirectRunner" ] @@ -358,7 +350,7 @@ task transformersInferenceTest { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "transformersInferenceTest-direct-py${pythonVersionSuffix}", "collect": "uses_transformers and it_postcommit" , "runner": "TestDirectRunner" ] @@ -374,12 +366,18 @@ task transformersInferenceTest { task testcontainersTest { dependsOn 'installGcpTest' dependsOn ':sdks:python:sdist' - + def requirementsFile = "${rootDir}/sdks/python/apache_beam/transforms/enrichment_tests_requirements.txt" + doFirst { + exec { + executable 'sh' + args '-c', ". ${envdir}/bin/activate && pip install -r $requirementsFile" + } + } doLast { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "testcontainersTest-direct-py${pythonVersionSuffix}", "collect": "uses_testcontainer", "runner": "TestDirectRunner", "region": "us-central1", @@ -407,7 +405,7 @@ task feastIntegrationTest { def testOpts = basicTestOpts def argMap = [ "test_opts": testOpts, - "suite": "postCommitIT-direct-py${pythonVersionSuffix}", + "suite": "feastIntegrationTest-direct-py${pythonVersionSuffix}", "collect": "uses_feast", "runner": "TestDirectRunner" ]