Skip to content

[Python] Default max_batch_size in the Gemini and OpenAI model handlers - #41361

Open
tannnmayy wants to merge 3 commits into
apache:masterfrom
tannnmayy:llm-default-max-batch-size
Open

tannnmayy wants to merge 3 commits into
apache:masterfrom
tannnmayy:llm-default-max-batch-size

Conversation

@tannnmayy

Copy link
Copy Markdown
Contributor

Fixes #41360

GeminiModelHandler and OpenAIModelHandler set no default max_batch_size, so default batches grow to about 1,000 prompts, and to 10,000 inputs with embedding_from_string, which is over the 2,048 inputs the embeddings endpoint accepts. Per-prompt requests are only sent 32 at a time, and a failed request retries the whole batch.

This PR defaults max_batch_size to 32, or to 2,048 with embedding_from_string, and never below min_batch_size. An explicit max_batch_size behaves as before.

Testing:

  • New tests in gemini_inference_test.py and openai_inference_test.py. They fail on master.
  • Pipelines with fake clients and default settings: embedding requests went from up to 10,000 inputs (7 of 20 over the limit) to at most 2,048 (0 of 43). Gemini batches went from about 1,000 prompts to 32; 3,000 prompts at 0.5 s per call took 51 s before and 53 s after.

This is from the same pass over the remote LLM handlers as #40914 and #41359. I'm happy to change the default values if you'd pick different ones, and if something else in this area would be more useful for me to work on, I'd be glad to.

R: @jrmccluskey
cc: @claudevdm

Neither handler set a default, so adaptive batching grew batches to around
1000 prompts, and to 10000 inputs for embedding_from_string, which is over
the 2048 inputs the API accepts in one request. Requests only run 32 at a
time, so those batches added little, but a failed request retries the whole
batch.

Default max_batch_size to 32, or to 2048 with embedding_from_string, and
never below min_batch_size.
@github-actions github-actions Bot added python size/s S: 10-49 lines changed labels Nov 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers (or comment /summarize-failures for a summary of the failing checks).

@claudevdm

Copy link
Copy Markdown
Collaborator

/gemini review

@github-actions github-actions Bot left a comment

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.

📋 Review Summary

This PR sets sensible default max_batch_size values for GeminiModelHandler (32) and OpenAIModelHandler (2048 for embedding_from_string, 32 otherwise), while ensuring the default never falls below an explicitly provided min_batch_size. This prevents adaptive batching from creating oversized batches that exceed OpenAI's 2048-input embedding limit or cause excessive wasted work on batch-level retries for concurrent per-item requests.

🔍 General Feedback

  • The implementation is clean, concise, and preserves backward compatibility when max_batch_size is explicitly provided.
  • Unit tests in both gemini_inference_test.py and openai_inference_test.py thoroughly cover the new defaults and min_batch_size interaction.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 45.45455% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.35%. Comparing base (de0e417) to head (8ab3300).
⚠️ Report is 217 commits behind head on master.

Files with missing lines Patch % Lines
...ython/apache_beam/ml/inference/openai_inference.py 0.00% 6 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41361      +/-   ##
============================================
+ Coverage     59.32%   59.35%   +0.03%     
  Complexity     4995     4995              
============================================
  Files          1463     1465       +2     
  Lines        186618   187185     +567     
  Branches       3729     3729              
============================================
+ Hits         110704   111112     +408     
- Misses        72543    72702     +159     
  Partials       3371     3371              
Flag Coverage Δ
python 80.68% <45.45%> (-0.06%) ⬇️

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

☔ View full report in Codecov by Harness.
📢 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.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @claudevdm for label python.
Backup reviewer: jrmccluskey (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

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).

@Mola-maker Mola-maker left a comment

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.

I ran the tests locally for both handlers: gemini_inference_test.py 23 passed, openai_inference_test.py 39 passed. The 5 new tests (test_default_max_batch_size, test_default_max_batch_size_is_not_below_min_batch_size, test_default_max_batch_size_for_embeddings) fail on the base commit and pass with this change, confirming the fix. The default of 32 (2,048 for embeddings) matches the issue's proposal, and an explicit max_batch_size is preserved. LGTM.

@tannnmayy

Copy link
Copy Markdown
Contributor Author

Thanks for testing this, @Mola-maker . I had a question, since I’m also a new contributor, is it fine on Beam for contributors who aren’t committers to review and test each other’s PRs like this? I’d like to start doing the same on other PRs if it’s welcome.

@Mola-maker

Copy link
Copy Markdown
Contributor

Both options are fine.I just like to help others,and helping reviewing prs is highly appreciated.
What matters most is that u need to @ members to review and run CI tests!

handler.batch_elements_kwargs(), {
'min_batch_size': 64, 'max_batch_size': 64
})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Would tests like these be worth adding next to yours? The first one fails on this branch and passes with the change above; the second checks that the default still applies when max_batch_weight is set.

