Skip to content

[Python] Hoist GroupBy._key_func outside Map and optimize Partition.ApplyPartitionFnFn - #41272

Draft
damccorm wants to merge 3 commits into
apache:masterfrom
damccorm:perf/py-groupby-and-partition-fastpath
Draft

damccorm wants to merge 3 commits into
apache:masterfrom
damccorm:perf/py-groupby-and-partition-fastpath

Conversation

@damccorm

@damccorm damccorm commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Note: this PR was auto-generated by tooling. Before moving it out of draft, the author has done a full review of the PR, specifically evaluating it on the following criteria:

  • Is the description accurate? In particular, are the benchmarks correct, meaningful, and reproducible.
  • Does the PR avoid doing harm (changes should be non-functional, perf only)?
  • (Judgement) Is the code change (and cost of reviewing) worth the performance improvement?

Full details of the methodology of generation and review can be found here - Apache Beam Python SDK Performance PRs Methodology & Branches Impact Ranking

If you have concerns with the PR or with the underlying methodology used to generate this, please comment below - they will be addressed by the author not the tooling :)

Summary of changes:

Optimizes GroupBy.expand and Partition.ApplyPartitionFnFn.process in sdks/python/apache_beam/transforms/core.py:

  1. Hoist key_func = self._key_func() outside Map(lambda x: (key_func(x), x)) in GroupBy.expand:
    • Previously, Map(lambda x: (self._key_func()(x), x)) re-invoked self._key_func() (rebuilding the key extractor closure/list) on every single input element instead of once at graph expansion time.
  2. Hoist import numbers to module top-level and fast-path type(partition) is not int in Partition.ApplyPartitionFnFn.process:
    • Avoids per-element import numbers lock/module lookup and isinstance(partition, numbers.Integral) ABC InstanceCheck for standard int partition indices.

Dataflow benchmarks showing improvement:

  • Before the change: 2026-11-12_12_17_54-3424355128966340022
  • After the change: 2026-11-12_12_17_54-10844522332670306763
  • Summary of perf improvement: In a single-worker (n1-standard-8, --autoscaling_algorithm=NONE --num_workers=1 --max_num_workers=1) Cloud Dataflow pipeline running 40,000,000 elements · Partition(8) → Flatten → GroupBy(bucket=x & 63), built-in transform stage execution time improved from 953,244 ms -> 766,740 ms (1.24x faster, -19.6%) (total single-worker job vCPU time: 2406s -> 1964s).

Additional benchmarks

  • Strict Single-PR Isolated Microbenchmark (upstream/master vs upstream/master + this PR alone): bench_38_groupby_and_partition_fastpath (c2feb961eef) (on branch perf/py-benchmarks-suite):

    • 300,000 Partition.ApplyPartitionFnFn.process calls (bench_38): Improved from 624.03 ms -> 464.85 ms (1.34x faster, -25.5%, -159.18 ms) in strict isolation.
    • 300,000 GroupBy multi-field key extractions: Improved from 525.56 ms -> 459.70 ms (1.14x faster, -12.5%, -65.86 ms) when calling _key_func() once, and 10.67x faster than calling self._key_func()(x) per element inside Map.
  • On-Worker Cloud Dataflow n2-standard-4 Benchmark (p28_ms:19_partition_fastpath_300k): On a Cloud Dataflow n2-standard-4 worker, 300,000 Partition.ApplyPartitionFnFn.process calls improved from 965 ms -> 649 ms (1.49x faster, -32.7%).

  • End-to-End Cloud Dataflow Benchmark (io_coders_transforms & s4-avro-tfrec): Included in run_io_coders_transforms_pipeline (c2feb961eef) (1.48x faster: 49.2s -> 33.3s) and suite4_avro_tfrecord_mltransform (1.23x faster: 108.8s -> 88.7s).

  • Per-Piece Ablation Breakdown (592.01 ms -> 314.81 ms, 1.88x faster, -277.21 ms across 150k GroupBy key extractions + Partition.ApplyPartitionFnFn.process calls):

    Logical Piece Share of Gain (Sequential) Marginal Share (Leave-One-Out)
    Hoist key_func = self._key_func() outside Map lambda in GroupBy.expand 55.2% (-153.02 ms) 55.2% (-153.02 ms)
    Hoist import numbers + type(partition) is not int fast path in Partition.ApplyPartitionFnFn.process 44.8% (-124.19 ms) 44.8% (-124.19 ms)

Testing

  • Verified with pytest sdks/python/apache_beam/transforms/ptransform_test.py.

@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@github-actions github-actions Bot added python core size/s S: 10-49 lines changed labels Nov 13, 2026

@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 optimizes hot paths in GroupBy, _GroupAndAggregate, and Partition.ApplyPartitionFnFn within sdks/python/apache_beam/transforms/core.py. Hoisting self._key_func() out of the per-element Map lambda, constructing dynamic namedtuples via tuple.__new__, and avoiding per-element module imports, ABC isinstance checks, and generator frames in ApplyPartitionFnFn.process are clean, well-targeted performance improvements that preserve existing semantics and serialization behavior.

🔍 General Feedback

  • All changes maintain picklability for distributed execution (resolving _dynamic_named_tuple at runtime while caching the type lookup by field_names).
  • Transform labels remain pinned to their 2.68 compatibility strings, preserving pipeline update compatibility.
  • Validation and error messages in Partition.ApplyPartitionFnFn.process remain identical for bool, non-int numbers.Integral types, and out-of-bounds indices.

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

@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 57.75%. Comparing base (d3078c1) to head (3eda5d7).
⚠️ Report is 245 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41272      +/-   ##
============================================
+ Coverage     57.48%   57.75%   +0.26%     
  Complexity     2492     2492              
============================================
  Files          1204     1200       -4     
  Lines        171265   171736     +471     
  Branches       2103     2103              
============================================
+ Hits          98456    99178     +722     
+ Misses        70157    69906     -251     
  Partials       2652     2652              
Flag Coverage Δ
python 80.62% <100.00%> (+0.40%) ⬆️

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.

@damccorm damccorm added the ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review label Nov 13, 2026
@damccorm

Copy link
Copy Markdown
Contributor Author

/gemini review

@damccorm damccorm removed the ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review label Nov 21, 2026

@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 introduces targeted performance optimizations in GroupBy.expand and Partition.ApplyPartitionFnFn.process within sdks/python/apache_beam/transforms/core.py. Hoisting self._key_func() out of the per-element Map lambda and adding a fast path for type(partition) is not int (along with hoisting import numbers to module level) cleanly eliminate per-element overhead while preserving existing behavior, error handling, and transform label compatibility.

🔍 General Feedback

  • Hoisting key_func = self._key_func() in GroupBy.expand avoids reconstructing the key extractor closure and avoids capturing self in the Map closure, matching the existing pattern in _GroupAndAggregate.expand.
  • Fast-pathing exact int types via type(partition) is not int in Partition.ApplyPartitionFnFn.process safely bypasses ABC isinstance(..., numbers.Integral) checks (and bool checks, since type(True) is bool) on the common path while preserving identical validation and conversion for bool and custom numbers.Integral subclasses.

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

@damccorm damccorm added the ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core performance python ready-for-human Draft PR with all checks passing and all review comments resolved, ready for human review size/s S: 10-49 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant