Skip to content
Closed
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
3 changes: 1 addition & 2 deletions .github/trigger_files/beam_PostCommit_Python.json
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down
6 changes: 3 additions & 3 deletions sdks/python/apache_beam/examples/inference/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 .
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,18 @@
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
from apache_beam.ml.inference.huggingface_inference import HuggingFaceModelHandlerKeyedTensor
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]:
Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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',
Expand Down Expand Up @@ -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]
Expand Down
8 changes: 6 additions & 2 deletions sdks/python/apache_beam/ml/inference/huggingface_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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)
Expand All @@ -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,
Expand All @@ -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)
Expand Down
47 changes: 47 additions & 0 deletions sdks/python/apache_beam/ml/inference/huggingface_inference_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Original file line number Diff line number Diff line change
Expand Up @@ -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
tensorflow>=2.12.0,<2.22
tf-keras>=2.16.0; python_version >= '3.12'
34 changes: 31 additions & 3 deletions sdks/python/apache_beam/ml/inference/pytorch_inference_it_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

"""End-to-End test for Pytorch Inference"""

import ast
import collections
import logging
import os
import unittest
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
google-cloud-monitoring>=2.27.0
Loading
Loading