Suggested change
def test_no_default_max_batch_size_when_size_is_element_size_fn(self):
# Without max_batch_weight, max_batch_size is counted in element_size_fn
# units, so a default of 32 would mean 32 characters here.
handler = GeminiModelHandler(
model_name="gemini-model-123",
request_fn=generate_from_string,
api_key="123456789",
element_size_fn=len)
self.assertEqual(handler.batch_elements_kwargs(), {'element_size_fn': len})
def test_default_max_batch_size_with_max_batch_weight(self):
handler = GeminiModelHandler(
model_name="gemini-model-123",
request_fn=generate_from_string,
api_key="123456789",
element_size_fn=len,
max_batch_weight=1000)
self.assertEqual(
handler.batch_elements_kwargs(), {
'max_batch_size': 32,
'max_batch_weight': 1000,
'element_size_fn': len
})

handler.batch_elements_kwargs(), {
'min_batch_size': 64, 'max_batch_size': 64
})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Would the same two tests make sense here, for chat and embeddings? The first fails on this branch and passes with the change above.

Suggested change
def test_no_default_max_batch_size_when_size_is_element_size_fn(self):
# Without max_batch_weight, max_batch_size is counted in element_size_fn
# units, so a default of 32 or 2048 would mean that many characters here.
for request_fn in (chat_completion_from_string, embedding_from_string):
handler = OpenAIModelHandler(
model_name=_TEST_MODEL,
request_fn=request_fn,
api_key='fake',
element_size_fn=len)
self.assertEqual(
handler.batch_elements_kwargs(), {'element_size_fn': len})
def test_default_max_batch_size_with_max_batch_weight(self):
handler = OpenAIModelHandler(
model_name=_TEST_EMBEDDING_MODEL,
request_fn=embedding_from_string,
api_key='fake',
element_size_fn=len,
max_batch_weight=1000)
self.assertEqual(
handler.batch_elements_kwargs(),
{
'max_batch_size': 2048,
'max_batch_weight': 1000,
'element_size_fn': len
})

Without max_batch_weight, BatchElements counts max_batch_size in
element_size_fn units, so the default would have meant 32 characters
rather than 32 prompts.
@github-actions github-actions Bot added size/m M: 50-249 lines changed and removed size/s S: 10-49 lines changed labels Nov 18, 2026
@tannnmayy
tannnmayy requested a review from claudevdm November 18, 2026 07:24
@tannnmayy

Copy link
Copy Markdown
Contributor Author

Thanks @claudevdm, without max_batch_weight, max_batch_size is counted in element_size_fn units, so the default put every prompt in its own batch.

I've added your change to both handlers, along with the docstring note and your tests. With your setup it now gives 35 batches in 1.2 s, the same as master (the previous commit gave 3,000 batches of one in 33 s). Without element_size_fn, the default is unchanged. All 66 tests in both files pass.

# so the default number of prompts does not apply.
sized_by_element_size_fn = (
element_size_fn is not None and max_batch_weight is None)
if max_batch_size is None and not sized_by_element_size_fn:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

With an embeddings request_fn that sends up to 2,048 inputs per request the default batch size might be too high?.

Suggested change
if max_batch_size is None and not sized_by_element_size_fn:
# A custom request_fn may send the whole batch in one request.
custom_request_fn = request_fn not in (
generate_from_string, generate_image_from_strings_and_images)
skip_default = sized_by_element_size_fn or custom_request_fn
if max_batch_size is None and not skip_default:

# so the default number of prompts does not apply.
sized_by_element_size_fn = (
element_size_fn is not None and max_batch_weight is None)
if max_batch_size is None and not sized_by_element_size_fn:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The same change for the OpenAI handler.

Suggested change
if max_batch_size is None and not sized_by_element_size_fn:
# A custom request_fn may send the whole batch in one request.
custom_request_fn = request_fn not in (
chat_completion_from_string,
chat_completion_from_conversation,
embedding_from_string)
skip_default = sized_by_element_size_fn or custom_request_fn
if max_batch_size is None and not skip_default:

max_batch_size: optional. the maximum batch size to use when
batching inputs.
batching inputs. Defaults to 2048 with embedding_from_string, the
most inputs the API accepts in one request, and to 32 otherwise.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
most inputs the API accepts in one request, and to 32 otherwise.
most inputs the API accepts in one request, and to 32 with the other
built-in request functions. There is no default when element_size_fn
is set without max_batch_weight, or with a custom request_fn: set it
to the largest batch the function can send.

A custom request_fn may send the whole batch in one request, so the default
number of prompts doesn't fit it. Keep the defaults for the built-in request
functions only.
@tannnmayy

Copy link
Copy Markdown
Contributor Author

Makes sense, I hadn't thought about a custom request_fn sending the whole batch at once. Applied your change to both handlers, used the same docstring wording for Gemini, and added a test for each. Should I also add a CHANGES.md note, since the defaults change for the built-in functions?

@tannnmayy
tannnmayy requested a review from claudevdm November 25, 2026 14:08
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.

[Bug]: Gemini and OpenAI model handlers set no default max_batch_size; default embedding requests exceed the API's 2,048-input limit

3 participants