Skip to content

Conversation

@AMOOOMA
Copy link
Contributor

@AMOOOMA AMOOOMA commented Dec 12, 2025

Renamed the original model manager to ModelHandlerManager which is more aligned to its function
Added Model Manager as a util class that offers managed access to models, the client can request models without having to worry about managing GPU OOMs.
Also added various tests that checks the functions of all classes.
Added optional functionality to spawn new process in multiprocessshared to support running models in parallel

Changes should be safe because they are defaulted to False.

Classes

GPUMonitor

  • start(): Begins background memory polling.
  • stop(): Stops polling.
  • reset_peak(): Resets peak usage tracking.
  • get_stats() -> (current, peak, total): Returns memory stats.

ResourceEstimator

  • is_unknown(model_tag: str) -> bool: Checks if model needs profiling.
  • get_estimate(model_tag: str, default_mb: float) -> float: Returns memory cost.
  • set_initial_estimate(model_tag: str, cost: float): Manually sets cost.
  • add_observation(active_snapshot, peak_memory): Updates cost model via NNLS solver.

ModelManager

  • acquire_model(tag: str, loader_func: Callable) -> Any: Gets model instance (handles isolation/concurrency).
  • release_model(tag: str, instance: Any): Returns model to pool.
  • force_reset(): Clears all models and caches.
  • shutdown(): Cleans up resources.

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
Contributor

Summary of Changes

Hello @AMOOOMA, 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 ML inference capabilities by introducing a robust ModelManager that intelligently handles model lifecycle and resource allocation, particularly for GPU environments. It actively monitors GPU memory, estimates model memory footprints, and employs a sophisticated eviction strategy to prevent OOM errors and optimize concurrent model execution. The changes also include a refactoring of existing model management components and an optional feature to spawn models in isolated processes, ensuring greater stability and efficiency for complex ML pipelines.

Highlights

  • New ModelManager for OOM Prevention: Introduced a new ModelManager class designed to automatically allocate models and prevent Out-Of-Memory (OOM) errors, especially crucial for GPU-intensive ML inference workloads.
  • GPU Memory Monitoring and Resource Estimation: Added GPUMonitor to track GPU memory usage (current, peak, total) and ResourceEstimator to dynamically estimate model memory costs using an NNLS solver, enabling intelligent resource allocation and eviction.
  • Refactored Model Handler Management: The original _ModelManager has been renamed to _ModelHandlerManager to better reflect its role in managing model handlers, distinguishing it from the new ModelManager.
  • Optional Multi-Process Spawning: Enhanced MultiProcessShared with an optional spawn_process functionality, allowing models to be run in isolated processes for better parallelism and resource management, with a 'Suicide Pact' mechanism for process cleanup.
  • Integration with RunInference Transform: The RunInference transform now supports the new ModelManager via use_model_manager and model_manager_args parameters, providing a seamless way to leverage these new memory management capabilities.
  • Comprehensive Testing: Extensive unit and integration tests have been added for the ModelManager, GPUMonitor, ResourceEstimator, and the new MultiProcessShared features, covering various scenarios including capacity checks, OOM recovery, and eviction strategies.
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.

@codecov
Copy link

codecov bot commented Dec 14, 2025

Codecov Report

❌ Patch coverage is 16.58615% with 518 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.91%. Comparing base (0274331) to head (ebb6ff5).
⚠️ Report is 26 commits behind head on master.

Files with missing lines Patch % Lines
...s/python/apache_beam/ml/inference/model_manager.py 2.13% 413 Missing ⚠️
...s/python/apache_beam/utils/multi_process_shared.py 43.75% 90 Missing ⚠️
sdks/python/apache_beam/ml/inference/base.py 61.53% 15 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             master   #37103       +/-   ##
=============================================
+ Coverage     40.38%   56.91%   +16.53%     
  Complexity     3476     3476               
=============================================
  Files          1226     1227        +1     
  Lines        188553   189150      +597     
  Branches       3607     3607               
=============================================
+ Hits          76138   107659    +31521     
+ Misses       109012    78088    -30924     
  Partials       3403     3403               
Flag Coverage Δ
python 80.25% <16.58%> (+39.64%) ⬆️

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.

@AMOOOMA AMOOOMA marked this pull request as ready for review December 15, 2025 19:47
@AMOOOMA
Copy link
Contributor Author

AMOOOMA commented Dec 15, 2025

R: @damccorm

@github-actions
Copy link
Contributor

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

Copy link
Contributor

@damccorm damccorm left a comment

Choose a reason for hiding this comment

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

Could you try splitting this PR up? Specifically, I think we could fairly easily decompose into:

  1. unsafe_hard_delete changes (and any other multi_process_shared.py changes)
  2. Changes to model_manager.py (most extensive changes)
  3. Changes to inference/base.py (smaller change set, but most impactful/dangerous)

return dir


def _run_with_oom_protection(func, *args, **kwargs):
Copy link
Contributor

Choose a reason for hiding this comment

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

It is surprising to me that we're handling this here - if we do this, we should probably not do it in all cases. But delegating to the caller seems more natural to me

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yep! will definitely split this change up. The OOM protection here is tricky, originally it's at the caller but I noticed the CUDA usage not being dropped down because the process will be left in a broken state but yeah now that I think about it I can probably pass it in as part of the constructor so it's more natural. will update!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Splitted into two and the base.py edit + model_manager_it_test.py would probably need to wait for them since there's no PR on top of PR probably.

Multi Process Shared #37112
Model Manager #37113

@AMOOOMA AMOOOMA marked this pull request as draft December 15, 2025 21:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants