Skip to content

ML pipelines: RunInference - OSS Image Object detection, OSS Image Captioning, OSS Image Classification#37186

Open
Amar3tto wants to merge 32 commits into
masterfrom
oss-image-detection
Open

ML pipelines: RunInference - OSS Image Object detection, OSS Image Captioning, OSS Image Classification#37186
Amar3tto wants to merge 32 commits into
masterfrom
oss-image-detection

Conversation

@Amar3tto
Copy link
Copy Markdown
Collaborator

Please add a meaningful description for your change here


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @Amar3tto, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances Apache Beam's machine learning capabilities by integrating a new PyTorch-based image object detection pipeline. The pipeline leverages the RunInference transform for efficient batched GPU inference with open-source TorchVision models, processing images from cloud storage and outputting structured detection results to BigQuery. This addition is complemented by a new performance benchmark and corresponding documentation, ensuring that the pipeline's efficiency and resource usage can be consistently monitored and evaluated.

Highlights

  • New PyTorch Object Detection Example: Introduced a new example pipeline for PyTorch image object detection using Apache Beam's RunInference, capable of processing image URIs from GCS, performing batched GPU inference with TorchVision models, and writing results to BigQuery.
  • Dedicated Performance Benchmark: Added a new benchmark test (PytorchImageObjectDetectionBenchmarkTest) to measure and track the performance of the PyTorch image object detection pipeline, focusing on stable GPU inference workloads.
  • Updated Documentation and Dependencies: Included new Python dependencies for PyTorch object detection and updated the project's website with a dedicated performance page for the new benchmark, including placeholders for Looker Studio metrics.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Ignored Files
  • Ignored by pattern: .github/workflows/** (2)
    • .github/workflows/beam_Inference_Python_Benchmarks_Dataflow.yml
    • .github/workflows/load-tests-pipeline-options/beam_Inference_Python_Benchmarks_Dataflow_Pytorch_Image_Detection.txt
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@Amar3tto Amar3tto changed the title ML pipelines: RunInference - OSS Image Object detection ML pipelines: RunInference - OSS Image Object detection, OSS Image Captioning Dec 31, 2025
@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 31, 2025

Codecov Report

❌ Patch coverage is 0% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 36.33%. Comparing base (358e007) to head (64187d9).
⚠️ Report is 13 commits behind head on master.

Files with missing lines Patch % Lines
...s/inference/pytorch_image_captioning_benchmarks.py 0.00% 14 Missing ⚠️
...rence/pytorch_image_object_detection_benchmarks.py 0.00% 14 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (358e007) and HEAD (64187d9). Click for more details.

HEAD has 3 uploads less than BASE
Flag BASE (358e007) HEAD (64187d9)
python 4 1
Additional details and impacted files
@@              Coverage Diff              @@
##             master   #37186       +/-   ##
=============================================
- Coverage     55.28%   36.33%   -18.96%     
  Complexity     1676     1676               
=============================================
  Files          1067     1069        +2     
  Lines        167148   167178       +30     
  Branches       1208     1208               
=============================================
- Hits          92415    60737    -31678     
- Misses        72551   104259    +31708     
  Partials       2182     2182               
Flag Coverage Δ
python 40.60% <0.00%> (-40.46%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Amar3tto Amar3tto changed the title ML pipelines: RunInference - OSS Image Object detection, OSS Image Captioning ML pipelines: RunInference - OSS Image Object detection, OSS Image Captioning, OSS Image Classification Jan 21, 2026
@Amar3tto Amar3tto requested a review from damccorm February 7, 2026 05:40
@Amar3tto Amar3tto marked this pull request as ready for review February 7, 2026 05:41
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Feb 7, 2026

Assigning reviewers:

R: @claudevdm for label python.
R: @liferoad for label build.
R: @shunping for label website.

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Comment thread website/www/site/data/performance.yaml Outdated
@Amar3tto Amar3tto requested a review from damccorm February 12, 2026 14:40
@Amar3tto
Copy link
Copy Markdown
Collaborator Author

@Abacn Could you please help with review?

Comment thread .github/workflows/beam_Inference_Python_Benchmarks_Dataflow.yml Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_object_detection.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_imagenet_rightfit.py Outdated
@damccorm
Copy link
Copy Markdown
Contributor

/gemini review

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces three new ML inference pipelines for image classification, object detection, and image captioning using PyTorch, along with their corresponding benchmarks and documentation. The pipelines are well-structured and showcase advanced Beam features like RunInference with custom model handlers and stateful DoFns. My review focuses on improving scalability, robustness, and maintainability. I've identified a few key areas for improvement, including a scalability bottleneck in the data loading pipelines, several instances of broad exception handling that could mask errors, some potentially buggy logic, and a few copy-paste errors in the new documentation pages. Overall, this is a valuable contribution, and the suggested changes aim to make these examples more robust and easier to understand.

Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_object_detection.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_imagenet_rightfit.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_imagenet_rightfit.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_imagenet_rightfit.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread website/www/site/content/en/performance/pytorchimagenetrightfitgpu/_index.md Outdated
Comment thread website/www/site/content/en/performance/pytorchimagenetrightfitoncecpu/_index.md Outdated
Comment thread website/www/site/content/en/performance/pytorchimagenetrightfitoncecpu/_index.md Outdated
Comment thread website/www/site/content/en/performance/pytorchimagenetrightfitoncegpu/_index.md Outdated
Comment thread website/www/site/content/en/performance/pytorchimagenetrightfitoncegpu/_index.md Outdated
@github-actions
Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @claudevdm @liferoad @shunping

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Mar 3, 2026

Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment assign to next reviewer:

R: @jrmccluskey for label python.
R: @damccorm for label build.
R: @damccorm for label website.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

@github-actions
Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @jrmccluskey @damccorm

@github-actions
Copy link
Copy Markdown
Contributor

Assigning new set of reviewers because Pr has gone too long without review. If you would like to opt out of this review, comment assign to next reviewer:

R: @shunping for label python.
R: @liferoad for label build.
R: @kennknowles for label website.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

@damccorm
Copy link
Copy Markdown
Contributor

waiting on author

@Amar3tto Amar3tto requested a review from damccorm May 7, 2026 13:53
Comment thread .github/workflows/beam_Inference_Python_Benchmarks_Dataflow.yml Outdated
Comment thread .github/workflows/beam_Inference_Python_Benchmarks_Dataflow.yml Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_captioning.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_object_detection.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_image_object_detection.py Outdated
Comment thread sdks/python/apache_beam/examples/inference/pytorch_imagenet_rightfit.py Outdated
@github-actions
Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @shunping @liferoad @kennknowles

@damccorm
Copy link
Copy Markdown
Contributor

waiting on author

@Amar3tto Amar3tto requested a review from damccorm May 21, 2026 13:24
@damccorm
Copy link
Copy Markdown
Contributor

/gemini review

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces several new PyTorch-based inference example pipelines, including image captioning, object detection, and image classification, along with associated benchmarks and performance documentation. Feedback from the reviewer highlighted a critical architectural issue where adaptive batch sizing logic was incorrectly placed on the launcher instead of the workers. Additionally, the reviewer suggested optimizing model loading by moving device placement to the load_model method, improving error handling by avoiding broad exceptions, and replacing print statements with proper logging to ensure compatibility with Beam runners.

with FileSystems.open(uri) as f:
image_bytes = f.read()
yield uri, {"image_bytes": image_bytes}
except Exception as e:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Catching a broad Exception is discouraged as it can mask unexpected errors and make debugging difficult. Consider catching more specific exceptions (e.g., IOError, GoogleCloudError) or logging the exception details with the stack trace.

Comment on lines +163 to +167
def load_model(self):
from transformers import BlipForConditionalGeneration, BlipProcessor
processor = BlipProcessor.from_pretrained(self.model_name)
model = BlipForConditionalGeneration.from_pretrained(self.model_name)
return (model, processor)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Moving the model to the device and setting it to evaluation mode should be done once during model loading rather than in every inference call to improve performance.

Suggested change
def load_model(self):
from transformers import BlipForConditionalGeneration, BlipProcessor
processor = BlipProcessor.from_pretrained(self.model_name)
model = BlipForConditionalGeneration.from_pretrained(self.model_name)
return (model, processor)
def load_model(self):
from transformers import BlipForConditionalGeneration, BlipProcessor
processor = BlipProcessor.from_pretrained(self.model_name)
model = BlipForConditionalGeneration.from_pretrained(self.model_name)
model.to(self.device)
model.eval()
return (model, processor)

Comment on lines +175 to +177
model, processor = model_bundle
model.to(self.device)
model.eval()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Redundant model device placement and evaluation mode setting. These operations should be handled in load_model.

Suggested change
model, processor = model_bundle
model.to(self.device)
model.eval()
model, processor = model_bundle

Comment on lines +235 to +239
def load_model(self):
from transformers import CLIPModel, CLIPProcessor
processor = CLIPProcessor.from_pretrained(self.model_name)
model = CLIPModel.from_pretrained(self.model_name)
return (model, processor)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Moving the model to the device and setting it to evaluation mode should be done once during model loading to avoid redundant operations during inference.

Suggested change
def load_model(self):
from transformers import CLIPModel, CLIPProcessor
processor = CLIPProcessor.from_pretrained(self.model_name)
model = CLIPModel.from_pretrained(self.model_name)
return (model, processor)
def load_model(self):
from transformers import CLIPModel, CLIPProcessor
processor = CLIPProcessor.from_pretrained(self.model_name)
model = CLIPModel.from_pretrained(self.model_name)
model.to(self.device)
model.eval()
return (model, processor)

Comment on lines +247 to +249
model, processor = model_bundle
model.to(self.device)
model.eval()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Redundant model device placement and evaluation mode setting. These operations should be handled in load_model.

Suggested change
model, processor = model_bundle
model.to(self.device)
model.eval()
model, processor = model_bundle

try:
subscriber.delete_subscription(
request={"subscription": full_subscription_path})
print(f"Deleted subscription: {subscription_name}")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using print for logging in a Beam pipeline is discouraged as it may not be captured correctly by the runner's logging system. Use the logging module instead.

Suggested change
print(f"Deleted subscription: {subscription_name}")
logging.info(f"Deleted subscription: {subscription_name}")

if logits is None:
# fallback: try first value if dict shape differs
try:
logits = next(iter(inference_obj.values()))
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Falling back to the first value in the model output dictionary is fragile. If the model returns multiple outputs (e.g., auxiliary logits or metadata), this might select the wrong tensor. It is safer to require an explicit key or handle known output structures for the supported models.

| 'RunInference' >> RunInference(KeyedModelHandler(model_handler)))
| 'RunInference' >> RunInference(
KeyedModelHandler(model_handler)).with_resource_hints(
accelerator="type:nvidia-tesla-t4;count:1;install-nvidia-driver"))
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding the resource hint. However, because of how resource hints work, this will currently add a GPU for the whole pipeline. The way resource hints work is they ask for the requested resource for the whole stage containing this step. Because this pipeline doesn't contain any shuffles, it will all end up being in the same stage, so it will all get the T4.

To fix this, could you please add a Reshuffle step directly before RunInference?

I'm not sure if this will make the pipeline run more efficiently or not; because it is primarily bound on IO, not compute, the benefits might not outweigh the shuffle costs. That is good for us to understand regardless, though.

@damccorm
Copy link
Copy Markdown
Contributor

Thanks - could you please address my comment and gemini's? Then I think this should be good to go

@damccorm
Copy link
Copy Markdown
Contributor

waiting on author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants